@bymax-one/nest-realtime 1.2.1 → 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 +104 -1
- package/README.md +81 -10
- package/dist/internal/index.cjs +70 -7
- package/dist/internal/index.d.cts +20 -2
- package/dist/internal/index.d.ts +20 -2
- package/dist/internal/index.mjs +71 -8
- package/dist/websocket/index.cjs +122 -77
- package/dist/websocket/index.d.cts +6 -0
- package/dist/websocket/index.d.ts +6 -0
- package/dist/websocket/index.mjs +123 -78
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,108 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
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
|
+
|
|
10
112
|
## [1.2.1] - 2026-10-30
|
|
11
113
|
|
|
12
114
|
**This version carries two behavioural breaks, both under Security below.** An authenticator that
|
|
@@ -468,7 +570,8 @@ First published release.
|
|
|
468
570
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
469
571
|
asked about NestJS and never put the same question to the other ten peers.
|
|
470
572
|
|
|
471
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
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
|
|
472
575
|
[1.2.1]: https://github.com/bymaxone/nest-realtime/compare/v1.2.0...v1.2.1
|
|
473
576
|
[1.2.0]: https://github.com/bymaxone/nest-realtime/compare/v1.1.2...v1.2.0
|
|
474
577
|
[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,
|
|
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
|
|
|
@@ -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
|
|
483
|
-
- ✅ **
|
|
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` | — |
|
|
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,17 @@ These names belong to the library. Do not reuse them for application events.
|
|
|
770
821
|
|
|
771
822
|
### Error Codes
|
|
772
823
|
|
|
773
|
-
|
|
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 |
|
|
774
835
|
|
|
775
836
|
### DI Tokens
|
|
776
837
|
|
|
@@ -783,7 +844,7 @@ These names belong to the library. Do not reuse them for application events.
|
|
|
783
844
|
| `useRealtime(options)` | `{ transport, connected, events, lastEvent, error, reconnectAttempts, reconnect, emit }` — opens the connection |
|
|
784
845
|
| `useRealtimeContext()` | The same value, from the nearest `<RealtimeProvider>` — throws when used outside one |
|
|
785
846
|
| `useRealtimeConnection(options)` | `{ connected, error, reconnectAttempts, reconnect }` — status only, no events array |
|
|
786
|
-
| `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 |
|
|
787
848
|
|
|
788
849
|
`RealtimeProvider` takes a single `options` prop of type `UseRealtimeOptions`:
|
|
789
850
|
|
|
@@ -800,7 +861,7 @@ These names belong to the library. Do not reuse them for application events.
|
|
|
800
861
|
| `maxAttempts` | `number` | — (unlimited) | **SSE only** — give up and close after N failures |
|
|
801
862
|
|
|
802
863
|
> [!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.
|
|
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.
|
|
804
865
|
|
|
805
866
|
---
|
|
806
867
|
|
|
@@ -818,6 +879,16 @@ SSE connections are long-lived HTTP responses, and several common proxy defaults
|
|
|
818
879
|
|
|
819
880
|
Platform-specific configuration is in [docs/proxies-cheat-sheet.md](./docs/proxies-cheat-sheet.md).
|
|
820
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
|
+
|
|
821
892
|
---
|
|
822
893
|
|
|
823
894
|
## 🤝 Contributing
|
package/dist/internal/index.cjs
CHANGED
|
@@ -219,7 +219,11 @@ exports.ConnectionRegistry = class ConnectionRegistry {
|
|
|
219
219
|
byId = /* @__PURE__ */ new Map();
|
|
220
220
|
byUserId = /* @__PURE__ */ new Map();
|
|
221
221
|
byTenantId = /* @__PURE__ */ new Map();
|
|
222
|
-
/**
|
|
222
|
+
/**
|
|
223
|
+
* Register a connection and index it by user and tenant.
|
|
224
|
+
*
|
|
225
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
226
|
+
*/
|
|
223
227
|
register(record) {
|
|
224
228
|
this.byId.set(record.connectionId, record);
|
|
225
229
|
this.addToSetMap(this.byUserId, record.userId, record.connectionId);
|
|
@@ -227,7 +231,11 @@ exports.ConnectionRegistry = class ConnectionRegistry {
|
|
|
227
231
|
this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
|
|
228
232
|
}
|
|
229
233
|
}
|
|
230
|
-
/**
|
|
234
|
+
/**
|
|
235
|
+
* Remove a connection from every index. Returns the removed record, if any.
|
|
236
|
+
*
|
|
237
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
238
|
+
*/
|
|
231
239
|
unregister(connectionId) {
|
|
232
240
|
const record = this.byId.get(connectionId);
|
|
233
241
|
if (!record) return void 0;
|
|
@@ -811,6 +819,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
811
819
|
hooks;
|
|
812
820
|
offlineDelivery;
|
|
813
821
|
logger = new common.Logger(exports.SseSubscriptionHandler.name);
|
|
822
|
+
authenticated = /* @__PURE__ */ new WeakMap();
|
|
814
823
|
/**
|
|
815
824
|
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
816
825
|
*
|
|
@@ -868,10 +877,22 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
868
877
|
async handle(req, res) {
|
|
869
878
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
870
879
|
res.setHeader("X-Accel-Buffering", "no");
|
|
871
|
-
const
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
880
|
+
const done = this.authenticated.get(req);
|
|
881
|
+
this.authenticated.delete(req);
|
|
882
|
+
let authenticated;
|
|
883
|
+
try {
|
|
884
|
+
authenticated = done ?? await this.authenticateRequest(req);
|
|
885
|
+
} catch (err) {
|
|
886
|
+
throw this.toClientError(err, "SSE authentication failed");
|
|
887
|
+
}
|
|
888
|
+
try {
|
|
889
|
+
return await this.openStream(req, res, authenticated);
|
|
890
|
+
} catch (err) {
|
|
891
|
+
throw this.serverError(err, "SSE handshake failed");
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
async openStream(req, res, authenticated) {
|
|
895
|
+
const { context, auth: resolvedAuth } = authenticated;
|
|
875
896
|
const connectionId = crypto.randomUUID();
|
|
876
897
|
const subject = new rxjs.Subject();
|
|
877
898
|
const close$ = new rxjs.Subject();
|
|
@@ -894,6 +915,33 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
894
915
|
queueEvents
|
|
895
916
|
});
|
|
896
917
|
}
|
|
918
|
+
/**
|
|
919
|
+
* Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
|
|
920
|
+
* `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
|
|
921
|
+
*/
|
|
922
|
+
async authenticateBeforeCommit(req) {
|
|
923
|
+
try {
|
|
924
|
+
this.authenticated.set(req, await this.authenticateRequest(req));
|
|
925
|
+
} catch (err) {
|
|
926
|
+
throw this.toClientError(err, "SSE authentication failed");
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
// Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
|
|
930
|
+
toClientError(err, what) {
|
|
931
|
+
return err instanceof common.HttpException ? err : this.serverError(err, what);
|
|
932
|
+
}
|
|
933
|
+
serverError(err, what) {
|
|
934
|
+
this.logger.error(
|
|
935
|
+
`${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
|
|
936
|
+
);
|
|
937
|
+
return new common.InternalServerErrorException();
|
|
938
|
+
}
|
|
939
|
+
async authenticateRequest(req) {
|
|
940
|
+
const context = buildAuthContext(req);
|
|
941
|
+
const auth = await this.transport.authenticate(context);
|
|
942
|
+
if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
943
|
+
return { context, auth: this.resolveAndValidateIdentity(auth) };
|
|
944
|
+
}
|
|
897
945
|
/**
|
|
898
946
|
* Build the live Observable using a subscribe-before-register pattern.
|
|
899
947
|
*
|
|
@@ -948,7 +996,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
948
996
|
this.fireHook(
|
|
949
997
|
() => this.hooks?.onError?.({ connectionId, error: err, transport: "sse" })
|
|
950
998
|
);
|
|
951
|
-
subscriber.error(err);
|
|
999
|
+
subscriber.error(this.serverError(err, "SSE registration failed"));
|
|
952
1000
|
});
|
|
953
1001
|
}
|
|
954
1002
|
/**
|
|
@@ -1005,6 +1053,20 @@ function normalizeEndpointPath(endpoint) {
|
|
|
1005
1053
|
// src/server/factories/sse-controller.factory.ts
|
|
1006
1054
|
function createSseController(endpoint) {
|
|
1007
1055
|
const ssePath = normalizeEndpointPath(endpoint);
|
|
1056
|
+
let SseAuthGuard = class {
|
|
1057
|
+
constructor(handler) {
|
|
1058
|
+
this.handler = handler;
|
|
1059
|
+
}
|
|
1060
|
+
handler;
|
|
1061
|
+
async canActivate(context) {
|
|
1062
|
+
await this.handler.authenticateBeforeCommit(context.switchToHttp().getRequest());
|
|
1063
|
+
return true;
|
|
1064
|
+
}
|
|
1065
|
+
};
|
|
1066
|
+
SseAuthGuard = __decorateClass([
|
|
1067
|
+
common.Injectable(),
|
|
1068
|
+
__decorateParam(0, common.Inject(exports.SseSubscriptionHandler))
|
|
1069
|
+
], SseAuthGuard);
|
|
1008
1070
|
let DynamicSseController = class {
|
|
1009
1071
|
// Explicit @Inject: the published bundle is built by esbuild/tsup, which does
|
|
1010
1072
|
// not emit `design:paramtypes` decorator metadata, so constructor params must
|
|
@@ -1018,6 +1080,7 @@ function createSseController(endpoint) {
|
|
|
1018
1080
|
}
|
|
1019
1081
|
};
|
|
1020
1082
|
__decorateClass([
|
|
1083
|
+
common.UseGuards(SseAuthGuard),
|
|
1021
1084
|
common.Sse(ssePath),
|
|
1022
1085
|
__decorateParam(0, common.Req()),
|
|
1023
1086
|
__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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
*
|
package/dist/internal/index.d.ts
CHANGED
|
@@ -648,9 +648,17 @@ declare class ConnectionRegistry {
|
|
|
648
648
|
private readonly byId;
|
|
649
649
|
private readonly byUserId;
|
|
650
650
|
private readonly byTenantId;
|
|
651
|
-
/**
|
|
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
|
-
/**
|
|
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
|
*
|
package/dist/internal/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'crypto';
|
|
2
|
-
import { Injectable, Optional, Inject, Logger, Global, Module, Sse, Req, Res, Controller, InternalServerErrorException, UnauthorizedException } from '@nestjs/common';
|
|
2
|
+
import { Injectable, Optional, Inject, Logger, Global, Module, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, HttpException, UnauthorizedException } from '@nestjs/common';
|
|
3
3
|
import { Subject, of, EMPTY, Observable, merge } from 'rxjs';
|
|
4
4
|
import { takeUntil, catchError, finalize } from 'rxjs/operators';
|
|
5
5
|
|
|
@@ -217,7 +217,11 @@ var ConnectionRegistry = class {
|
|
|
217
217
|
byId = /* @__PURE__ */ new Map();
|
|
218
218
|
byUserId = /* @__PURE__ */ new Map();
|
|
219
219
|
byTenantId = /* @__PURE__ */ new Map();
|
|
220
|
-
/**
|
|
220
|
+
/**
|
|
221
|
+
* Register a connection and index it by user and tenant.
|
|
222
|
+
*
|
|
223
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
224
|
+
*/
|
|
221
225
|
register(record) {
|
|
222
226
|
this.byId.set(record.connectionId, record);
|
|
223
227
|
this.addToSetMap(this.byUserId, record.userId, record.connectionId);
|
|
@@ -225,7 +229,11 @@ var ConnectionRegistry = class {
|
|
|
225
229
|
this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
|
|
226
230
|
}
|
|
227
231
|
}
|
|
228
|
-
/**
|
|
232
|
+
/**
|
|
233
|
+
* Remove a connection from every index. Returns the removed record, if any.
|
|
234
|
+
*
|
|
235
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
236
|
+
*/
|
|
229
237
|
unregister(connectionId) {
|
|
230
238
|
const record = this.byId.get(connectionId);
|
|
231
239
|
if (!record) return void 0;
|
|
@@ -809,6 +817,7 @@ var SseSubscriptionHandler = class {
|
|
|
809
817
|
hooks;
|
|
810
818
|
offlineDelivery;
|
|
811
819
|
logger = new Logger(SseSubscriptionHandler.name);
|
|
820
|
+
authenticated = /* @__PURE__ */ new WeakMap();
|
|
812
821
|
/**
|
|
813
822
|
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
814
823
|
*
|
|
@@ -866,10 +875,22 @@ var SseSubscriptionHandler = class {
|
|
|
866
875
|
async handle(req, res) {
|
|
867
876
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
868
877
|
res.setHeader("X-Accel-Buffering", "no");
|
|
869
|
-
const
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
878
|
+
const done = this.authenticated.get(req);
|
|
879
|
+
this.authenticated.delete(req);
|
|
880
|
+
let authenticated;
|
|
881
|
+
try {
|
|
882
|
+
authenticated = done ?? await this.authenticateRequest(req);
|
|
883
|
+
} catch (err) {
|
|
884
|
+
throw this.toClientError(err, "SSE authentication failed");
|
|
885
|
+
}
|
|
886
|
+
try {
|
|
887
|
+
return await this.openStream(req, res, authenticated);
|
|
888
|
+
} catch (err) {
|
|
889
|
+
throw this.serverError(err, "SSE handshake failed");
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
async openStream(req, res, authenticated) {
|
|
893
|
+
const { context, auth: resolvedAuth } = authenticated;
|
|
873
894
|
const connectionId = randomUUID();
|
|
874
895
|
const subject = new Subject();
|
|
875
896
|
const close$ = new Subject();
|
|
@@ -892,6 +913,33 @@ var SseSubscriptionHandler = class {
|
|
|
892
913
|
queueEvents
|
|
893
914
|
});
|
|
894
915
|
}
|
|
916
|
+
/**
|
|
917
|
+
* Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
|
|
918
|
+
* `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
|
|
919
|
+
*/
|
|
920
|
+
async authenticateBeforeCommit(req) {
|
|
921
|
+
try {
|
|
922
|
+
this.authenticated.set(req, await this.authenticateRequest(req));
|
|
923
|
+
} catch (err) {
|
|
924
|
+
throw this.toClientError(err, "SSE authentication failed");
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
// Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
|
|
928
|
+
toClientError(err, what) {
|
|
929
|
+
return err instanceof HttpException ? err : this.serverError(err, what);
|
|
930
|
+
}
|
|
931
|
+
serverError(err, what) {
|
|
932
|
+
this.logger.error(
|
|
933
|
+
`${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
|
|
934
|
+
);
|
|
935
|
+
return new InternalServerErrorException();
|
|
936
|
+
}
|
|
937
|
+
async authenticateRequest(req) {
|
|
938
|
+
const context = buildAuthContext(req);
|
|
939
|
+
const auth = await this.transport.authenticate(context);
|
|
940
|
+
if (!auth) throw new UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
941
|
+
return { context, auth: this.resolveAndValidateIdentity(auth) };
|
|
942
|
+
}
|
|
895
943
|
/**
|
|
896
944
|
* Build the live Observable using a subscribe-before-register pattern.
|
|
897
945
|
*
|
|
@@ -946,7 +994,7 @@ var SseSubscriptionHandler = class {
|
|
|
946
994
|
this.fireHook(
|
|
947
995
|
() => this.hooks?.onError?.({ connectionId, error: err, transport: "sse" })
|
|
948
996
|
);
|
|
949
|
-
subscriber.error(err);
|
|
997
|
+
subscriber.error(this.serverError(err, "SSE registration failed"));
|
|
950
998
|
});
|
|
951
999
|
}
|
|
952
1000
|
/**
|
|
@@ -1003,6 +1051,20 @@ function normalizeEndpointPath(endpoint) {
|
|
|
1003
1051
|
// src/server/factories/sse-controller.factory.ts
|
|
1004
1052
|
function createSseController(endpoint) {
|
|
1005
1053
|
const ssePath = normalizeEndpointPath(endpoint);
|
|
1054
|
+
let SseAuthGuard = class {
|
|
1055
|
+
constructor(handler) {
|
|
1056
|
+
this.handler = handler;
|
|
1057
|
+
}
|
|
1058
|
+
handler;
|
|
1059
|
+
async canActivate(context) {
|
|
1060
|
+
await this.handler.authenticateBeforeCommit(context.switchToHttp().getRequest());
|
|
1061
|
+
return true;
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
SseAuthGuard = __decorateClass([
|
|
1065
|
+
Injectable(),
|
|
1066
|
+
__decorateParam(0, Inject(SseSubscriptionHandler))
|
|
1067
|
+
], SseAuthGuard);
|
|
1006
1068
|
let DynamicSseController = class {
|
|
1007
1069
|
// Explicit @Inject: the published bundle is built by esbuild/tsup, which does
|
|
1008
1070
|
// not emit `design:paramtypes` decorator metadata, so constructor params must
|
|
@@ -1016,6 +1078,7 @@ function createSseController(endpoint) {
|
|
|
1016
1078
|
}
|
|
1017
1079
|
};
|
|
1018
1080
|
__decorateClass([
|
|
1081
|
+
UseGuards(SseAuthGuard),
|
|
1019
1082
|
Sse(ssePath),
|
|
1020
1083
|
__decorateParam(0, Req()),
|
|
1021
1084
|
__decorateParam(1, Res({ passthrough: true }))
|
package/dist/websocket/index.cjs
CHANGED
|
@@ -393,6 +393,86 @@ exports.CompositeTransport = __decorateClass([
|
|
|
393
393
|
__decorateParam(0, common.Inject(internal.SseTransport)),
|
|
394
394
|
__decorateParam(1, common.Inject(exports.WebSocketTransport))
|
|
395
395
|
], exports.CompositeTransport);
|
|
396
|
+
var realtimeServers = /* @__PURE__ */ new WeakSet();
|
|
397
|
+
function isRealtimeIoServer(server) {
|
|
398
|
+
return typeof server === "object" && server !== null && realtimeServers.has(server);
|
|
399
|
+
}
|
|
400
|
+
var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
|
|
401
|
+
adapterLogger = new common.Logger(_RealtimeIoAdapter.name);
|
|
402
|
+
options;
|
|
403
|
+
constructor(app) {
|
|
404
|
+
super(app);
|
|
405
|
+
this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Bind the gateway to `websocket.namespace` when configured.
|
|
409
|
+
*
|
|
410
|
+
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
411
|
+
* the module options resolve — so the namespace cannot be declared there.
|
|
412
|
+
* Instead we build the root server via `super.create` (which routes through the
|
|
413
|
+
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
414
|
+
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
415
|
+
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
416
|
+
* namespace leaves the root server untouched.
|
|
417
|
+
*/
|
|
418
|
+
create(port, options) {
|
|
419
|
+
const server = super.create(port, options);
|
|
420
|
+
const ns = this.options.websocket?.namespace;
|
|
421
|
+
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
422
|
+
const namespace = server.of(ns);
|
|
423
|
+
realtimeServers.add(namespace);
|
|
424
|
+
return namespace;
|
|
425
|
+
}
|
|
426
|
+
return server;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Create the Socket.IO server with merged WebSocket options.
|
|
430
|
+
*
|
|
431
|
+
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
432
|
+
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
433
|
+
* dep — its absence does not crash the lib).
|
|
434
|
+
*/
|
|
435
|
+
createIOServer(port, opts) {
|
|
436
|
+
const wsOpts = this.options.websocket ?? {};
|
|
437
|
+
const mergedOpts = {
|
|
438
|
+
...opts,
|
|
439
|
+
cors: wsOpts.cors ?? opts?.cors,
|
|
440
|
+
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
441
|
+
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
442
|
+
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
443
|
+
};
|
|
444
|
+
const server = super.createIOServer(port, mergedOpts);
|
|
445
|
+
if (wsOpts.redisAdapter?.pubClient) {
|
|
446
|
+
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
447
|
+
}
|
|
448
|
+
realtimeServers.add(server);
|
|
449
|
+
return server;
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Lazily load and install `@socket.io/redis-adapter`.
|
|
453
|
+
*
|
|
454
|
+
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
455
|
+
* not crash the lib. A load or install failure is logged and tolerated;
|
|
456
|
+
* the lib degrades gracefully to single-instance mode.
|
|
457
|
+
*/
|
|
458
|
+
installRedisAdapter(server, pubClient) {
|
|
459
|
+
try {
|
|
460
|
+
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
461
|
+
const pub = pubClient;
|
|
462
|
+
const sub = pub.duplicate();
|
|
463
|
+
server.adapter(createAdapter(pub, sub));
|
|
464
|
+
this.adapterLogger.log(
|
|
465
|
+
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
466
|
+
);
|
|
467
|
+
} catch (err) {
|
|
468
|
+
this.adapterLogger.error(
|
|
469
|
+
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
// src/websocket/transports/websocket/realtime.gateway.ts
|
|
396
476
|
function firstQueryValue(value) {
|
|
397
477
|
return Array.isArray(value) ? value[0] : value;
|
|
398
478
|
}
|
|
@@ -405,11 +485,43 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
405
485
|
options;
|
|
406
486
|
logger = new common.Logger(exports.RealtimeGateway.name);
|
|
407
487
|
server;
|
|
488
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
489
|
+
authenticated = /* @__PURE__ */ new WeakMap();
|
|
490
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
491
|
+
authenticateHandshake = async (socket, next) => {
|
|
492
|
+
try {
|
|
493
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
494
|
+
if (!auth) {
|
|
495
|
+
const refusal = new Error(internal.REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
496
|
+
refusal.data = { code: internal.REALTIME_ERROR_CODES.AUTH_FAILED };
|
|
497
|
+
next(refusal);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
501
|
+
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
502
|
+
this.authenticated.set(socket, resolvedAuth);
|
|
503
|
+
next();
|
|
504
|
+
} catch (err) {
|
|
505
|
+
this.logger.error(
|
|
506
|
+
`handshake refused for socket ${socket.id}: ${err instanceof Error ? err.message : String(err)}`
|
|
507
|
+
);
|
|
508
|
+
next(new Error("Internal Server Error"));
|
|
509
|
+
}
|
|
510
|
+
};
|
|
408
511
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
409
512
|
afterInit(server) {
|
|
513
|
+
server.use(this.authenticateHandshake);
|
|
410
514
|
this.transport.setServer(server);
|
|
515
|
+
if (!isRealtimeIoServer(server)) this.reportMissingAdapter();
|
|
411
516
|
this.logger.log("RealtimeGateway initialized");
|
|
412
517
|
}
|
|
518
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
519
|
+
reportMissingAdapter() {
|
|
520
|
+
const configured = Object.keys(this.options.websocket ?? {});
|
|
521
|
+
this.logger.error(
|
|
522
|
+
"RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options" + (configured.length > 0 ? ` (${configured.join(", ")})` : "") + " 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'."
|
|
523
|
+
);
|
|
524
|
+
}
|
|
413
525
|
/**
|
|
414
526
|
* Handle a new WebSocket connection.
|
|
415
527
|
*
|
|
@@ -462,13 +574,17 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
462
574
|
}
|
|
463
575
|
async handleConnection(socket) {
|
|
464
576
|
try {
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
577
|
+
let resolvedAuth = this.authenticated.get(socket);
|
|
578
|
+
this.authenticated.delete(socket);
|
|
579
|
+
if (!resolvedAuth) {
|
|
580
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
581
|
+
if (!auth) {
|
|
582
|
+
socket.disconnect(true);
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
586
|
+
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
469
587
|
}
|
|
470
|
-
const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
471
|
-
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
472
588
|
await this.transport.registerSocket(socket, resolvedAuth);
|
|
473
589
|
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
474
590
|
socket.emit(internal.RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
|
|
@@ -632,76 +748,5 @@ exports.BymaxRealtimeWebSocketModule = __decorateClass([
|
|
|
632
748
|
common.Global(),
|
|
633
749
|
common.Module({})
|
|
634
750
|
], exports.BymaxRealtimeWebSocketModule);
|
|
635
|
-
var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
|
|
636
|
-
adapterLogger = new common.Logger(_RealtimeIoAdapter.name);
|
|
637
|
-
options;
|
|
638
|
-
constructor(app) {
|
|
639
|
-
super(app);
|
|
640
|
-
this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
|
|
641
|
-
}
|
|
642
|
-
/**
|
|
643
|
-
* Bind the gateway to `websocket.namespace` when configured.
|
|
644
|
-
*
|
|
645
|
-
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
646
|
-
* the module options resolve — so the namespace cannot be declared there.
|
|
647
|
-
* Instead we build the root server via `super.create` (which routes through the
|
|
648
|
-
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
649
|
-
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
650
|
-
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
651
|
-
* namespace leaves the root server untouched.
|
|
652
|
-
*/
|
|
653
|
-
create(port, options) {
|
|
654
|
-
const server = super.create(port, options);
|
|
655
|
-
const ns = this.options.websocket?.namespace;
|
|
656
|
-
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
657
|
-
return server.of(ns);
|
|
658
|
-
}
|
|
659
|
-
return server;
|
|
660
|
-
}
|
|
661
|
-
/**
|
|
662
|
-
* Create the Socket.IO server with merged WebSocket options.
|
|
663
|
-
*
|
|
664
|
-
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
665
|
-
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
666
|
-
* dep — its absence does not crash the lib).
|
|
667
|
-
*/
|
|
668
|
-
createIOServer(port, opts) {
|
|
669
|
-
const wsOpts = this.options.websocket ?? {};
|
|
670
|
-
const mergedOpts = {
|
|
671
|
-
...opts,
|
|
672
|
-
cors: wsOpts.cors ?? opts?.cors,
|
|
673
|
-
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
674
|
-
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
675
|
-
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
676
|
-
};
|
|
677
|
-
const server = super.createIOServer(port, mergedOpts);
|
|
678
|
-
if (wsOpts.redisAdapter?.pubClient) {
|
|
679
|
-
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
680
|
-
}
|
|
681
|
-
return server;
|
|
682
|
-
}
|
|
683
|
-
/**
|
|
684
|
-
* Lazily load and install `@socket.io/redis-adapter`.
|
|
685
|
-
*
|
|
686
|
-
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
687
|
-
* not crash the lib. A load or install failure is logged and tolerated;
|
|
688
|
-
* the lib degrades gracefully to single-instance mode.
|
|
689
|
-
*/
|
|
690
|
-
installRedisAdapter(server, pubClient) {
|
|
691
|
-
try {
|
|
692
|
-
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
693
|
-
const pub = pubClient;
|
|
694
|
-
const sub = pub.duplicate();
|
|
695
|
-
server.adapter(createAdapter(pub, sub));
|
|
696
|
-
this.adapterLogger.log(
|
|
697
|
-
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
698
|
-
);
|
|
699
|
-
} catch (err) {
|
|
700
|
-
this.adapterLogger.error(
|
|
701
|
-
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
702
|
-
);
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
};
|
|
706
751
|
|
|
707
752
|
exports.RealtimeIoAdapter = RealtimeIoAdapter;
|
|
@@ -226,8 +226,14 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
226
226
|
private readonly logger;
|
|
227
227
|
server: Server;
|
|
228
228
|
constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
|
|
229
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
230
|
+
private readonly authenticated;
|
|
231
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
232
|
+
private readonly authenticateHandshake;
|
|
229
233
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
230
234
|
afterInit(server: Server): void;
|
|
235
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
236
|
+
private reportMissingAdapter;
|
|
231
237
|
/**
|
|
232
238
|
* Handle a new WebSocket connection.
|
|
233
239
|
*
|
|
@@ -226,8 +226,14 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
226
226
|
private readonly logger;
|
|
227
227
|
server: Server;
|
|
228
228
|
constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
|
|
229
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
230
|
+
private readonly authenticated;
|
|
231
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
232
|
+
private readonly authenticateHandshake;
|
|
229
233
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
230
234
|
afterInit(server: Server): void;
|
|
235
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
236
|
+
private reportMissingAdapter;
|
|
231
237
|
/**
|
|
232
238
|
* Handle a new WebSocket connection.
|
|
233
239
|
*
|
package/dist/websocket/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
|
|
2
|
-
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES, REALTIME_ERROR_CODES, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController,
|
|
2
|
+
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES, REALTIME_ERROR_CODES, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
|
|
3
3
|
import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
|
|
4
4
|
import { IoAdapter } from '@nestjs/platform-socket.io';
|
|
5
5
|
|
|
@@ -391,6 +391,86 @@ CompositeTransport = __decorateClass([
|
|
|
391
391
|
__decorateParam(0, Inject(SseTransport)),
|
|
392
392
|
__decorateParam(1, Inject(WebSocketTransport))
|
|
393
393
|
], CompositeTransport);
|
|
394
|
+
var realtimeServers = /* @__PURE__ */ new WeakSet();
|
|
395
|
+
function isRealtimeIoServer(server) {
|
|
396
|
+
return typeof server === "object" && server !== null && realtimeServers.has(server);
|
|
397
|
+
}
|
|
398
|
+
var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
399
|
+
adapterLogger = new Logger(_RealtimeIoAdapter.name);
|
|
400
|
+
options;
|
|
401
|
+
constructor(app) {
|
|
402
|
+
super(app);
|
|
403
|
+
this.options = app.get(REALTIME_OPTIONS_TOKEN);
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Bind the gateway to `websocket.namespace` when configured.
|
|
407
|
+
*
|
|
408
|
+
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
409
|
+
* the module options resolve — so the namespace cannot be declared there.
|
|
410
|
+
* Instead we build the root server via `super.create` (which routes through the
|
|
411
|
+
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
412
|
+
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
413
|
+
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
414
|
+
* namespace leaves the root server untouched.
|
|
415
|
+
*/
|
|
416
|
+
create(port, options) {
|
|
417
|
+
const server = super.create(port, options);
|
|
418
|
+
const ns = this.options.websocket?.namespace;
|
|
419
|
+
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
420
|
+
const namespace = server.of(ns);
|
|
421
|
+
realtimeServers.add(namespace);
|
|
422
|
+
return namespace;
|
|
423
|
+
}
|
|
424
|
+
return server;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Create the Socket.IO server with merged WebSocket options.
|
|
428
|
+
*
|
|
429
|
+
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
430
|
+
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
431
|
+
* dep — its absence does not crash the lib).
|
|
432
|
+
*/
|
|
433
|
+
createIOServer(port, opts) {
|
|
434
|
+
const wsOpts = this.options.websocket ?? {};
|
|
435
|
+
const mergedOpts = {
|
|
436
|
+
...opts,
|
|
437
|
+
cors: wsOpts.cors ?? opts?.cors,
|
|
438
|
+
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
439
|
+
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
440
|
+
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
441
|
+
};
|
|
442
|
+
const server = super.createIOServer(port, mergedOpts);
|
|
443
|
+
if (wsOpts.redisAdapter?.pubClient) {
|
|
444
|
+
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
445
|
+
}
|
|
446
|
+
realtimeServers.add(server);
|
|
447
|
+
return server;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Lazily load and install `@socket.io/redis-adapter`.
|
|
451
|
+
*
|
|
452
|
+
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
453
|
+
* not crash the lib. A load or install failure is logged and tolerated;
|
|
454
|
+
* the lib degrades gracefully to single-instance mode.
|
|
455
|
+
*/
|
|
456
|
+
installRedisAdapter(server, pubClient) {
|
|
457
|
+
try {
|
|
458
|
+
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
459
|
+
const pub = pubClient;
|
|
460
|
+
const sub = pub.duplicate();
|
|
461
|
+
server.adapter(createAdapter(pub, sub));
|
|
462
|
+
this.adapterLogger.log(
|
|
463
|
+
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
464
|
+
);
|
|
465
|
+
} catch (err) {
|
|
466
|
+
this.adapterLogger.error(
|
|
467
|
+
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
|
|
473
|
+
// src/websocket/transports/websocket/realtime.gateway.ts
|
|
394
474
|
function firstQueryValue(value) {
|
|
395
475
|
return Array.isArray(value) ? value[0] : value;
|
|
396
476
|
}
|
|
@@ -403,11 +483,43 @@ var RealtimeGateway = class {
|
|
|
403
483
|
options;
|
|
404
484
|
logger = new Logger(RealtimeGateway.name);
|
|
405
485
|
server;
|
|
486
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
487
|
+
authenticated = /* @__PURE__ */ new WeakMap();
|
|
488
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
489
|
+
authenticateHandshake = async (socket, next) => {
|
|
490
|
+
try {
|
|
491
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
492
|
+
if (!auth) {
|
|
493
|
+
const refusal = new Error(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
494
|
+
refusal.data = { code: REALTIME_ERROR_CODES.AUTH_FAILED };
|
|
495
|
+
next(refusal);
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
499
|
+
assertIdentityIsNotBlank(resolvedAuth);
|
|
500
|
+
this.authenticated.set(socket, resolvedAuth);
|
|
501
|
+
next();
|
|
502
|
+
} catch (err) {
|
|
503
|
+
this.logger.error(
|
|
504
|
+
`handshake refused for socket ${socket.id}: ${err instanceof Error ? err.message : String(err)}`
|
|
505
|
+
);
|
|
506
|
+
next(new Error("Internal Server Error"));
|
|
507
|
+
}
|
|
508
|
+
};
|
|
406
509
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
407
510
|
afterInit(server) {
|
|
511
|
+
server.use(this.authenticateHandshake);
|
|
408
512
|
this.transport.setServer(server);
|
|
513
|
+
if (!isRealtimeIoServer(server)) this.reportMissingAdapter();
|
|
409
514
|
this.logger.log("RealtimeGateway initialized");
|
|
410
515
|
}
|
|
516
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
517
|
+
reportMissingAdapter() {
|
|
518
|
+
const configured = Object.keys(this.options.websocket ?? {});
|
|
519
|
+
this.logger.error(
|
|
520
|
+
"RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options" + (configured.length > 0 ? ` (${configured.join(", ")})` : "") + " 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'."
|
|
521
|
+
);
|
|
522
|
+
}
|
|
411
523
|
/**
|
|
412
524
|
* Handle a new WebSocket connection.
|
|
413
525
|
*
|
|
@@ -460,13 +572,17 @@ var RealtimeGateway = class {
|
|
|
460
572
|
}
|
|
461
573
|
async handleConnection(socket) {
|
|
462
574
|
try {
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
575
|
+
let resolvedAuth = this.authenticated.get(socket);
|
|
576
|
+
this.authenticated.delete(socket);
|
|
577
|
+
if (!resolvedAuth) {
|
|
578
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
579
|
+
if (!auth) {
|
|
580
|
+
socket.disconnect(true);
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
584
|
+
assertIdentityIsNotBlank(resolvedAuth);
|
|
467
585
|
}
|
|
468
|
-
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
469
|
-
assertIdentityIsNotBlank(resolvedAuth);
|
|
470
586
|
await this.transport.registerSocket(socket, resolvedAuth);
|
|
471
587
|
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
472
588
|
socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
|
|
@@ -630,76 +746,5 @@ BymaxRealtimeWebSocketModule = __decorateClass([
|
|
|
630
746
|
Global(),
|
|
631
747
|
Module({})
|
|
632
748
|
], BymaxRealtimeWebSocketModule);
|
|
633
|
-
var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
634
|
-
adapterLogger = new Logger(_RealtimeIoAdapter.name);
|
|
635
|
-
options;
|
|
636
|
-
constructor(app) {
|
|
637
|
-
super(app);
|
|
638
|
-
this.options = app.get(REALTIME_OPTIONS_TOKEN);
|
|
639
|
-
}
|
|
640
|
-
/**
|
|
641
|
-
* Bind the gateway to `websocket.namespace` when configured.
|
|
642
|
-
*
|
|
643
|
-
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
644
|
-
* the module options resolve — so the namespace cannot be declared there.
|
|
645
|
-
* Instead we build the root server via `super.create` (which routes through the
|
|
646
|
-
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
647
|
-
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
648
|
-
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
649
|
-
* namespace leaves the root server untouched.
|
|
650
|
-
*/
|
|
651
|
-
create(port, options) {
|
|
652
|
-
const server = super.create(port, options);
|
|
653
|
-
const ns = this.options.websocket?.namespace;
|
|
654
|
-
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
655
|
-
return server.of(ns);
|
|
656
|
-
}
|
|
657
|
-
return server;
|
|
658
|
-
}
|
|
659
|
-
/**
|
|
660
|
-
* Create the Socket.IO server with merged WebSocket options.
|
|
661
|
-
*
|
|
662
|
-
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
663
|
-
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
664
|
-
* dep — its absence does not crash the lib).
|
|
665
|
-
*/
|
|
666
|
-
createIOServer(port, opts) {
|
|
667
|
-
const wsOpts = this.options.websocket ?? {};
|
|
668
|
-
const mergedOpts = {
|
|
669
|
-
...opts,
|
|
670
|
-
cors: wsOpts.cors ?? opts?.cors,
|
|
671
|
-
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
672
|
-
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
673
|
-
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
674
|
-
};
|
|
675
|
-
const server = super.createIOServer(port, mergedOpts);
|
|
676
|
-
if (wsOpts.redisAdapter?.pubClient) {
|
|
677
|
-
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
678
|
-
}
|
|
679
|
-
return server;
|
|
680
|
-
}
|
|
681
|
-
/**
|
|
682
|
-
* Lazily load and install `@socket.io/redis-adapter`.
|
|
683
|
-
*
|
|
684
|
-
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
685
|
-
* not crash the lib. A load or install failure is logged and tolerated;
|
|
686
|
-
* the lib degrades gracefully to single-instance mode.
|
|
687
|
-
*/
|
|
688
|
-
installRedisAdapter(server, pubClient) {
|
|
689
|
-
try {
|
|
690
|
-
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
691
|
-
const pub = pubClient;
|
|
692
|
-
const sub = pub.duplicate();
|
|
693
|
-
server.adapter(createAdapter(pub, sub));
|
|
694
|
-
this.adapterLogger.log(
|
|
695
|
-
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
696
|
-
);
|
|
697
|
-
} catch (err) {
|
|
698
|
-
this.adapterLogger.error(
|
|
699
|
-
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
700
|
-
);
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
};
|
|
704
749
|
|
|
705
750
|
export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter, WebSocketTransport };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bymax-one/nest-realtime",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.2",
|
|
4
4
|
"description": "Realtime backend → frontend communication for NestJS — dual-transport SSE (default) and WebSocket (opt-in) with a unified server-side API.",
|
|
5
5
|
"author": "Bymax One <support@bymax.one>",
|
|
6
6
|
"license": "MIT",
|