@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.
package/CHANGELOG.md CHANGED
@@ -2,11 +2,45 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
+ Versioning is **not** strict [SemVer](https://semver.org/spec/v2.0.0.html) while this API is pre-stable: breaking changes ship in minor and patch releases by explicit `@bymax-one` policy, so a version number carries no compatibility information. The **Apply to a derived backend** note, on the entries that carry one, is the compatibility contract: read it, not the number.
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.17] - 2026-11-17
11
+
12
+ ### Added
13
+
14
+ - **`onConnectFailure: 'ignore' | 'close'`, a module option for what a failing `onConnect` does to its connection.** A hook that throws or rejects was only logged on both transports, so a host whose `onConnect` did work the connection depends on (a presence record, a scoped join) kept serving a connection that work had not reached. With `'close'` the failure is logged and the connection is closed. On both transports the hook has run, so `onConnect` is seen before the `onDisconnect` that follows it, and an event published while the hook runs may already have reached the client: on WebSocket the connection is closed before `connection:established` is sent, on SSE the stream is ended once the hook settles. Scope a connection in `AuthenticationResult.rooms` when no event may be missed. On WebSocket a hook that does not settle within `hookTimeoutMs` counts as a failure; on SSE the hook has no limit. The default is `'ignore'`, the behaviour of every earlier release, and any other value is refused at start-up with `REALTIME_INVALID_OPTIONS`.
15
+
16
+ #### Apply to a derived backend
17
+
18
+ Nothing changes unless you set the option. If you do, make sure your `onConnect` fails only when the connection should not stand: a hook that throws for a transient reason (a metrics client down) will then close the connection.
19
+
20
+ ### Security
21
+
22
+ - **The text of a driver or a broker travelled on the 503 errors the library raises when they were stringified.** `unavailableError` set the failure underneath, a driver's message naming a host and a port, on the instance's own enumerable `message` and `cause`. A controller's 503 body was generic, but a filter, a logger or a socket acknowledgement that ran `JSON.stringify` on the instance sent them on. Both are now non-enumerable: `error.message` and `error.cause` still hold the text for whoever logs it, and the stringified instance carries the generic response and the stable `code`.
23
+
24
+ - **`joinRoom` could put a connection in another user's or tenant's room.** `AuthenticationResult.rooms` refused names that start with `user:`, `tenant:` or `connection:`, but `RealtimeService.joinRoom` and `leaveRoom` took any name. On WebSocket `emitToUser` and `emitToTenant` are delivered to the room named after the identity, so a host that forwarded a client-supplied room id to `joinRoom` let that client receive `user:<victim>` or `tenant:<other>` events by naming the room. Both calls now refuse those three prefixes with `REALTIME_AUTH_FAILED`, by the same rule admission uses; the message names the call, the field and the prefix, never the room id. `emitToRoom` does not refuse the prefixes: a name it is given only reaches that user's or tenant's own connections.
25
+
26
+ - **A room name that was not a string skipped that check.** socket.io's `join` and `leave` accept an array of names, so on WebSocket `joinRoom(id, ['user:<victim>'])`, `['tenant:<other>']`, `['connection:<id>']`, `['ok', 'user:<victim>']` and a nested array all resolved, and the connection then received what `emitToUser`, `emitToTenant` and the per-connection room delivered; `leaveRoom` took the same values. On SSE `emitToUser` and `emitToTenant` read the connection registry rather than a room, so the same names did not reach those events there; a room named that way was still joined, and `emitToRoom` with that name reached it. `joinRoom`, `leaveRoom` and `emitToRoom` now refuse a `roomId` that is not a non-empty string, before any room API sees it, with `REALTIME_AUTH_FAILED` and a message that names the call and the kind of value, never the value. The check is on `RealtimeService`, `WebSocketTransport`, `CompositeTransport` and the SSE transport, so injecting a transport directly is covered too. Measured: with real Socket.IO clients, an array, a nested array, a mixed array and a `Set` naming another identity's room are refused and the attacker's connection receives none of the events published for that identity; an object with a `toString`, a number, `null`, `undefined`, a `String` object and the empty string are refused in a unit table on the service and the SSE transport.
27
+
28
+ - **A per-user connection cap, the replay ring's size and the WebSocket payload bound could be switched off by a value that is not an integer.** The checks on `sse.maxConnectionsPerUser` and `sse.replayBufferSize` were comparisons (`< 0`), and `websocket.maxConnectionsPerUser` and `websocket.maxHttpBufferSize` had none, so `NaN`, which fails every comparison, passed and made the bounds they feed never trip. Measured: five connections of one user were all kept under `NaN` and `Infinity` on both transports; a replay ring given 1,000 events held all 1,000; and a Socket.IO server given `NaN`, `Infinity`, `-1` or `0` delivered a 2,000,000-byte payload that the default 1,000,000 bound refuses. A fraction and a numeric string were accepted too and then coerced by the comparison they fed. The four options are now validated at start-up as safe integers, `>= 0` for the counts and `>= 1` for the payload bound, each with a most, with `REALTIME_INVALID_OPTIONS`: 100,000 for either per-user cap and for `sse.replayBufferSize`, and 104,857,600 bytes (100 MiB) for `websocket.maxHttpBufferSize`. `Number.isInteger(1e300)` is true and the comparisons these options feed never trip at that size, so `1e300`, `Number.MAX_VALUE` and `2 ** 53` were a bound in name only; the integer options that had no most now refuse anything past 9,007,199,254,740,991.
29
+
30
+ #### Apply to a derived backend
31
+
32
+ Read the failure from `error.message` and `error.cause`, as before; do not rely on them appearing in `JSON.stringify(error)` or in `Object.keys(error)`.
33
+
34
+ A host that puts connections in a `user:`, `tenant:` or `connection:` room by hand now gets a rejected promise from `joinRoom` or `leaveRoom`; no call puts a connection in those rooms, because the library joins them itself from the identity it resolved. To send to one identity or tenant use `emitToUser` or `emitToTenant`; on WebSocket, to send to one connection use `emitToRoom('connection:<id>', ...)`, which is not refused. A `roomId` that is not a non-empty string, an array included, is refused the same way. Application rooms are unaffected.
35
+
36
+ At start-up a value that is not an integer is refused where it used to be accepted: `NaN`, `Infinity`, fractions and numeric strings for `sse.maxConnectionsPerUser`, `sse.replayBufferSize`, `websocket.maxConnectionsPerUser` and `websocket.maxHttpBufferSize`, plus `-1` for `websocket.maxConnectionsPerUser` (it switched the cap off, as `0` does) and `0` or a negative for `websocket.maxHttpBufferSize` (each switched the payload bound off). `0` is still how to switch off the two per-user caps, and `0` still means no replay for `sse.replayBufferSize`. If you want an unbounded value, say it with `0` where that is allowed, not with `Infinity`. A value above 100,000 for either per-user cap or `sse.replayBufferSize`, or above 104,857,600 for `websocket.maxHttpBufferSize`, is refused too.
37
+
38
+ `WebSocketTransport` gains two private members, `joinRooms` and `runOnConnect`, which `registerSocket` calls. A TypeScript subclass that declares a member with either name no longer compiles (TS2415, a private member of the base), and a JavaScript subclass that defines either replaces the joins of the user, tenant and connection rooms, or the call to `onConnect`, without any error. Do not declare members named `joinRooms` or `runOnConnect` in a subclass.
39
+
40
+ `RealtimeService.emitToRoom` is now an `async` method: it already returned `Promise<void>`, and a synchronous throw, including the refusal of a `roomId` that is not a non-empty string, now comes back as a rejected promise. `./internal` exports `requireRoomName` and `refuseReservedRoom`; `./internal` is not public API and carries no compatibility promise, so do not import them.
41
+
42
+ On SSE the `reason` that `onDisconnect` receives is set when the library closed the connection with one (`disconnect(connectionId, reason)`, the connection bounds) and is `undefined` otherwise: a connection that ended on its own, one that `onConnectFailure: 'close'` refused, or one closed at shutdown.
43
+
10
44
  ## [1.2.16] - 2026-11-14
