@bymax-one/nest-realtime 1.2.0 → 1.2.2

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
@@ -5,6 +5,173 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [Unreleased]
9
+
10
+ ## [1.2.2] - 2026-10-31
11
+
12
+ ### Fixed
13
+
14
+ - **A refused WebSocket handshake is now a `connect_error` with a code, not a connect followed by a
15
+ silent disconnect.** The gateway authenticated in `handleConnection`, after Socket.IO had already
16
+ accepted the socket, so a client saw `connect` and then a bare `disconnect` with no reason it could
17
+ act on. Authentication now runs in a Socket.IO middleware on the handshake: a `null` result fails the
18
+ connection with `connect_error` carrying `err.data.code === 'REALTIME_AUTH_FAILED'`, and an
19
+ authenticator that throws fails it with a generic `Internal Server Error` that never carries the
20
+ thrown message. `authenticate()` still runs once per connection. **Apply note:** a client that
21
+ treated any `disconnect` as a refusal must now listen for `connect_error`
22
+ (`socket.on('connect_error', (err) => err.data?.code)`); `socket.active` is `false` after a
23
+ refusal, so Socket.IO does not reconnect on its own.
24
+
25
+ - **An SSE refusal that needs I/O is now a `401`, not a `200` followed by an error event.** The
26
+ SSE route returned the handler's promise and authenticated inside it. In an application with an
27
+ interceptor registered (a logging interceptor, for one), Nest commits `200 text/event-stream` from
28
+ a timer on the next macrotask, without waiting for that promise, so an authenticator that awaited
29
+ real I/O (a revocation or session lookup, a Redis read) before refusing lost the race. The client
30
+ had already received a `200`, then got
31
+ `event: error` with `REALTIME_AUTH_FAILED` and a closed stream, which a browser `EventSource`
32
+ treats as reconnectable and retries in a loop, while access logs recorded a `200` for refused
33
+ credentials. A refusal reached synchronously, or within microtasks (no cookie, a forged or expired
34
+ token checked in memory), got its `401`, and so did a late one in an application with no
35
+ interceptor. No connection was ever registered, so nothing was exposed.
36
+
37
+ Authentication now runs in a guard on the SSE route, which Nest awaits before the route and before
38
+ the stream starts, and the handler takes its result, so `authenticate()` still runs once per
39
+ connection. A refusal answers `401` (`REALTIME_AUTH_FAILED`), a blank identity `500` and an
40
+ authenticator that throws a `5xx`, whatever the authenticator awaited and whether or not an
41
+ interceptor is registered. Fixes
42
+ [#161](https://github.com/bymaxone/nest-realtime/issues/161).
43
+
44
+ The library also no longer lets an error's message reach the stream. Nest 11.2.3 writes the
45
+ message of an error raised after the stream has started into the `event: error` frame, so a
46
+ rejected connection registration, or a failure of another dependency after authentication, could
47
+ put text such as `connect ECONNREFUSED 10.20.30.40:6379` in front of the client. Any error that
48
+ is not an HTTP exception is now logged server-side and sent as a generic 500; an HTTP exception
49
+ an authenticator throws on purpose (a rate limit, say) is sent unchanged.
50
+
51
+ **Apply to a consumer.** Nothing to change. If you worked around the old behaviour by treating
52
+ an `error` event with `REALTIME_AUTH_FAILED` on a `200` stream as a refusal, that workaround can go:
53
+ the refusal is now the HTTP status, and `EventSource` stops on a `401` instead of reconnecting.
54
+ A test that asserted `200` for a refused connection should assert `401`.
55
+
56
+ ### Changed
57
+
58
+ - **`RealtimeGateway` now logs an error at start-up when the WebSocket adapter in use is not
59
+ `RealtimeIoAdapter`.** Under any other adapter the `websocket.*` options (`cors`, `namespace`,
60
+ `pingIntervalMs`, `pingTimeoutMs`, `maxHttpBufferSize`, `redisAdapter`) are dropped, and the
61
+ gateway's own CORS is `origin: false`, so a browser on another origin cannot connect. Nothing
62
+ reported this before. The message names the options it found and the fix,
63
+ `app.useWebSocketAdapter(new RealtimeIoAdapter(app))` in `main.ts`. It is a log line, not an
64
+ exception: an application that works today (same-origin, or Socket.IO's own defaults) keeps booting.
65
+
66
+ ### Internal
67
+
68
+ - `check:published` compiles every README snippet, not only the ones that import the package, through
69
+ the TypeScript API, so a parse-level elision in one snippet no longer hides the semantic errors in
70
+ the others. The names a snippet uses without declaring them are typed in
71
+ `scripts/readme-prelude.d.ts`, so a wrong method, option or destructured field is an error instead
72
+ of a call on `any`.
73
+ - `check:published` accepts a dot inside a relative module name (`./app.module`), which the path
74
+ allowlist added with the relative-import resolution rejected; `..` segments are still refused.
75
+ - `check:published` resolves a relative import in a README snippet to the snippet that exports the
76
+ imported names, and fails one that no snippet exports and no stub under `scripts/readme-modules/`
77
+ types, instead of ignoring it as an unresolved module that makes the names `any`.
78
+ - `check:published` tolerates a parse error in a README snippet only where the syntax tree shows a
79
+ bare `...` standing in for an argument, element or property, at that exact line and column, so a
80
+ real syntax error elsewhere in a snippet is no longer ignored.
81
+
82
+ ### Documentation
83
+
84
+ - **README:** a new step 7, "Add WebSocket", shows the complete working setup: the module from
85
+ `/websocket`, `RealtimeIoAdapter` in `main.ts` and `redisAdapter`. The README never named
86
+ `BymaxRealtimeWebSocketModule` or `RealtimeIoAdapter` before, and the sentence saying the Redis
87
+ adapter "is registered for you" omitted that this only happens once the adapter is installed.
88
+ Also documented: the error codes that are reserved and never raised today (`REALTIME_INVALID_TICKET`,
89
+ `REALTIME_PUBSUB_UNAVAILABLE`, `REALTIME_PAYLOAD_TOO_LARGE`, `REALTIME_REPLAY_BUFFER_MISS`) in a
90
+ status table; that presence is a contract and the server must emit `presence:*`; that the server
91
+ ignores events a WebSocket client sends; the per-entry-point option types, `PRESENCE_EVENT_NAMES`
92
+ and `UsePresenceReturn`; and that `RealtimeGateway`, `WebSocketTransport` and `CompositeTransport`
93
+ are exported for the module's own wiring.
94
+ A Troubleshooting entry quotes the start-up error verbatim, and a test fails if the README and the
95
+ message differ.
96
+ - `ConnectionRegistry.register` and `unregister` are tagged `@internal`: they are the transports'
97
+ own bookkeeping, and a record added by an application is counted by the lookups (an `sse` one also
98
+ suppresses offline-queue appends for that user) while nothing can be delivered to it.
99
+ - **README:** the Testing section no longer states a test count and a mutant count, which had
100
+ drifted from the suite (626 tests in 37 suites against 663 in 43; only the end-to-end count was
101
+ still right). It keeps the claims a gate enforces: 100% coverage and a mutation break threshold
102
+ of 100.
103
+
104
+ ### Tests
105
+
106
+ - `RealtimeIoAdapter` marks the servers and namespaces it creates, and `RealtimeGateway` checks
107
+ them in `afterInit`; both are covered, with the case of a server from another adapter.
108
+ - A spec parses the README and asserts it against the code: the `sse` and `reauthenticationPolicy`
109
+ defaults in the Configuration table, the error codes, the DI tokens and the reserved event names.
110
+ A default or a name that changes in code without the README now fails the suite.
111
+
112
+ ## [1.2.1] - 2026-10-30
113
+
114
+ **This version carries two behavioural breaks, both under Security below.** An authenticator that
115
+ returns a blank identity is now refused, and `tenantResolver` now runs on WebSocket connections.
116
+ Neither is a compile error: both change what a running backend does, so read "⚠️ Apply to a consumer"
117
+ before upgrading. Each closes a defect in which connections shared one delivery bucket or
118
+ were routed to a tenant that differed by transport.
119
+
120
+ ### Security
121
+
122
+ - **BREAKING (bootstrap-time): a blank identity is refused on both transports.** An authenticator
123
+ that returns `''` or a whitespace-only `userId`, or a present-but-blank `tenantId`, now fails the
124
+ connection. Such a value used to be indexed under an empty key and
125
+ joined to the room `user:` or `tenant:`, so every such connection shared one bucket and received
126
+ every emit addressed to it for the life of the subscription. An absent `tenantId` stays valid and
127
+ means no tenant.
128
+ - **BREAKING (behavioural): `tenantResolver` now runs on WebSocket connections**, as it already
129
+ did on SSE. It was read on the SSE path and ignored on the WebSocket path, so one user opening
130
+ both transports could be routed to two different tenants by the same configuration. Resolution
131
+ goes through one shared function, so a connection carries the same tenant on either transport,
132
+ and `null` is treated as absent. An application that relied on the resolver not running on
133
+ WebSocket was relying on that defect.
134
+ - Reauthentication now covers WebSocket connections, which previously kept delivering after their
135
+ credentials were revoked. Its failure meta reports the real `conn.transport` instead of a fixed
136
+ `'sse'`.
137
+
138
+ ### Changed
139
+
140
+ - `tenantResolver` may return `string | undefined | null`. Not breaking: a resolver typed
141
+ `() => string | undefined` still satisfies the wider signature.
142
+
143
+ ### Fixed
144
+
145
+ - `RealtimeIoAdapter` renamed its private logger field from `logger` to `adapterLogger`, so it cannot
146
+ collide with a member of the same name on the `IoAdapter` base class; behaviour is unchanged.
147
+
148
+ ### ⚠️ Apply to a consumer
149
+
150
+ - **Blank identity.** Make `authenticate()` return a non-empty `userId`, or `null` to reject the
151
+ connection. Omit `tenantId` for a connection that belongs to no tenant; do not return `''`. A
152
+ blank identity answers HTTP 500 with a generic body on SSE, and is disconnected on WebSocket;
153
+ both log the reason server-side, so a claim that can be blank (an unset `sub` or `tid`) shows up
154
+ as a failed connection rather than a shared room.
155
+ - **`tenantResolver` is honoured on WebSocket.** It now also receives WebSocket connections, and
156
+ it gets the `AuthenticationResult`, not the transport. A resolver that was only correct for SSE must be made
157
+ correct for both; returning `undefined` or `null` keeps `auth.tenantId`.
158
+ - **Reauthentication disconnects WebSocket connections.** They are now checked as well. If
159
+ `revalidate()` can return `false` for a credential that is still acceptable, those sockets are
160
+ now disconnected on the next cycle.
161
+
162
+ ### Documentation
163
+
164
+ - The README separates the authenticator path from the `tenantResolver` path for an absent tenant,
165
+ and lists which reserved events the library emits and which it only reserves.
166
+ - `IPresenceStorage` is documented as a contract the application drives; the library does not
167
+ emit `presence:*` events.
168
+ - `SECURITY.md` states that only the latest minor line (1.2.x) receives security fixes; its table listed
169
+ `0.1.x`.
170
+ - The architecture notes, the auth patterns and the nest-auth bridge example match the code: `authorization`
171
+ is dropped on SSE, `auth.token` and `auth.ticket` reach the authenticator through the header and
172
+ `ctx.query.ticket`, `RealtimeIoAdapter` is imported from `/websocket`, and `cacheTtlMs` only matters when it
173
+ exceeds `intervalSeconds`.
174
+
8
175
  ## [1.2.0] - 2026-08-29
9
176
 
10
177
  **Shipped as a minor, and two entries below are strictly speaking breaking.** Both are called
@@ -403,7 +570,9 @@ First published release.
403
570
  rather than by the manual sweep that raised the NestJS floors — that sweep
404
571
  asked about NestJS and never put the same question to the other ten peers.
405
572
 
406
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.0...HEAD
573
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.2...HEAD
574
+ [1.2.2]: https://github.com/bymaxone/nest-realtime/compare/v1.2.1...v1.2.2
575
+ [1.2.1]: https://github.com/bymaxone/nest-realtime/compare/v1.2.0...v1.2.1
407
576
  [1.2.0]: https://github.com/bymaxone/nest-realtime/compare/v1.1.2...v1.2.0
408
577
  [1.1.2]: https://github.com/bymaxone/nest-realtime/compare/v1.1.1...v1.1.2
409
578
  [1.1.1]: https://github.com/bymaxone/nest-realtime/compare/v1.1.0...v1.1.1
package/README.md CHANGED
@@ -74,13 +74,13 @@ pnpm add @bymax-one/nest-realtime
74
74
  - ✅ **Offline queue** — `IOfflineQueueStorage` holds events for absent users and flushes them on reconnect
75
75
  - ✅ **Replay buffer** — per-user ring buffer answers `Last-Event-ID` after a dropped SSE stream
76
76
  - ✅ **FIFO connection limits** — the oldest connection is evicted, so a new tab never gets a 429
77
- - ✅ **Presence** — optional `IPresenceStorage` powers `presence:online` / `presence:offline`
77
+ - ✅ **Presence contract** — optional `IPresenceStorage` seam and `usePresence()` hook; the library never calls the storage or emits `presence:*` itself, so your application does both
78
78
 
79
79
  ### 🧩 Developer Experience
80
80
 
81
81
  - ✅ **4 subpath exports** — server, WebSocket, shared types, and React; tree-shakeable, ESM + CJS dual output
82
82
  - ✅ **Dynamic module** — `forRoot()` and `forRootAsync()` with `useFactory` / `useClass` / `useExisting`
83
- - ✅ **Strict TypeScript, zero `any`** — `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` on
83
+ - ✅ **Strict TypeScript, zero `any`** — `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` enabled
84
84
  - ✅ **Horizontal scaling** — `IRealtimePubSub` for SSE fan-out, `@socket.io/redis-adapter` for WebSocket
85
85
  - ✅ **Bundle gate in CI** — the SSE-only React bundle is measured on every build and fails over budget
86
86
 
@@ -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. 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
 
@@ -305,11 +354,11 @@ All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `
305
354
  | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
306
355
  | **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
307
356
  | **authenticator** | `IConnectionAuthenticator` | — (**required**) |
308
- | **tenantResolver** | `(auth) => string \| undefined` — derives `tenantId` from the auth result | `auth.tenantId` |
357
+ | **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` |
309
358
  | **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed` (fire-and-forget) | — |
310
359
  | **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
311
360
  | **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
312
- | **presence** | `IPresenceStorage` — online-user tracking | — (disabled) |
361
+ | **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
313
362
  | **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `maxConnectionsPerUser`, `emitConnectionEvent` | `/realtime/sse`, `30000`, `100`, `5`, `true` |
314
363
  | **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults) |
315
364
  | **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs` | `300`, `'disconnect'`, `60000` |
@@ -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,12 +591,52 @@ 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
 
547
598
  Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePubSub`, `RedisOfflineQueue`.
548
599
 
600
+ #### Identity must be present or absent, never blank
601
+
602
+ `userId` must be a non-empty string, and `tenantId` must be either absent or a non-empty
603
+ string. A connection whose authenticator — or whose `tenantResolver` — yields a blank one is
604
+ **refused at bootstrap** rather than registered.
605
+
606
+ The reason is that blank is not missing. `userId` and `tenantId` key the connection registry
607
+ and compose the `user:` and `tenant:` rooms, so every connection carrying `''` lands under the
608
+ same key and joins the same room; a later emit to that key reaches all of them. On a long-lived
609
+ subscription that is not one wrong response but a stream that keeps delivering.
610
+
611
+ To place a connection in no tenant, the **authenticator omits `tenantId`** — that is indexed
612
+ under none and joins no tenant room, which an empty string is not. Whitespace counts as blank:
613
+ `' '` composes `user: ` just as `''` does.
614
+
615
+ Omission is the form to write, because it is the only one that compiles everywhere.
616
+ `AuthenticationResult` declares `tenantId?: string`; the runtime accepts an explicit `undefined`
617
+ or `null` too — an untyped claim spread into the result produces them routinely — but whether
618
+ either *type-checks* depends on the consuming project's `tsconfig`, which the published
619
+ declarations do not control:
620
+
621
+ | consumer's `tsconfig` | `tenantId: undefined` | `tenantId: null` |
622
+ | ----------------------------------------- | --------------------- | ---------------- |
623
+ | `strict` + `exactOptionalPropertyTypes` | `TS2375` | `TS2322` |
624
+ | `strict`, no `exactOptionalPropertyTypes` | compiles | `TS2322` |
625
+ | no `strictNullChecks` | compiles | compiles |
626
+
627
+ Omitting the key is correct in all three.
628
+
629
+ `tenantResolver` cannot clear a tenant, and this is the one asymmetry worth reading twice.
630
+ Resolution is `tenantResolver?.(auth) ?? auth.tenantId`, so a resolver returning `undefined` or
631
+ `null` means *no opinion* and falls back to the tenant the authenticator supplied. A resolver
632
+ written to place a connection in no tenant by returning `null` leaves it in `auth.tenantId`'s
633
+ room instead, still receiving that tenant's events. Decide the absent case in the
634
+ authenticator, where absence is what it looks like.
635
+
636
+ A blank identity surfaces as a server fault rather than a `401`, because the client's
637
+ credentials were accepted and the fault is in the authenticator. Return `null` to reject a
638
+ client.
639
+
549
640
  #### Carrying handshake context into the hooks
550
641
 
551
642
  `AuthenticationResult.metadata` is a free-form bag the library carries verbatim: it reaches
@@ -593,6 +684,21 @@ composeRoomId('TENANT', tenantId) // → "tenant:t_acme"
593
684
  composeRoomId('RESOURCE', 'invoice', invoiceId) // → "resource:invoice:42"
594
685
  ```
595
686
 
687
+ `composeRoomId` joins its parts with `:` and escapes nothing, so a part must not contain `:`. The `encodeURIComponent` advice below holds for that `:` separator only, because it escapes `:` and leaves characters such as `-`, `.`, `_` and `~` alone.
688
+ `('a:b', 'c')` and `('a', 'b:c')` both give `resource:a:b:c` and land in the same room. When a
689
+ part comes from outside your code, encode it first:
690
+ `composeRoomId('RESOURCE', encodeURIComponent(type), encodeURIComponent(id))`.
691
+
692
+ A `resource:` room is not tenant-scoped: two tenants using the same type and id share it. When ids
693
+ are only unique within a tenant, pass the tenant as its own encoded part —
694
+ `composeRoomId('RESOURCE', 'invoice', encodeURIComponent(tenantId), encodeURIComponent(id))` —
695
+ because gluing them into one part with a separator that ids may contain, such as `-`, lets two
696
+ different pairs compose the same room.
697
+
698
+ Never pass client-supplied input to `joinRoom` or `emitToRoom` as a room id without checking that
699
+ it cannot start with the reserved `user:` or `tenant:` prefixes. The library does not guard them,
700
+ and joining `tenant:<other>` receives that tenant's events.
701
+
596
702
  #### Role-scoped delivery
597
703
 
598
704
  There is no `emitToRole`. Roles are the consumer's authorization vocabulary, not
@@ -692,23 +798,40 @@ const onConnect = joinRoleRoom({ get: () => ({ joinRoom }) }, 'admin', 'role:adm
692
798
 
693
799
  ### Reserved Events
694
800
 
695
- Emitted by the library. Do not reuse these names 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`).
802
+
803
+ **Emitted today**
804
+
805
+ | Event | Meaning |
806
+ | ------------------------------------ | ------------------------------------------------------- |
807
+ | `connection:established` | Handshake accepted (suppress via `emitConnectionEvent`) |
808
+ | `connection:reauthentication-failed` | Credentials no longer valid |
809
+
810
+ **Reserved, not emitted by the library.** An application may emit them itself; the library never does. The default SSE client subscribes to all of them except `error`. The browser dispatches a server-sent `error` event to the same handler as its own connection failures, so do not emit `error` over SSE: the client treats it as a dropped connection.
696
811
 
697
- | Event | Meaning |
698
- | -------------------------------------- | ------------------------------------------------------- |
699
- | `connection:established` | Handshake accepted (suppress via `emitConnectionEvent`) |
700
- | `connection:reauthentication-failed` | Credentials no longer valid |
701
- | `connection:credential-expiring` | Credential nearing expiry |
702
- | `room:joined` / `room:left` | Room membership changed |
703
- | `error` | Transport-level error |
704
- | `presence:online` / `presence:offline` | Presence changed (requires `IPresenceStorage`) |
812
+ | Event | Meaning |
813
+ | -------------------------------------- | -------------------------------------------------------------------- |
814
+ | `connection:credential-expiring` | Credential nearing expiry |
815
+ | `room:joined` / `room:left` | Room membership changed |
816
+ | `error` | Transport-level error |
817
+ | `presence:online` / `presence:offline` | Presence changed; emitted by your code, `IPresenceStorage` is a seam |
705
818
 
706
819
  > [!NOTE]
707
820
  > The SSE heartbeat is a `: keepalive` **comment line**, not a named event. It never appears in the `Last-Event-ID` id-space and never reaches a client listener.
708
821
 
709
822
  ### Error Codes
710
823
 
711
- `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_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
834
+ | `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
712
835
 
713
836
  ### DI Tokens
714
837
 
@@ -721,7 +844,7 @@ Emitted by the library. Do not reuse these names for application events.
721
844
  | `useRealtime(options)` | `{ transport, connected, events, lastEvent, error, reconnectAttempts, reconnect, emit }` — opens the connection |
722
845
  | `useRealtimeContext()` | The same value, from the nearest `<RealtimeProvider>` — throws when used outside one |
723
846
  | `useRealtimeConnection(options)` | `{ connected, error, reconnectAttempts, reconnect }` — status only, no events array |
724
- | `usePresence()` | `{ onlineUserIds, isOnline(userId), count }` — reads presence events from the provider |
847
+ | `usePresence()` | `UsePresenceReturn`: `{ onlineUserIds, isOnline(userId), count }` — reads `presence:*` events from the provider; your server must emit them |
725
848
 
726
849
  `RealtimeProvider` takes a single `options` prop of type `UseRealtimeOptions`:
727
850
 
@@ -738,7 +861,7 @@ Emitted by the library. Do not reuse these names for application events.
738
861
  | `maxAttempts` | `number` | — (unlimited) | **SSE only** — give up and close after N failures |
739
862
 
740
863
  > [!NOTE]
741
- > `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.
864
+ > `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.
742
865
 
743
866
  ---
744
867
 
@@ -756,6 +879,16 @@ SSE connections are long-lived HTTP responses, and several common proxy defaults
756
879
 
757
880
  Platform-specific configuration is in [docs/proxies-cheat-sheet.md](./docs/proxies-cheat-sheet.md).
758
881
 
882
+ ### Troubleshooting
883
+
884
+ **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`:
885
+
886
+ ```
887
+ 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'.
888
+ ```
889
+
890
+ 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.
891
+
759
892
  ---
760
893
 
761
894
  ## 🤝 Contributing