@bymax-one/nest-realtime 1.2.1 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,136 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.3] - 2026-10-31
11
+
12
+ **Apply before upgrading, if you set `websocket.redisAdapter`:** make sure `@socket.io/redis-adapter`
13
+ is installed and that `pubClient` is an ioredis client. 1.2.2 and earlier logged one error and served a single
14
+ instance when the adapter could not be installed, and every ESM consumer was in that state, so
15
+ WebSocket events did not cross instances. The boot now fails with `REALTIME_REDIS_ADAPTER_FAILED`
16
+ instead. A Redis that is merely unreachable does not fail the boot.
17
+
18
+ ### Fixed
19
+
20
+ - **The WebSocket Redis adapter now installs in the ES module build.** The adapter loaded
21
+ `@socket.io/redis-adapter` with a bare `require`, which an ES module does not have, so for every
22
+ consumer importing the package as ESM the load threw, one error line was logged, and the server
23
+ stayed single-instance: an emit on one instance never reached a client on another. Measured on the
24
+ published bundle with two instances and a real Redis, 0 of 5000 messages crossed; with the adapter
25
+ installed, 5000 of 5000 did. CommonJS consumers were not affected. The ESM bundle now declares a
26
+ `require` that resolves from the package, and still loads when a consumer's bundler re-bundles it
27
+ into CommonJS, where `import.meta.url` is undefined. `pnpm size` fails when an ESM bundle calls a
28
+ `require` it does not declare, and `pnpm check:runtime` boots the packed tarball in ESM, in
29
+ CommonJS and re-bundled into CommonJS, and asserts the adapter registers in each.
30
+
31
+ - **A WebSocket authenticator that rejects with a value that is not an `Error` no longer leaves the
32
+ socket connected.** The catch in `handleConnection` read `.message` from whatever was thrown, so a
33
+ rejection with `null` or `undefined` made the catch itself throw before `socket.disconnect(true)`
34
+ ran. The reason is now logged as `String(reason)` when it is not an `Error`, and the socket is
35
+ always closed. The handshake middleware already logged it this way; this is the path that runs when
36
+ the gateway is used without it.
37
+
38
+ ## [1.2.2] - 2026-10-31
39
+
40
+ ### Fixed
41
+
42
+ - **A refused WebSocket handshake is now a `connect_error` with a code, not a connect followed by a
43
+ silent disconnect.** The gateway authenticated in `handleConnection`, after Socket.IO had already
44
+ accepted the socket, so a client saw `connect` and then a bare `disconnect` with no reason it could
45
+ act on. Authentication now runs in a Socket.IO middleware on the handshake: a `null` result fails the
46
+ connection with `connect_error` carrying `err.data.code === 'REALTIME_AUTH_FAILED'`, and an
47
+ authenticator that throws fails it with a generic `Internal Server Error` that never carries the
48
+ thrown message. `authenticate()` still runs once per connection. **Apply note:** a client that
49
+ treated any `disconnect` as a refusal must now listen for `connect_error`
50
+ (`socket.on('connect_error', (err) => err.data?.code)`); `socket.active` is `false` after a
51
+ refusal, so Socket.IO does not reconnect on its own.
52
+
53
+ - **An SSE refusal that needs I/O is now a `401`, not a `200` followed by an error event.** The
54
+ SSE route returned the handler's promise and authenticated inside it. In an application with an
55
+ interceptor registered (a logging interceptor, for one), Nest commits `200 text/event-stream` from
56
+ a timer on the next macrotask, without waiting for that promise, so an authenticator that awaited
57
+ real I/O (a revocation or session lookup, a Redis read) before refusing lost the race. The client
58
+ had already received a `200`, then got
59
+ `event: error` with `REALTIME_AUTH_FAILED` and a closed stream, which a browser `EventSource`
60
+ treats as reconnectable and retries in a loop, while access logs recorded a `200` for refused
61
+ credentials. A refusal reached synchronously, or within microtasks (no cookie, a forged or expired
62
+ token checked in memory), got its `401`, and so did a late one in an application with no
63
+ interceptor. No connection was ever registered, so nothing was exposed.
64
+
65
+ Authentication now runs in a guard on the SSE route, which Nest awaits before the route and before
66
+ the stream starts, and the handler takes its result, so `authenticate()` still runs once per
67
+ connection. A refusal answers `401` (`REALTIME_AUTH_FAILED`), a blank identity `500` and an
68
+ authenticator that throws a `5xx`, whatever the authenticator awaited and whether or not an
69
+ interceptor is registered. Fixes
70
+ [#161](https://github.com/bymaxone/nest-realtime/issues/161).
71
+
72
+ The library also no longer lets an error's message reach the stream. Nest 11.2.3 writes the
73
+ message of an error raised after the stream has started into the `event: error` frame, so a
74
+ rejected connection registration, or a failure of another dependency after authentication, could
75
+ put text such as `connect ECONNREFUSED 10.20.30.40:6379` in front of the client. Any error that
76
+ is not an HTTP exception is now logged server-side and sent as a generic 500; an HTTP exception
77
+ an authenticator throws on purpose (a rate limit, say) is sent unchanged.
78
+
79
+ **Apply to a consumer.** Nothing to change. If you worked around the old behaviour by treating
80
+ an `error` event with `REALTIME_AUTH_FAILED` on a `200` stream as a refusal, that workaround can go:
81
+ the refusal is now the HTTP status, and `EventSource` stops on a `401` instead of reconnecting.
82
+ A test that asserted `200` for a refused connection should assert `401`.
83
+
84
+ ### Changed
85
+
86
+ - **`RealtimeGateway` now logs an error at start-up when the WebSocket adapter in use is not
87
+ `RealtimeIoAdapter`.** Under any other adapter the `websocket.*` options (`cors`, `namespace`,
88
+ `pingIntervalMs`, `pingTimeoutMs`, `maxHttpBufferSize`, `redisAdapter`) are dropped, and the
89
+ gateway's own CORS is `origin: false`, so a browser on another origin cannot connect. Nothing
90
+ reported this before. The message names the options it found and the fix,
91
+ `app.useWebSocketAdapter(new RealtimeIoAdapter(app))` in `main.ts`. It is a log line, not an
92
+ exception: an application that works today (same-origin, or Socket.IO's own defaults) keeps booting.
93
+
94
+ ### Internal
95
+
96
+ - `check:published` compiles every README snippet, not only the ones that import the package, through
97
+ the TypeScript API, so a parse-level elision in one snippet no longer hides the semantic errors in
98
+ the others. The names a snippet uses without declaring them are typed in
99
+ `scripts/readme-prelude.d.ts`, so a wrong method, option or destructured field is an error instead
100
+ of a call on `any`.
101
+ - `check:published` accepts a dot inside a relative module name (`./app.module`), which the path
102
+ allowlist added with the relative-import resolution rejected; `..` segments are still refused.
103
+ - `check:published` resolves a relative import in a README snippet to the snippet that exports the
104
+ imported names, and fails one that no snippet exports and no stub under `scripts/readme-modules/`
105
+ types, instead of ignoring it as an unresolved module that makes the names `any`.
106
+ - `check:published` tolerates a parse error in a README snippet only where the syntax tree shows a
107
+ bare `...` standing in for an argument, element or property, at that exact line and column, so a
108
+ real syntax error elsewhere in a snippet is no longer ignored.
109
+
110
+ ### Documentation
111
+
112
+ - **README:** a new step 7, "Add WebSocket", shows the complete working setup: the module from
113
+ `/websocket`, `RealtimeIoAdapter` in `main.ts` and `redisAdapter`. The README never named
114
+ `BymaxRealtimeWebSocketModule` or `RealtimeIoAdapter` before, and the sentence saying the Redis
115
+ adapter "is registered for you" omitted that this only happens once the adapter is installed.
116
+ Also documented: the error codes that are reserved and never raised today (`REALTIME_INVALID_TICKET`,
117
+ `REALTIME_PUBSUB_UNAVAILABLE`, `REALTIME_PAYLOAD_TOO_LARGE`, `REALTIME_REPLAY_BUFFER_MISS`) in a
118
+ status table; that presence is a contract and the server must emit `presence:*`; that the server
119
+ ignores events a WebSocket client sends; the per-entry-point option types, `PRESENCE_EVENT_NAMES`
120
+ and `UsePresenceReturn`; and that `RealtimeGateway`, `WebSocketTransport` and `CompositeTransport`
121
+ are exported for the module's own wiring.
122
+ A Troubleshooting entry quotes the start-up error verbatim, and a test fails if the README and the
123
+ message differ.
124
+ - `ConnectionRegistry.register` and `unregister` are tagged `@internal`: they are the transports'
125
+ own bookkeeping, and a record added by an application is counted by the lookups (an `sse` one also
126
+ suppresses offline-queue appends for that user) while nothing can be delivered to it.
127
+ - **README:** the Testing section no longer states a test count and a mutant count, which had
128
+ drifted from the suite (626 tests in 37 suites against 663 in 43; only the end-to-end count was
129
+ still right). It keeps the claims a gate enforces: 100% coverage and a mutation break threshold
130
+ of 100.
131
+
132
+ ### Tests
133
+
134
+ - `RealtimeIoAdapter` marks the servers and namespaces it creates, and `RealtimeGateway` checks
135
+ them in `afterInit`; both are covered, with the case of a server from another adapter.
136
+ - A spec parses the README and asserts it against the code: the `sse` and `reauthenticationPolicy`
137
+ defaults in the Configuration table, the error codes, the DI tokens and the reserved event names.
138
+ A default or a name that changes in code without the README now fails the suite.
139
+
10
140
  ## [1.2.1] - 2026-10-30
11
141
 
12
142
  **This version carries two behavioural breaks, both under Security below.** An authenticator that
@@ -468,7 +598,9 @@ First published release.
468
598
  rather than by the manual sweep that raised the NestJS floors — that sweep
469
599
  asked about NestJS and never put the same question to the other ten peers.
470
600
 
471
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.1...HEAD
601
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.3...HEAD
602
+ [1.2.3]: https://github.com/bymaxone/nest-realtime/compare/v1.2.2...v1.2.3
603
+ [1.2.2]: https://github.com/bymaxone/nest-realtime/compare/v1.2.1...v1.2.2
472
604
  [1.2.1]: https://github.com/bymaxone/nest-realtime/compare/v1.2.0...v1.2.1
473
605
  [1.2.0]: https://github.com/bymaxone/nest-realtime/compare/v1.1.2...v1.2.0
474
606
  [1.1.2]: https://github.com/bymaxone/nest-realtime/compare/v1.1.1...v1.1.2
package/README.md CHANGED
@@ -103,6 +103,8 @@ One package, four entry points — import only what your app needs:
103
103
  server websocket react
104
104
  ```
105
105
 
106
+ `/websocket` also exports `RealtimeGateway`, `WebSocketTransport` and `CompositeTransport`. They are exported for the module's own wiring and for tests: applications register `BymaxRealtimeWebSocketModule` and install `RealtimeIoAdapter`, and do not construct them.
107
+
106
108
  The `shared` subpath carries no Node or NestJS import, so the same event names and error codes are used on both sides of the wire without duplicating a constant.
107
109
 
108
110
  **The `websocket` subpath exists so the server one costs nothing extra.** Everything that touches `@nestjs/websockets`, `@nestjs/platform-socket.io` and `socket.io` is reachable only through it, so an application on SSE — the default transport — never installs the Socket.IO stack. Importing it is what opts in, in the install as much as in the configuration.
@@ -177,7 +179,7 @@ export class CookieAuthenticator implements IConnectionAuthenticator {
177
179
  ```
178
180
 
179
181
  > [!NOTE]
180
- > Returning `null` rejects the connection — throwing is not required. See [Auth Inversion](#-security-model) for the ticket and bearer patterns.
182
+ > Returning `null` rejects the connection — throwing is not required. On SSE the client gets a `401`; on WebSocket the handshake fails with a `connect_error` whose `err.data.code` is `REALTIME_AUTH_FAILED` (`socket.active` is `false`, so Socket.IO does not retry on its own). See [Auth Inversion](#-security-model) for the ticket and bearer patterns.
181
183
 
182
184
  ### 3. Register the Module
183
185
 
@@ -293,7 +295,54 @@ BymaxRealtimeModule.forRoot({
293
295
  })
294
296
  ```
295
297
 
296
- For WebSocket, pass an ioredis client to `websocket.redisAdapter.pubClient` and `@socket.io/redis-adapter` is registered for you.
298
+ For WebSocket, scaling goes through Socket.IO's own Redis adapter instead, configured in [step 7](#7-add-websocket-optional); `pubsub` and `offlineQueue` do not apply to WebSocket connections.
299
+
300
+ ### 7. Add WebSocket (optional)
301
+
302
+ WebSocket lives behind its own subpath, so an SSE application never installs the Socket.IO stack. Install its peers (see [Install](#1-install)), then do two things: register `BymaxRealtimeWebSocketModule` from `/websocket` instead of `BymaxRealtimeModule`, and install `RealtimeIoAdapter` in `main.ts`.
303
+
304
+ ```typescript
305
+ // app.module.ts
306
+ import { Module } from '@nestjs/common'
307
+ import { BymaxRealtimeWebSocketModule } from '@bymax-one/nest-realtime/websocket'
308
+ import Redis from 'ioredis'
309
+ import { CookieAuthenticator } from './auth/cookie-authenticator'
310
+
311
+ const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')
312
+
313
+ @Module({
314
+ imports: [
315
+ BymaxRealtimeWebSocketModule.forRoot({
316
+ transport: 'websocket', // or 'both' to serve SSE as well
317
+ authenticator: new CookieAuthenticator(),
318
+ websocket: {
319
+ cors: { origin: 'https://app.example.com', credentials: true },
320
+ redisAdapter: { pubClient: redis }, // only to scale across instances
321
+ },
322
+ }),
323
+ ],
324
+ })
325
+ export class AppModule {}
326
+ ```
327
+
328
+ ```typescript
329
+ // main.ts
330
+ import { NestFactory } from '@nestjs/core'
331
+ import { RealtimeIoAdapter } from '@bymax-one/nest-realtime/websocket'
332
+ import { AppModule } from './app.module'
333
+
334
+ async function bootstrap() {
335
+ const app = await NestFactory.create(AppModule)
336
+ app.useWebSocketAdapter(new RealtimeIoAdapter(app))
337
+ await app.listen(3000)
338
+ }
339
+ bootstrap()
340
+ ```
341
+
342
+ > [!IMPORTANT]
343
+ > The `main.ts` line is not optional. `RealtimeIoAdapter` is what applies `websocket.cors`, `namespace`, `pingIntervalMs`, `pingTimeoutMs`, `maxHttpBufferSize` and `redisAdapter`. Without it those options are ignored, the gateway's own CORS stays closed (`origin: false`) so a browser on another origin cannot connect, and the module logs an error at start-up that names this fix.
344
+
345
+ With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls `pubClient.duplicate()` for the subscriber; the library never opens its own Redis connection. If it cannot be installed (the package is missing, the client has no `duplicate()`), the boot fails with `REALTIME_REDIS_ADAPTER_FAILED` instead of serving a single instance; a Redis that is merely unreachable does not fail the boot. Socket.IO's polling fallback needs sticky sessions even then — see [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md). On the frontend, a `ws://` or `wss://` `url` selects WebSocket in `RealtimeProvider`. Replay through `Last-Event-ID` and the offline queue are SSE features: a WebSocket connection has neither.
297
346
 
298
347
  ---
299
348
 
@@ -317,6 +366,8 @@ All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `
317
366
  > [!NOTE]
318
367
  > `websocket.maxConnectionsPerUser` is **opt-in** and unlimited unless set to a positive number, while `sse.maxConnectionsPerUser` defaults to `5`. The two transports differ here on purpose: an SSE stream holds an HTTP connection open, a Socket.IO client multiplexes.
319
368
 
369
+ 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`.
370
+
320
371
  > [!IMPORTANT]
321
372
  > **`forRootAsync` takes the SSE route on the registration, not from the factory.** NestJS
322
373
  > registers controllers at decoration time, before any factory has run, so `sse.endpoint`
@@ -479,8 +530,8 @@ When integrating `@bymax-one/nest-realtime` in production, verify each of the fo
479
530
  A realtime channel fails in ways that are hard to reproduce — dropped streams, races between reconnect and revocation, one instance not seeing another's emit. The suite is built so those failures are caught by a test, not by a user.
480
531
 
481
532
  - ✅ **100% coverage** — statements, branches, functions, and lines, enforced as a release gate
482
- - ✅ **100.00% mutation score** — 655 killed and 7 timed out, zero survivors, verified with [Stryker](https://stryker-mutator.io/) (break threshold 100)
483
- - ✅ **626 tests** — 593 unit and integration across 37 suites, plus 33 end-to-end across 6
533
+ - ✅ **100% mutation score** — zero survivors, gated by [Stryker](https://stryker-mutator.io/) with a break threshold of 100
534
+ - ✅ **Unit, integration and end-to-end suites** — the end-to-end ones drive real Socket.IO connections in-process
484
535
  - ✅ **Cross-instance e2e** — real Redis pub/sub fan-out between two live instances, not a mocked channel
485
536
  - ✅ **Bundle-size gate** — the SSE-only React bundle is measured on every build and fails over budget
486
537
 
@@ -523,7 +574,7 @@ All methods return `Promise<void>`.
523
574
 
524
575
  ### ConnectionRegistry
525
576
 
526
- Read-side view of live connections — useful for admin endpoints and metrics.
577
+ Read-side view of live connections — useful for admin endpoints and metrics. The class also has `register` and `unregister`; those are the transports' own bookkeeping, so do not call them (a record you add has no stream or socket behind it).
527
578
 
528
579
  | Method | Returns |
529
580
  | -------------------------------- | ------------------------------------------------ |
@@ -540,7 +591,7 @@ Read-side view of live connections — useful for admin endpoints and metrics.
540
591
  | `IConnectionAuthenticator` | ✅ | Validate a connection, return `userId` / `tenantId` |
541
592
  | `IRealtimePubSub` | — | Cross-instance fan-out for SSE |
542
593
  | `IOfflineQueueStorage` | — | Hold events for disconnected users |
543
- | `IPresenceStorage` | — | Track who is online |
594
+ | `IPresenceStorage` | — | Contract only: the library never calls it; your code stores presence and emits `presence:online` / `presence:offline` |
544
595
  | `IConnectionLifecycleHooks` | — | Fire-and-forget connect / disconnect / error callbacks |
545
596
  | `ITransport` | — | Implemented by the library; the seam every transport shares |
546
597
 
@@ -747,7 +798,7 @@ const onConnect = joinRoleRoom({ get: () => ({ joinRoom }) }, 'admin', 'role:adm
747
798
 
748
799
  ### Reserved Events
749
800
 
750
- These names belong to the library. Do not reuse them for application events.
801
+ These names belong to the library. Do not reuse them for application events. They are exported from `/shared` as `RESERVED_EVENT_NAMES` and `PRESENCE_EVENT_NAMES` (type `PresenceEventName`).
751
802
 
752
803
  **Emitted today**
753
804
 
@@ -770,7 +821,18 @@ These names belong to the library. Do not reuse them for application events.
770
821
 
771
822
  ### Error Codes
772
823
 
773
- `REALTIME_INVALID_OPTIONS` · `REALTIME_NO_AUTHENTICATOR` · `REALTIME_AUTH_FAILED` · `REALTIME_REAUTHENTICATION_FAILED` · `REALTIME_TOO_MANY_CONNECTIONS` · `REALTIME_INVALID_TICKET` · `REALTIME_PUBSUB_UNAVAILABLE` · `REALTIME_PAYLOAD_TOO_LARGE` · `REALTIME_REPLAY_BUFFER_MISS`
824
+ | Code | Status |
825
+ | ---------------------------------- | ------------------------------------------------------------------- |
826
+ | `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option |
827
+ | `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
828
+ | `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
829
+ | `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
830
+ | `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
831
+ | `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
832
+ | `REALTIME_PUBSUB_UNAVAILABLE` | Reserved, never raised today: a pub/sub failure is logged |
833
+ | `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
834
+ | `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
835
+ | `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
774
836
 
775
837
  ### DI Tokens
776
838
 
@@ -783,7 +845,7 @@ These names belong to the library. Do not reuse them for application events.
783
845
  | `useRealtime(options)` | `{ transport, connected, events, lastEvent, error, reconnectAttempts, reconnect, emit }` — opens the connection |
784
846
  | `useRealtimeContext()` | The same value, from the nearest `<RealtimeProvider>` — throws when used outside one |
785
847
  | `useRealtimeConnection(options)` | `{ connected, error, reconnectAttempts, reconnect }` — status only, no events array |
786
- | `usePresence()` | `{ onlineUserIds, isOnline(userId), count }` — reads presence events from the provider |
848
+ | `usePresence()` | `UsePresenceReturn`: `{ onlineUserIds, isOnline(userId), count }` — reads `presence:*` events from the provider; your server must emit them |
787
849
 
788
850
  `RealtimeProvider` takes a single `options` prop of type `UseRealtimeOptions`:
789
851
 
@@ -800,7 +862,7 @@ These names belong to the library. Do not reuse them for application events.
800
862
  | `maxAttempts` | `number` | — (unlimited) | **SSE only** — give up and close after N failures |
801
863
 
802
864
  > [!NOTE]
803
- > `emit` is WebSocket-exclusive — SSE is server → client only. `reconnectAttempts` is always `0` on WebSocket, where Socket.IO owns the retry policy and exposes no count.
865
+ > `emit` is WebSocket-exclusive — SSE is server → client only — and the server ignores what it sends: `RealtimeGateway` registers no message handlers, so receiving client events needs a gateway of your own. `reconnectAttempts` is always `0` on WebSocket, where Socket.IO owns the retry policy and exposes no count.
804
866
 
805
867
  ---
806
868
 
@@ -818,6 +880,16 @@ SSE connections are long-lived HTTP responses, and several common proxy defaults
818
880
 
819
881
  Platform-specific configuration is in [docs/proxies-cheat-sheet.md](./docs/proxies-cheat-sheet.md).
820
882
 
883
+ ### Troubleshooting
884
+
885
+ **The log shows `RealtimeIoAdapter is not the active WebSocket adapter`.** The gateway logs this once at start-up, as an error, when its Socket.IO server was not created by `RealtimeIoAdapter`:
886
+
887
+ ```
888
+ RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options are ignored and the gateway CORS stays closed (origin: false): browsers on another origin cannot connect. Add app.useWebSocketAdapter(new RealtimeIoAdapter(app)) in main.ts, importing it from '@bymax-one/nest-realtime/websocket'.
889
+ ```
890
+
891
+ When `websocket` options are set, their names follow the words "the websocket options" in parentheses, for example `(cors, redisAdapter)`. The fix is the `main.ts` line in [step 7](#7-add-websocket-optional): `RealtimeIoAdapter` applies `cors`, `namespace`, `pingIntervalMs`, `pingTimeoutMs`, `maxHttpBufferSize` and `redisAdapter`, and until it is installed none of them takes effect.
892
+
821
893
  ---
822
894
 
823
895
  ## 🤝 Contributing
@@ -28,6 +28,7 @@ var REALTIME_ERROR_CODES = {
28
28
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
29
29
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
30
30
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
31
+ REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
31
32
  PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
32
33
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
33
34
  };
@@ -219,7 +220,11 @@ exports.ConnectionRegistry = class ConnectionRegistry {
219
220
  byId = /* @__PURE__ */ new Map();
220
221
  byUserId = /* @__PURE__ */ new Map();
221
222
  byTenantId = /* @__PURE__ */ new Map();
222
- /** Register a connection and index it by user and tenant. */
223
+ /**
224
+ * Register a connection and index it by user and tenant.
225
+ *
226
+ * @internal Transport bookkeeping: applications must not call it.
227
+ */
223
228
  register(record) {
224
229
  this.byId.set(record.connectionId, record);
225
230
  this.addToSetMap(this.byUserId, record.userId, record.connectionId);
@@ -227,7 +232,11 @@ exports.ConnectionRegistry = class ConnectionRegistry {
227
232
  this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
228
233
  }
229
234
  }
230
- /** Remove a connection from every index. Returns the removed record, if any. */
235
+ /**
236
+ * Remove a connection from every index. Returns the removed record, if any.
237
+ *
238
+ * @internal Transport bookkeeping: applications must not call it.
239
+ */
231
240
  unregister(connectionId) {
232
241
  const record = this.byId.get(connectionId);
233
242
  if (!record) return void 0;
@@ -811,6 +820,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
811
820
  hooks;
812
821
  offlineDelivery;
813
822
  logger = new common.Logger(exports.SseSubscriptionHandler.name);
823
+ authenticated = /* @__PURE__ */ new WeakMap();
814
824
  /**
815
825
  * Resolve the tenant this connection routes on, and refuse a blank identity.
816
826
  *
@@ -868,10 +878,22 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
868
878
  async handle(req, res) {
869
879
  res.setHeader("Cache-Control", "no-cache, no-transform");
870
880
  res.setHeader("X-Accel-Buffering", "no");
871
- const context = buildAuthContext(req);
872
- const auth = await this.transport.authenticate(context);
873
- if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
874
- const resolvedAuth = this.resolveAndValidateIdentity(auth);
881
+ const done = this.authenticated.get(req);
882
+ this.authenticated.delete(req);
883
+ let authenticated;
884
+ try {
885
+ authenticated = done ?? await this.authenticateRequest(req);
886
+ } catch (err) {
887
+ throw this.toClientError(err, "SSE authentication failed");
888
+ }
889
+ try {
890
+ return await this.openStream(req, res, authenticated);
891
+ } catch (err) {
892
+ throw this.serverError(err, "SSE handshake failed");
893
+ }
894
+ }
895
+ async openStream(req, res, authenticated) {
896
+ const { context, auth: resolvedAuth } = authenticated;
875
897
  const connectionId = crypto.randomUUID();
876
898
  const subject = new rxjs.Subject();
877
899
  const close$ = new rxjs.Subject();
@@ -894,6 +916,33 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
894
916
  queueEvents
895
917
  });
896
918
  }
919
+ /**
920
+ * Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
921
+ * `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
922
+ */
923
+ async authenticateBeforeCommit(req) {
924
+ try {
925
+ this.authenticated.set(req, await this.authenticateRequest(req));
926
+ } catch (err) {
927
+ throw this.toClientError(err, "SSE authentication failed");
928
+ }
929
+ }
930
+ // Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
931
+ toClientError(err, what) {
932
+ return err instanceof common.HttpException ? err : this.serverError(err, what);
933
+ }
934
+ serverError(err, what) {
935
+ this.logger.error(
936
+ `${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
937
+ );
938
+ return new common.InternalServerErrorException();
939
+ }
940
+ async authenticateRequest(req) {
941
+ const context = buildAuthContext(req);
942
+ const auth = await this.transport.authenticate(context);
943
+ if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
944
+ return { context, auth: this.resolveAndValidateIdentity(auth) };
945
+ }
897
946
  /**
898
947
  * Build the live Observable using a subscribe-before-register pattern.
899
948
  *
@@ -948,7 +997,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
948
997
  this.fireHook(
949
998
  () => this.hooks?.onError?.({ connectionId, error: err, transport: "sse" })
950
999
  );
951
- subscriber.error(err);
1000
+ subscriber.error(this.serverError(err, "SSE registration failed"));
952
1001
  });
953
1002
  }
954
1003
  /**
@@ -1005,6 +1054,20 @@ function normalizeEndpointPath(endpoint) {
1005
1054
  // src/server/factories/sse-controller.factory.ts
1006
1055
  function createSseController(endpoint) {
1007
1056
  const ssePath = normalizeEndpointPath(endpoint);
1057
+ let SseAuthGuard = class {
1058
+ constructor(handler) {
1059
+ this.handler = handler;
1060
+ }
1061
+ handler;
1062
+ async canActivate(context) {
1063
+ await this.handler.authenticateBeforeCommit(context.switchToHttp().getRequest());
1064
+ return true;
1065
+ }
1066
+ };
1067
+ SseAuthGuard = __decorateClass([
1068
+ common.Injectable(),
1069
+ __decorateParam(0, common.Inject(exports.SseSubscriptionHandler))
1070
+ ], SseAuthGuard);
1008
1071
  let DynamicSseController = class {
1009
1072
  // Explicit @Inject: the published bundle is built by esbuild/tsup, which does
1010
1073
  // not emit `design:paramtypes` decorator metadata, so constructor params must
@@ -1018,6 +1081,7 @@ function createSseController(endpoint) {
1018
1081
  }
1019
1082
  };
1020
1083
  __decorateClass([
1084
+ common.UseGuards(SseAuthGuard),
1021
1085
  common.Sse(ssePath),
1022
1086
  __decorateParam(0, common.Req()),
1023
1087
  __decorateParam(1, common.Res({ passthrough: true }))
@@ -648,9 +648,17 @@ declare class ConnectionRegistry {
648
648
  private readonly byId;
649
649
  private readonly byUserId;
650
650
  private readonly byTenantId;
651
- /** Register a connection and index it by user and tenant. */
651
+ /**
652
+ * Register a connection and index it by user and tenant.
653
+ *
654
+ * @internal Transport bookkeeping: applications must not call it.
655
+ */
652
656
  register(record: ConnectionRecord): void;
653
- /** Remove a connection from every index. Returns the removed record, if any. */
657
+ /**
658
+ * Remove a connection from every index. Returns the removed record, if any.
659
+ *
660
+ * @internal Transport bookkeeping: applications must not call it.
661
+ */
654
662
  unregister(connectionId: string): ConnectionRecord | undefined;
655
663
  /** Look up a single connection by id. */
656
664
  get(connectionId: string): ConnectionRecord | undefined;
@@ -1171,6 +1179,7 @@ declare class SseSubscriptionHandler {
1171
1179
  private readonly hooks?;
1172
1180
  private readonly offlineDelivery?;
1173
1181
  private readonly logger;
1182
+ private readonly authenticated;
1174
1183
  constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined);
1175
1184
  /**
1176
1185
  * Resolve the tenant this connection routes on, and refuse a blank identity.
@@ -1218,6 +1227,15 @@ declare class SseSubscriptionHandler {
1218
1227
  * written to the server log.
1219
1228
  */
1220
1229
  handle(req: SseRequest, res: SseResponse): Promise<Observable<MessageEvent>>;
1230
+ private openStream;
1231
+ /**
1232
+ * Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
1233
+ * `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
1234
+ */
1235
+ authenticateBeforeCommit(req: SseRequest): Promise<void>;
1236
+ private toClientError;
1237
+ private serverError;
1238
+ private authenticateRequest;
1221
1239
  /**
1222
1240
  * Build the live Observable using a subscribe-before-register pattern.
1223
1241
  *
@@ -1645,6 +1663,7 @@ declare const REALTIME_ERROR_CODES: {
1645
1663
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
1646
1664
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
1647
1665
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
1666
+ readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
1648
1667
  readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
1649
1668
  readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
1650
1669
  };
@@ -648,9 +648,17 @@ declare class ConnectionRegistry {
648
648
  private readonly byId;
649
649
  private readonly byUserId;
650
650
  private readonly byTenantId;
651
- /** Register a connection and index it by user and tenant. */
651
+ /**
652
+ * Register a connection and index it by user and tenant.
653
+ *
654
+ * @internal Transport bookkeeping: applications must not call it.
655
+ */
652
656
  register(record: ConnectionRecord): void;
653
- /** Remove a connection from every index. Returns the removed record, if any. */
657
+ /**
658
+ * Remove a connection from every index. Returns the removed record, if any.
659
+ *
660
+ * @internal Transport bookkeeping: applications must not call it.
661
+ */
654
662
  unregister(connectionId: string): ConnectionRecord | undefined;
655
663
  /** Look up a single connection by id. */
656
664
  get(connectionId: string): ConnectionRecord | undefined;
@@ -1171,6 +1179,7 @@ declare class SseSubscriptionHandler {
1171
1179
  private readonly hooks?;
1172
1180
  private readonly offlineDelivery?;
1173
1181
  private readonly logger;
1182
+ private readonly authenticated;
1174
1183
  constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined);
1175
1184
  /**
1176
1185
  * Resolve the tenant this connection routes on, and refuse a blank identity.
@@ -1218,6 +1227,15 @@ declare class SseSubscriptionHandler {
1218
1227
  * written to the server log.
1219
1228
  */
1220
1229
  handle(req: SseRequest, res: SseResponse): Promise<Observable<MessageEvent>>;
1230
+ private openStream;
1231
+ /**
1232
+ * Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
1233
+ * `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
1234
+ */
1235
+ authenticateBeforeCommit(req: SseRequest): Promise<void>;
1236
+ private toClientError;
1237
+ private serverError;
1238
+ private authenticateRequest;
1221
1239
  /**
1222
1240
  * Build the live Observable using a subscribe-before-register pattern.
1223
1241
  *
@@ -1645,6 +1663,7 @@ declare const REALTIME_ERROR_CODES: {
1645
1663
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
1646
1664
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
1647
1665
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
1666
+ readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
1648
1667
  readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
1649
1668
  readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
1650
1669
  };