@bymax-one/nest-realtime 1.2.16 → 1.2.17

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.
@@ -105,8 +105,9 @@ interface AuthenticationResult {
105
105
  * They are joined before the connection is announced or `onConnect` runs, so no event
106
106
  * published to one of them can fall between admission and a later `joinRoom` — the
107
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`.
108
+ * and a hook that throws is only logged (unless `onConnectFailure` is `'close'`), so a
109
+ * connection scoped from there can go live, and stay, without its room; scope in `rooms`,
110
+ * not in `onConnect`.
110
111
  *
111
112
  * Each name must be a non-blank string of at most `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH`
112
113
  * characters, must not start with `user:`, `tenant:` or `connection:` (the library
@@ -114,7 +115,7 @@ interface AuthenticationResult {
114
115
  * hold at most `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once.
115
116
  * A result that breaks a rule is a contract violation, refused like a blank `userId`:
116
117
  * 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
+ * They apply to this field only; `joinRoom` has no limit on count or length and refuses only the reserved prefixes.
118
119
  *
119
120
  * The rooms are fixed at admission. `revalidate` is handed them back, but a different
120
121
  * set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for
@@ -488,6 +489,16 @@ interface BymaxRealtimeModuleOptions {
488
489
  tenantResolver?: (auth: AuthenticationResult) => string | undefined | null;
489
490
  hooks?: IConnectionLifecycleHooks;
490
491
  hookTimeoutMs?: number;
492
+ /**
493
+ * What a failing `onConnect` does to the connection it was called for.
494
+ *
495
+ * `'ignore'` (the default): the failure is logged and the connection stays.
496
+ * `'close'`: the failure is logged and the connection is closed, on both transports. On
497
+ * WebSocket the connection is refused before it is announced; on SSE the hook is not awaited,
498
+ * so events published in the meantime may already have been delivered. Scope a connection in
499
+ * `AuthenticationResult.rooms`, not in the hook, when none may be missed.
500
+ */
501
+ onConnectFailure?: 'ignore' | 'close';
491
502
  authenticateTimeoutMs?: number;
492
503
  maxPendingHandshakes?: number;
493
504
  /**
@@ -939,6 +950,9 @@ declare class RealtimeService {
939
950
  /**
940
951
  * Send to a logical room. Use the prefix convention (`user:{id}`,
941
952
  * `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
953
+ *
954
+ * @throws {Error} `REALTIME_AUTH_FAILED` when `roomId` is not a non-empty string: socket.io
955
+ * reads an array as several rooms.
942
956
  */
943
957
  emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
944
958
  /** Send to every connected client. Use sparingly. */
@@ -946,16 +960,19 @@ declare class RealtimeService {
946
960
  /**
947
961
  * Add a specific connection to a room.
948
962
  *
949
- * The room id is not checked. Never pass client-supplied input that could start
950
- * with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
951
- * receives that tenant's events.
963
+ * Rooms of the application's own are free-form, but a name that starts with `user:`,
964
+ * `tenant:` or `connection:` is refused, the rule that `AuthenticationResult.rooms` is
965
+ * held to: joining `tenant:<other>` would receive that tenant's events. A `roomId` that is
966
+ * not a non-empty string is refused too, whatever it holds: socket.io reads an array as
967
+ * several room names.
952
968
  *
953
969
  * Acts on a connection this instance holds; for any other id it resolves and changes
954
970
  * nothing. A failure of the transport that holds the connection rejects the call.
955
971
  */
956
972
  joinRoom(connectionId: string, roomId: string): Promise<void>;
957
973
  /**
958
- * Remove a specific connection from a room.
974
+ * Remove a specific connection from a room. A name that starts with `user:`, `tenant:` or
975
+ * `connection:` is refused, as in `joinRoom`, and so is a `roomId` that is not a non-empty string.
959
976
  *
960
977
  * Acts on a connection this instance holds; for any other id it resolves and changes
961
978
  * nothing. A failure of the transport that holds the connection rejects the call.
@@ -1805,6 +1822,7 @@ declare class SseSubscriptionHandler {
1805
1822
  * so it never disrupts the connection lifecycle or live event delivery.
1806
1823
  *
1807
1824
  * @param invoke - A zero-arg function that calls the hook (handles optionality).
1825
+ * @param onFailure - What to do, once the failure is logged, when the hook failed.
1808
1826
  */
1809
1827
  private fireHook;
1810
1828
  }
@@ -2250,6 +2268,30 @@ type UnavailableError = ServiceUnavailableException & {
2250
2268
  */
2251
2269
  declare function unavailableError(code: RealtimeErrorCode, who: string, what: string, cause: unknown): UnavailableError;
2252
2270
 
2271
+ /**
2272
+ * Refuse a room name that is not a non-empty string.
2273
+ *
2274
+ * socket.io's room calls take an array of names, so a value that is not a string would
2275
+ * skip every check written for strings and still reach the rooms. The public type is `string`;
2276
+ * the shape is refused rather than each element checked.
2277
+ *
2278
+ * @param operation - The public call that was made.
2279
+ * @param roomId - The room name it was given.
2280
+ * @throws Error carrying `REALTIME_AUTH_FAILED` when `roomId` is not a non-empty string.
2281
+ */
2282
+ declare function requireRoomName(operation: string, roomId: unknown): asserts roomId is string;
2283
+ /**
2284
+ * Refuse a room name the library composes, for a call that would put a connection in it or take
2285
+ * it out. The message names the operation, the field and the prefix, never the room id, which is
2286
+ * the caller's input.
2287
+ *
2288
+ * @param operation - The public call that was made.
2289
+ * @param roomId - The room name it was given.
2290
+ * @throws Error carrying `REALTIME_AUTH_FAILED` when `roomId` is not a non-empty string, or starts
2291
+ * with a reserved prefix.
2292
+ */
2293
+ declare function refuseReservedRoom(operation: string, roomId: unknown): void;
2294
+
2253
2295
  /**
2254
2296
  * @fileoverview The error every coded failure of this library is built with.
2255
2297
  * @layer utils
@@ -2409,5 +2451,5 @@ declare const RESERVED_EVENT_NAMES: {
2409
2451
  /** Union of reserved event name values. */
2410
2452
  type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
2411
2453
 
2412
- export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, 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, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
2454
+ export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, 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, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };
2413
2455
  export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, QuitableClient, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
@@ -105,8 +105,9 @@ interface AuthenticationResult {
105
105
  * They are joined before the connection is announced or `onConnect` runs, so no event
106
106
  * published to one of them can fall between admission and a later `joinRoom` — the
107
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`.
108
+ * and a hook that throws is only logged (unless `onConnectFailure` is `'close'`), so a
109
+ * connection scoped from there can go live, and stay, without its room; scope in `rooms`,
110
+ * not in `onConnect`.
110
111
  *
111
112
  * Each name must be a non-blank string of at most `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH`
112
113
  * characters, must not start with `user:`, `tenant:` or `connection:` (the library
@@ -114,7 +115,7 @@ interface AuthenticationResult {
114
115
  * hold at most `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once.
115
116
  * A result that breaks a rule is a contract violation, refused like a blank `userId`:
116
117
  * 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
+ * They apply to this field only; `joinRoom` has no limit on count or length and refuses only the reserved prefixes.
118
119
  *
119
120
  * The rooms are fixed at admission. `revalidate` is handed them back, but a different
120
121
  * set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for
@@ -488,6 +489,16 @@ interface BymaxRealtimeModuleOptions {
488
489
  tenantResolver?: (auth: AuthenticationResult) => string | undefined | null;
489
490
  hooks?: IConnectionLifecycleHooks;
490
491
  hookTimeoutMs?: number;
492
+ /**
493
+ * What a failing `onConnect` does to the connection it was called for.
494
+ *
495
+ * `'ignore'` (the default): the failure is logged and the connection stays.
496
+ * `'close'`: the failure is logged and the connection is closed, on both transports. On
497
+ * WebSocket the connection is refused before it is announced; on SSE the hook is not awaited,
498
+ * so events published in the meantime may already have been delivered. Scope a connection in
499
+ * `AuthenticationResult.rooms`, not in the hook, when none may be missed.
500
+ */
501
+ onConnectFailure?: 'ignore' | 'close';
491
502
  authenticateTimeoutMs?: number;
492
503
  maxPendingHandshakes?: number;
493
504
  /**
@@ -939,6 +950,9 @@ declare class RealtimeService {
939
950
  /**
940
951
  * Send to a logical room. Use the prefix convention (`user:{id}`,
941
952
  * `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
953
+ *
954
+ * @throws {Error} `REALTIME_AUTH_FAILED` when `roomId` is not a non-empty string: socket.io
955
+ * reads an array as several rooms.
942
956
  */
943
957
  emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
944
958
  /** Send to every connected client. Use sparingly. */
@@ -946,16 +960,19 @@ declare class RealtimeService {
946
960
  /**
947
961
  * Add a specific connection to a room.
948
962
  *
949
- * The room id is not checked. Never pass client-supplied input that could start
950
- * with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
951
- * receives that tenant's events.
963
+ * Rooms of the application's own are free-form, but a name that starts with `user:`,
964
+ * `tenant:` or `connection:` is refused, the rule that `AuthenticationResult.rooms` is
965
+ * held to: joining `tenant:<other>` would receive that tenant's events. A `roomId` that is
966
+ * not a non-empty string is refused too, whatever it holds: socket.io reads an array as
967
+ * several room names.
952
968
  *
953
969
  * Acts on a connection this instance holds; for any other id it resolves and changes
954
970
  * nothing. A failure of the transport that holds the connection rejects the call.
955
971
  */
956
972
  joinRoom(connectionId: string, roomId: string): Promise<void>;
957
973
  /**
958
- * Remove a specific connection from a room.
974
+ * Remove a specific connection from a room. A name that starts with `user:`, `tenant:` or
975
+ * `connection:` is refused, as in `joinRoom`, and so is a `roomId` that is not a non-empty string.
959
976
  *
960
977
  * Acts on a connection this instance holds; for any other id it resolves and changes
961
978
  * nothing. A failure of the transport that holds the connection rejects the call.
@@ -1805,6 +1822,7 @@ declare class SseSubscriptionHandler {
1805
1822
  * so it never disrupts the connection lifecycle or live event delivery.
1806
1823
  *
1807
1824
  * @param invoke - A zero-arg function that calls the hook (handles optionality).
1825
+ * @param onFailure - What to do, once the failure is logged, when the hook failed.
1808
1826
  */
1809
1827
  private fireHook;
1810
1828
  }
@@ -2250,6 +2268,30 @@ type UnavailableError = ServiceUnavailableException & {
2250
2268
  */
2251
2269
  declare function unavailableError(code: RealtimeErrorCode, who: string, what: string, cause: unknown): UnavailableError;
2252
2270
 
2271
+ /**
2272
+ * Refuse a room name that is not a non-empty string.
2273
+ *
2274
+ * socket.io's room calls take an array of names, so a value that is not a string would
2275
+ * skip every check written for strings and still reach the rooms. The public type is `string`;
2276
+ * the shape is refused rather than each element checked.
2277
+ *
2278
+ * @param operation - The public call that was made.
2279
+ * @param roomId - The room name it was given.
2280
+ * @throws Error carrying `REALTIME_AUTH_FAILED` when `roomId` is not a non-empty string.
2281
+ */
2282
+ declare function requireRoomName(operation: string, roomId: unknown): asserts roomId is string;
2283
+ /**
2284
+ * Refuse a room name the library composes, for a call that would put a connection in it or take
2285
+ * it out. The message names the operation, the field and the prefix, never the room id, which is
2286
+ * the caller's input.
2287
+ *
2288
+ * @param operation - The public call that was made.
2289
+ * @param roomId - The room name it was given.
2290
+ * @throws Error carrying `REALTIME_AUTH_FAILED` when `roomId` is not a non-empty string, or starts
2291
+ * with a reserved prefix.
2292
+ */
2293
+ declare function refuseReservedRoom(operation: string, roomId: unknown): void;
2294
+
2253
2295
  /**
2254
2296
  * @fileoverview The error every coded failure of this library is built with.
2255
2297
  * @layer utils
@@ -2409,5 +2451,5 @@ declare const RESERVED_EVENT_NAMES: {
2409
2451
  /** Union of reserved event name values. */
2410
2452
  type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
2411
2453
 
2412
- export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, 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, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
2454
+ export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, 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, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };
2413
2455
  export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, QuitableClient, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
@@ -108,17 +108,30 @@ function validateOptions(options) {
108
108
  );
109
109
  }
110
110
  validateHookTimeout(options);
111
+ validateOnConnectFailure(options);
111
112
  validateSseOptions(options);
112
113
  validateReauthPolicy(options);
113
114
  }
114
115
  var MAX_TIMER_MS = 2147483647;
116
+ var MAX_PER_USER_CONNECTIONS = 1e5;
117
+ var MAX_REPLAY_EVENTS = 1e5;
118
+ var MAX_HTTP_BUFFER_BYTES = 100 * 1024 * 1024;
115
119
  function assertInteger(path, value, least, most) {
116
120
  if (value === void 0) return;
117
- const valid = typeof value === "number" && Number.isInteger(value) && value >= least && (most === void 0 || value <= most);
121
+ const valid = typeof value === "number" && Number.isSafeInteger(value) && value >= least && (most === void 0 || value <= most);
118
122
  if (valid) return;
119
123
  throw realtimeError(
120
124
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
121
- `options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, got ${String(value)}`,
125
+ `options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, got ${String(value)}${most === void 0 && Number.isInteger(value) && !Number.isSafeInteger(value) ? ` (the most is ${Number.MAX_SAFE_INTEGER})` : ""}`,
126
+ { who: "BymaxRealtimeModule" }
127
+ );
128
+ }
129
+ function validateOnConnectFailure(options) {
130
+ const value = options.onConnectFailure;
131
+ if (value === void 0 || value === "ignore" || value === "close") return;
132
+ throw realtimeError(
133
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
134
+ `options.onConnectFailure must be 'ignore' or 'close', got ${String(value)}`,
122
135
  { who: "BymaxRealtimeModule" }
123
136
  );
124
137
  }
@@ -127,6 +140,18 @@ function validateHookTimeout(options) {
127
140
  assertInteger("authenticateTimeoutMs", options.authenticateTimeoutMs, 1, MAX_TIMER_MS);
128
141
  assertInteger("maxPendingHandshakes", options.maxPendingHandshakes, 1);
129
142
  assertInteger("maxConnections", options.maxConnections, 1);
143
+ assertInteger(
144
+ "websocket.maxConnectionsPerUser",
145
+ options.websocket?.maxConnectionsPerUser,
146
+ 0,
147
+ MAX_PER_USER_CONNECTIONS
148
+ );
149
+ assertInteger(
150
+ "websocket.maxHttpBufferSize",
151
+ options.websocket?.maxHttpBufferSize,
152
+ 1,
153
+ MAX_HTTP_BUFFER_BYTES
154
+ );
130
155
  assertInteger("websocket.pingIntervalMs", options.websocket?.pingIntervalMs, 1, MAX_TIMER_MS);
131
156
  assertInteger("websocket.pingTimeoutMs", options.websocket?.pingTimeoutMs, 1, MAX_TIMER_MS);
132
157
  }
@@ -166,18 +191,12 @@ function validateSseOptions(options) {
166
191
  { who: "BymaxRealtimeModule" }
167
192
  );
168
193
  }
169
- if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
170
- throw realtimeError(
171
- REALTIME_ERROR_CODES.INVALID_OPTIONS,
172
- `options.sse.replayBufferSize must be >= 0`,
173
- { who: "BymaxRealtimeModule" }
174
- );
175
- }
194
+ assertInteger("sse.replayBufferSize", sse?.replayBufferSize, 0, MAX_REPLAY_EVENTS);
176
195
  assertInteger("sse.replayTtlMs", sse?.replayTtlMs, 1, MAX_TIMER_MS);
