@bymax-one/nest-realtime 1.2.16 → 1.2.18

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,69 @@
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.18] - 2026-11-17
11
+
12
+ ### Security
13
+
14
+ - **An option set to `undefined` resolved to "no bound", and a refusal echoed what it was given.** The defaults were merged with `{ ...DEFAULT_SSE, ...options.sse }`, so an own key holding `undefined` overwrote its default. Measured on 1.2.17 with `sse: { maxConnectionsPerUser: undefined, maxQueuedBytes: undefined, maxQueuedEvents: undefined, stallHeartbeats: undefined, replayBufferSize: undefined }`: the options the services receive carried `undefined` for all five, the per-user eviction returns early on `undefined` (no cap), and the three queue bounds are read with `?? 0`, which switches them off. A host that spelled an option as `cond ? value : undefined` therefore ran with the bound off instead of the default. Separately, the refusals of the numeric and enum options ended in `got <value>`, which printed whatever the host had passed: a token pasted into the wrong field, or the source text of a function. Now the keys that hold `undefined` or `null` are dropped, at the top level and in `sse`, `websocket` and `reauthenticationPolicy`, before the defaults are merged and before validation, so such an option resolves to its default and is validated as absent; a group handed over as a class instance is read through its fields and getters, as the services read it, so it is covered too. Every refusal of an option names the option and the type of what it received (`received a string`), prints a finite number, and echoes nothing else; the two `forRootAsync` endpoint refusals no longer print the paths.
15
+
16
+ - **`RedisOfflineQueue` accepted a `maxPerUser` or a `ttlSeconds` that loses or corrupts the queue.** Measured on Redis 7: a `ttlSeconds` of `0` or a negative made `EXPIRE` delete the key, so every append was dropped without an error; a `maxPerUser` of `0` made the trim remove every entry; and `NaN`, a fraction, `Infinity`, `1e300` or a value Redis rejects made the pipeline fail after `ZADD` had already run, which left the entries untrimmed or the key without an expiry, and every append rejected. A numeric string such as `'3'` concatenated in the trim (`'3' + 1` is `'31'`), keeping up to 30 events. The constructor now refuses anything that is not a safe integer from 1 to 100,000 for `maxPerUser` and from 1 to 2,147,483,647 for `ttlSeconds`, with `REALTIME_INVALID_OPTIONS` naming the option and its range and describing what it received by type (a finite number is printed). A `maxPerUser` or `ttlSeconds` of `undefined` or `null` is read as unset and takes its default.
17
+
18
+ - **A malformed pluggable piece, group or flag was accepted at start-up and failed later, or did the opposite of what it said.** Measured on 1.2.17 with `forRoot`: `pubsub: {}` and a `pubsub` without `subscribe` were accepted and the application then failed at init with a raw `this.pubsub.subscribe is not a function`; `sse.endpoint: 5` failed at registration with `endpoint.startsWith is not a function`; `offlineQueue: {}` and `presence: {}` were accepted, and with `offlineQueue: {}` an emit to an offline user rejected at run time with `REALTIME_TRANSPORT_UNAVAILABLE`; `tenantResolver: 'x'` was accepted and every handshake then threw a `TypeError` at `tenantResolver?.(auth)`; `hooks`, `sse`, `websocket` and `reauthenticationPolicy` were accepted as strings; `sse.emitConnectionEvent: 'no'` was accepted and read as true because it is truthy. `forRoot` now refuses each at registration with `REALTIME_INVALID_OPTIONS`, naming the option and describing what it received by type: a group (`sse`, `websocket`, `reauthenticationPolicy`) and `hooks` must be objects; `pubsub`, `offlineQueue` and `presence` must be objects with every function of their interface, which may be on a class prototype; each lifecycle hook that is set and `tenantResolver` must be functions; the two `emitConnectionEvent` flags must be booleans; and `sse.endpoint` must be a non-blank string, with or without a leading slash.
19
+
20
+ #### Apply to a derived backend
21
+
22
+ An option that holds `null` was refused (`got null`) and is now read as unset, like `undefined`: it takes its default. An option you meant to leave unlimited with `undefined` now takes its default instead, so say `0` where `0` switches the bound off. A test that pinned the text of a refusal (`got 1000`, `(got: carrier-pigeon)`) now reads `received 1000` and `received a string`.
23
+
24
+ A queue built with `new RedisOfflineQueue({ client, maxPerUser, ttlSeconds })` now throws at construction for a value outside those ranges, where it used to start and lose events. If you passed `0` to mean unlimited, there is no such mode: pick the count you can afford to hold per user.
25
+
26
+ A test double for the bus, the offline queue or presence that implements only the functions a test calls is now refused at registration: give it every required function, as a no-op where it does nothing. A flag you passed as a string (`'false'`) is refused instead of being read as true; pass a boolean.
27
+
28
+ ### Documentation
29
+
30
+ - **Details the 1.2.17 notes did not state.** A subclass of `WebSocketTransport` that replaces `joinRooms` drops, besides the user, tenant and connection rooms, the rooms an authenticator returns (`AuthenticationResult.rooms`) and the update of the `RoomRegistry`; a `static` member named `joinRooms` or `runOnConnect` compiles, because only the instance members are private; and for `emitToRoom` the change a caller can observe in 1.2.17 is that a `roomId` that is not a non-empty string is refused as a rejected promise, an outcome 1.2.16 did not have. `CONTRIBUTING.md` no longer describes a `commit-msg` hook and a `pre-commit` hook that this repository does not have.
31
+
32
+ - **A shutdown can wait six seconds for a client that stopped reading.** `app.close()` ends every stream at once, but Node's HTTP server then waits for the sockets of clients that no longer read, for `keepAliveTimeout` and a check interval: 6,004 ms measured, against 3 ms with `forceCloseConnections: true`. The README's "Shutdown" section now says so. Apply: pass `{ forceCloseConnections: true }` to `NestFactory.create`, or give the process a termination grace of at least 7 seconds.
33
+
34
+ ## [1.2.17] - 2026-11-17
35
+
36
+ ### Added
37
+
38
+ - **`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`.
39
+
40
+ #### Apply to a derived backend
41
+
42
+ 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.
43
+
44
+ ### Security
45
+
46
+ - **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`.
47
+
48
+ - **`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.
49
+
50
+ - **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.
51
+
52
+ - **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.
53
+
54
+ #### Apply to a derived backend
55
+
56
+ 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)`.
57
+
58
+ 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.
59
+
60
+ 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.
61
+
62
+ `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.
63
+
64
+ `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.
65
+
66
+ 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.
67
+
10
68
  ## [1.2.16] - 2026-11-14
11
69
 
12
70
  ### Fixed
@@ -1105,7 +1163,9 @@ First published release.
1105
1163
  rather than by the manual sweep that raised the NestJS floors — that sweep
1106
1164
  asked about NestJS and never put the same question to the other ten peers.
1107
1165
 
1108
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.16...HEAD
1166
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.18...HEAD
1167
+ [1.2.18]: https://github.com/bymaxone/nest-realtime/compare/v1.2.17...v1.2.18
1168
+ [1.2.17]: https://github.com/bymaxone/nest-realtime/compare/v1.2.16...v1.2.17
1109
1169
  [1.2.16]: https://github.com/bymaxone/nest-realtime/compare/v1.2.15...v1.2.16
1110
1170
  [1.2.15]: https://github.com/bymaxone/nest-realtime/compare/v1.2.14...v1.2.15
1111
1171
  [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,11 @@ 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.
407
+
408
+ An option that holds `undefined` or `null` is read as unset: it takes its default, in the module options and in `sse`, `websocket` and `reauthenticationPolicy`, so `maxConnectionsPerUser: cond ? 3 : undefined` means the default cap of `5`, never no cap. Say `0` where `0` switches a bound off. A refusal of an option names the option and the type of what it received (`received a string`), prints a finite number, and echoes nothing else, so a value pasted into the wrong field does not reach a log.
409
+
410
+ The shape of what you pass is checked at start-up too, and refused with `REALTIME_INVALID_OPTIONS`: `sse`, `websocket`, `reauthenticationPolicy` and `hooks` must be objects; `pubsub`, `offlineQueue` and `presence` must have every function of their interface (`IRealtimePubSub`, `IOfflineQueueStorage`, `IPresenceStorage`), on the object or its prototype; each hook that is set and `tenantResolver` must be a function; `sse.emitConnectionEvent` and `websocket.emitConnectionEvent` must be booleans; `sse.endpoint` must be a non-blank string, with or without a leading slash.
406
411
 
407
412
  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
413
 
@@ -646,11 +651,11 @@ The unified emit API. Identical on every transport.
646
651
 
647
652
  All methods return `Promise<void>`.
648
653
 
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.
654
+ **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
655
 
651
656
  **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
657
 
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.
658
+ `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
659
 
