@bymax-one/nest-realtime 1.2.5 → 1.2.7
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 +135 -1
- package/README.md +87 -53
- package/dist/internal/index.cjs +370 -77
- package/dist/internal/index.d.cts +221 -51
- package/dist/internal/index.d.ts +221 -51
- package/dist/internal/index.mjs +369 -78
- package/dist/server/index.d.cts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/shared/index.cjs +1 -0
- package/dist/shared/index.d.cts +1 -0
- package/dist/shared/index.d.ts +1 -0
- package/dist/shared/index.mjs +1 -0
- package/dist/websocket/index.cjs +76 -24
- package/dist/websocket/index.d.cts +30 -11
- package/dist/websocket/index.d.ts +30 -11
- package/dist/websocket/index.mjs +77 -25
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,138 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.7] - 2026-11-01
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **A revocation that cannot reach its connection no longer answers success.** `disconnect()` on
|
|
15
|
+
`RealtimeService` resolved even when the revocation was never delivered: a failed cross-instance
|
|
16
|
+
publish was logged and swallowed, and in `transport: 'both'` a failure of either transport was
|
|
17
|
+
swallowed with no log at all, so a revoked client could stay connected while the caller was told it
|
|
18
|
+
was gone. It now rejects with `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the revocation and
|
|
19
|
+
with `REALTIME_TRANSPORT_UNAVAILABLE` when the transport that holds the connection fails or the
|
|
20
|
+
WebSocket server is not attached. It resolves when the connection was closed on this instance or the
|
|
21
|
+
revocation was handed to the bus. `joinRoom` and `leaveRoom` reject the same way when the
|
|
22
|
+
transport that holds the connection fails, in place of reporting a join or a leave that did not
|
|
23
|
+
happen, and they now change nothing for a connection the instance does not hold (they used to
|
|
24
|
+
record a room membership with no connection behind it). An emit stays at-most-once and still
|
|
25
|
+
resolves when its publish fails.
|
|
26
|
+
- **A revocation that fails during re-authentication is retried.** The cycle kept the failure to
|
|
27
|
+
itself and stopped revalidating the remaining connections; it now logs it, goes on, and revalidates
|
|
28
|
+
the connection again on the next cycle. A rejected cycle no longer leaves an unhandled rejection.
|
|
29
|
+
- **A failed publish or a failed offline-queue write is no longer silent.** An emit whose publish
|
|
30
|
+
to the other instances was refused still resolves, as before, but the failure is now logged with
|
|
31
|
+
`REALTIME_PUBSUB_UNAVAILABLE` and the operation and passed to the new `onDeliveryFailure` hook,
|
|
32
|
+
which is where to count it. `emitToUser` now waits for the offline queue instead of firing and
|
|
33
|
+
forgetting it, reports a failed write the same way, and rejects with
|
|
34
|
+
`REALTIME_TRANSPORT_UNAVAILABLE` only when the event has no delivery path left: the user is
|
|
35
|
+
offline here, the queue could not keep it, and the bus failed or cannot reach another instance
|
|
36
|
+
(the default in-memory bus). With `transport: 'both'`, a rejection from either path, or from
|
|
37
|
+
both, is logged as a warning and the call resolves; `onDeliveryFailure` is not called for that
|
|
38
|
+
rejection. A failed offline-queue read on reconnect is reported too. A remote `disconnect` that
|
|
39
|
+
fails no longer leaves an unhandled rejection, an unparsable bus payload is counted and reported
|
|
40
|
+
at most once a minute instead of vanishing, and an emit made before the WebSocket gateway attaches
|
|
41
|
+
its server says so once.
|
|
42
|
+
- **An instance that cannot hear the others no longer comes up silently deaf.** When the Redis
|
|
43
|
+
pub/sub subscription at boot was refused (a wrong password, a missing permission) the library logged a warning and started anyway, so the instance missed every
|
|
44
|
+
cross-instance revocation. A refusal now fails the boot with `REALTIME_PUBSUB_UNAVAILABLE`. When
|
|
45
|
+
Redis is merely unreachable the boot used to hang, waiting for a subscribe that ioredis keeps
|
|
46
|
+
queued (measured above 40 s on a closed port); it now completes, logs
|
|
47
|
+
`REALTIME_PUBSUB_UNAVAILABLE` once, and the instance reports itself unready until a connection
|
|
48
|
+
succeeds. The state follows the connection for the life of the process: a drop makes it unready
|
|
49
|
+
again, logged once per outage rather than once per retry, and it is ready only once the SUBSCRIBE
|
|
50
|
+
is confirmed, whether or not the client has `autoResubscribe` on.
|
|
51
|
+
The subscriber client no longer relies on ioredis replaying its subscription after a reconnect:
|
|
52
|
+
that replay had no handler for a refusal, so a re-subscribe the server refused (an ACL changed
|
|
53
|
+
while the instance ran) surfaced as an unhandled rejection that can end the Node process. The
|
|
54
|
+
library now sends its own `SUBSCRIBE` on every reconnect and reports a refusal in the log.
|
|
55
|
+
|
|
56
|
+
#### Apply to a derived backend
|
|
57
|
+
|
|
58
|
+
Await `disconnect()` and handle its rejection where you revoke a connection: a rejection means the
|
|
59
|
+
connection may still be connected, so retry or alert. A caller that ignored the returned promise now
|
|
60
|
+
risks an unhandled rejection. `joinRoom` and `leaveRoom` can reject the same way, and are local to the
|
|
61
|
+
instance that holds the connection. `REALTIME_ERROR_CODES` gains `TRANSPORT_UNAVAILABLE`.
|
|
62
|
+
|
|
63
|
+
With `transport: 'sse'`, `emitToUser` can now reject, with `REALTIME_TRANSPORT_UNAVAILABLE`, when an
|
|
64
|
+
offline queue is configured, the user is offline on this instance, the queue could not keep the event
|
|
65
|
+
and no other instance can have delivered it. Count `onDeliveryFailure` (new, optional, nothing to implement) to see
|
|
66
|
+
the publishes and queue writes that failed without failing the call.
|
|
67
|
+
|
|
68
|
+
A Redis that refuses the pub/sub subscription (a wrong password, a missing permission) now fails
|
|
69
|
+
the application's boot instead of logging and continuing, so a misconfigured credential or ACL
|
|
70
|
+
surfaces at startup. A Redis that is only unreachable no longer hangs the boot: the instance boots
|
|
71
|
+
unready and subscribes when a connection succeeds. Wire `isPubSubReady()` into the readiness probe
|
|
72
|
+
so an instance that is up but cannot hear the others (Redis unreachable, or the subscriber
|
|
73
|
+
connection dropped) is taken out of rotation; see the README. A custom `IRealtimePubSub` needs no
|
|
74
|
+
change: `isSubscribed` is optional, and a bus without it counts as subscribed.
|
|
75
|
+
|
|
76
|
+
### Added
|
|
77
|
+
|
|
78
|
+
- `IConnectionLifecycleHooks.onDeliveryFailure(failure)`, with the exported `DeliveryFailure` type
|
|
79
|
+
(`code`, `op`, `error`), called when a delivery path fails but the call that used it still
|
|
80
|
+
resolves.
|
|
81
|
+
- `RealtimeService.isPubSubReady()`, for a readiness probe: false while the instance does not hear
|
|
82
|
+
the other instances. `RedisRealtimePubSub.isSubscribed()` is the state behind it, and
|
|
83
|
+
`IRealtimePubSub.isSubscribed?()` lets a custom bus report its own.
|
|
84
|
+
|
|
85
|
+
### Internal
|
|
86
|
+
|
|
87
|
+
- The `internal` and `websocket` bundle budgets in `pnpm size` are raised to fit the revocation that
|
|
88
|
+
rejects when it cannot reach its connection, the report of a delivery path that failed and the
|
|
89
|
+
subscriber's lifecycle state, a boot that ends when the server closes the connection without an
|
|
90
|
+
error, and per-connection retirement: the `internal` budget goes from 15,900 B to 18,250 B for a
|
|
91
|
+
measured 18,232 B (15,868 B in 1.2.6) and the `websocket` budget from 7,000 B to 7,550 B for a
|
|
92
|
+
measured 7,477 B.
|
|
93
|
+
- The workflow jobs that check out the repository and then run its scripts no longer keep the job's
|
|
94
|
+
token in the git configuration: `persist-credentials: false` on the checkout wherever no later
|
|
95
|
+
step pushes or tags.
|
|
96
|
+
|
|
97
|
+
## [1.2.6] - 2026-11-01
|
|
98
|
+
|
|
99
|
+
### Fixed
|
|
100
|
+
|
|
101
|
+
- **The SSE client address no longer comes from the leftmost `X-Forwarded-For` entry.** The
|
|
102
|
+
connection context's `ip` and the `ip` the hooks receive were the first raw entry of that header,
|
|
103
|
+
which the client writes, with no check that it was an address and no regard for the application's
|
|
104
|
+
`trust proxy` setting: with `trust proxy` set to `'loopback'` and the header `6.6.6.6, 203.0.113.9`,
|
|
105
|
+
Express reported `203.0.113.9` and the library reported `6.6.6.6`. On SSE `ip` is now the address `trust proxy` produced (`req.ip`, else an address from `req.ips`, else the socket
|
|
106
|
+
peer), `''` when no channel carries an address, and a header text that is not an address is never
|
|
107
|
+
returned. WebSocket is unchanged: it reads the handshake's peer address. `SseRequest` gains an
|
|
108
|
+
optional `ips`.
|
|
109
|
+
|
|
110
|
+
#### Apply to a derived backend
|
|
111
|
+
|
|
112
|
+
A hook or an authenticator that reads `ip` on SSE may now see a different value, and the new one is
|
|
113
|
+
the correct one: the address your `trust proxy` setting vouches for. Behind a reverse proxy, set
|
|
114
|
+
`trust proxy` on the application (for example `app.set('trust proxy', 'loopback')`), or `ip` is the
|
|
115
|
+
proxy's address, as it already was on WebSocket. An application that never set it sees the socket
|
|
116
|
+
peer where it used to see whatever the client put in the header. `ip` is `''` where it used to be
|
|
117
|
+
`'unknown'` when nothing carries an address. Compare against `remoteAddress` to tell the proxy from
|
|
118
|
+
the client.
|
|
119
|
+
|
|
120
|
+
### Tests
|
|
121
|
+
|
|
122
|
+
- **The README Quick Start is executed, not only type-checked.** Specs take the Quick Start
|
|
123
|
+
blocks from the README text, compile them and run them against a real Nest application over HTTP,
|
|
124
|
+
a real Socket.IO handshake and jsdom. A wrong option shape, a route that is never mounted, a missing `eventNames` entry or a
|
|
125
|
+
`main.ts` without the adapter now fails a test instead of reaching a reader. No source or
|
|
126
|
+
published-surface change, so there is nothing to apply.
|
|
127
|
+
|
|
128
|
+
### Internal
|
|
129
|
+
|
|
130
|
+
- The Release workflow takes the GitHub Release notes from the tag's CHANGELOG section before the
|
|
131
|
+
gates run, matching the heading literally, and fails the release when the section is missing or
|
|
132
|
+
blank instead of falling back to a pointer. The notes reach `gh release create` through a file.
|
|
133
|
+
- `pnpm check:api` compares the built `.d.ts` and `.d.cts` files, comments ignored, with the previous
|
|
134
|
+
published version, and the Release workflow runs it before the publish. It always prints what
|
|
135
|
+
differs. A difference passes only when the CHANGELOG section of the version being released holds
|
|
136
|
+
an "Apply to a derived backend" note (or the older "Apply to a consumer"). There is no override.
|
|
137
|
+
- A workflow runs the same check in a pull request that changes `package.json` and moves the version,
|
|
138
|
+
so a release that changes the declarations without the note fails before the tag. A pull request
|
|
139
|
+
that leaves the version alone skips it.
|
|
140
|
+
- The `internal` bundle budget in `pnpm size` is raised to fit the client-address validation.
|
|
141
|
+
|
|
10
142
|
## [1.2.5] - 2026-11-01
|
|
11
143
|
|
|
12
144
|
### Added
|
|
@@ -634,7 +766,9 @@ First published release.
|
|
|
634
766
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
635
767
|
asked about NestJS and never put the same question to the other ten peers.
|
|
636
768
|
|
|
637
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
769
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.7...HEAD
|
|
770
|
+
[1.2.7]: https://github.com/bymaxone/nest-realtime/compare/v1.2.6...v1.2.7
|
|
771
|
+
[1.2.6]: https://github.com/bymaxone/nest-realtime/compare/v1.2.5...v1.2.6
|
|
638
772
|
[1.2.5]: https://github.com/bymaxone/nest-realtime/compare/v1.2.4...v1.2.5
|
|
639
773
|
[1.2.4]: https://github.com/bymaxone/nest-realtime/compare/v1.2.3...v1.2.4
|
|
640
774
|
[1.2.3]: https://github.com/bymaxone/nest-realtime/compare/v1.2.2...v1.2.3
|
package/README.md
CHANGED
|
@@ -350,18 +350,18 @@ With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls
|
|
|
350
350
|
|
|
351
351
|
All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `authenticator` are required.
|
|
352
352
|
|
|
353
|
-
| Group | Key Options
|
|
354
|
-
| -------------------------- |
|
|
355
|
-
| **transport** | `'sse'` \| `'websocket'` \| `'both'`
|
|
356
|
-
| **authenticator** | `IConnectionAuthenticator`
|
|
357
|
-
| **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result, on **both** transports; `undefined` and `null` mean "no opinion" and fall back
|
|
358
|
-
| **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed` (fire-and-forget)
|
|
359
|
-
| **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE
|
|
360
|
-
| **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away
|
|
361
|
-
| **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it
|
|
362
|
-
| **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `maxConnectionsPerUser`, `emitConnectionEvent`
|
|
363
|
-
| **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter`
|
|
364
|
-
| **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`
|
|
353
|
+
| Group | Key Options | Default |
|
|
354
|
+
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
|
|
355
|
+
| **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
|
|
356
|
+
| **authenticator** | `IConnectionAuthenticator` | — (**required**) |
|
|
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` |
|
|
358
|
+
| **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget) | — |
|
|
359
|
+
| **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
|
|
360
|
+
| **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
|
|
361
|
+
| **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
|
|
362
|
+
| **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `maxConnectionsPerUser`, `emitConnectionEvent` | `/realtime/sse`, `30000`, `100`, `5`, `true` |
|
|
363
|
+
| **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults) |
|
|
364
|
+
| **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs` | `300`, `'disconnect'`, `60000` |
|
|
365
365
|
|
|
366
366
|
> [!NOTE]
|
|
367
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.
|
|
@@ -494,16 +494,16 @@ When integrating `@bymax-one/nest-realtime` in production, verify each of the fo
|
|
|
494
494
|
|
|
495
495
|
## 🛡️ Security Table
|
|
496
496
|
|
|
497
|
-
| Layer | Implementation
|
|
498
|
-
| --------------------- |
|
|
499
|
-
| Credential validation | Delegated entirely to consumer-supplied `IConnectionAuthenticator`
|
|
500
|
-
| Auth library imports | None — enforced by a CI grep over `src/`
|
|
501
|
-
| Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result
|
|
502
|
-
| Connection revocation | `disconnect(connectionId)`, propagated cross-instance via `op: 'disconnect'
|
|
503
|
-
| Credential expiry | Interval re-authentication with `disconnect` or event on failure
|
|
504
|
-
| Connection flooding | FIFO eviction per user — oldest closed, new admitted, never a 429
|
|
505
|
-
| SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform` by default
|
|
506
|
-
| WebSocket origin | Explicit `cors` config passed straight to Socket.IO
|
|
497
|
+
| Layer | Implementation |
|
|
498
|
+
| --------------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
|
499
|
+
| Credential validation | Delegated entirely to consumer-supplied `IConnectionAuthenticator` |
|
|
500
|
+
| Auth library imports | None — enforced by a CI grep over `src/` |
|
|
501
|
+
| Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result |
|
|
502
|
+
| Connection revocation | `disconnect(connectionId)`, propagated cross-instance via `op: 'disconnect'`; rejects when it cannot reach the connection |
|
|
503
|
+
| Credential expiry | Interval re-authentication with `disconnect` or event on failure |
|
|
504
|
+
| Connection flooding | FIFO eviction per user — oldest closed, new admitted, never a 429 |
|
|
505
|
+
| SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform` by default |
|
|
506
|
+
| WebSocket origin | Explicit `cors` config passed straight to Socket.IO |
|
|
507
507
|
|
|
508
508
|
> [!IMPORTANT]
|
|
509
509
|
> This package holds **zero credential logic**. That is its central security property — and it means the strength of your realtime auth is exactly the strength of the authenticator you plug in.
|
|
@@ -572,6 +572,35 @@ The unified emit API. Identical on every transport.
|
|
|
572
572
|
|
|
573
573
|
All methods return `Promise<void>`.
|
|
574
574
|
|
|
575
|
+
**Revocation is never best-effort.** `disconnect(connectionId)` resolves when the connection was closed on this instance or when the revocation was handed to the bus (`IRealtimePubSub`). It **rejects** when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish, `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. A rejection means the connection may still be connected, so retry. An emit is different: `emitToUser`, `emitToTenant`, `emitToRoom` and `broadcast` stay at-most-once, and **resolve even when the publish to the other instances failed**. That failure is not silent: it is logged with `REALTIME_PUBSUB_UNAVAILABLE` and the operation, and passed to the `onDeliveryFailure` hook, which is where to count it. `emitToUser` also resolves, reporting it the same way, when the offline queue could not keep an event for a user who is offline here, because another instance may have delivered it live. It rejects only when the event has no delivery path left: the user is offline here, the queue failed, and the bus failed or cannot reach another instance (the default in-memory bus).
|
|
576
|
+
|
|
577
|
+
`joinRoom` and `leaveRoom` act on a connection **this instance holds**; for any other id they resolve and change nothing. A failure of the transport that holds the connection rejects the call.
|
|
578
|
+
|
|
579
|
+
**An instance must hear the others.** With `RedisRealtimePubSub`, a subscription the server refuses (a wrong password, a missing permission) **fails the boot**: retrying cannot fix it, and an instance that never hears a revocation must not look healthy. A Redis that is only unreachable does not block the boot. The instance starts, logs once that it is not subscribed, and subscribes when a connection succeeds. Until then, and again whenever the subscriber connection drops, `isPubSubReady()` is false. Put it in your readiness probe:
|
|
580
|
+
|
|
581
|
+
```ts
|
|
582
|
+
import { Injectable } from '@nestjs/common'
|
|
583
|
+
import { HealthIndicatorService } from '@nestjs/terminus'
|
|
584
|
+
import { RealtimeService } from '@bymax-one/nest-realtime'
|
|
585
|
+
|
|
586
|
+
@Injectable()
|
|
587
|
+
export class RealtimeHealthIndicator {
|
|
588
|
+
constructor(
|
|
589
|
+
private readonly realtime: RealtimeService,
|
|
590
|
+
private readonly indicators: HealthIndicatorService,
|
|
591
|
+
) {}
|
|
592
|
+
|
|
593
|
+
check(key = 'realtime') {
|
|
594
|
+
const indicator = this.indicators.check(key)
|
|
595
|
+
return this.realtime.isPubSubReady()
|
|
596
|
+
? indicator.up()
|
|
597
|
+
: indicator.down({ reason: 'not subscribed to the realtime bus' })
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
```
|
|
601
|
+
|
|
602
|
+
`isPubSubReady()` is true for a bus that reports no state, such as the default in-memory one, and with `transport: 'websocket'`, which does not use the bus.
|
|
603
|
+
|
|
575
604
|
### ConnectionRegistry
|
|
576
605
|
|
|
577
606
|
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).
|
|
@@ -586,14 +615,14 @@ Read-side view of live connections — useful for admin endpoints and metrics. T
|
|
|
586
615
|
|
|
587
616
|
### Contracts
|
|
588
617
|
|
|
589
|
-
| Interface | Required | Purpose
|
|
590
|
-
| --------------------------- | :------: |
|
|
591
|
-
| `IConnectionAuthenticator` | ✅ | Validate a connection, return `userId` / `tenantId`
|
|
592
|
-
| `IRealtimePubSub` | — | Cross-instance fan-out for SSE
|
|
593
|
-
| `IOfflineQueueStorage` | — | Hold events for disconnected users
|
|
618
|
+
| Interface | Required | Purpose |
|
|
619
|
+
| --------------------------- | :------: | --------------------------------------------------------------------------------------------------------------------- |
|
|
620
|
+
| `IConnectionAuthenticator` | ✅ | Validate a connection, return `userId` / `tenantId` |
|
|
621
|
+
| `IRealtimePubSub` | — | Cross-instance fan-out for SSE |
|
|
622
|
+
| `IOfflineQueueStorage` | — | Hold events for disconnected users |
|
|
594
623
|
| `IPresenceStorage` | — | Contract only: the library never calls it; your code stores presence and emits `presence:online` / `presence:offline` |
|
|
595
|
-
| `IConnectionLifecycleHooks` | — | Fire-and-forget connect / disconnect / error callbacks
|
|
596
|
-
| `ITransport` | — | Implemented by the library; the seam every transport shares
|
|
624
|
+
| `IConnectionLifecycleHooks` | — | Fire-and-forget connect / disconnect / error callbacks |
|
|
625
|
+
| `ITransport` | — | Implemented by the library; the seam every transport shares |
|
|
597
626
|
|
|
598
627
|
Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePubSub`, `RedisOfflineQueue`.
|
|
599
628
|
|
|
@@ -615,7 +644,7 @@ under none and joins no tenant room, which an empty string is not. Whitespace co
|
|
|
615
644
|
Omission is the form to write, because it is the only one that compiles everywhere.
|
|
616
645
|
`AuthenticationResult` declares `tenantId?: string`; the runtime accepts an explicit `undefined`
|
|
617
646
|
or `null` too — an untyped claim spread into the result produces them routinely — but whether
|
|
618
|
-
either
|
|
647
|
+
either _type-checks_ depends on the consuming project's `tsconfig`, which the published
|
|
619
648
|
declarations do not control:
|
|
620
649
|
|
|
621
650
|
| consumer's `tsconfig` | `tenantId: undefined` | `tenantId: null` |
|
|
@@ -628,7 +657,7 @@ Omitting the key is correct in all three.
|
|
|
628
657
|
|
|
629
658
|
`tenantResolver` cannot clear a tenant, and this is the one asymmetry worth reading twice.
|
|
630
659
|
Resolution is `tenantResolver?.(auth) ?? auth.tenantId`, so a resolver returning `undefined` or
|
|
631
|
-
`null` means
|
|
660
|
+
`null` means _no opinion_ and falls back to the tenant the authenticator supplied. A resolver
|
|
632
661
|
written to place a connection in no tenant by returning `null` leaves it in `auth.tenantId`'s
|
|
633
662
|
room instead, still receiving that tenant's events. Decide the absent case in the
|
|
634
663
|
authenticator, where absence is what it looks like.
|
|
@@ -670,12 +699,16 @@ does not refresh it. The library never reads a key.
|
|
|
670
699
|
|
|
671
700
|
#### Client address versus peer address
|
|
672
701
|
|
|
673
|
-
`authenticate` receives two addresses
|
|
702
|
+
`authenticate` receives two addresses. On SSE `ip` is the address your application's
|
|
703
|
+
`trust proxy` setting produced, validated: `X-Forwarded-For` is never read directly, a header text
|
|
704
|
+
that is not an address is never returned, and `ip` is `''` when no channel carries an address.
|
|
705
|
+
Without `trust proxy` it is the peer. Only `remoteAddress` can be trusted without knowing that
|
|
706
|
+
setting:
|
|
674
707
|
|
|
675
|
-
| Field | SSE
|
|
676
|
-
| --------------- |
|
|
677
|
-
| `ip` | `
|
|
678
|
-
| `remoteAddress` | `req.socket.remoteAddress`
|
|
708
|
+
| Field | SSE | WebSocket | Forgeable by the client |
|
|
709
|
+
| --------------- | ----------------------------------------------------- | ------------------- | ------------------------------------------------ |
|
|
710
|
+
| `ip` | `req.ip`, which follows the app's `trust proxy` value | `handshake.address` | Only as far as `trust proxy` believes the header |
|
|
711
|
+
| `remoteAddress` | `req.socket.remoteAddress` | `handshake.address` | No |
|
|
679
712
|
|
|
680
713
|
`remoteAddress` is the TCP peer, read from the socket and never from a header. Behind a reverse
|
|
681
714
|
proxy it is the proxy's address. Use it to decide whether a forwarded header such as
|
|
@@ -836,18 +869,19 @@ These names belong to the library. Do not reuse them for application events. The
|
|
|
836
869
|
|
|
837
870
|
### Error Codes
|
|
838
871
|
|
|
839
|
-
| Code | Status
|
|
840
|
-
| ---------------------------------- |
|
|
841
|
-
| `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option
|
|
842
|
-
| `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid
|
|
843
|
-
| `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal
|
|
844
|
-
| `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails
|
|
845
|
-
| `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed
|
|
846
|
-
| `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write
|
|
847
|
-
| `REALTIME_PUBSUB_UNAVAILABLE` |
|
|
848
|
-
| `
|
|
849
|
-
| `
|
|
850
|
-
| `
|
|
872
|
+
| Code | Status |
|
|
873
|
+
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
874
|
+
| `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option |
|
|
875
|
+
| `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
|
|
876
|
+
| `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
|
|
877
|
+
| `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
|
|
878
|
+
| `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
|
|
879
|
+
| `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
|
|
880
|
+
| `REALTIME_PUBSUB_UNAVAILABLE` | Raised as the rejection of a disconnect when the bus refuses the revocation; an emit's publish failure is logged and passed to the delivery-failure hook |
|
|
881
|
+
| `REALTIME_TRANSPORT_UNAVAILABLE` | Raised as the rejection of a disconnect, a join or a leave when the transport that holds the connection fails or has no server attached, and of an emit to an offline user that has no delivery path left |
|
|
882
|
+
| `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
|
|
883
|
+
| `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
|
|
884
|
+
| `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
|
|
851
885
|
|
|
852
886
|
### DI Tokens
|
|
853
887
|
|
|
@@ -855,11 +889,11 @@ These names belong to the library. Do not reuse them for application events. The
|
|
|
855
889
|
|
|
856
890
|
### React Hooks
|
|
857
891
|
|
|
858
|
-
| Hook | Returns
|
|
859
|
-
| -------------------------------- |
|
|
860
|
-
| `useRealtime(options)` | `{ transport, connected, events, lastEvent, error, reconnectAttempts, reconnect, emit }` — opens the connection
|
|
861
|
-
| `useRealtimeContext()` | The same value, from the nearest `<RealtimeProvider>` — throws when used outside one
|
|
862
|
-
| `useRealtimeConnection(options)` | `{ connected, error, reconnectAttempts, reconnect }` — status only, no events array
|
|
892
|
+
| Hook | Returns |
|
|
893
|
+
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
894
|
+
| `useRealtime(options)` | `{ transport, connected, events, lastEvent, error, reconnectAttempts, reconnect, emit }` — opens the connection |
|
|
895
|
+
| `useRealtimeContext()` | The same value, from the nearest `<RealtimeProvider>` — throws when used outside one |
|
|
896
|
+
| `useRealtimeConnection(options)` | `{ connected, error, reconnectAttempts, reconnect }` — status only, no events array |
|
|
863
897
|
| `usePresence()` | `UsePresenceReturn`: `{ onlineUserIds, isOnline(userId), count }` — reads `presence:*` events from the provider; your server must emit them |
|
|
864
898
|
|
|
865
899
|
`RealtimeProvider` takes a single `options` prop of type `UseRealtimeOptions`:
|