@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 { randomUUID } from 'crypto';
2
- import { Injectable, Optional, Inject, Logger, Global, Module, Sse, Req, Res, Controller, UnauthorizedException } from '@nestjs/common';
2
+ import { Injectable, Optional, Inject, Logger, Global, Module, Sse, Req, Res, Controller, InternalServerErrorException, UnauthorizedException } from '@nestjs/common';
3
3
  import { Subject, of, EMPTY, Observable, merge } from 'rxjs';
4
4
  import { takeUntil, catchError, finalize } from 'rxjs/operators';
5
5
 
@@ -175,6 +175,31 @@ var RESERVED_EVENT_NAMES = {
175
175
  ERROR: "error"
176
176
  };
177
177
 
178
+ // src/server/utils/assert-identity.ts
179
+ function isBlank(value) {
180
+ return typeof value !== "string" || value.trim().length === 0;
181
+ }
182
+ function resolveAuthTenant(options, auth) {
183
+ const resolved = options.tenantResolver?.(auth) ?? auth.tenantId;
184
+ if (resolved === void 0 || resolved === null) {
185
+ const { tenantId: _dropped, ...withoutTenant } = auth;
186
+ return withoutTenant;
187
+ }
188
+ return { ...auth, tenantId: resolved };
189
+ }
190
+ function assertIdentityIsNotBlank(auth) {
191
+ if (isBlank(auth.userId)) {
192
+ throw new Error(
193
+ `${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
194
+ );
195
+ }
196
+ if (auth.tenantId !== void 0 && isBlank(auth.tenantId)) {
197
+ throw new Error(
198
+ `${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
199
+ );
200
+ }
201
+ }
202
+
178
203
  // src/server/utils/parse-cookie-header.ts
179
204
  function parseCookieHeader(cookieHeader) {
180
205
  const out = /* @__PURE__ */ Object.create(null);
@@ -502,7 +527,8 @@ var SseTransport = class {
502
527
  originalAuth: {
503
528
  userId: params.auth.userId,
504
529
  tenantId: params.auth.tenantId,
505
- roles: params.auth.roles
530
+ roles: params.auth.roles,
531
+ metadata: params.auth.metadata
506
532
  }
507
533
  };
508
534
  this.connections.register(record);
@@ -524,6 +550,7 @@ var SseTransport = class {
524
550
  userId: record.userId,
525
551
  tenantId: record.tenantId,
526
552
  roles: record.originalAuth.roles,
553
+ metadata: record.originalAuth.metadata,
527
554
  transport: "sse",
528
555
  ip: record.ip,
529
556
  userAgent: record.userAgent,
@@ -761,6 +788,7 @@ function buildMeta(record) {
761
788
  userId: record.userId,
762
789
  tenantId: record.tenantId,
763
790
  roles: record.originalAuth.roles,
791
+ metadata: record.originalAuth.metadata,
764
792
  transport: "sse",
765
793
  ip: record.ip,
766
794
  userAgent: record.userAgent,
@@ -781,6 +809,39 @@ var SseSubscriptionHandler = class {
781
809
  hooks;
782
810
  offlineDelivery;
783
811
  logger = new Logger(SseSubscriptionHandler.name);
812
+ /**
813
+ * Resolve the tenant this connection routes on, and refuse a blank identity.
814
+ *
815
+ * Both transports resolve the routing tenant through this one function, so a
816
+ * connection carries the same tenant whichever one opened it. The check runs on
817
+ * the resolved value rather than the raw one — validating what the server does not
818
+ * use would validate nothing.
819
+ *
820
+ * A blank identity is the consumer's configuration rather than the client's
821
+ * credentials, so it is deliberately not a 401: a 401 would tell a client its
822
+ * credentials were rejected when they were accepted, inviting a retry that cannot
823
+ * succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
824
+ * once, not an unhandled crash logging a stack on every reconnect.
825
+ *
826
+ * The reason names the operator's fix, so it goes to the server log and the client
827
+ * receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
828
+ * without a message.
829
+ *
830
+ * @param auth - The result the consumer's authenticator returned.
831
+ * @returns The same result with the routing tenant resolved.
832
+ * @throws InternalServerErrorException with the generic body when a trait is present
833
+ * but blank.
834
+ */
835
+ resolveAndValidateIdentity(auth) {
836
+ const resolvedAuth = resolveAuthTenant(this.options, auth);
837
+ try {
838
+ assertIdentityIsNotBlank(resolvedAuth);
839
+ } catch (err) {
840
+ this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
841
+ throw new InternalServerErrorException();
842
+ }
843
+ return resolvedAuth;
844
+ }
784
845
  /**
785
846
  * Handle an incoming SSE connection request end-to-end.
786
847
  *
@@ -792,7 +853,15 @@ var SseSubscriptionHandler = class {
792
853
  * @param req - The incoming request (SSE GET).
793
854
  * @param res - The response (passthrough for header mutations and heartbeat writes).
794
855
  * @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
795
- * @throws UnauthorizedException when authentication returns null.
856
+ * @throws UnauthorizedException when authentication returns null — the client's
857
+ * credentials were rejected, which is a 401.
858
+ * @throws InternalServerErrorException when the authenticator, or the configured
859
+ * `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
860
+ * a 401: the credentials were accepted and the fault is the consumer's
861
+ * configuration, so it surfaces as a 500 rather than telling a client to retry
862
+ * something that cannot succeed. The exception carries no message, so the client
863
+ * gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
864
+ * written to the server log.
796
865
  */
797
866
  async handle(req, res) {
798
867
  res.setHeader("Cache-Control", "no-cache, no-transform");
@@ -800,8 +869,7 @@ var SseSubscriptionHandler = class {
800
869
  const context = buildAuthContext(req);
801
870
  const auth = await this.transport.authenticate(context);
802
871
  if (!auth) throw new UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
803
- const resolvedTenantId = this.options.tenantResolver?.(auth) ?? auth.tenantId;
804
- const resolvedAuth = resolvedTenantId !== void 0 ? { ...auth, tenantId: resolvedTenantId } : auth;
872
+ const resolvedAuth = this.resolveAndValidateIdentity(auth);
805
873
  const connectionId = randomUUID();
806
874
  const subject = new Subject();
807
875
  const close$ = new Subject();
@@ -927,9 +995,14 @@ SseSubscriptionHandler = __decorateClass([
927
995
  __decorateParam(4, Inject(OfflineQueueDeliveryService))
928
996
  ], SseSubscriptionHandler);
929
997
 
998
+ // src/server/utils/normalize-endpoint-path.ts
999
+ function normalizeEndpointPath(endpoint) {
1000
+ return endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
1001
+ }
1002
+
930
1003
  // src/server/factories/sse-controller.factory.ts
931
1004
  function createSseController(endpoint) {
932
- const ssePath = endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
1005
+ const ssePath = normalizeEndpointPath(endpoint);
933
1006
  let DynamicSseController = class {
934
1007
  // Explicit @Inject: the published bundle is built by esbuild/tsup, which does
935
1008
  // not emit `design:paramtypes` decorator metadata, so constructor params must
@@ -1019,7 +1092,13 @@ var RealtimeService = class {
1019
1092
  broadcast(event, data) {
1020
1093
  return this.transport.broadcast(event, data);
1021
1094
  }
1022
- /** Add a specific connection to a room. */
1095
+ /**
1096
+ * Add a specific connection to a room.
1097
+ *
1098
+ * The room id is not checked. Never pass client-supplied input that could start
1099
+ * with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
1100
+ * receives that tenant's events.
1101
+ */
1023
1102
  joinRoom(connectionId, roomId) {
1024
1103
  return this.transport.joinRoom(connectionId, roomId);
1025
1104
  }
@@ -1089,7 +1168,7 @@ var ReauthenticationService = class {
1089
1168
  this.positiveCache.clear();
1090
1169
  }
1091
1170
  /**
1092
- * Run one revalidation cycle over all active SSE connections.
1171
+ * Run one revalidation cycle over every active connection, SSE and WebSocket alike.
1093
1172
  *
1094
1173
  * A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
1095
1174
  * refreshes the cache. A negative result (or a thrown error) invokes the configured
@@ -1099,14 +1178,19 @@ var ReauthenticationService = class {
1099
1178
  */
1100
1179
  async runCycle() {
1101
1180
  const now = Date.now();
1102
- for (const conn of this.connections.allByTransport("sse")) {
1181
+ const connections = [
1182
+ ...this.connections.allByTransport("sse"),
1183
+ ...this.connections.allByTransport("websocket")
1184
+ ];
1185
+ for (const conn of connections) {
1103
1186
  try {
1104
1187
  const lastValid = this.positiveCache.get(conn.connectionId);
1105
1188
  if (lastValid !== void 0 && now - lastValid < this.policy.cacheTtlMs) continue;
1106
1189
  const originalAuth = {
1107
1190
  userId: conn.originalAuth.userId,
1108
1191
  ...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
1109
- ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {}
1192
+ ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {},
1193
+ ...conn.originalAuth.metadata !== void 0 ? { metadata: conn.originalAuth.metadata } : {}
1110
1194
  };
1111
1195
  const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
1112
1196
  if (rawResult === true) {
@@ -1136,7 +1220,8 @@ var ReauthenticationService = class {
1136
1220
  userId: conn.userId,
1137
1221
  tenantId: conn.tenantId,
1138
1222
  roles: conn.originalAuth.roles,
1139
- transport: "sse",
1223
+ metadata: conn.originalAuth.metadata,
1224
+ transport: conn.transport,
1140
1225
  ip: conn.ip,
1141
1226
  userAgent: conn.userAgent,
1142
1227
  connectedAt: conn.connectedAt
@@ -1158,6 +1243,7 @@ ReauthenticationService = __decorateClass([
1158
1243
  ], ReauthenticationService);
1159
1244
 
1160
1245
  // src/server/composition/realtime-module.factory.ts
1246
+ var DEFAULT_ASYNC_SSE_ENDPOINT = "/events";
1161
1247
  var EXPORTED_TOKENS = [
1162
1248
  RealtimeService,
1163
1249
  ConnectionRegistry,
@@ -1222,6 +1308,20 @@ function composeForRoot(moduleClass, wiring, logger, options) {
1222
1308
  exports: EXPORTED_TOKENS
1223
1309
  };
1224
1310
  }
1311
+ function assertSseEndpointApplies(asyncOptions, moduleName) {
1312
+ if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
1313
+ throw new Error(
1314
+ `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`
1315
+ );
1316
+ }
1317
+ function bindSseEndpoint(resolved, declared, bound, moduleName) {
1318
+ if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
1319
+ throw new Error(
1320
+ `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`
1321
+ );
1322
+ }
1323
+ return Object.freeze({ ...resolved, sse: { ...resolved.sse, endpoint: bound } });
1324
+ }
1225
1325
  function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
1226
1326
  if (!raw) {
1227
1327
  throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
@@ -1249,9 +1349,22 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1249
1349
  );
1250
1350
  }
1251
1351
  assertModeSupported(wiring, asyncOptions.transport, moduleName);
1352
+ assertSseEndpointApplies(asyncOptions, moduleName);
1252
1353
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
1253
1354
  const instanceId = randomUUID();
1254
- const resolve = (raw, source) => resolveAsyncOptions(raw, asyncOptions.transport, instanceId, source, logger, moduleName);
1355
+ const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
1356
+ const resolve = (raw, source) => {
1357
+ const resolved = resolveAsyncOptions(
1358
+ raw,
1359
+ asyncOptions.transport,
1360
+ instanceId,
1361
+ source,
1362
+ logger,
1363
+ moduleName
1364
+ );
1365
+ if (asyncOptions.transport === "websocket") return resolved;
1366
+ return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
1367
+ };
1255
1368
  const resolvedOptionsProvider = asyncOptions.useFactory ? {
1256
1369
  provide: REALTIME_OPTIONS_TOKEN,
1257
1370
  useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
@@ -1266,7 +1379,10 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1266
1379
  };
1267
1380
  const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
1268
1381
  const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
1269
- const { providers: transportProviders, controllers } = wiring.buildAsync(asyncOptions.transport);
1382
+ const { providers: transportProviders, controllers } = wiring.buildAsync({
1383
+ mode: asyncOptions.transport,
1384
+ sseEndpoint: boundSseEndpoint
1385
+ });
1270
1386
  return {
1271
1387
  module: moduleClass,
1272
1388
  imports: asyncOptions.imports ?? [],
@@ -1367,7 +1483,6 @@ RealtimePubSubSubscriber = __decorateClass([
1367
1483
  ], RealtimePubSubSubscriber);
1368
1484
 
1369
1485
  // src/server/composition/sse-wiring.ts
1370
- var DEFAULT_ASYNC_ENDPOINT = "/events";
1371
1486
  var sseWiring = {
1372
1487
  modes: ["sse"],
1373
1488
  build(resolved) {
@@ -1382,7 +1497,7 @@ var sseWiring = {
1382
1497
  gateways: []
1383
1498
  };
1384
1499
  },
1385
- buildAsync() {
1500
+ buildAsync({ sseEndpoint }) {
1386
1501
  return {
1387
1502
  providers: [
1388
1503
  SseTransport,
@@ -1390,7 +1505,7 @@ var sseWiring = {
1390
1505
  RealtimePubSubSubscriber,
1391
1506
  { provide: REALTIME_TRANSPORT_TOKEN, useExisting: SseTransport }
1392
1507
  ],
1393
- controllers: [createSseController(DEFAULT_ASYNC_ENDPOINT)]
1508
+ controllers: [createSseController(sseEndpoint)]
1394
1509
  };
1395
1510
  }
1396
1511
  };
@@ -1418,9 +1533,12 @@ var BymaxRealtimeModule = class {
1418
1533
  * configuration rejects at bootstrap and the application fails to start with
1419
1534
  * a clear error.
1420
1535
  *
1421
- * Controllers are registered at decoration time, so this path binds the SSE
1422
- * controller to the default endpoint `/events`. A non-default endpoint needs
1423
- * `forRoot` with pre-resolved options.
1536
+ * Controllers are registered at decoration time, so the SSE route comes from
1537
+ * `sseEndpoint` on the registration rather than from the `sse.endpoint` the
1538
+ * factory resolves — the factory has not run yet when the controller is
1539
+ * built. It defaults to `/events`, and a factory that resolves a disagreeing
1540
+ * `sse.endpoint` is rejected at bootstrap rather than silently served on
1541
+ * another path.
1424
1542
  *
1425
1543
  * @throws when no factory pattern is given, more than one is, or the factory
1426
1544
  * resolves a transport other than `'sse'`.
@@ -1428,6 +1546,7 @@ var BymaxRealtimeModule = class {
1428
1546
  * ```ts
1429
1547
  * BymaxRealtimeModule.forRootAsync({
1430
1548
  * transport: 'sse',
1549
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
1431
1550
  * imports: [ConfigModule],
1432
1551
  * inject: [ConfigService],
1433
1552
  * useFactory: (cfg: ConfigService) => ({
@@ -1619,4 +1738,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1619
1738
  }
1620
1739
  };
1621
1740
 
1622
- export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, sseWiring };
1741
+ export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
@@ -106,7 +106,12 @@ exports.WebSocketTransport = class WebSocketTransport {
106
106
  connectedAt,
107
107
  subject: null,
108
108
  close$: null,
109
- originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
109
+ originalAuth: {
110
+ userId: auth.userId,
111
+ tenantId: auth.tenantId,
112
+ roles: auth.roles,
113
+ metadata: auth.metadata
114
+ }
110
115
  });
111
116
  await socket.join(`${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
112
117
  if (auth.tenantId) await socket.join(`${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
@@ -119,6 +124,7 @@ exports.WebSocketTransport = class WebSocketTransport {
119
124
  userId: auth.userId,
120
125
  tenantId: auth.tenantId,
121
126
  roles: auth.roles,
127
+ metadata: auth.metadata,
122
128
  transport: "websocket",
123
129
  ip: socket.handshake.address,
124
130
  userAgent: socket.handshake.headers["user-agent"],
@@ -144,6 +150,7 @@ exports.WebSocketTransport = class WebSocketTransport {
144
150
  userId: record.userId,
145
151
  tenantId: record.tenantId,
146
152
  roles: record.originalAuth.roles,
153
+ metadata: record.originalAuth.metadata,
147
154
  transport: "websocket",
148
155
  ip: record.ip,
149
156
  userAgent: record.userAgent,
@@ -423,34 +430,54 @@ exports.RealtimeGateway = class RealtimeGateway {
423
430
  * Fail-closed: any thrown error disconnects the socket immediately so it cannot
424
431
  * linger in an unregistered state and receive broadcast events.
425
432
  */
433
+ /**
434
+ * Map a Socket.IO handshake onto the transport-agnostic auth context.
435
+ *
436
+ * Socket.IO carries credentials in three places and the authenticator sees one
437
+ * shape: `handshake.auth` is merged into the headers and query it stands in for,
438
+ * and a repeated `ticket` parameter is collapsed to its first value, because the
439
+ * ticket pattern is single-valued and an array reaching an authenticator that
440
+ * expects a string is a bug at the far end.
441
+ *
442
+ * @param socket - The connecting Socket.IO socket.
443
+ * @returns The context handed to `IConnectionAuthenticator.authenticate`.
444
+ */
445
+ buildAuthContext(socket) {
446
+ const { handshake } = socket;
447
+ const headers = this.normalizeHeaders(handshake.headers);
448
+ const query = { ...handshake.query };
449
+ const handshakeAuth = handshake.auth;
450
+ if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
451
+ if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
452
+ const ticket = firstQueryValue(query["ticket"]);
453
+ if (ticket !== void 0) query["ticket"] = ticket;
454
+ return {
455
+ cookies: internal.parseCookieHeader(handshake.headers.cookie ?? ""),
456
+ headers,
457
+ query,
458
+ ip: handshake.address,
459
+ userAgent: handshake.headers["user-agent"],
460
+ transport: "websocket"
461
+ };
462
+ }
426
463
  async handleConnection(socket) {
427
464
  try {
428
- const { handshake } = socket;
429
- const headers = this.normalizeHeaders(handshake.headers);
430
- const query = { ...handshake.query };
431
- const handshakeAuth = handshake.auth;
432
- if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
433
- if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
434
- const ticket = firstQueryValue(query["ticket"]);
435
- if (ticket !== void 0) query["ticket"] = ticket;
436
- const ctx = {
437
- cookies: internal.parseCookieHeader(handshake.headers.cookie ?? ""),
438
- headers,
439
- query,
440
- ip: handshake.address,
441
- userAgent: handshake.headers["user-agent"],
442
- transport: "websocket"
443
- };
444
- const auth = await this.transport.authenticator().authenticate(ctx);
465
+ const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
445
466
  if (!auth) {
446
467
  socket.disconnect(true);
447
468
  return;
448
469
  }
449
- await this.transport.registerSocket(socket, auth);
470
+ const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
471
+ internal.assertIdentityIsNotBlank(resolvedAuth);
472
+ await this.transport.registerSocket(socket, resolvedAuth);
450
473
  if (this.options.websocket?.emitConnectionEvent !== false) {
451
474
  socket.emit(internal.RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
452
475
  connectionId: socket.id,
453
- traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
476
+ traits: {
477
+ userId: resolvedAuth.userId,
478
+ tenantId: resolvedAuth.tenantId,
479
+ roles: resolvedAuth.roles
480
+ }
454
481
  });
455
482
  }
456
483
  } catch (err) {
@@ -490,7 +517,6 @@ exports.RealtimeGateway = __decorateClass([
490
517
  ], exports.RealtimeGateway);
491
518
 
492
519
  // src/websocket/websocket-wiring.ts
493
- var DEFAULT_ASYNC_ENDPOINT = "/events";
494
520
  var webSocketWiring = {
495
521
  modes: ["websocket", "both"],
496
522
  build(resolved) {
@@ -517,7 +543,7 @@ var webSocketWiring = {
517
543
  gateways: [exports.RealtimeGateway]
518
544
  };
519
545
  },
520
- buildAsync(mode) {
546
+ buildAsync({ mode, sseEndpoint }) {
521
547
  if (mode === "websocket") {
522
548
  return {
523
549
  providers: [
@@ -538,7 +564,7 @@ var webSocketWiring = {
538
564
  internal.RealtimePubSubSubscriber,
539
565
  { provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
540
566
  ],
541
- controllers: [internal.createSseController(DEFAULT_ASYNC_ENDPOINT)]
567
+ controllers: [internal.createSseController(sseEndpoint)]
542
568
  };
543
569
  }
544
570
  };
@@ -569,9 +595,12 @@ exports.BymaxRealtimeWebSocketModule = class BymaxRealtimeWebSocketModule {
569
595
  * Configure the module asynchronously so options — and the authenticator —
570
596
  * can be resolved through DI.
571
597
  *
572
- * Controllers are registered at decoration time, so `'both'` binds the SSE
573
- * controller to the default endpoint `/events`. A non-default endpoint needs
574
- * `forRoot` with pre-resolved options.
598
+ * Controllers are registered at decoration time, so under `'both'` the SSE
599
+ * route comes from `sseEndpoint` on the registration rather than from the
600
+ * `sse.endpoint` the factory resolves — the factory has not run yet when the
601
+ * controller is built. It defaults to `/events`, and a factory that resolves
602
+ * a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
603
+ * registers no SSE controller, so `sseEndpoint` is rejected there outright.
575
604
  *
576
605
  * @throws when no factory pattern is given, more than one is, or the factory
577
606
  * resolves a transport other than the one declared.
@@ -579,6 +608,7 @@ exports.BymaxRealtimeWebSocketModule = class BymaxRealtimeWebSocketModule {
579
608
  * ```ts
580
609
  * BymaxRealtimeWebSocketModule.forRootAsync({
581
610
  * transport: 'both',
611
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
582
612
  * imports: [ConfigModule],
583
613
  * inject: [ConfigService],
584
614
  * useFactory: (cfg: ConfigService) => ({
@@ -603,7 +633,7 @@ exports.BymaxRealtimeWebSocketModule = __decorateClass([
603
633
  common.Module({})
604
634
  ], exports.BymaxRealtimeWebSocketModule);
605
635
  var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
606
- logger = new common.Logger(_RealtimeIoAdapter.name);
636
+ adapterLogger = new common.Logger(_RealtimeIoAdapter.name);
607
637
  options;
608
638
  constructor(app) {
609
639
  super(app);
@@ -663,11 +693,11 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
663
693
  const pub = pubClient;
664
694
  const sub = pub.duplicate();
665
695
  server.adapter(createAdapter(pub, sub));
666
- this.logger.log(
696
+ this.adapterLogger.log(
667
697
  "Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
668
698
  );
669
699
  } catch (err) {
670
- this.logger.error(
700
+ this.adapterLogger.error(
671
701
  `Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
672
702
  );
673
703
  }
@@ -34,9 +34,12 @@ declare class BymaxRealtimeWebSocketModule {
34
34
  * Configure the module asynchronously so options — and the authenticator —
35
35
  * can be resolved through DI.
36
36
  *
37
- * Controllers are registered at decoration time, so `'both'` binds the SSE
38
- * controller to the default endpoint `/events`. A non-default endpoint needs
39
- * `forRoot` with pre-resolved options.
37
+ * Controllers are registered at decoration time, so under `'both'` the SSE
38
+ * route comes from `sseEndpoint` on the registration rather than from the
39
+ * `sse.endpoint` the factory resolves — the factory has not run yet when the
40
+ * controller is built. It defaults to `/events`, and a factory that resolves
41
+ * a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
42
+ * registers no SSE controller, so `sseEndpoint` is rejected there outright.
40
43
  *
41
44
  * @throws when no factory pattern is given, more than one is, or the factory
42
45
  * resolves a transport other than the one declared.
@@ -44,6 +47,7 @@ declare class BymaxRealtimeWebSocketModule {
44
47
  * ```ts
45
48
  * BymaxRealtimeWebSocketModule.forRootAsync({
46
49
  * transport: 'both',
50
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
47
51
  * imports: [ConfigModule],
48
52
  * inject: [ConfigService],
49
53
  * useFactory: (cfg: ConfigService) => ({
@@ -244,6 +248,19 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
244
248
  * Fail-closed: any thrown error disconnects the socket immediately so it cannot
245
249
  * linger in an unregistered state and receive broadcast events.
246
250
  */
251
+ /**
252
+ * Map a Socket.IO handshake onto the transport-agnostic auth context.
253
+ *
254
+ * Socket.IO carries credentials in three places and the authenticator sees one
255
+ * shape: `handshake.auth` is merged into the headers and query it stands in for,
256
+ * and a repeated `ticket` parameter is collapsed to its first value, because the
257
+ * ticket pattern is single-valued and an array reaching an authenticator that
258
+ * expects a string is a bug at the far end.
259
+ *
260
+ * @param socket - The connecting Socket.IO socket.
261
+ * @returns The context handed to `IConnectionAuthenticator.authenticate`.
262
+ */
263
+ private buildAuthContext;
247
264
  handleConnection(socket: Socket): Promise<void>;
248
265
  /** Handle a WebSocket disconnection — unregister the connection. */
249
266
  handleDisconnect(socket: Socket): Promise<void>;
@@ -281,7 +298,7 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
281
298
  * (spec §11.5).
282
299
  */
283
300
  declare class RealtimeIoAdapter extends IoAdapter {
284
- private readonly logger;
301
+ private readonly adapterLogger;
285
302
  private readonly options;
286
303
  constructor(app: INestApplicationContext);
287
304
  /**
@@ -34,9 +34,12 @@ declare class BymaxRealtimeWebSocketModule {
34
34
  * Configure the module asynchronously so options — and the authenticator —
35
35
  * can be resolved through DI.
36
36
  *
37
- * Controllers are registered at decoration time, so `'both'` binds the SSE
38
- * controller to the default endpoint `/events`. A non-default endpoint needs
39
- * `forRoot` with pre-resolved options.
37
+ * Controllers are registered at decoration time, so under `'both'` the SSE
38
+ * route comes from `sseEndpoint` on the registration rather than from the
39
+ * `sse.endpoint` the factory resolves — the factory has not run yet when the
40
+ * controller is built. It defaults to `/events`, and a factory that resolves
41
+ * a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
42
+ * registers no SSE controller, so `sseEndpoint` is rejected there outright.
40
43
  *
41
44
  * @throws when no factory pattern is given, more than one is, or the factory
42
45
  * resolves a transport other than the one declared.
@@ -44,6 +47,7 @@ declare class BymaxRealtimeWebSocketModule {
44
47
  * ```ts
45
48
  * BymaxRealtimeWebSocketModule.forRootAsync({
46
49
  * transport: 'both',
50
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
47
51
  * imports: [ConfigModule],
48
52
  * inject: [ConfigService],
49
53
  * useFactory: (cfg: ConfigService) => ({
@@ -244,6 +248,19 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
244
248
  * Fail-closed: any thrown error disconnects the socket immediately so it cannot
245
249
  * linger in an unregistered state and receive broadcast events.
246
250
  */
251
+ /**
252
+ * Map a Socket.IO handshake onto the transport-agnostic auth context.
253
+ *
254
+ * Socket.IO carries credentials in three places and the authenticator sees one
255
+ * shape: `handshake.auth` is merged into the headers and query it stands in for,
256
+ * and a repeated `ticket` parameter is collapsed to its first value, because the
257
+ * ticket pattern is single-valued and an array reaching an authenticator that
258
+ * expects a string is a bug at the far end.
259
+ *
260
+ * @param socket - The connecting Socket.IO socket.
261
+ * @returns The context handed to `IConnectionAuthenticator.authenticate`.
262
+ */
263
+ private buildAuthContext;
247
264
  handleConnection(socket: Socket): Promise<void>;
248
265
  /** Handle a WebSocket disconnection — unregister the connection. */
249
266
  handleDisconnect(socket: Socket): Promise<void>;
@@ -281,7 +298,7 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
281
298
  * (spec §11.5).
282
299
  */
283
300
  declare class RealtimeIoAdapter extends IoAdapter {
284
- private readonly logger;
301
+ private readonly adapterLogger;
285
302
  private readonly options;
286
303
  constructor(app: INestApplicationContext);
287
304
  /**