655
660
  **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
661
 
@@ -702,6 +707,8 @@ Read-side view of live connections — useful for admin endpoints and metrics. T
702
707
 
703
708
  Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePubSub`, `RedisOfflineQueue`.
704
709
 
710
+ `RedisOfflineQueue` takes `maxPerUser` (default 500) and `ttlSeconds` (default 3600), each an integer: `maxPerUser` from 1 to 100,000 and `ttlSeconds` from 1 to 2,147,483,647. A value outside that is refused when the queue is constructed, with `REALTIME_INVALID_OPTIONS`, because Redis would otherwise turn it into a silent loss: see the changelog entry for what each value did.
711
+
705
712
  #### Identity must be present or absent, never blank
706
713
 
707
714
  `userId` must be a non-empty string, and `tenantId` either absent or a non-empty string. A connection whose authenticator, or whose `tenantResolver`, yields a blank one is **refused at bootstrap** as a server fault, not a `401`: blank is not missing. Every connection carrying `''` lands under the same registry key and joins the same `user:` or `tenant:` room, and a later emit reaches all of them. Whitespace counts as blank.
@@ -763,7 +770,7 @@ characters and must not start with `user:`, `tenant:` or `connection:`; at most
763
770
  `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once. A result that breaks a rule
764
771
  is refused like a blank `userId` — a server fault (500 on SSE, a generic `connect_error` on
765
772
  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.
773
+ measurements, and they apply to this field only: `joinRoom` is not held to them.
767
774
 
768
775
  The rooms are fixed at admission and handed back to `revalidate` in the original result. A
769
776
  different set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for changes
@@ -808,7 +815,7 @@ composeRoomId('RESOURCE', 'invoice', invoiceId) // → "resource:invoice:42"
808
815
 
809
816
  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
817
 
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.
818
+ `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
819
 
813
820
  #### Role-scoped delivery
814
821
 
@@ -922,6 +929,8 @@ Nest's default exception filter does not log an `HttpException`, so a `503` from
922
929
 
923
930
  From the `onModuleDestroy` phase on, which runs ahead of every `beforeApplicationShutdown`, a new SSE stream gets a 503 whose message is `REALTIME_TRANSPORT_UNAVAILABLE` and a new WebSocket handshake gets a `connect_error` whose `data.code` is that code. A slow `onModuleDestroy` in a module nearer the root than the realtime module still runs first, and until it returns a connection is accepted.
924
931
 
932
+ A client that stopped reading holds its socket open after the library has ended its stream, and Node's HTTP server waits for it: `app.close()` took 6,004 ms with such clients and 3 ms with `forceCloseConnections: true`. Create the application with `NestFactory.create(AppModule, { forceCloseConnections: true })`, or give the process a termination grace of at least 7 seconds.
933
+
925
934
  ### DI Tokens
926
935
 
927
936
  `REALTIME_OPTIONS_TOKEN` · `REALTIME_TRANSPORT_TOKEN` · `REALTIME_AUTHENTICATOR_TOKEN` · `REALTIME_PUBSUB_TOKEN` · `REALTIME_OFFLINE_QUEUE_TOKEN` · `REALTIME_PRESENCE_TOKEN` · `REALTIME_HOOKS_TOKEN` · `REALTIME_INSTANCE_ID_TOKEN`