11
45
 
12
46
  ### Fixed
@@ -1105,7 +1139,8 @@ First published release.
1105
1139
  rather than by the manual sweep that raised the NestJS floors — that sweep
1106
1140
  asked about NestJS and never put the same question to the other ten peers.
1107
1141
 
1108
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.16...HEAD
1142
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.17...HEAD
1143
+ [1.2.17]: https://github.com/bymaxone/nest-realtime/compare/v1.2.16...v1.2.17
1109
1144
  [1.2.16]: https://github.com/bymaxone/nest-realtime/compare/v1.2.15...v1.2.16
1110
1145
  [1.2.15]: https://github.com/bymaxone/nest-realtime/compare/v1.2.14...v1.2.15
1111
1146
  [1.2.14]: https://github.com/bymaxone/nest-realtime/compare/v1.2.13...v1.2.14
package/README.md CHANGED
@@ -339,22 +339,23 @@ With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls
339
339
 
340
340
  All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `authenticator` are required.
341
341
 
342
- | Group | Key Options | Default |
343
- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
344
- | **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
345
- | **authenticator** | `IConnectionAuthenticator` | — (**required**) |
346
- | **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result, on **both** transports; `undefined` and `null` mean "no opinion" and fall back | `auth.tenantId` |
347
- | **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget) | — |
348
- | **hookTimeoutMs** | How long the library waits for a hook it awaits (`onDisconnect` on both transports, WebSocket `onConnect`) before giving up on it; integer from 1 to 2147483647 | `5000` |
349
- | **authenticateTimeoutMs** | How long a handshake waits for `authenticate` before it is refused (SSE `503`, WebSocket the generic error); integer from 1 to 2147483647 | `10000` |
350
- | **maxPendingHandshakes** | How many calls to `authenticate` may be waiting at once, across both transports; over it a handshake is refused at once without calling it; integer >= 1 | `1000` |
351
- | **maxConnections** | How many connections one instance holds, both transports together; a handshake past it is refused before `authenticate` is called (SSE `503`, WebSocket the generic error); integer >= 1, no way to switch it off | `10000` |
352
- | **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
353
- | **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
354
- | **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
355
- | **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `replayTtlMs`, `replayMaxIdleUsers`, `maxConnectionsPerUser`, `emitConnectionEvent`, `maxQueuedBytes`, `maxQueuedEvents`, `stallHeartbeats` | `/realtime/sse`, `30000`, `100`, `300000`, `1000`, `5`, `true`, `2097152`, `1000`, `3` |
356
- | **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults), `5` for `maxConnectionsPerUser` |
357
- | **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`, `revalidateTimeoutMs`, `concurrency` | `300`, `'disconnect'`, `60000`, `10000`, `8` |
342
+ | Group | Key Options | Default |
343
+ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
344
+ | **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
345
+ | **authenticator** | `IConnectionAuthenticator` | — (**required**) |
346
+ | **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result, on **both** transports; `undefined` and `null` mean "no opinion" and fall back | `auth.tenantId` |
347
+ | **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget) | — |
348
+ | **hookTimeoutMs** | How long the library waits for a hook it awaits (`onDisconnect` on both transports, WebSocket `onConnect`) before giving up on it; integer from 1 to 2147483647 | `5000` |
349
+ | **onConnectFailure** | What a failing `onConnect` does to its connection: `'ignore'` logs it and keeps the connection, `'close'` logs it and closes the connection on both transports, after the hook has run; anything else is refused at start-up | `'ignore'` |
350
+ | **authenticateTimeoutMs** | How long a handshake waits for `authenticate` before it is refused (SSE `503`, WebSocket the generic error); integer from 1 to 2147483647 | `10000` |
351
+ | **maxPendingHandshakes** | How many calls to `authenticate` may be waiting at once, across both transports; over it a handshake is refused at once without calling it; integer >= 1 | `1000` |
352
+ | **maxConnections** | How many connections one instance holds, both transports together; a handshake past it is refused before `authenticate` is called (SSE `503`, WebSocket the generic error); integer >= 1, no way to switch it off | `10000` |
353
+ | **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
354
+ | **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
355
+ | **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
356
+ | **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `replayTtlMs`, `replayMaxIdleUsers`, `maxConnectionsPerUser`, `emitConnectionEvent`, `maxQueuedBytes`, `maxQueuedEvents`, `stallHeartbeats` | `/realtime/sse`, `30000`, `100`, `300000`, `1000`, `5`, `true`, `2097152`, `1000`, `3` |
357
+ | **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults), `5` for `maxConnectionsPerUser` |
358
+ | **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`, `revalidateTimeoutMs`, `concurrency` | `300`, `'disconnect'`, `60000`, `10000`, `8` |
358
359
 