177
196
  assertInteger("sse.replayMaxIdleUsers", sse?.replayMaxIdleUsers, 1);
178
197
  for (const name of ["maxQueuedBytes", "maxQueuedEvents", "stallHeartbeats"]) {
179
198
  const value = sse?.[name];
180
- if (value !== void 0 && !(typeof value === "number" && Number.isInteger(value) && value >= 0)) {
199
+ if (value !== void 0 && !(typeof value === "number" && Number.isSafeInteger(value) && value >= 0)) {
181
200
  throw realtimeError(
182
201
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
183
202
  `options.sse.${name} must be an integer >= 0 (0 switches the bound off), got ${String(value)}`,
@@ -185,13 +204,12 @@ function validateSseOptions(options) {
185
204
  );
186
205
  }
187
206
  }
188
- if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
189
- throw realtimeError(
190
- REALTIME_ERROR_CODES.INVALID_OPTIONS,
191
- `options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`,
192
- { who: "BymaxRealtimeModule" }
193
- );
194
- }
207
+ assertInteger(
208
+ "sse.maxConnectionsPerUser",
209
+ sse?.maxConnectionsPerUser,
210
+ 0,
211
+ MAX_PER_USER_CONNECTIONS
212
+ );
195
213
  }
196
214
 
197
215
  // src/server/utils/describe-error.ts
