@bymax-one/nest-realtime 1.2.10 → 1.2.12

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 CHANGED
@@ -7,6 +7,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.12] - 2026-11-12
11
+
12
+ ### Added
13
+
14
+ - **`AuthenticationResult.rooms`: rooms joined at admission.** An authenticator can return extra
15
+ rooms (a workspace, a project) that are joined before the connection is announced,
16
+ on both transports. Joining from `onConnect` leaves a window: the connection is already live, so an
17
+ event published to the room in between is missed, and room events have no replay. On SSE `onConnect`
18
+ is not awaited and a hook that throws is only logged, so a connection scoped there can stay
19
+ live without its room. A name must be a non-blank string of at most
20
+ `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH` characters and must not start with `user:`,
21
+ `tenant:` or `connection:`; at most `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates
22
+ join once. A result that breaks a rule is refused like a blank `userId`. The limits are bounds
23
+ against abuse, not measurements, and apply to this field only; `joinRoom` is unchanged. The rooms
24
+ are fixed at admission: `revalidate` receives them, and a different set returned later is not
25
+ re-synchronized. `ADMISSION_ROOM_LIMITS` is exported from the root and `./shared` entries.
26
+
27
+ #### Apply to a derived backend
28
+
29
+ `ConnectionRecord.originalAuth` gains an optional `rooms`. A custom `IConnectionAuthenticator` is
30
+ unaffected; one that wants a scoped room returns it in `rooms` instead of joining it from
31
+ `onConnect`. A subclass of `SseTransport` or `WebSocketTransport` that overrides
32
+ `registerConnection` or `registerSocket` has to join `auth.rooms` itself.
33
+
34
+ ### Fixed
35
+
36
+ - The JSDoc of `onModuleDestroy` on both transports now opens with its limit: a slow
37
+ `onModuleDestroy` in a module nearer the root than the realtime module still runs first.
38
+
39
+ ## [1.2.11] - 2026-11-09
40
+
41
+ ### Fixed
42
+
43
+ - **Refusal during shutdown begins at `onModuleDestroy`, not at `beforeApplicationShutdown`.** Nest
44
+ runs the hooks of a module nearer the root before those of a module it imports, so a host's slow
45
+ `beforeApplicationShutdown` in the root module ran before the transport's own, and a WebSocket
46
+ handshake or an SSE stream arriving in that window was accepted. Nest runs every module's
47
+ `onModuleDestroy` before any `beforeApplicationShutdown`, so both transports now mark shutdown as
48
+ begun there: from then on a handshake gets `REALTIME_TRANSPORT_UNAVAILABLE` and a stream gets a 503. A slow `onModuleDestroy` in a module nearer the root than the realtime module still runs
49
+ first, and until it returns a connection is accepted: put slow shutdown work in
50
+ `beforeApplicationShutdown`, or make the host stop accepting traffic before it calls `close()`.
51
+
52
+ #### Apply to a derived backend
53
+
54
+ `SseTransport` and `WebSocketTransport` gain a public `onModuleDestroy()` that marks shutdown as
55
+ begun. A subclass that overrides it has to call `super.onModuleDestroy()`.
56
+
10
57
  ## [1.2.10] - 2026-11-09
11
58
 
12
59
  ### Fixed
@@ -937,7 +984,9 @@ First published release.
937
984
  rather than by the manual sweep that raised the NestJS floors — that sweep
938
985
  asked about NestJS and never put the same question to the other ten peers.
939
986
 
940
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.10...HEAD
987
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.12...HEAD
988
+ [1.2.12]: https://github.com/bymaxone/nest-realtime/compare/v1.2.11...v1.2.12
989
+ [1.2.11]: https://github.com/bymaxone/nest-realtime/compare/v1.2.10...v1.2.11
941
990
  [1.2.10]: https://github.com/bymaxone/nest-realtime/compare/v1.2.9...v1.2.10
942
991
  [1.2.9]: https://github.com/bymaxone/nest-realtime/compare/v1.2.8...v1.2.9
943
992
  [1.2.8]: https://github.com/bymaxone/nest-realtime/compare/v1.2.7...v1.2.8
package/README.md CHANGED
@@ -699,6 +699,41 @@ const hooks: IConnectionLifecycleHooks = {
699
699
  Like `roles`, it is a **connect-time snapshot**: a `revalidate` that keeps the connection alive
700
700
  does not refresh it. The library never reads a key.
701
701
 
702
+ #### Joining rooms at admission
703
+
704
+ `AuthenticationResult.rooms` lists extra rooms (a workspace, a project) that the library joins
705
+ beside `user:` and `tenant:`, **before** the connection is announced:
706
+
707
+ ```typescript
708
+ class WorkspaceAuthenticator implements IConnectionAuthenticator {
709
+ constructor(private readonly sessions: SessionStore) {}
710
+
711
+ async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
712
+ const session = await this.sessions.find(ctx.cookies['sid'])
713
+ if (!session) return null
714
+ return { userId: session.userId, rooms: [`workspace:${session.workspaceId}`] }
715
+ }
716
+ }
717
+ ```
718
+
719
+ Scope a connection here, not by calling `joinRoom` from `onConnect`. `onConnect` runs after the
720
+ connection is live, so an event published to the room in between is missed, and room events have
721
+ no replay. Measured with a publish made while the `onConnect` join was still pending: both SSE and
722
+ WebSocket delivered the next event and not that one. On SSE `onConnect` is also not awaited, and a
723
+ hook that throws is only logged as a warning, so a connection scoped from there can stay live
724
+ without its room. Neither behaviour changes; `rooms` is the way around both.
725
+
726
+ A name must be a non-blank string of at most `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH`
727
+ characters and must not start with `user:`, `tenant:` or `connection:`; at most
728
+ `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once. A result that breaks a rule
729
+ is refused like a blank `userId` — a server fault (500 on SSE, a generic `connect_error` on
730
+ WebSocket), not a 401 — and nothing is registered. The two limits are bounds against abuse, not
731
+ measurements, and they apply to this field only: `joinRoom` stays free-form.
732
+
733
+ The rooms are fixed at admission and handed back to `revalidate` in the original result. A
734
+ different set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for changes
735
+ during the connection.
736
+
702
737
  #### Client address versus peer address
703
738
 
704
739
  `authenticate` receives two addresses. On SSE `ip` is the address your application's
@@ -754,7 +789,8 @@ and joining `tenant:<other>` receives that tenant's events.
754
789
  There is no `emitToRole`. Roles are the consumer's authorization vocabulary, not
755
790
  the transport's — the library carries them through without interpreting them (see
756
791
  [Auth Inversion](#auth-inversion)). To deliver to a subset of connections by role,
757
- build a room for it in `onConnect`, where `ConnectionEventMeta.roles` carries the
792
+ build a room for it in `onConnect` (a room that must hold from the first event belongs in
793
+ [`rooms`](#joining-rooms-at-admission) instead), where `ConnectionEventMeta.roles` carries the
758
794
  snapshot the authenticator produced:
759
795
 
760
796
  ```typescript
@@ -871,19 +907,19 @@ These names belong to the library. Do not reuse them for application events. The
871
907
 
872
908
  ### Error Codes
873
909
 
874
- | Code | Status |
875
- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
876
- | `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option |
877
- | `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
878
- | `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
879
- | `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
880
- | `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
881
- | `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
882
- | `REALTIME_PUBSUB_UNAVAILABLE` | Raised as the rejection of a disconnect when the bus refuses the revocation; an emit's publish failure is logged and passed to the delivery-failure hook |
883
- | `REALTIME_TRANSPORT_UNAVAILABLE` | Raised as the rejection of a disconnect, a join or a leave when the transport that holds the connection fails or has no server attached, and of an emit to an offline user that has no delivery path left. Also what a new SSE stream or WebSocket handshake is refused with once shutdown has begun: a 503 whose message is the code, and a connect_error whose data.code is the code |
884
- | `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
885
- | `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
886
- | `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
910
+ | Code | Status |
911
+ | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
912
+ | `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option |
913
+ | `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
914
+ | `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
915
+ | `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
916
+ | `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
917
+ | `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
918
+ | `REALTIME_PUBSUB_UNAVAILABLE` | Raised as the rejection of a disconnect when the bus refuses the revocation; an emit's publish failure is logged and passed to the delivery-failure hook |
919
+ | `REALTIME_TRANSPORT_UNAVAILABLE` | Raised as the rejection of a disconnect, a join or a leave when the transport that holds the connection fails or has no server attached, and of an emit to an offline user that has no delivery path left. Also what a new SSE stream or WebSocket handshake is refused with once shutdown has begun: a 503 whose message is the code, and a connect_error whose data.code is the code. Shutdown begins, for this purpose, in the onModuleDestroy phase, ahead of every beforeApplicationShutdown hook, so a slow beforeApplicationShutdown in the host does not leave a window; a slow onModuleDestroy in a module nearer the root than the realtime module still runs first, and a connection is accepted until it returns. |
920
+ | `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
921
+ | `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
922
+ | `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
887
923
 
888
924
  ### DI Tokens
889
925
 
@@ -225,6 +225,50 @@ var RESERVED_EVENT_NAMES = {
225
225
  ERROR: "error"
226
226
  };
227
227
 
228
+ // src/shared/constants/admission-rooms.constants.ts
229
+ var ADMISSION_ROOM_LIMITS = {
230
+ MAX_ROOMS: 32,
231
+ MAX_ROOM_NAME_LENGTH: 256
232
+ };
233
+
234
+ // src/shared/constants/room-prefixes.constants.ts
235
+ var ROOM_PREFIXES = {
236
+ USER: "user",
237
+ TENANT: "tenant",
238
+ RESOURCE: "resource"
239
+ };
240
+
241
+ // src/server/utils/assert-admission-rooms.ts
242
+ var RESERVED_ROOM_PREFIXES = [
243
+ `${ROOM_PREFIXES.USER}:`,
244
+ `${ROOM_PREFIXES.TENANT}:`,
245
+ "connection:"
246
+ ];
247
+ function refuse(detail) {
248
+ throw realtimeError(
249
+ REALTIME_ERROR_CODES.AUTH_FAILED,
250
+ `the authenticator returned rooms that are not valid: ${detail}. Fix the authenticator; the limits are bounds against abuse and apply to this field only.`
251
+ );
252
+ }
253
+ function assertAdmissionRooms(auth) {
254
+ const { rooms } = auth;
255
+ if (rooms === void 0) return;
256
+ if (!Array.isArray(rooms)) refuse("`rooms` is not an array");
257
+ if (rooms.length > ADMISSION_ROOM_LIMITS.MAX_ROOMS) {
258
+ refuse(`${rooms.length} rooms exceeds the limit of ${ADMISSION_ROOM_LIMITS.MAX_ROOMS}`);
259
+ }
260
+ for (const room of rooms) {
261
+ if (typeof room !== "string" || room.trim().length === 0) {
262
+ refuse("every room must be a non-blank string");
263
+ }
264
+ if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
265
+ refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
266
+ }
267
+ const reserved = RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
268
+ if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
269
+ }
270
+ }
271
+
228
272
  // src/server/utils/assert-identity.ts
229
273
  function isBlank(value) {
230
274
  return typeof value !== "string" || value.trim().length === 0;
@@ -418,13 +462,6 @@ exports.RoomRegistry = __decorateClass([
418
462
  common.Injectable()
419
463
  ], exports.RoomRegistry);
420
464
 
421
- // src/shared/constants/room-prefixes.constants.ts
422
- var ROOM_PREFIXES = {
423
- USER: "user",
424
- TENANT: "tenant",
425
- RESOURCE: "resource"
426
- };
427
-
428
465
  // src/server/utils/compose-room-id.ts
429
466
  function composeRoomId(prefix, ...parts) {
430
467
  return [ROOM_PREFIXES[prefix], ...parts].join(":");
@@ -551,6 +588,9 @@ exports.SseTransport = class SseTransport {
551
588
  options;
552
589
  instanceId;
553
590
  offlineQueue;
591
+ onModuleDestroy() {
592
+ __privateSet(this, _shuttingDown, true);
593
+ }
554
594
  async beforeApplicationShutdown() {
555
595
  __privateSet(this, _shuttingDown, true);
556
596
  this.heartbeat.stopAll();
@@ -588,6 +628,7 @@ exports.SseTransport = class SseTransport {
588
628
  userId: params.auth.userId,
589
629
  tenantId: params.auth.tenantId,
590
630
  roles: params.auth.roles,
631
+ rooms: params.auth.rooms,
591
632
  metadata: params.auth.metadata
592
633
  }
593
634
  };
@@ -596,6 +637,7 @@ exports.SseTransport = class SseTransport {
596
637
  if (params.auth.tenantId !== void 0) {
597
638
  this.rooms.join(params.connectionId, composeRoomId("TENANT", params.auth.tenantId));
598
639
  }
640
+ for (const room of params.auth.rooms ?? []) this.rooms.join(params.connectionId, room);
599
641
  await this.evictBeyondLimit(params.auth.userId);
600
642
  }
601
643
  async unregisterConnection(connectionId, reason) {
@@ -876,6 +918,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
876
918
  const resolvedAuth = resolveAuthTenant(this.options, auth);
877
919
  try {
878
920
  assertIdentityIsNotBlank(resolvedAuth);
921
+ assertAdmissionRooms(resolvedAuth);
879
922
  } catch (err) {
880
923
  this.logger.error(`SSE connection refused \u2014 responding 500: ${describeError(err)}`);
881
924
  throw new common.InternalServerErrorException();
@@ -1162,6 +1205,7 @@ exports.ReauthenticationService = class ReauthenticationService {
1162
1205
  userId: conn.originalAuth.userId,
1163
1206
  ...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
1164
1207
  ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {},
1208
+ ...conn.originalAuth.rooms !== void 0 ? { rooms: conn.originalAuth.rooms } : {},
1165
1209
  ...conn.originalAuth.metadata !== void 0 ? { metadata: conn.originalAuth.metadata } : {}
1166
1210
  };
1167
1211
  const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
@@ -1798,6 +1842,7 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1798
1842
  }
1799
1843
  };
1800
1844
 
1845
+ exports.ADMISSION_ROOM_LIMITS = ADMISSION_ROOM_LIMITS;
1801
1846
  exports.REALTIME_AUTHENTICATOR_TOKEN = REALTIME_AUTHENTICATOR_TOKEN;
1802
1847
  exports.REALTIME_ERROR_CODES = REALTIME_ERROR_CODES;
1803
1848
  exports.REALTIME_HOOKS_TOKEN = REALTIME_HOOKS_TOKEN;
@@ -1811,6 +1856,7 @@ exports.RESERVED_EVENT_NAMES = RESERVED_EVENT_NAMES;
1811
1856
  exports.ROOM_PREFIXES = ROOM_PREFIXES;
1812
1857
  exports.RedisOfflineQueue = RedisOfflineQueue;
1813
1858
  exports.RedisRealtimePubSub = RedisRealtimePubSub;
1859
+ exports.assertAdmissionRooms = assertAdmissionRooms;
1814
1860
  exports.assertIdentityIsNotBlank = assertIdentityIsNotBlank;
1815
1861
  exports.composeForRoot = composeForRoot;
1816
1862
  exports.composeForRootAsync = composeForRootAsync;
@@ -99,6 +99,28 @@ interface AuthenticationResult {
99
99
  */
100
100
  readonly tenantId?: string;
101
101
  readonly roles?: readonly string[];
102
+ /**
103
+ * Extra rooms to join this connection to at admission, beside `user:` and `tenant:`.
104
+ *
105
+ * They are joined before the connection is announced or `onConnect` runs, so no event
106
+ * published to one of them can fall between admission and a later `joinRoom` — the
107
+ * window a join from `onConnect` leaves open. On SSE `onConnect` is not awaited
108
+ * and a hook that throws is only logged, so a connection scoped from there can go
109
+ * live, and stay, without its room; scope in `rooms`, not in `onConnect`.
110
+ *
111
+ * Each name must be a non-blank string of at most `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH`
112
+ * characters, must not start with `user:`, `tenant:` or `connection:` (the library
113
+ * composes those from the identity it resolved, or reserves them), and the list may
114
+ * hold at most `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once.
115
+ * A result that breaks a rule is a contract violation, refused like a blank `userId`:
116
+ * a server fault, not a 401. The limits are bounds against abuse, not measurements.
117
+ * They apply to this field only; `joinRoom` stays free-form.
118
+ *
119
+ * The rooms are fixed at admission. `revalidate` is handed them back, but a different
120
+ * set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for
121
+ * changes during the connection.
122
+ */
123
+ readonly rooms?: readonly string[];
102
124
  /**
103
125
  * Free-form extras for downstream code (e.g. feature flags, plan tier, a
104
126
  * correlation id read off the handshake headers).
@@ -709,6 +731,8 @@ interface ConnectionRecord {
709
731
  userId: string;
710
732
  tenantId: string | undefined;
711
733
  roles: readonly string[] | undefined;
734
+ /** The rooms the authenticator joined at admission, as returned. */
735
+ rooms?: readonly string[] | undefined;
712
736
  /** The authenticator's free-form bag, carried through verbatim and never read. */
713
737
  metadata: Record<string, unknown> | undefined;
714
738
  };
@@ -1215,6 +1239,13 @@ declare class SseTransport implements ITransport {
1215
1239
  readonly kind: "sse";
1216
1240
  private readonly logger;
1217
1241
  constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, auth: IConnectionAuthenticator, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined);
1242
+ /**
1243
+ * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
1244
+ * nearer the root than the realtime module still runs first, and until it returns a stream is
1245
+ * accepted; nothing the library owns runs earlier. A slow `beforeApplicationShutdown` in such a
1246
+ * module runs before this transport's own, which is why the flag is set here.
1247
+ */
1248
+ onModuleDestroy(): void;
1218
1249
  /**
1219
1250
  * Tear down every SSE connection and stop heartbeat before the HTTP server closes.
1220
1251
  *
@@ -1732,6 +1763,19 @@ declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'te
1732
1763
  */
1733
1764
  declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
1734
1765
 
1766
+ /**
1767
+ * Refuse an authentication result whose `rooms` break the admission rules.
1768
+ *
1769
+ * Like a blank identity, a bad room is a contract violation by the authenticator, so it
1770
+ * is refused at admission rather than trimmed or skipped: a connection quietly missing a
1771
+ * room it was meant to join would be live and unscoped. Every check is on the runtime
1772
+ * value, because the declared type is a promise, not a fact.
1773
+ *
1774
+ * @param auth - The resolved authentication result.
1775
+ * @throws Error carrying `REALTIME_AUTH_FAILED` when `rooms` is present and invalid.
1776
+ */
1777
+ declare function assertAdmissionRooms(auth: AuthenticationResult): void;
1778
+
1735
1779
  /**
1736
1780
  * @fileoverview Canonical room id prefixes for scoping emits and auto-join.
1737
1781
  * @layer shared
@@ -1918,6 +1962,27 @@ interface PublicConnectionMeta {
1918
1962
  readonly connectedAt: Date;
1919
1963
  }
1920
1964
 
1965
+ /**
1966
+ * @fileoverview Bounds on the rooms an authenticator may join a connection to at admission.
1967
+ * @layer shared
1968
+ */
1969
+ /**
1970
+ * Bounds applied to `AuthenticationResult.rooms`.
1971
+ *
1972
+ * Both values are bounds against abuse, not measurements: they keep a buggy or
1973
+ * hostile authenticator from joining a connection to an unbounded set of rooms or to
1974
+ * a room whose name is a payload. Neither was derived from a benchmark or from a
1975
+ * limit of Socket.IO or of the registries, and neither is a recommendation — a host
1976
+ * that needs few rooms should use far fewer. They apply only to the `rooms` field;
1977
+ * `joinRoom` accepts any room name.
1978
+ */
1979
+ declare const ADMISSION_ROOM_LIMITS: {
1980
+ /** The most rooms one authentication result may carry. */
1981
+ readonly MAX_ROOMS: 32;
1982
+ /** The longest room name, in UTF-16 code units (`String.prototype.length`). */
1983
+ readonly MAX_ROOM_NAME_LENGTH: 256;
1984
+ };
1985
+
1921
1986
  /**
1922
1987
  * @fileoverview Event names reserved by the library (the §13 catalog).
1923
1988
  * @layer shared
@@ -1943,5 +2008,5 @@ declare const RESERVED_EVENT_NAMES: {
1943
2008
  /** Union of reserved event name values. */
1944
2009
  type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
1945
2010
 
1946
- 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, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
2011
+ export { ADMISSION_ROOM_LIMITS, 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, assertAdmissionRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
1947
2012
  export type { AuthenticationResult, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
@@ -99,6 +99,28 @@ interface AuthenticationResult {
99
99
  */
100
100
  readonly tenantId?: string;
101
101
  readonly roles?: readonly string[];
102
+ /**
103
+ * Extra rooms to join this connection to at admission, beside `user:` and `tenant:`.
104
+ *
105
+ * They are joined before the connection is announced or `onConnect` runs, so no event
106
+ * published to one of them can fall between admission and a later `joinRoom` — the
107
+ * window a join from `onConnect` leaves open. On SSE `onConnect` is not awaited
108
+ * and a hook that throws is only logged, so a connection scoped from there can go
109
+ * live, and stay, without its room; scope in `rooms`, not in `onConnect`.
110
+ *
111
+ * Each name must be a non-blank string of at most `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH`
112
+ * characters, must not start with `user:`, `tenant:` or `connection:` (the library
113
+ * composes those from the identity it resolved, or reserves them), and the list may
114
+ * hold at most `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once.
115
+ * A result that breaks a rule is a contract violation, refused like a blank `userId`:
116
+ * a server fault, not a 401. The limits are bounds against abuse, not measurements.
117
+ * They apply to this field only; `joinRoom` stays free-form.
118
+ *
119
+ * The rooms are fixed at admission. `revalidate` is handed them back, but a different
120
+ * set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for
121
+ * changes during the connection.
122
+ */
123
+ readonly rooms?: readonly string[];
102
124
  /**
103
125
  * Free-form extras for downstream code (e.g. feature flags, plan tier, a
104
126
  * correlation id read off the handshake headers).
@@ -709,6 +731,8 @@ interface ConnectionRecord {
709
731
  userId: string;
710
732
  tenantId: string | undefined;
711
733
  roles: readonly string[] | undefined;
734
+ /** The rooms the authenticator joined at admission, as returned. */
735
+ rooms?: readonly string[] | undefined;
712
736
  /** The authenticator's free-form bag, carried through verbatim and never read. */
713
737
  metadata: Record<string, unknown> | undefined;
714
738
  };
@@ -1215,6 +1239,13 @@ declare class SseTransport implements ITransport {
1215
1239
  readonly kind: "sse";
1216
1240
  private readonly logger;
1217
1241
  constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, auth: IConnectionAuthenticator, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined);
1242
+ /**
1243
+ * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
1244
+ * nearer the root than the realtime module still runs first, and until it returns a stream is
1245
+ * accepted; nothing the library owns runs earlier. A slow `beforeApplicationShutdown` in such a
1246
+ * module runs before this transport's own, which is why the flag is set here.
1247
+ */
1248
+ onModuleDestroy(): void;
1218
1249
  /**
1219
1250
  * Tear down every SSE connection and stop heartbeat before the HTTP server closes.
1220
1251
  *
@@ -1732,6 +1763,19 @@ declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'te
1732
1763
  */
1733
1764
  declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
1734
1765
 
1766
+ /**
1767
+ * Refuse an authentication result whose `rooms` break the admission rules.
1768
+ *
1769
+ * Like a blank identity, a bad room is a contract violation by the authenticator, so it
1770
+ * is refused at admission rather than trimmed or skipped: a connection quietly missing a
1771
+ * room it was meant to join would be live and unscoped. Every check is on the runtime
1772
+ * value, because the declared type is a promise, not a fact.
1773
+ *
1774
+ * @param auth - The resolved authentication result.
1775
+ * @throws Error carrying `REALTIME_AUTH_FAILED` when `rooms` is present and invalid.
1776
+ */
1777
+ declare function assertAdmissionRooms(auth: AuthenticationResult): void;
1778
+
1735
1779
  /**
1736
1780
  * @fileoverview Canonical room id prefixes for scoping emits and auto-join.
1737
1781
  * @layer shared
@@ -1918,6 +1962,27 @@ interface PublicConnectionMeta {
1918
1962
  readonly connectedAt: Date;
1919
1963
  }
1920
1964
 
1965
+ /**
1966
+ * @fileoverview Bounds on the rooms an authenticator may join a connection to at admission.
1967
+ * @layer shared
1968
+ */
1969
+ /**
1970
+ * Bounds applied to `AuthenticationResult.rooms`.
1971
+ *
1972
+ * Both values are bounds against abuse, not measurements: they keep a buggy or
1973
+ * hostile authenticator from joining a connection to an unbounded set of rooms or to
1974
+ * a room whose name is a payload. Neither was derived from a benchmark or from a
1975
+ * limit of Socket.IO or of the registries, and neither is a recommendation — a host
1976
+ * that needs few rooms should use far fewer. They apply only to the `rooms` field;
1977
+ * `joinRoom` accepts any room name.
1978
+ */
1979
+ declare const ADMISSION_ROOM_LIMITS: {
1980
+ /** The most rooms one authentication result may carry. */
1981
+ readonly MAX_ROOMS: 32;
1982
+ /** The longest room name, in UTF-16 code units (`String.prototype.length`). */
1983
+ readonly MAX_ROOM_NAME_LENGTH: 256;
1984
+ };
1985
+
1921
1986
  /**
1922
1987
  * @fileoverview Event names reserved by the library (the §13 catalog).
1923
1988
  * @layer shared
@@ -1943,5 +2008,5 @@ declare const RESERVED_EVENT_NAMES: {
1943
2008
  /** Union of reserved event name values. */
1944
2009
  type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
1945
2010
 
1946
- 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, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
2011
+ export { ADMISSION_ROOM_LIMITS, 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, assertAdmissionRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
1947
2012
  export type { AuthenticationResult, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
@@ -223,6 +223,50 @@ var RESERVED_EVENT_NAMES = {
223
223
  ERROR: "error"
224
224
  };
225
225
 
226
+ // src/shared/constants/admission-rooms.constants.ts
227
+ var ADMISSION_ROOM_LIMITS = {
228
+ MAX_ROOMS: 32,
229
+ MAX_ROOM_NAME_LENGTH: 256
230
+ };
231
+
232
+ // src/shared/constants/room-prefixes.constants.ts
233
+ var ROOM_PREFIXES = {
234
+ USER: "user",
235
+ TENANT: "tenant",
236
+ RESOURCE: "resource"
237
+ };
238
+
239
+ // src/server/utils/assert-admission-rooms.ts
240
+ var RESERVED_ROOM_PREFIXES = [
241
+ `${ROOM_PREFIXES.USER}:`,
242
+ `${ROOM_PREFIXES.TENANT}:`,
243
+ "connection:"
244
+ ];
245
+ function refuse(detail) {
246
+ throw realtimeError(
247
+ REALTIME_ERROR_CODES.AUTH_FAILED,
248
+ `the authenticator returned rooms that are not valid: ${detail}. Fix the authenticator; the limits are bounds against abuse and apply to this field only.`
249
+ );
250
+ }
251
+ function assertAdmissionRooms(auth) {
252
+ const { rooms } = auth;
253
+ if (rooms === void 0) return;
254
+ if (!Array.isArray(rooms)) refuse("`rooms` is not an array");
255
+ if (rooms.length > ADMISSION_ROOM_LIMITS.MAX_ROOMS) {
256
+ refuse(`${rooms.length} rooms exceeds the limit of ${ADMISSION_ROOM_LIMITS.MAX_ROOMS}`);
257
+ }
258
+ for (const room of rooms) {
259
+ if (typeof room !== "string" || room.trim().length === 0) {
260
+ refuse("every room must be a non-blank string");
261
+ }
262
+ if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
263
+ refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
264
+ }
265
+ const reserved = RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
266
+ if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
267
+ }
268
+ }
269
+
226
270
  // src/server/utils/assert-identity.ts
227
271
  function isBlank(value) {
228
272
  return typeof value !== "string" || value.trim().length === 0;
@@ -416,13 +460,6 @@ RoomRegistry = __decorateClass([
416
460
  Injectable()
417
461
  ], RoomRegistry);
418
462
 
419
- // src/shared/constants/room-prefixes.constants.ts
420
- var ROOM_PREFIXES = {
421
- USER: "user",
422
- TENANT: "tenant",
423
- RESOURCE: "resource"
424
- };
425
-
426
463
  // src/server/utils/compose-room-id.ts
427
464
  function composeRoomId(prefix, ...parts) {
428
465
  return [ROOM_PREFIXES[prefix], ...parts].join(":");
@@ -549,6 +586,9 @@ var SseTransport = class {
549
586
  options;
550
587
  instanceId;
551
588
  offlineQueue;
589
+ onModuleDestroy() {
590
+ __privateSet(this, _shuttingDown, true);
591
+ }
552
592
  async beforeApplicationShutdown() {
553
593
  __privateSet(this, _shuttingDown, true);
554
594
  this.heartbeat.stopAll();
@@ -586,6 +626,7 @@ var SseTransport = class {
586
626
  userId: params.auth.userId,
587
627
  tenantId: params.auth.tenantId,
588
628
  roles: params.auth.roles,
629
+ rooms: params.auth.rooms,
589
630
  metadata: params.auth.metadata
590
631
  }
591
632
  };
@@ -594,6 +635,7 @@ var SseTransport = class {
594
635
  if (params.auth.tenantId !== void 0) {
595
636
  this.rooms.join(params.connectionId, composeRoomId("TENANT", params.auth.tenantId));
596
637
  }
638
+ for (const room of params.auth.rooms ?? []) this.rooms.join(params.connectionId, room);
597
639
  await this.evictBeyondLimit(params.auth.userId);
598
640
  }
599
641
  async unregisterConnection(connectionId, reason) {
@@ -874,6 +916,7 @@ var SseSubscriptionHandler = class {
874
916
  const resolvedAuth = resolveAuthTenant(this.options, auth);
875
917
  try {
876
918
  assertIdentityIsNotBlank(resolvedAuth);
919
+ assertAdmissionRooms(resolvedAuth);
877
920
  } catch (err) {
878
921
  this.logger.error(`SSE connection refused \u2014 responding 500: ${describeError(err)}`);
879
922
  throw new InternalServerErrorException();
@@ -1160,6 +1203,7 @@ var ReauthenticationService = class {
1160
1203
  userId: conn.originalAuth.userId,
1161
1204
  ...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
1162
1205
  ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {},
1206
+ ...conn.originalAuth.rooms !== void 0 ? { rooms: conn.originalAuth.rooms } : {},
1163
1207
  ...conn.originalAuth.metadata !== void 0 ? { metadata: conn.originalAuth.metadata } : {}
1164
1208
  };
1165
1209
  const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
@@ -1796,4 +1840,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1796
1840
  }
1797
1841
  };
1798
1842
 
1799
- 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, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
1843
+ export { ADMISSION_ROOM_LIMITS, 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, assertAdmissionRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
@@ -4,6 +4,10 @@ var internal = require('@bymax-one/nest-realtime/internal');
4
4
 
5
5
 
6
6
 
7
+ Object.defineProperty(exports, "ADMISSION_ROOM_LIMITS", {
8
+ enumerable: true,
9
+ get: function () { return internal.ADMISSION_ROOM_LIMITS; }
10
+ });
7
11
  Object.defineProperty(exports, "BymaxRealtimeModule", {
8
12
  enumerable: true,
9
13
  get: function () { return internal.BymaxRealtimeModule; }
@@ -1 +1 @@
1
- export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
1
+ export { ADMISSION_ROOM_LIMITS, AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
@@ -1 +1 @@
1
- export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
1
+ export { ADMISSION_ROOM_LIMITS, AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
@@ -1 +1 @@
1
- export { BymaxRealtimeModule, ConnectionRegistry, InMemoryPubSub, 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, RealtimeService, RedisOfflineQueue, RedisRealtimePubSub, composeRoomId } from '@bymax-one/nest-realtime/internal';
1
+ export { ADMISSION_ROOM_LIMITS, BymaxRealtimeModule, ConnectionRegistry, InMemoryPubSub, 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, RealtimeService, RedisOfflineQueue, RedisRealtimePubSub, composeRoomId } from '@bymax-one/nest-realtime/internal';
@@ -7,6 +7,12 @@ var ROOM_PREFIXES = {
7
7
  RESOURCE: "resource"
8
8
  };
9
9
 
10
+ // src/shared/constants/admission-rooms.constants.ts
11
+ var ADMISSION_ROOM_LIMITS = {
12
+ MAX_ROOMS: 32,
13
+ MAX_ROOM_NAME_LENGTH: 256
14
+ };
15
+
10
16
  // src/shared/constants/reserved-events.constants.ts
11
17
  var RESERVED_EVENT_NAMES = {
12
18
  CONNECTION_ESTABLISHED: "connection:established",
@@ -36,6 +42,7 @@ var REALTIME_ERROR_CODES = {
36
42
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
37
43
  };
38
44
 
45
+ exports.ADMISSION_ROOM_LIMITS = ADMISSION_ROOM_LIMITS;
39
46
  exports.PRESENCE_EVENT_NAMES = PRESENCE_EVENT_NAMES;
40
47
  exports.REALTIME_ERROR_CODES = REALTIME_ERROR_CODES;
41
48
  exports.RESERVED_EVENT_NAMES = RESERVED_EVENT_NAMES;
@@ -93,6 +93,27 @@ declare const ROOM_PREFIXES: {
93
93
  /** Union of canonical room prefix values (`'user' | 'tenant' | 'resource'`). */
94
94
  type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
95
95
 
96
+ /**
97
+ * @fileoverview Bounds on the rooms an authenticator may join a connection to at admission.
98
+ * @layer shared
99
+ */
100
+ /**
101
+ * Bounds applied to `AuthenticationResult.rooms`.
102
+ *
103
+ * Both values are bounds against abuse, not measurements: they keep a buggy or
104
+ * hostile authenticator from joining a connection to an unbounded set of rooms or to
105
+ * a room whose name is a payload. Neither was derived from a benchmark or from a
106
+ * limit of Socket.IO or of the registries, and neither is a recommendation — a host
107
+ * that needs few rooms should use far fewer. They apply only to the `rooms` field;
108
+ * `joinRoom` accepts any room name.
109
+ */
110
+ declare const ADMISSION_ROOM_LIMITS: {
111
+ /** The most rooms one authentication result may carry. */
112
+ readonly MAX_ROOMS: 32;
113
+ /** The longest room name, in UTF-16 code units (`String.prototype.length`). */
114
+ readonly MAX_ROOM_NAME_LENGTH: 256;
115
+ };
116
+
96
117
  /**
97
118
  * @fileoverview Event names reserved by the library (the §13 catalog).
98
119
  * @layer shared
@@ -161,5 +182,5 @@ declare const REALTIME_ERROR_CODES: {
161
182
  /** Union of canonical error code values. */
162
183
  type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
163
184
 
164
- export { PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
185
+ export { ADMISSION_ROOM_LIMITS, PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
165
186
  export type { PresenceEventName, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, ReservedEventName, RoomPrefix, TransportMode };
@@ -93,6 +93,27 @@ declare const ROOM_PREFIXES: {
93
93
  /** Union of canonical room prefix values (`'user' | 'tenant' | 'resource'`). */
94
94
  type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
95
95
 
96
+ /**
97
+ * @fileoverview Bounds on the rooms an authenticator may join a connection to at admission.
98
+ * @layer shared
99
+ */
100
+ /**
101
+ * Bounds applied to `AuthenticationResult.rooms`.
102
+ *
103
+ * Both values are bounds against abuse, not measurements: they keep a buggy or
104
+ * hostile authenticator from joining a connection to an unbounded set of rooms or to
105
+ * a room whose name is a payload. Neither was derived from a benchmark or from a
106
+ * limit of Socket.IO or of the registries, and neither is a recommendation — a host
107
+ * that needs few rooms should use far fewer. They apply only to the `rooms` field;
108
+ * `joinRoom` accepts any room name.
109
+ */
110
+ declare const ADMISSION_ROOM_LIMITS: {
111
+ /** The most rooms one authentication result may carry. */
112
+ readonly MAX_ROOMS: 32;
113
+ /** The longest room name, in UTF-16 code units (`String.prototype.length`). */
114
+ readonly MAX_ROOM_NAME_LENGTH: 256;
115
+ };
116
+
96
117
  /**
97
118
  * @fileoverview Event names reserved by the library (the §13 catalog).
98
119
  * @layer shared
@@ -161,5 +182,5 @@ declare const REALTIME_ERROR_CODES: {
161
182
  /** Union of canonical error code values. */
162
183
  type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
163
184
 
164
- export { PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
185
+ export { ADMISSION_ROOM_LIMITS, PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
165
186
  export type { PresenceEventName, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, ReservedEventName, RoomPrefix, TransportMode };
@@ -5,6 +5,12 @@ var ROOM_PREFIXES = {
5
5
  RESOURCE: "resource"
6
6
  };
7
7
 
8
+ // src/shared/constants/admission-rooms.constants.ts
9
+ var ADMISSION_ROOM_LIMITS = {
10
+ MAX_ROOMS: 32,
11
+ MAX_ROOM_NAME_LENGTH: 256
12
+ };
13
+
8
14
  // src/shared/constants/reserved-events.constants.ts
9
15
  var RESERVED_EVENT_NAMES = {
10
16
  CONNECTION_ESTABLISHED: "connection:established",
@@ -34,4 +40,4 @@ var REALTIME_ERROR_CODES = {
34
40
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
35
41
  };
36
42
 
37
- export { PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
43
+ export { ADMISSION_ROOM_LIMITS, PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
@@ -51,6 +51,9 @@ exports.WebSocketTransport = class WebSocketTransport {
51
51
  auth;
52
52
  hooks;
53
53
  options;
54
+ onModuleDestroy() {
55
+ __privateSet(this, _shuttingDown, true);
56
+ }
54
57
  async beforeApplicationShutdown() {
55
58
  __privateSet(this, _shuttingDown, true);
56
59
  }
@@ -95,14 +98,17 @@ exports.WebSocketTransport = class WebSocketTransport {
95
98
  userId: auth.userId,
96
99
  tenantId: auth.tenantId,
97
100
  roles: auth.roles,
101
+ rooms: auth.rooms,
98
102
  metadata: auth.metadata
99
103
  }
100
104
  });
101
105
  await socket.join(`${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
102
106
  if (auth.tenantId) await socket.join(`${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
103
107
  await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
108
+ for (const room of auth.rooms ?? []) await socket.join(room);
104
109
  this.rooms.join(socket.id, `${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
105
110
  if (auth.tenantId) this.rooms.join(socket.id, `${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
111
+ for (const room of auth.rooms ?? []) this.rooms.join(socket.id, room);
106
112
  await this.evictBeyondLimit(auth.userId);
107
113
  await this.hooks.onConnect?.({
108
114
  connectionId: socket.id,
@@ -386,6 +392,7 @@ exports.RealtimeGateway = class RealtimeGateway {
386
392
  }
387
393
  const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
388
394
  internal.assertIdentityIsNotBlank(resolvedAuth);
395
+ internal.assertAdmissionRooms(resolvedAuth);
389
396
  this.authenticated.set(socket, resolvedAuth);
390
397
  next();
391
398
  } catch (err) {
@@ -445,6 +452,7 @@ exports.RealtimeGateway = class RealtimeGateway {
445
452
  }
446
453
  resolvedAuth = internal.resolveAuthTenant(this.options, auth);
447
454
  internal.assertIdentityIsNotBlank(resolvedAuth);
455
+ internal.assertAdmissionRooms(resolvedAuth);
448
456
  }
449
457
  await this.transport.registerSocket(socket, resolvedAuth);
450
458
  if (this.options.websocket?.emitConnectionEvent !== false) {
@@ -85,7 +85,17 @@ declare class WebSocketTransport implements ITransport {
85
85
  private warnedUnattached;
86
86
  constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
87
87
  /**
88
- * Mark shutdown as begun, so the gateway refuses a handshake from here on.
88
+ * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
89
+ * nearer the root than the realtime module still runs first, and until it returns a handshake is
90
+ * accepted; nothing the library owns runs earlier.
91
+ *
92
+ * Nest runs every module's `onModuleDestroy` before any `beforeApplicationShutdown`, and within a
93
+ * phase it runs a module nearer the root before one it imports, so a slow `beforeApplicationShutdown`
94
+ * in the host's root module runs before this transport's own, which is why the flag is set here.
95
+ */
96
+ onModuleDestroy(): void;
97
+ /**
98
+ * Mark shutdown as begun, for a caller that runs only this hook; `onModuleDestroy` already did.
89
99
  *
90
100
  * Socket.IO closes every connection that is open when the server closes, so no connection is
91
101
  * torn down here; a socket accepted after this point would only be closed a moment later, and
@@ -85,7 +85,17 @@ declare class WebSocketTransport implements ITransport {
85
85
  private warnedUnattached;
86
86
  constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
87
87
  /**
88
- * Mark shutdown as begun, so the gateway refuses a handshake from here on.
88
+ * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
89
+ * nearer the root than the realtime module still runs first, and until it returns a handshake is
90
+ * accepted; nothing the library owns runs earlier.
91
+ *
92
+ * Nest runs every module's `onModuleDestroy` before any `beforeApplicationShutdown`, and within a
93
+ * phase it runs a module nearer the root before one it imports, so a slow `beforeApplicationShutdown`
94
+ * in the host's root module runs before this transport's own, which is why the flag is set here.
95
+ */
96
+ onModuleDestroy(): void;
97
+ /**
98
+ * Mark shutdown as begun, for a caller that runs only this hook; `onModuleDestroy` already did.
89
99
  *
90
100
  * Socket.IO closes every connection that is open when the server closes, so no connection is
91
101
  * torn down here; a socket accepted after this point would only be closed a moment later, and
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
3
- import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, describeError, parseCookieHeader, RESERVED_EVENT_NAMES, realtimeError } from '@bymax-one/nest-realtime/internal';
3
+ import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, assertAdmissionRooms, describeError, parseCookieHeader, RESERVED_EVENT_NAMES, realtimeError } from '@bymax-one/nest-realtime/internal';
4
4
  import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
5
5
  import { IoAdapter } from '@nestjs/platform-socket.io';
6
6
 
@@ -51,6 +51,9 @@ var WebSocketTransport = class {
51
51
  auth;
52
52
  hooks;
53
53
  options;
54
+ onModuleDestroy() {
55
+ __privateSet(this, _shuttingDown, true);
56
+ }
54
57
  async beforeApplicationShutdown() {
55
58
  __privateSet(this, _shuttingDown, true);
56
59
  }
@@ -95,14 +98,17 @@ var WebSocketTransport = class {
95
98
  userId: auth.userId,
96
99
  tenantId: auth.tenantId,
97
100
  roles: auth.roles,
101
+ rooms: auth.rooms,
98
102
  metadata: auth.metadata
99
103
  }
100
104
  });
101
105
  await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
102
106
  if (auth.tenantId) await socket.join(`${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
103
107
  await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
108
+ for (const room of auth.rooms ?? []) await socket.join(room);
104
109
  this.rooms.join(socket.id, `${ROOM_PREFIXES.USER}:${auth.userId}`);
105
110
  if (auth.tenantId) this.rooms.join(socket.id, `${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
111
+ for (const room of auth.rooms ?? []) this.rooms.join(socket.id, room);
106
112
  await this.evictBeyondLimit(auth.userId);
107
113
  await this.hooks.onConnect?.({
108
114
  connectionId: socket.id,
@@ -386,6 +392,7 @@ var RealtimeGateway = class {
386
392
  }
387
393
  const resolvedAuth = resolveAuthTenant(this.options, auth);
388
394
  assertIdentityIsNotBlank(resolvedAuth);
395
+ assertAdmissionRooms(resolvedAuth);
389
396
  this.authenticated.set(socket, resolvedAuth);
390
397
  next();
391
398
  } catch (err) {
@@ -445,6 +452,7 @@ var RealtimeGateway = class {
445
452
  }
446
453
  resolvedAuth = resolveAuthTenant(this.options, auth);
447
454
  assertIdentityIsNotBlank(resolvedAuth);
455
+ assertAdmissionRooms(resolvedAuth);
448
456
  }
449
457
  await this.transport.registerSocket(socket, resolvedAuth);
450
458
  if (this.options.websocket?.emitConnectionEvent !== false) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.10",
3
+ "version": "1.2.12",
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",