359
360
  `sse.heartbeatMs` must be between 5,000 and 90,000 ms. Any other value, including `NaN` and a non-number, stops the application at start-up with `REALTIME_INVALID_OPTIONS`. `websocket.pingIntervalMs` and `websocket.pingTimeoutMs` must be integers from 1 to 2147483647 (Socket.IO runs both as timers, and Node runs a longer one as 1 ms). `sse.replayTtlMs` must be an integer from 1 to 2147483647 and `sse.replayMaxIdleUsers` an integer of 1 or more. `sse.maxQueuedBytes`, `sse.maxQueuedEvents` and `sse.stallHeartbeats` must be integers of 0 or more, and `0` switches that bound off.
360
361
 
@@ -368,7 +369,7 @@ All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `
368
369
 
369
370
  #### Hooks the library waits for
370
371
 
371
- A hook is a notification: its failure is logged and nothing else changes. Three hooks are awaited by the library, and each is given up on after `hookTimeoutMs` (default 5,000 ms; an integer from 1 to 2147483647, checked at start-up): `onDisconnect` on both transports and `onConnect` on WebSocket, which is awaited before the connection is announced. A hook that has not settled by then is logged as `did not settle within N ms` and abandoned, whatever it returns later. The other hooks are not waited for and have no limit. On SSE the client is cut first and `onDisconnect` runs after, so a slow hook cannot keep a connection open; on shutdown every connection is closed at once, so a hook that never settles delays closing the application by about one `hookTimeoutMs`, not by one per connection. A hook that needs longer than the timeout must hand its work off and return.
372
+ A hook is a notification: its failure is logged and nothing else changes. The library awaits some hooks, and gives up on each after `hookTimeoutMs` (default 5,000 ms; an integer from 1 to 2147483647, checked at start-up): `onDisconnect` on both transports and `onConnect` on WebSocket, which is awaited before the connection is announced. A hook that has not settled by then is logged as `did not settle within N ms` and abandoned, whatever it returns later. The other hooks are not waited for and have no limit. On SSE the client is cut first and `onDisconnect` runs after, so a slow hook cannot keep a connection open; on shutdown every connection is closed at once, so a hook that never settles delays closing the application by about one `hookTimeoutMs`, not by one per connection. A hook that needs longer than the timeout must hand its work off and return. A host whose `onConnect` does work the connection depends on can set `onConnectFailure: 'close'`: a failing `onConnect` then closes the connection, which on WebSocket is closed before `connection:established` is sent and on SSE is ended after the hook settles. On both transports `onConnect` is seen before the `onDisconnect` that follows it, and an event published while the hook runs may already have reached the client; scope a connection in `AuthenticationResult.rooms` when none may be missed. A connection that `'close'` refuses has also already displaced the user's oldest one when the user is at `maxConnectionsPerUser`: eviction happens at admission, before `onConnect`. On WebSocket the `reason` that `onDisconnect` receives is `CLIENT_DISCONNECT` for every connection, including one the server closed (`disconnect(connectionId, reason)` and `onConnectFailure: 'close'`), so it does not say who closed the connection; on SSE the reason is set when the library closed the connection with one (`disconnect(connectionId, reason)`, the connection bounds) and is `undefined` otherwise: a connection that ended on its own, one that `onConnectFailure: 'close'` refused, or one closed at shutdown.
372
373
 
373
374
  #### The offline-queue read on a reconnect
374
375
 
@@ -402,7 +403,7 @@ The limit has a cost, and it is not a defence by itself. It trades a process tha
402
403
  An SSE response writes one event at a time and waits for the client to read before the next, so everything behind that wait is held in server memory. Each connection is bounded: when the events and bytes sent to it and not yet taken by its socket pass `sse.maxQueuedEvents` or `sse.maxQueuedBytes` (an event that is alone in the queue is always taken, however large), or no byte has left the process for `sse.stallHeartbeats` heartbeats in a row while the response holds bytes, the connection is closed with the reason `REALTIME_SLOW_CONSUMER` and a warning is logged. Only that connection is closed; the client reconnects and `Last-Event-ID` replays what it missed. A connection whose response has no socket to measure is not bounded.
403
404
 
404
405
  > [!NOTE]
405
- > `maxConnectionsPerUser` defaults to `5` on both transports: a user's sixth connection closes their oldest, which is sent a disconnect. `0` switches the cap off. The cap is per user and does not bound the connections of an instance: many users, or a token minted per request, are bounded by your proxy or the process's file-descriptor limit, not by this option.
406
+ > `maxConnectionsPerUser` defaults to `5` on both transports: a user's sixth connection closes their oldest, which is sent a disconnect. The oldest is closed when the new connection is admitted, before `onConnect` runs, so a connection that `onConnectFailure: 'close'` refuses has already displaced it. `0` switches the cap off. The cap, `replayBufferSize` and `websocket.maxHttpBufferSize` must be integers (`0` or more, and `1` or more for the payload bound) and have a most: 100,000 for the cap on either transport, 100,000 events for `replayBufferSize` (memory per user stream is that times the size of a frame), and 104,857,600 bytes (100 MiB) for `websocket.maxHttpBufferSize`, whose Socket.IO default is 1,000,000 bytes. `NaN`, `Infinity`, a fraction, a numeric string, a value past its most and any integer past 9,007,199,254,740,991 (`1e300`, `2 ** 53`) are refused at start-up, since a comparison with `NaN` is never true and a bound that large never trips. The cap is per user and does not bound the connections of an instance: many users, or a token minted per request, are bounded by your proxy or the process's file-descriptor limit, not by this option.
406
407
 
407
408
  The options are typed per entry point: `SseRealtimeModuleOptions` and `SseRealtimeModuleAsyncOptions` fix `transport: 'sse'`, and `WebSocketRealtimeModuleOptions` and `WebSocketRealtimeModuleAsyncOptions` (from `/websocket`) fix `'websocket' | 'both'`. `forRootAsync` takes `useFactory`, `useClass` (a `BymaxRealtimeModuleOptionsFactory`) or `useExisting`.
408
409
 
@@ -646,11 +647,11 @@ The unified emit API. Identical on every transport.
646
647
 
647
648
  All methods return `Promise<void>`.
648
649
 
649
- **Revocation is never best-effort.** `disconnect(connectionId)` resolves once the connection was closed on this instance or the revocation was handed to the bus (`IRealtimePubSub`). It **rejects**, with `error.code` set to a `RealtimeErrorCode`, when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish (`RedisRealtimePubSub` refuses at once while its Redis client is not ready, and after 2,000 ms when the client is ready but the server does not answer), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. Branch on the code, not the message; the error is Nest's `ServiceUnavailableException` (HTTP `503`) with `code` set, so a controller that lets it escape answers `503` with the generic body (see "What a client is told"). A rejection means the connection may still be connected, so retry.
650
+ **Revocation is never best-effort.** `disconnect(connectionId)` resolves once the connection was closed on this instance or the revocation was handed to the bus (`IRealtimePubSub`). It **rejects**, with `error.code` set to a `RealtimeErrorCode`, when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish (`RedisRealtimePubSub` refuses at once while its Redis client is not ready, and after 2,000 ms when the client is ready but the server does not answer), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. Branch on the code, not the message; the error is Nest's `ServiceUnavailableException` (HTTP `503`) with `code` set, so a controller that lets it escape answers `503` with the generic body (see "What a client is told"). `error.message` and `error.cause` are not enumerable, so `JSON.stringify(error)` carries the generic response and the `code` only; `error.stack` and `util.inspect(error)` still carry the text of the driver or the broker, which belongs in your server logs and nowhere a client reads. A rejection means the connection may still be connected, so retry.
650
651
 
651
652
  **Emits are at-most-once.** `emitToUser`, `emitToTenant`, `emitToRoom` and `broadcast` **resolve even when the publish to the other instances failed**; that failure is logged with `REALTIME_PUBSUB_UNAVAILABLE` and passed to the `onDeliveryFailure` hook, which is where to count it. An offline queue that could not keep an event for a user who is offline here is reported the same way, since another instance may have delivered it live; a failure on one transport of `'both'` is only logged. An emit rejects only when the event has no delivery path left: for `emitToUser`, the user is offline here, the queue failed, and the bus failed or cannot reach another instance (the default in-memory bus); with `'both'`, a failure on both transports rejects with `REALTIME_TRANSPORT_UNAVAILABLE`. A rejected emit is not proof that no client received it, so retry only where a duplicate is acceptable.
652
653
 
653
- `joinRoom` and `leaveRoom` act on a connection **this instance holds**; for any other id they resolve and change nothing. A failure of the transport that holds the connection rejects the call.
654
+ `joinRoom` and `leaveRoom` act on a connection **this instance holds**; for any other id they resolve and change nothing. A failure of the transport that holds the connection rejects the call. Both refuse a room id that starts with `user:`, `tenant:` or `connection:`, the names the library composes, and one that is not a non-empty string, with `REALTIME_AUTH_FAILED`; any other name is free-form.
654
655
 
655
656
  **An instance must hear the others.** With `RedisRealtimePubSub`, a subscription the server refuses (a wrong password, a missing permission) **fails the boot**: retrying cannot fix it, and an instance that never hears a revocation must not look healthy. A Redis that is only unreachable does not block the boot. The instance starts, logs once that it is not subscribed, and subscribes when a connection succeeds. Until then, whenever the subscriber connection drops, and whenever the Redis client that publishes cannot publish, `isPubSubReady()` is false. A client built with `lazyConnect` is connected by the adapter. Put it in your readiness probe:
656
657
 
@@ -763,7 +764,7 @@ characters and must not start with `user:`, `tenant:` or `connection:`; at most
763
764
  `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once. A result that breaks a rule