@@ -373,12 +391,39 @@ var ROOM_PREFIXES = {
373
391
  RESOURCE: "resource"
374
392
  };
375
393
 
376
- // src/server/utils/admit-rooms.ts
394
+ // src/server/utils/reserved-room.ts
377
395
  var RESERVED_ROOM_PREFIXES = [
378
396
  `${ROOM_PREFIXES.USER}:`,
379
397
  `${ROOM_PREFIXES.TENANT}:`,
380
398
  "connection:"
381
399
  ];
400
+ function reservedRoomPrefix(room) {
401
+ return RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
402
+ }
403
+ function describeShape(value) {
404
+ if (value === null) return "null";
405
+ return Array.isArray(value) ? "an array" : typeof value;
406
+ }
407
+ function requireRoomName(operation, roomId) {
408
+ if (typeof roomId === "string" && roomId.length > 0) return;
409
+ throw realtimeError(
410
+ REALTIME_ERROR_CODES.AUTH_FAILED,
411
+ `${operation}: \`roomId\` must be a non-empty string, got ${describeShape(roomId)}`,
412
+ { who: "RealtimeService" }
413
+ );
414
+ }
415
+ function refuseReservedRoom(operation, roomId) {
416
+ requireRoomName(operation, roomId);
417
+ const prefix = reservedRoomPrefix(roomId);
418
+ if (prefix === void 0) return;
419
+ throw realtimeError(
420
+ REALTIME_ERROR_CODES.AUTH_FAILED,
421
+ `${operation}: \`roomId\` starts with the reserved prefix "${prefix}", which the library composes itself`,
422
+ { who: "RealtimeService" }
423
+ );
424
+ }
425
+
426
+ // src/server/utils/admit-rooms.ts
382
427
  function refuse(detail) {
383
428
  throw realtimeError(
384
429
  REALTIME_ERROR_CODES.AUTH_FAILED,
@@ -405,7 +450,7 @@ function admitRooms(auth) {
405
450
  if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
406
451
  refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
407
452
  }
408
- const reserved = RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
453
+ const reserved = reservedRoomPrefix(room);
409
454
  if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
410
455
  }
411
456
  return { ...auth, rooms: Object.freeze(admitted) };
@@ -774,7 +819,12 @@ function composeRoomId(prefix, ...parts) {
774
819
  }
775
820
  function unavailableError(code, who, what, cause) {
776
821
  const { message } = realtimeError(code, `${what} (${describeError(cause)})`, { who });
777
- return Object.assign(new ServiceUnavailableException(), { code, message, cause });
822
+ const error = Object.assign(new ServiceUnavailableException(), { code });
823
+ Object.defineProperties(error, {
824
+ message: { value: message, enumerable: false, writable: true, configurable: true },
825
+ cause: { value: cause, enumerable: false, writable: true, configurable: true }
826
+ });
827
+ return error;
778
828
  }
779
829
  var InMemoryPubSub = class {
780
830
  handlers = /* @__PURE__ */ new Set();
@@ -1184,6 +1234,7 @@ var SseTransport = class {
1184
1234
  await this.publish({ op: "emitToTenant", args: { tenantId, event, data, id } });
1185
1235
  }
1186
1236
  async emitToRoom(roomId, event, data) {
1237
+ requireRoomName("emitToRoom", roomId);
1187
1238
  const id = this.idGen.next();
1188
1239
  this.emitToRoomLocal(roomId, event, data, id);
1189
1240
  await this.publish({ op: "emitToRoom", args: { roomId, event, data, id } });
@@ -1194,10 +1245,12 @@ var SseTransport = class {
1194
1245
  await this.publish({ op: "broadcast", args: { event, data, id } });
1195
1246
  }
1196
1247
  async joinRoom(connectionId, roomId) {
1248
+ refuseReservedRoom("joinRoom", roomId);
1197
1249
  if (this.connections.get(connectionId)?.transport === "sse")
1198
1250
  this.rooms.join(connectionId, roomId);
1199
1251
  }
1200
1252
  async leaveRoom(connectionId, roomId) {
1253
+ refuseReservedRoom("leaveRoom", roomId);
1201
1254
  if (this.connections.get(connectionId)?.transport === "sse")
1202
1255
  this.rooms.leave(connectionId, roomId);
1203
1256
  }
@@ -1640,7 +1693,10 @@ var SseSubscriptionHandler = class {
1640
1693
  }
1641
1694
  const record = this.transport.getConnection(connectionId);
1642
1695
  if (record) {
1643
- this.fireHook(() => this.hooks?.onConnect?.(buildMeta(record)));
1696
+ this.fireHook(
1697
+ () => this.hooks?.onConnect?.(buildMeta(record)),
1698
+ this.options.onConnectFailure === "close" ? () => subscriber.complete() : void 0
1699
+ );
1644
1700
  }
1645
1701
  const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
1646
1702
  this.heartbeat.start(
@@ -1650,9 +1706,11 @@ var SseSubscriptionHandler = class {
1650
1706
  () => this.transport.checkStall(connectionId)
1651
1707
  );
1652
1708
  }
1653
- fireHook(invoke) {
1709
+ fireHook(invoke, onFailure) {
1654
1710
  void runHook(invoke).then((failed) => {
1655
- if (failed) this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
1711
+ if (!failed) return;
1712
+ this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
1713
+ onFailure?.();
1656
1714
  });
1657
1715
  }
1658
1716
  };
@@ -1731,16 +1789,19 @@ var RealtimeService = class {
1731
1789
  emitToTenant(tenantId, event, data) {
1732
1790
  return this.transport.emitToTenant(tenantId, event, data);
1733
1791
  }
1734
- emitToRoom(roomId, event, data) {
1792
+ async emitToRoom(roomId, event, data) {
1793
+ requireRoomName("emitToRoom", roomId);
1735
1794
  return this.transport.emitToRoom(roomId, event, data);
1736
1795
  }
1737
1796
  broadcast(event, data) {
1738
1797
  return this.transport.broadcast(event, data);
1739
1798
  }
1740
- joinRoom(connectionId, roomId) {
1799
+ async joinRoom(connectionId, roomId) {
1800
+ refuseReservedRoom("joinRoom", roomId);
1741
1801
  return this.transport.joinRoom(connectionId, roomId);
1742
1802
  }
1743
- leaveRoom(connectionId, roomId) {
1803
+ async leaveRoom(connectionId, roomId) {
1804
+ refuseReservedRoom("leaveRoom", roomId);
1744
1805
  return this.transport.leaveRoom(connectionId, roomId);
1745
1806
  }
1746
1807
  disconnect(connectionId, reason) {
@@ -2044,26 +2105,54 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
2044
2105
  logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
2045
2106
  return resolved;
2046
2107
  }
2047
- function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2048
- const moduleName = moduleClass.name;
2108
+ function assertOneFactoryPattern(asyncOptions, moduleName) {
2049
2109
  const patterns = [
2050
2110
  asyncOptions.useFactory,
2051
2111
  asyncOptions.useClass,
2052
2112
  asyncOptions.useExisting
2053
2113
  ].filter((pattern) => pattern !== void 0);
2054
- if (patterns.length !== 1) {
2055
- throw realtimeError(
2056
- REALTIME_ERROR_CODES.INVALID_OPTIONS,
2057
- `forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
2058
- { who: moduleName }
2059
- );
2114
+ if (patterns.length === 1) return;
2115
+ throw realtimeError(
2116
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
2117
+ `forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
2118
+ { who: moduleName }
2119
+ );
2120
+ }
2121
+ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2122
+ if (asyncOptions.useFactory) {
2123
+ return {
2124
+ provide: REALTIME_OPTIONS_TOKEN,
2125
+ useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
2126
+ inject: [...asyncOptions.inject ?? []]
2127
+ };
2060
2128
  }
2061
- assertModeSupported(wiring, asyncOptions.transport, moduleName);
2062
- assertSseEndpointApplies(asyncOptions, moduleName);
2063
- const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2064
- const instanceId = randomUUID();
2065
- const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2066
- const resolve = (raw, source) => {
2129
+ return {
2130
+ provide: REALTIME_OPTIONS_TOKEN,
2131
+ useFactory: async (factory) => resolve(
2132
+ await factory.createRealtimeOptions(),
2133
+ "createRealtimeOptions"
2134
+ ),
2135
+ inject: [asyncOptions.useExisting ?? factoryToken]
2136
+ };
2137
+ }
2138
+ function fromOptions(token, read) {
2139
+ return { provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] };
2140
+ }
2141
+ function buildOptionDerivedProviders(logger, instanceId) {
2142
+ return [
2143
+ fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
2144
+ fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
2145
+ warnIfSingleInstance(opts.pubsub, opts.transport, logger);
2146
+ return opts.pubsub ?? new InMemoryPubSub();
2147
+ }),
2148
+ fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
2149
+ { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
2150
+ fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
2151
+ fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence)
2152
+ ];
2153
+ }
2154
+ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName) {
2155
+ return (raw, source) => {
2067
2156
  const resolved = resolveAsyncOptions(
2068
2157
  raw,
2069
2158
  asyncOptions.transport,
@@ -2075,20 +2164,17 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2075
2164
  if (asyncOptions.transport === "websocket") return resolved;
2076
2165
  return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
2077
2166
  };
2078
- const resolvedOptionsProvider = asyncOptions.useFactory ? {
2079
- provide: REALTIME_OPTIONS_TOKEN,
2080
- useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
2081
- inject: [...asyncOptions.inject ?? []]
2082
- } : {
2083
- provide: REALTIME_OPTIONS_TOKEN,
2084
- useFactory: async (factory) => resolve(
2085
- await factory.createRealtimeOptions(),
2086
- "createRealtimeOptions"
2087
- ),
2088
- inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
2089
- };
2167
+ }
2168
+ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2169
+ const moduleName = moduleClass.name;
2170
+ assertOneFactoryPattern(asyncOptions, moduleName);
2171
+ assertModeSupported(wiring, asyncOptions.transport, moduleName);
2172
+ assertSseEndpointApplies(asyncOptions, moduleName);
2173
+ const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2174
+ const instanceId = randomUUID();
2175
+ const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2176
+ const resolve = buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName);
2090
2177
  const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
2091
- const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
2092
2178
  const { providers: transportProviders, controllers } = wiring.buildAsync({
2093
2179
  mode: asyncOptions.transport,
2094
2180
  sseEndpoint: boundSseEndpoint
@@ -2099,16 +2185,8 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2099
2185
  controllers,
2100
2186
  providers: [
2101
2187
  ...factoryClassProvider,
2102
- resolvedOptionsProvider,
2103
- fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
2104
- fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
2105
- warnIfSingleInstance(opts.pubsub, opts.transport, logger);
2106
- return opts.pubsub ?? new InMemoryPubSub();
2107
- }),
2108
- fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
2109
- { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
2110
- fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
2111
- fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
2188
+ buildOptionsProvider(asyncOptions, resolve, FACTORY_TOKEN),
2189
+ ...buildOptionDerivedProviders(logger, instanceId),
2112
2190
  ...SHARED_SERVICES,
2113
2191
  ...transportProviders,
2114
2192
  ...asyncOptions.extraProviders ?? []
@@ -2569,4 +2647,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2569
2647
  }
2570
2648
  };
2571
2649
 
2572
- export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, 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, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
2650
+ export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, 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, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };