@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.
@@ -47,10 +47,10 @@ interface ConnectionAuthContext {
47
47
  /**
48
48
  * Query string parameters — useful for the ticket pattern.
49
49
  *
50
- * Values follow the Node `ParsedUrlQuery` shape: a repeated key (`?a=1&a=2`)
51
- * arrives as a `string[]`. Authenticators that expect a single value should
52
- * normalize accordingly; the WebSocket gateway already collapses the `ticket`
53
- * parameter to a single string before delegating.
50
+ * On WebSocket a repeated key (`?a=1&a=2`) arrives as a `string[]`, except the
51
+ * `ticket` parameter, which the gateway collapses to a single string. On SSE only
52
+ * a single string value is kept; a repeated key arrives as `undefined`.
53
+ * Authenticators that expect a single value should check `typeof value === 'string'`.
54
54
  */
55
55
  readonly query: Record<string, string | string[] | undefined>;
56
56
  /**
@@ -69,7 +69,20 @@ interface ConnectionAuthContext {
69
69
  * may carry extra fields through the `metadata` bag.
70
70
  */
71
71
  interface AuthenticationResult {
72
+ /**
73
+ * The authenticated account. Must be a non-empty string: a blank one indexes
74
+ * every such connection under a single key and joins them all to the room
75
+ * `user:`, so it is refused at connection bootstrap rather than registered.
76
+ */
72
77
  readonly userId: string;
78
+ /**
79
+ * The tenant this connection routes on, or absent when it belongs to none.
80
+ *
81
+ * Absent and empty are different. Omitting it — or returning `undefined` or
82
+ * `null` — means no tenant: indexed under none, joining no tenant room. An empty
83
+ * or whitespace-only string is refused, because it is a shared bucket rather than
84
+ * a missing value: every connection carrying `''` lands under the same key.
85
+ */
73
86
  readonly tenantId?: string;
74
87
  readonly roles?: readonly string[];
75
88
  /**
@@ -110,6 +123,12 @@ interface IConnectionAuthenticator {
110
123
  *
111
124
  * @returns the authenticated result, or `null` to reject the connection (the
112
125
  * transport replies 401 / disconnects accordingly).
126
+ *
127
+ * Returning a result whose `userId` is blank, or whose `tenantId` is present but
128
+ * blank, is not a second way to reject: it is a contract violation. The connection
129
+ * is refused either way, but it surfaces as a server fault rather than a 401,
130
+ * because the credentials were accepted and the fault is in this method. Return
131
+ * `null` to reject a client.
113
132
  */
114
133
  authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
115
134
  /**
@@ -328,7 +347,17 @@ interface ReauthenticationPolicy {
328
347
  interface BymaxRealtimeModuleOptions {
329
348
  transport: TransportMode;
330
349
  authenticator: IConnectionAuthenticator;
331
- tenantResolver?: (auth: AuthenticationResult) => string | undefined;
350
+ /**
351
+ * Derive the tenant a connection routes on from the authenticated result.
352
+ *
353
+ * Applied on **both** transports. `undefined` and `null` both mean "no opinion"
354
+ * and fall back to `auth.tenantId` rather than clearing it; to place a connection
355
+ * in no tenant, return a result without one from the authenticator. `null` is in
356
+ * the signature because the implementation accepts it and a type narrower than the
357
+ * behaviour forces a cast on anyone testing the boundary. A blank string is
358
+ * refused, on the same terms as `AuthenticationResult.tenantId`.
359
+ */
360
+ tenantResolver?: (auth: AuthenticationResult) => string | undefined | null;
332
361
  hooks?: IConnectionLifecycleHooks;
333
362
  pubsub?: IRealtimePubSub;
334
363
  offlineQueue?: IOfflineQueueStorage;
@@ -619,9 +648,17 @@ declare class ConnectionRegistry {
619
648
  private readonly byId;
620
649
  private readonly byUserId;
621
650
  private readonly byTenantId;
622
- /** Register a connection and index it by user and tenant. */
651
+ /**
652
+ * Register a connection and index it by user and tenant.
653
+ *
654
+ * @internal Transport bookkeeping: applications must not call it.
655
+ */
623
656
  register(record: ConnectionRecord): void;
624
- /** Remove a connection from every index. Returns the removed record, if any. */
657
+ /**
658
+ * Remove a connection from every index. Returns the removed record, if any.
659
+ *
660
+ * @internal Transport bookkeeping: applications must not call it.
661
+ */
625
662
  unregister(connectionId: string): ConnectionRecord | undefined;
626
663
  /** Look up a single connection by id. */
627
664
  get(connectionId: string): ConnectionRecord | undefined;
@@ -740,7 +777,13 @@ declare class RealtimeService {
740
777
  emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
741
778
  /** Send to every connected client. Use sparingly. */
742
779
  broadcast(event: string, data: unknown): Promise<void>;
743
- /** Add a specific connection to a room. */
780
+ /**
781
+ * Add a specific connection to a room.
782
+ *
783
+ * The room id is not checked. Never pass client-supplied input that could start
784
+ * with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
785
+ * receives that tenant's events.
786
+ */
744
787
  joinRoom(connectionId: string, roomId: string): Promise<void>;
745
788
  /** Remove a specific connection from a room. */
746
789
  leaveRoom(connectionId: string, roomId: string): Promise<void>;
@@ -754,8 +797,8 @@ declare class RealtimeService {
754
797
  */
755
798
 
756
799
  /**
757
- * Periodically revalidates active SSE connections through the consumer-provided
758
- * `IConnectionAuthenticator.revalidate` contract.
800
+ * Periodically revalidates every active connection, on both transports, through the
801
+ * consumer-provided `IConnectionAuthenticator.revalidate` contract.
759
802
  *
760
803
  * A short positive cache (default 60 s) avoids hammering the auth backend on every
761
804
  * interval tick. On failure the service either disconnects immediately or first emits
@@ -791,7 +834,7 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
791
834
  */
792
835
  onApplicationShutdown(): void;
793
836
  /**
794
- * Run one revalidation cycle over all active SSE connections.
837
+ * Run one revalidation cycle over every active connection, SSE and WebSocket alike.
795
838
  *
796
839
  * A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
797
840
  * refreshes the cache. A negative result (or a thrown error) invokes the configured
@@ -1136,7 +1179,32 @@ declare class SseSubscriptionHandler {
1136
1179
  private readonly hooks?;
1137
1180
  private readonly offlineDelivery?;
1138
1181
  private readonly logger;
1182
+ private readonly authenticated;
1139
1183
  constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined);
1184
+ /**
1185
+ * Resolve the tenant this connection routes on, and refuse a blank identity.
1186
+ *
1187
+ * Both transports resolve the routing tenant through this one function, so a
1188
+ * connection carries the same tenant whichever one opened it. The check runs on
1189
+ * the resolved value rather than the raw one — validating what the server does not
1190
+ * use would validate nothing.
1191
+ *
1192
+ * A blank identity is the consumer's configuration rather than the client's
1193
+ * credentials, so it is deliberately not a 401: a 401 would tell a client its
1194
+ * credentials were rejected when they were accepted, inviting a retry that cannot
1195
+ * succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
1196
+ * once, not an unhandled crash logging a stack on every reconnect.
1197
+ *
1198
+ * The reason names the operator's fix, so it goes to the server log and the client
1199
+ * receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
1200
+ * without a message.
1201
+ *
1202
+ * @param auth - The result the consumer's authenticator returned.
1203
+ * @returns The same result with the routing tenant resolved.
1204
+ * @throws InternalServerErrorException with the generic body when a trait is present
1205
+ * but blank.
1206
+ */
1207
+ private resolveAndValidateIdentity;
1140
1208
  /**
1141
1209
  * Handle an incoming SSE connection request end-to-end.
1142
1210
  *
@@ -1148,9 +1216,26 @@ declare class SseSubscriptionHandler {
1148
1216
  * @param req - The incoming request (SSE GET).
1149
1217
  * @param res - The response (passthrough for header mutations and heartbeat writes).
1150
1218
  * @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
1151
- * @throws UnauthorizedException when authentication returns null.
1219
+ * @throws UnauthorizedException when authentication returns null — the client's
1220
+ * credentials were rejected, which is a 401.
1221
+ * @throws InternalServerErrorException when the authenticator, or the configured
1222
+ * `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
1223
+ * a 401: the credentials were accepted and the fault is the consumer's
1224
+ * configuration, so it surfaces as a 500 rather than telling a client to retry
1225
+ * something that cannot succeed. The exception carries no message, so the client
1226
+ * gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
1227
+ * written to the server log.
1152
1228
  */
1153
1229
  handle(req: SseRequest, res: SseResponse): Promise<Observable<MessageEvent>>;
1230
+ private openStream;
1231
+ /**
1232
+ * Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
1233
+ * `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
1234
+ */
1235
+ authenticateBeforeCommit(req: SseRequest): Promise<void>;
1236
+ private toClientError;
1237
+ private serverError;
1238
+ private authenticateRequest;
1154
1239
  /**
1155
1240
  * Build the live Observable using a subscribe-before-register pattern.
1156
1241
  *
@@ -1376,6 +1461,45 @@ declare class RedisOfflineQueue implements IOfflineQueueStorage {
1376
1461
  acknowledge(userId: string, upToId: string): Promise<void>;
1377
1462
  }
1378
1463
 
1464
+ /**
1465
+ * Resolve the tenant a connection routes on, and normalize a nullish result.
1466
+ *
1467
+ * Both transports must resolve the routing tenant through this one function. Two
1468
+ * copies of the rule can disagree, and a connection routed on one tenant by SSE and
1469
+ * another by WebSocket is a delivery to the wrong audience.
1470
+ *
1471
+ * `null` normalizes to `undefined` rather than passing through. `ConnectionRegistry`
1472
+ * guards on `!== undefined`, so a `null` tenant would otherwise be indexed under
1473
+ * `null` and compose the room `tenant:null` — the same shared-bucket defect as the
1474
+ * empty string, in a value a JWT claim produces routinely.
1475
+ *
1476
+ * @param options - The module options, read for an optional `tenantResolver`.
1477
+ * @param auth - The authentication result the consumer's authenticator returned.
1478
+ * @returns The same result with `tenantId` resolved, or absent when there is none.
1479
+ */
1480
+ declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'tenantResolver'>, auth: AuthenticationResult): AuthenticationResult;
1481
+ /**
1482
+ * Reject an authentication result whose identity traits are present but blank.
1483
+ *
1484
+ * `userId` and `tenantId` index the registry and compose the `user:` and `tenant:`
1485
+ * rooms, so a blank one is not a missing value — it is a shared bucket. Every
1486
+ * connection whose authenticator returned `''` lands under the same key and joins
1487
+ * the same room, and a later emit to that key reaches all of them. On a long-lived
1488
+ * subscription that is not one wrong response but a stream that keeps delivering
1489
+ * for the life of the connection.
1490
+ *
1491
+ * An absent `tenantId` stays valid and means exactly what it says: this connection
1492
+ * belongs to no tenant, so it is indexed under none and joins no tenant room. The
1493
+ * distinction drawn is between *absent* and *empty*, and only the second is refused.
1494
+ *
1495
+ * Whitespace counts as blank. `' '` composes `user: ` and indexes under `' '`, which
1496
+ * is the same defect wearing a different character.
1497
+ *
1498
+ * @param auth - The resolved authentication result, after `resolveAuthTenant`.
1499
+ * @throws Error carrying `REALTIME_AUTH_FAILED` when a trait is present but blank.
1500
+ */
1501
+ declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
1502
+
1379
1503
  /**
1380
1504
  * @fileoverview Canonical room id prefixes for scoping emits and auto-join.
1381
1505
  * @layer shared
@@ -1408,7 +1532,13 @@ type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
1408
1532
  * Build a canonical room id following the library's prefix convention.
1409
1533
  *
1410
1534
  * Validation of the parts (e.g. non-empty ids) is the caller's responsibility —
1411
- * this helper only joins the prefix and parts with `:`.
1535
+ * this helper only joins the prefix and parts with `:` and escapes nothing, so a
1536
+ * part must not contain `:`. `('a:b', 'c')` and `('a', 'b:c')` both give
1537
+ * `resource:a:b:c`; encode parts that come from outside with `encodeURIComponent`, which escapes `:` and so
1538
+ * is sound for this `:` separator only.
1539
+ *
1540
+ * A `RESOURCE` room carries no tenant. When ids are only unique within one, pass
1541
+ * the tenant as its own encoded part rather than gluing it to the id.
1412
1542
  *
1413
1543
  * @example
1414
1544
  * ```ts
@@ -1539,4 +1669,4 @@ declare const REALTIME_ERROR_CODES: {
1539
1669
  /** Union of canonical error code values. */
1540
1670
  type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
1541
1671
 
1542
- export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, 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, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, sseWiring };
1672
+ export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, 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, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
@@ -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, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, HttpException, 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);
@@ -192,7 +217,11 @@ var ConnectionRegistry = class {
192
217
  byId = /* @__PURE__ */ new Map();
193
218
  byUserId = /* @__PURE__ */ new Map();
194
219
  byTenantId = /* @__PURE__ */ new Map();
195
- /** Register a connection and index it by user and tenant. */
220
+ /**
221
+ * Register a connection and index it by user and tenant.
222
+ *
223
+ * @internal Transport bookkeeping: applications must not call it.
224
+ */
196
225
  register(record) {
197
226
  this.byId.set(record.connectionId, record);
198
227
  this.addToSetMap(this.byUserId, record.userId, record.connectionId);
@@ -200,7 +229,11 @@ var ConnectionRegistry = class {
200
229
  this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
201
230
  }
202
231
  }
203
- /** Remove a connection from every index. Returns the removed record, if any. */
232
+ /**
233
+ * Remove a connection from every index. Returns the removed record, if any.
234
+ *
235
+ * @internal Transport bookkeeping: applications must not call it.
236
+ */
204
237
  unregister(connectionId) {
205
238
  const record = this.byId.get(connectionId);
206
239
  if (!record) return void 0;
@@ -784,6 +817,40 @@ var SseSubscriptionHandler = class {
784
817
  hooks;
785
818
  offlineDelivery;
786
819
  logger = new Logger(SseSubscriptionHandler.name);
820
+ authenticated = /* @__PURE__ */ new WeakMap();
821
+ /**
822
+ * Resolve the tenant this connection routes on, and refuse a blank identity.
823
+ *
824
+ * Both transports resolve the routing tenant through this one function, so a
825
+ * connection carries the same tenant whichever one opened it. The check runs on
826
+ * the resolved value rather than the raw one — validating what the server does not
827
+ * use would validate nothing.
828
+ *
829
+ * A blank identity is the consumer's configuration rather than the client's
830
+ * credentials, so it is deliberately not a 401: a 401 would tell a client its
831
+ * credentials were rejected when they were accepted, inviting a retry that cannot
832
+ * succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
833
+ * once, not an unhandled crash logging a stack on every reconnect.
834
+ *
835
+ * The reason names the operator's fix, so it goes to the server log and the client
836
+ * receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
837
+ * without a message.
838
+ *
839
+ * @param auth - The result the consumer's authenticator returned.
840
+ * @returns The same result with the routing tenant resolved.
841
+ * @throws InternalServerErrorException with the generic body when a trait is present
842
+ * but blank.
843
+ */
844
+ resolveAndValidateIdentity(auth) {
845
+ const resolvedAuth = resolveAuthTenant(this.options, auth);
846
+ try {
847
+ assertIdentityIsNotBlank(resolvedAuth);
848
+ } catch (err) {
849
+ this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
850
+ throw new InternalServerErrorException();
851
+ }
852
+ return resolvedAuth;
853
+ }
787
854
  /**
788
855
  * Handle an incoming SSE connection request end-to-end.
789
856
  *
@@ -795,16 +862,35 @@ var SseSubscriptionHandler = class {
795
862
  * @param req - The incoming request (SSE GET).
796
863
  * @param res - The response (passthrough for header mutations and heartbeat writes).
797
864
  * @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
798
- * @throws UnauthorizedException when authentication returns null.
865
+ * @throws UnauthorizedException when authentication returns null — the client's
866
+ * credentials were rejected, which is a 401.
867
+ * @throws InternalServerErrorException when the authenticator, or the configured
868
+ * `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
869
+ * a 401: the credentials were accepted and the fault is the consumer's
870
+ * configuration, so it surfaces as a 500 rather than telling a client to retry
871
+ * something that cannot succeed. The exception carries no message, so the client
872
+ * gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
873
+ * written to the server log.
799
874
  */
800
875
  async handle(req, res) {
801
876
  res.setHeader("Cache-Control", "no-cache, no-transform");
802
877
  res.setHeader("X-Accel-Buffering", "no");
803
- const context = buildAuthContext(req);
804
- const auth = await this.transport.authenticate(context);
805
- if (!auth) throw new UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
806
- const resolvedTenantId = this.options.tenantResolver?.(auth) ?? auth.tenantId;
807
- const resolvedAuth = resolvedTenantId !== void 0 ? { ...auth, tenantId: resolvedTenantId } : auth;
878
+ const done = this.authenticated.get(req);
879
+ this.authenticated.delete(req);
880
+ let authenticated;
881
+ try {
882
+ authenticated = done ?? await this.authenticateRequest(req);
883
+ } catch (err) {
884
+ throw this.toClientError(err, "SSE authentication failed");
885
+ }
886
+ try {
887
+ return await this.openStream(req, res, authenticated);
888
+ } catch (err) {
889
+ throw this.serverError(err, "SSE handshake failed");
890
+ }
891
+ }
892
+ async openStream(req, res, authenticated) {
893
+ const { context, auth: resolvedAuth } = authenticated;
808
894
  const connectionId = randomUUID();
809
895
  const subject = new Subject();
810
896
  const close$ = new Subject();
@@ -827,6 +913,33 @@ var SseSubscriptionHandler = class {
827
913
  queueEvents
828
914
  });
829
915
  }
916
+ /**
917
+ * Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
918
+ * `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
919
+ */
920
+ async authenticateBeforeCommit(req) {
921
+ try {
922
+ this.authenticated.set(req, await this.authenticateRequest(req));
923
+ } catch (err) {
924
+ throw this.toClientError(err, "SSE authentication failed");
925
+ }
926
+ }
927
+ // Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
928
+ toClientError(err, what) {
929
+ return err instanceof HttpException ? err : this.serverError(err, what);
930
+ }
931
+ serverError(err, what) {
932
+ this.logger.error(
933
+ `${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
934
+ );
935
+ return new InternalServerErrorException();
936
+ }
937
+ async authenticateRequest(req) {
938
+ const context = buildAuthContext(req);
939
+ const auth = await this.transport.authenticate(context);
940
+ if (!auth) throw new UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
941
+ return { context, auth: this.resolveAndValidateIdentity(auth) };
942
+ }
830
943
  /**
831
944
  * Build the live Observable using a subscribe-before-register pattern.
832
945
  *
@@ -881,7 +994,7 @@ var SseSubscriptionHandler = class {
881
994
  this.fireHook(
882
995
  () => this.hooks?.onError?.({ connectionId, error: err, transport: "sse" })
883
996
  );
884
- subscriber.error(err);
997
+ subscriber.error(this.serverError(err, "SSE registration failed"));
885
998
  });
886
999
  }
887
1000
  /**
@@ -938,6 +1051,20 @@ function normalizeEndpointPath(endpoint) {
938
1051
  // src/server/factories/sse-controller.factory.ts
939
1052
  function createSseController(endpoint) {
940
1053
  const ssePath = normalizeEndpointPath(endpoint);
1054
+ let SseAuthGuard = class {
1055
+ constructor(handler) {
1056
+ this.handler = handler;
1057
+ }
1058
+ handler;
1059
+ async canActivate(context) {
1060
+ await this.handler.authenticateBeforeCommit(context.switchToHttp().getRequest());
1061
+ return true;
1062
+ }
1063
+ };
1064
+ SseAuthGuard = __decorateClass([
1065
+ Injectable(),
1066
+ __decorateParam(0, Inject(SseSubscriptionHandler))
1067
+ ], SseAuthGuard);
941
1068
  let DynamicSseController = class {
942
1069
  // Explicit @Inject: the published bundle is built by esbuild/tsup, which does
943
1070
  // not emit `design:paramtypes` decorator metadata, so constructor params must
@@ -951,6 +1078,7 @@ function createSseController(endpoint) {
951
1078
  }
952
1079
  };
953
1080
  __decorateClass([
1081
+ UseGuards(SseAuthGuard),
954
1082
  Sse(ssePath),
955
1083
  __decorateParam(0, Req()),
956
1084
  __decorateParam(1, Res({ passthrough: true }))
@@ -1027,7 +1155,13 @@ var RealtimeService = class {
1027
1155
  broadcast(event, data) {
1028
1156
  return this.transport.broadcast(event, data);
1029
1157
  }
1030
- /** Add a specific connection to a room. */
1158
+ /**
1159
+ * Add a specific connection to a room.
1160
+ *
1161
+ * The room id is not checked. Never pass client-supplied input that could start
1162
+ * with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
1163
+ * receives that tenant's events.
1164
+ */
1031
1165
  joinRoom(connectionId, roomId) {
1032
1166
  return this.transport.joinRoom(connectionId, roomId);
1033
1167
  }
@@ -1097,7 +1231,7 @@ var ReauthenticationService = class {
1097
1231
  this.positiveCache.clear();
1098
1232
  }
1099
1233
  /**
1100
- * Run one revalidation cycle over all active SSE connections.
1234
+ * Run one revalidation cycle over every active connection, SSE and WebSocket alike.
1101
1235
  *
1102
1236
  * A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
1103
1237
  * refreshes the cache. A negative result (or a thrown error) invokes the configured
@@ -1107,7 +1241,11 @@ var ReauthenticationService = class {
1107
1241
  */
1108
1242
  async runCycle() {
1109
1243
  const now = Date.now();
1110
- for (const conn of this.connections.allByTransport("sse")) {
1244
+ const connections = [
1245
+ ...this.connections.allByTransport("sse"),
1246
+ ...this.connections.allByTransport("websocket")
1247
+ ];
1248
+ for (const conn of connections) {
1111
1249
  try {
1112
1250
  const lastValid = this.positiveCache.get(conn.connectionId);
1113
1251
  if (lastValid !== void 0 && now - lastValid < this.policy.cacheTtlMs) continue;
@@ -1146,7 +1284,7 @@ var ReauthenticationService = class {
1146
1284
  tenantId: conn.tenantId,
1147
1285
  roles: conn.originalAuth.roles,
1148
1286
  metadata: conn.originalAuth.metadata,
1149
- transport: "sse",
1287
+ transport: conn.transport,
1150
1288
  ip: conn.ip,
1151
1289
  userAgent: conn.userAgent,
1152
1290
  connectedAt: conn.connectedAt
@@ -1663,4 +1801,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1663
1801
  }
1664
1802
  };
1665
1803
 
1666
- 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 };
1804
+ 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 };