764
765
  is refused like a blank `userId` — a server fault (500 on SSE, a generic `connect_error` on
765
766
  WebSocket), not a 401 — and nothing is registered. The two limits are bounds against abuse, not
766
- measurements, and they apply to this field only: `joinRoom` stays free-form.
767
+ measurements, and they apply to this field only: `joinRoom` is not held to them.
767
768
 
768
769
  The rooms are fixed at admission and handed back to `revalidate` in the original result. A
769
770
  different set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for changes
@@ -808,7 +809,7 @@ composeRoomId('RESOURCE', 'invoice', invoiceId) // → "resource:invoice:42"
808
809
 
809
810
  A `resource:` room is not tenant-scoped: two tenants using the same type and id share it. When ids are only unique within a tenant, pass the tenant as its own encoded part rather than gluing it to the id with a separator that ids may contain, such as `-`.
810
811
 
811
- Never pass client-supplied input to `joinRoom` or `emitToRoom` as a room id without checking that it cannot start with `user:` or `tenant:`. `joinRoom` is not guarded (only the `rooms` field is validated), and joining `tenant:<other>` receives that tenant's events.
812
+ `joinRoom` and `leaveRoom` refuse a room id that starts with `user:`, `tenant:` or `connection:`, and all three of `joinRoom`, `leaveRoom` and `emitToRoom` refuse an id that is not a non-empty string (an array, a `Set`, an object, a number, `null`), so a client-supplied value cannot put a connection in another user's or tenant's room. Each refusal is `REALTIME_AUTH_FAILED`. `emitToRoom` does not refuse the prefixes: it can send to such a name, which only reaches that user's or tenant's own connections, so authorise who may emit before you pass it a client-supplied id.
812
813
 
813
814
  #### Role-scoped delivery
814
815
 
@@ -110,17 +110,30 @@ function validateOptions(options) {
110
110
  );
111
111
  }
112
112
  validateHookTimeout(options);
113
+ validateOnConnectFailure(options);
113
114
  validateSseOptions(options);
114
115
  validateReauthPolicy(options);
115
116
  }
116
117
  var MAX_TIMER_MS = 2147483647;
118
+ var MAX_PER_USER_CONNECTIONS = 1e5;
119
+ var MAX_REPLAY_EVENTS = 1e5;
120
+ var MAX_HTTP_BUFFER_BYTES = 100 * 1024 * 1024;
117
121
  function assertInteger(path, value, least, most) {
118
122
  if (value === void 0) return;
119
- const valid = typeof value === "number" && Number.isInteger(value) && value >= least && (most === void 0 || value <= most);
123
+ const valid = typeof value === "number" && Number.isSafeInteger(value) && value >= least && (most === void 0 || value <= most);
120
124
  if (valid) return;
121
125
  throw realtimeError(
122
126
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
123
- `options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, got ${String(value)}`,
127
+ `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})` : ""}`,
128
+ { who: "BymaxRealtimeModule" }
129
+ );
130
+ }
131
+ function validateOnConnectFailure(options) {
132
+ const value = options.onConnectFailure;
133
+ if (value === void 0 || value === "ignore" || value === "close") return;
134
+ throw realtimeError(
135
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
136
+ `options.onConnectFailure must be 'ignore' or 'close', got ${String(value)}`,
124
137
  { who: "BymaxRealtimeModule" }
125
138
  );
126
139
  }
@@ -129,6 +142,18 @@ function validateHookTimeout(options) {
129
142
  assertInteger("authenticateTimeoutMs", options.authenticateTimeoutMs, 1, MAX_TIMER_MS);
130
143
  assertInteger("maxPendingHandshakes", options.maxPendingHandshakes, 1);
131
144
  assertInteger("maxConnections", options.maxConnections, 1);
145
+ assertInteger(
146
+ "websocket.maxConnectionsPerUser",
147
+ options.websocket?.maxConnectionsPerUser,
148
+ 0,
149
+ MAX_PER_USER_CONNECTIONS
150
+ );
151
+ assertInteger(
152
+ "websocket.maxHttpBufferSize",
153
+ options.websocket?.maxHttpBufferSize,
154
+ 1,
155
+ MAX_HTTP_BUFFER_BYTES
156
+ );
132
157
  assertInteger("websocket.pingIntervalMs", options.websocket?.pingIntervalMs, 1, MAX_TIMER_MS);
133
158
  assertInteger("websocket.pingTimeoutMs", options.websocket?.pingTimeoutMs, 1, MAX_TIMER_MS);
134
159
  }
@@ -168,18 +193,12 @@ function validateSseOptions(options) {
168
193
  { who: "BymaxRealtimeModule" }
169
194
  );
170
195
  }
171
- if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
172
- throw realtimeError(
173
- REALTIME_ERROR_CODES.INVALID_OPTIONS,
174
- `options.sse.replayBufferSize must be >= 0`,
175
- { who: "BymaxRealtimeModule" }
176
- );
177
- }
196
+ assertInteger("sse.replayBufferSize", sse?.replayBufferSize, 0, MAX_REPLAY_EVENTS);
178
197
  assertInteger("sse.replayTtlMs", sse?.replayTtlMs, 1, MAX_TIMER_MS);
179
198
  assertInteger("sse.replayMaxIdleUsers", sse?.replayMaxIdleUsers, 1);
180
199
  for (const name of ["maxQueuedBytes", "maxQueuedEvents", "stallHeartbeats"]) {
181
200
  const value = sse?.[name];
182
- if (value !== void 0 && !(typeof value === "number" && Number.isInteger(value) && value >= 0)) {
201
+ if (value !== void 0 && !(typeof value === "number" && Number.isSafeInteger(value) && value >= 0)) {
183
202
  throw realtimeError(
184
203
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
185
204
  `options.sse.${name} must be an integer >= 0 (0 switches the bound off), got ${String(value)}`,
@@ -187,13 +206,12 @@ function validateSseOptions(options) {
187
206
  );
188
207
  }
189
208
  }
190
- if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
191
- throw realtimeError(
192
- REALTIME_ERROR_CODES.INVALID_OPTIONS,
193
- `options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`,
194
- { who: "BymaxRealtimeModule" }
195
- );
196
- }
209
+ assertInteger(
210
+ "sse.maxConnectionsPerUser",
211
+ sse?.maxConnectionsPerUser,
212
+ 0,
213
+ MAX_PER_USER_CONNECTIONS
214
+ );
197
215
  }
198
216
 
199
217
  // src/server/utils/describe-error.ts
@@ -375,12 +393,39 @@ var ROOM_PREFIXES = {
375
393
  RESOURCE: "resource"
376
394
  };
377
395
 
378
- // src/server/utils/admit-rooms.ts
396
+ // src/server/utils/reserved-room.ts
379
397
  var RESERVED_ROOM_PREFIXES = [
380
398
  `${ROOM_PREFIXES.USER}:`,
381
399
  `${ROOM_PREFIXES.TENANT}:`,
382
400
  "connection:"
383
401
  ];
402
+ function reservedRoomPrefix(room) {
403
+ return RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
404
+ }
405
+ function describeShape(value) {
406
+ if (value === null) return "null";
407
+ return Array.isArray(value) ? "an array" : typeof value;
408
+ }
409
+ function requireRoomName(operation, roomId) {
410
+ if (typeof roomId === "string" && roomId.length > 0) return;
411
+ throw realtimeError(
412
+ REALTIME_ERROR_CODES.AUTH_FAILED,
413
+ `${operation}: \`roomId\` must be a non-empty string, got ${describeShape(roomId)}`,
414
+ { who: "RealtimeService" }
415
+ );
416
+ }
417
+ function refuseReservedRoom(operation, roomId) {
418
+ requireRoomName(operation, roomId);
419
+ const prefix = reservedRoomPrefix(roomId);
420
+ if (prefix === void 0) return;
421
+ throw realtimeError(
422
+ REALTIME_ERROR_CODES.AUTH_FAILED,
423
+ `${operation}: \`roomId\` starts with the reserved prefix "${prefix}", which the library composes itself`,
424
+ { who: "RealtimeService" }
425
+ );
426
+ }
427
+
428
+ // src/server/utils/admit-rooms.ts
384
429
  function refuse(detail) {
385
430
  throw realtimeError(
386
431
  REALTIME_ERROR_CODES.AUTH_FAILED,
@@ -407,7 +452,7 @@ function admitRooms(auth) {
407
452
  if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
408
453
  refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
409
454
  }
410
- const reserved = RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
455
+ const reserved = reservedRoomPrefix(room);
411
456
  if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
412
457
  }
413
458
  return { ...auth, rooms: Object.freeze(admitted) };
@@ -776,7 +821,12 @@ function composeRoomId(prefix, ...parts) {
776
821
  }
777
822
  function unavailableError(code, who, what, cause) {
778
823
  const { message } = realtimeError(code, `${what} (${describeError(cause)})`, { who });
779
- return Object.assign(new common.ServiceUnavailableException(), { code, message, cause });
824
+ const error = Object.assign(new common.ServiceUnavailableException(), { code });
825
+ Object.defineProperties(error, {
826
+ message: { value: message, enumerable: false, writable: true, configurable: true },
827
+ cause: { value: cause, enumerable: false, writable: true, configurable: true }
828
+ });
829
+ return error;
780
830
  }
781
831
  exports.InMemoryPubSub = class InMemoryPubSub {
782
832
  handlers = /* @__PURE__ */ new Set();
@@ -1186,6 +1236,7 @@ exports.SseTransport = class SseTransport {
1186
1236
  await this.publish({ op: "emitToTenant", args: { tenantId, event, data, id } });
1187
1237
  }
1188
1238
  async emitToRoom(roomId, event, data) {
1239
+ requireRoomName("emitToRoom", roomId);
1189
1240
  const id = this.idGen.next();
1190
1241
  this.emitToRoomLocal(roomId, event, data, id);
1191
1242
  await this.publish({ op: "emitToRoom", args: { roomId, event, data, id } });
@@ -1196,10 +1247,12 @@ exports.SseTransport = class SseTransport {
1196
1247
  await this.publish({ op: "broadcast", args: { event, data, id } });
1197
1248
  }
1198
1249
  async joinRoom(connectionId, roomId) {
1250
+ refuseReservedRoom("joinRoom", roomId);
1199
1251
  if (this.connections.get(connectionId)?.transport === "sse")
1200
1252
  this.rooms.join(connectionId, roomId);
1201
1253
  }
1202
1254
  async leaveRoom(connectionId, roomId) {
1255
+ refuseReservedRoom("leaveRoom", roomId);
1203
1256
  if (this.connections.get(connectionId)?.transport === "sse")
1204
1257
  this.rooms.leave(connectionId, roomId);
1205
1258
  }
@@ -1642,7 +1695,10 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1642
1695
  }
1643
1696
  const record = this.transport.getConnection(connectionId);
1644
1697
  if (record) {
1645
- this.fireHook(() => this.hooks?.onConnect?.(buildMeta(record)));
1698
+ this.fireHook(
1699
+ () => this.hooks?.onConnect?.(buildMeta(record)),
1700
+ this.options.onConnectFailure === "close" ? () => subscriber.complete() : void 0
1701
+ );
1646
1702
  }
1647
1703
  const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
1648
1704
  this.heartbeat.start(
@@ -1652,9 +1708,11 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1652
1708
  () => this.transport.checkStall(connectionId)
1653
1709
  );
1654
1710
  }
1655
- fireHook(invoke) {
1711
+ fireHook(invoke, onFailure) {
1656
1712
  void runHook(invoke).then((failed) => {
1657
- if (failed) this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
1713
+ if (!failed) return;
1714
+ this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
1715
+ onFailure?.();
1658
1716
  });
1659
1717
  }
1660
1718
  };
@@ -1733,16 +1791,19 @@ exports.RealtimeService = class RealtimeService {
1733
1791
  emitToTenant(tenantId, event, data) {
1734
1792
  return this.transport.emitToTenant(tenantId, event, data);
1735
1793
  }
1736
- emitToRoom(roomId, event, data) {
1794
+ async emitToRoom(roomId, event, data) {
1795
+ requireRoomName("emitToRoom", roomId);
1737
1796
  return this.transport.emitToRoom(roomId, event, data);
1738
1797
  }
1739
1798
  broadcast(event, data) {
1740
1799
  return this.transport.broadcast(event, data);
1741
1800
  }
1742
- joinRoom(connectionId, roomId) {
1801
+ async joinRoom(connectionId, roomId) {
1802
+ refuseReservedRoom("joinRoom", roomId);
1743
1803
  return this.transport.joinRoom(connectionId, roomId);
1744
1804
  }
1745
- leaveRoom(connectionId, roomId) {
1805
+ async leaveRoom(connectionId, roomId) {
1806
+ refuseReservedRoom("leaveRoom", roomId);
1746
1807
  return this.transport.leaveRoom(connectionId, roomId);
1747
1808
  }
1748
1809
  disconnect(connectionId, reason) {
@@ -2046,26 +2107,54 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
2046
2107
  logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
2047
2108
  return resolved;
2048
2109
  }
2049
- function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2050
- const moduleName = moduleClass.name;
2110
+ function assertOneFactoryPattern(asyncOptions, moduleName) {
2051
2111
  const patterns = [
2052
2112
  asyncOptions.useFactory,
2053
2113
  asyncOptions.useClass,
2054
2114
  asyncOptions.useExisting
2055
2115
  ].filter((pattern) => pattern !== void 0);
2056
- if (patterns.length !== 1) {
2057
- throw realtimeError(
2058
- REALTIME_ERROR_CODES.INVALID_OPTIONS,
2059
- `forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
2060
- { who: moduleName }
2061
- );
2116
+ if (patterns.length === 1) return;
2117
+ throw realtimeError(
2118
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
2119
+ `forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
2120
+ { who: moduleName }
2121
+ );
2122
+ }
2123
+ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2124
+ if (asyncOptions.useFactory) {
2125
+ return {
2126
+ provide: REALTIME_OPTIONS_TOKEN,
2127
+ useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
2128
+ inject: [...asyncOptions.inject ?? []]
2129
+ };
2062
2130
  }
2063
- assertModeSupported(wiring, asyncOptions.transport, moduleName);
2064
- assertSseEndpointApplies(asyncOptions, moduleName);
2065
- const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2066
- const instanceId = crypto.randomUUID();
2067
- const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2068
- const resolve = (raw, source) => {
2131
+ return {
2132
+ provide: REALTIME_OPTIONS_TOKEN,
2133
+ useFactory: async (factory) => resolve(
2134
+ await factory.createRealtimeOptions(),
2135
+ "createRealtimeOptions"
2136
+ ),
2137
+ inject: [asyncOptions.useExisting ?? factoryToken]
2138
+ };
2139
+ }
2140
+ function fromOptions(token, read) {
2141
+ return { provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] };
2142
+ }
2143
+ function buildOptionDerivedProviders(logger, instanceId) {
2144
+ return [
2145
+ fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
2146
+ fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
2147
+ warnIfSingleInstance(opts.pubsub, opts.transport, logger);
2148
+ return opts.pubsub ?? new exports.InMemoryPubSub();
2149
+ }),
2150
+ fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
2151
+ { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
2152
+ fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
2153
+ fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence)
2154
+ ];
2155
+ }
2156
+ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName) {
2157
+ return (raw, source) => {
2069
2158
  const resolved = resolveAsyncOptions(
2070
2159
  raw,
2071
2160
  asyncOptions.transport,
@@ -2077,20 +2166,17 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2077
2166
  if (asyncOptions.transport === "websocket") return resolved;
2078
2167
  return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
2079
2168
  };
2080
- const resolvedOptionsProvider = asyncOptions.useFactory ? {
2081
- provide: REALTIME_OPTIONS_TOKEN,
2082
- useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
2083
- inject: [...asyncOptions.inject ?? []]
2084
- } : {
2085
- provide: REALTIME_OPTIONS_TOKEN,
2086
- useFactory: async (factory) => resolve(
2087
- await factory.createRealtimeOptions(),
2088
- "createRealtimeOptions"
2089
- ),
2090
- inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
2091
- };
2169
+ }
2170
+ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2171
+ const moduleName = moduleClass.name;
2172
+ assertOneFactoryPattern(asyncOptions, moduleName);
2173
+ assertModeSupported(wiring, asyncOptions.transport, moduleName);
2174
+ assertSseEndpointApplies(asyncOptions, moduleName);
2175
+ const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2176
+ const instanceId = crypto.randomUUID();
2177
+ const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2178
+ const resolve = buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName);
2092
2179
  const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
2093
- const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
2094
2180
  const { providers: transportProviders, controllers } = wiring.buildAsync({
2095
2181
  mode: asyncOptions.transport,
2096
2182
  sseEndpoint: boundSseEndpoint
@@ -2101,16 +2187,8 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2101
2187
  controllers,
2102
2188
  providers: [
2103
2189
  ...factoryClassProvider,
2104
- resolvedOptionsProvider,
2105
- fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
2106
- fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
2107
- warnIfSingleInstance(opts.pubsub, opts.transport, logger);
2108
- return opts.pubsub ?? new exports.InMemoryPubSub();
2109
- }),
2110
- fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
2111
- { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
2112
- fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
2113
- fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
2190
+ buildOptionsProvider(asyncOptions, resolve, FACTORY_TOKEN),
2191
+ ...buildOptionDerivedProviders(logger, instanceId),
2114
2192
  ...SHARED_SERVICES,
2115
2193
  ...transportProviders,
2116
2194
  ...asyncOptions.extraProviders ?? []
@@ -2599,7 +2677,9 @@ exports.describeError = describeError;
2599
2677
  exports.parseCookieHeader = parseCookieHeader;
2600
2678
  exports.quitWithin = quitWithin;
2601
2679
  exports.realtimeError = realtimeError;
2680
+ exports.refuseReservedRoom = refuseReservedRoom;
2602
2681
  exports.reportDeliveryFailure = reportDeliveryFailure;
2682
+ exports.requireRoomName = requireRoomName;
2603
2683
  exports.resolveAuthTenant = resolveAuthTenant;
2604
2684
  exports.runHook = runHook;
2605
2685
  exports.sseWiring = sseWiring;