@bymax-one/nest-realtime 1.2.0 → 1.2.1
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 +67 -1
- package/README.md +75 -13
- package/dist/internal/index.cjs +84 -7
- package/dist/internal/index.d.cts +124 -12
- package/dist/internal/index.d.ts +124 -12
- package/dist/internal/index.mjs +84 -9
- package/dist/websocket/index.cjs +42 -22
- package/dist/websocket/index.d.cts +14 -1
- package/dist/websocket/index.d.ts +14 -1
- package/dist/websocket/index.mjs +43 -23
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,71 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [1.2.1] - 2026-10-30
|
|
11
|
+
|
|
12
|
+
**This version carries two behavioural breaks, both under Security below.** An authenticator that
|
|
13
|
+
returns a blank identity is now refused, and `tenantResolver` now runs on WebSocket connections.
|
|
14
|
+
Neither is a compile error: both change what a running backend does, so read "⚠️ Apply to a consumer"
|
|
15
|
+
before upgrading. Each closes a defect in which connections shared one delivery bucket or
|
|
16
|
+
were routed to a tenant that differed by transport.
|
|
17
|
+
|
|
18
|
+
### Security
|
|
19
|
+
|
|
20
|
+
- **BREAKING (bootstrap-time): a blank identity is refused on both transports.** An authenticator
|
|
21
|
+
that returns `''` or a whitespace-only `userId`, or a present-but-blank `tenantId`, now fails the
|
|
22
|
+
connection. Such a value used to be indexed under an empty key and
|
|
23
|
+
joined to the room `user:` or `tenant:`, so every such connection shared one bucket and received
|
|
24
|
+
every emit addressed to it for the life of the subscription. An absent `tenantId` stays valid and
|
|
25
|
+
means no tenant.
|
|
26
|
+
- **BREAKING (behavioural): `tenantResolver` now runs on WebSocket connections**, as it already
|
|
27
|
+
did on SSE. It was read on the SSE path and ignored on the WebSocket path, so one user opening
|
|
28
|
+
both transports could be routed to two different tenants by the same configuration. Resolution
|
|
29
|
+
goes through one shared function, so a connection carries the same tenant on either transport,
|
|
30
|
+
and `null` is treated as absent. An application that relied on the resolver not running on
|
|
31
|
+
WebSocket was relying on that defect.
|
|
32
|
+
- Reauthentication now covers WebSocket connections, which previously kept delivering after their
|
|
33
|
+
credentials were revoked. Its failure meta reports the real `conn.transport` instead of a fixed
|
|
34
|
+
`'sse'`.
|
|
35
|
+
|
|
36
|
+
### Changed
|
|
37
|
+
|
|
38
|
+
- `tenantResolver` may return `string | undefined | null`. Not breaking: a resolver typed
|
|
39
|
+
`() => string | undefined` still satisfies the wider signature.
|
|
40
|
+
|
|
41
|
+
### Fixed
|
|
42
|
+
|
|
43
|
+
- `RealtimeIoAdapter` renamed its private logger field from `logger` to `adapterLogger`, so it cannot
|
|
44
|
+
collide with a member of the same name on the `IoAdapter` base class; behaviour is unchanged.
|
|
45
|
+
|
|
46
|
+
### ⚠️ Apply to a consumer
|
|
47
|
+
|
|
48
|
+
- **Blank identity.** Make `authenticate()` return a non-empty `userId`, or `null` to reject the
|
|
49
|
+
connection. Omit `tenantId` for a connection that belongs to no tenant; do not return `''`. A
|
|
50
|
+
blank identity answers HTTP 500 with a generic body on SSE, and is disconnected on WebSocket;
|
|
51
|
+
both log the reason server-side, so a claim that can be blank (an unset `sub` or `tid`) shows up
|
|
52
|
+
as a failed connection rather than a shared room.
|
|
53
|
+
- **`tenantResolver` is honoured on WebSocket.** It now also receives WebSocket connections, and
|
|
54
|
+
it gets the `AuthenticationResult`, not the transport. A resolver that was only correct for SSE must be made
|
|
55
|
+
correct for both; returning `undefined` or `null` keeps `auth.tenantId`.
|
|
56
|
+
- **Reauthentication disconnects WebSocket connections.** They are now checked as well. If
|
|
57
|
+
`revalidate()` can return `false` for a credential that is still acceptable, those sockets are
|
|
58
|
+
now disconnected on the next cycle.
|
|
59
|
+
|
|
60
|
+
### Documentation
|
|
61
|
+
|
|
62
|
+
- The README separates the authenticator path from the `tenantResolver` path for an absent tenant,
|
|
63
|
+
and lists which reserved events the library emits and which it only reserves.
|
|
64
|
+
- `IPresenceStorage` is documented as a contract the application drives; the library does not
|
|
65
|
+
emit `presence:*` events.
|
|
66
|
+
- `SECURITY.md` states that only the latest minor line (1.2.x) receives security fixes; its table listed
|
|
67
|
+
`0.1.x`.
|
|
68
|
+
- The architecture notes, the auth patterns and the nest-auth bridge example match the code: `authorization`
|
|
69
|
+
is dropped on SSE, `auth.token` and `auth.ticket` reach the authenticator through the header and
|
|
70
|
+
`ctx.query.ticket`, `RealtimeIoAdapter` is imported from `/websocket`, and `cacheTtlMs` only matters when it
|
|
71
|
+
exceeds `intervalSeconds`.
|
|
72
|
+
|
|
8
73
|
## [1.2.0] - 2026-08-29
|
|
9
74
|
|
|
10
75
|
**Shipped as a minor, and two entries below are strictly speaking breaking.** Both are called
|
|
@@ -403,7 +468,8 @@ First published release.
|
|
|
403
468
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
404
469
|
asked about NestJS and never put the same question to the other ten peers.
|
|
405
470
|
|
|
406
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
471
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.1...HEAD
|
|
472
|
+
[1.2.1]: https://github.com/bymaxone/nest-realtime/compare/v1.2.0...v1.2.1
|
|
407
473
|
[1.2.0]: https://github.com/bymaxone/nest-realtime/compare/v1.1.2...v1.2.0
|
|
408
474
|
[1.1.2]: https://github.com/bymaxone/nest-realtime/compare/v1.1.1...v1.1.2
|
|
409
475
|
[1.1.1]: https://github.com/bymaxone/nest-realtime/compare/v1.1.0...v1.1.1
|
package/README.md
CHANGED
|
@@ -74,13 +74,13 @@ pnpm add @bymax-one/nest-realtime
|
|
|
74
74
|
- ✅ **Offline queue** — `IOfflineQueueStorage` holds events for absent users and flushes them on reconnect
|
|
75
75
|
- ✅ **Replay buffer** — per-user ring buffer answers `Last-Event-ID` after a dropped SSE stream
|
|
76
76
|
- ✅ **FIFO connection limits** — the oldest connection is evicted, so a new tab never gets a 429
|
|
77
|
-
- ✅ **Presence** — optional `IPresenceStorage`
|
|
77
|
+
- ✅ **Presence contract** — optional `IPresenceStorage` seam and `usePresence()` hook; the library never calls the storage or emits `presence:*` itself, so your application does both
|
|
78
78
|
|
|
79
79
|
### 🧩 Developer Experience
|
|
80
80
|
|
|
81
81
|
- ✅ **4 subpath exports** — server, WebSocket, shared types, and React; tree-shakeable, ESM + CJS dual output
|
|
82
82
|
- ✅ **Dynamic module** — `forRoot()` and `forRootAsync()` with `useFactory` / `useClass` / `useExisting`
|
|
83
|
-
- ✅ **Strict TypeScript, zero `any`** — `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes`
|
|
83
|
+
- ✅ **Strict TypeScript, zero `any`** — `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` enabled
|
|
84
84
|
- ✅ **Horizontal scaling** — `IRealtimePubSub` for SSE fan-out, `@socket.io/redis-adapter` for WebSocket
|
|
85
85
|
- ✅ **Bundle gate in CI** — the SSE-only React bundle is measured on every build and fails over budget
|
|
86
86
|
|
|
@@ -305,11 +305,11 @@ All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `
|
|
|
305
305
|
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
|
|
306
306
|
| **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
|
|
307
307
|
| **authenticator** | `IConnectionAuthenticator` | — (**required**) |
|
|
308
|
-
| **tenantResolver** | `(auth) => string \| undefined` — derives `tenantId` from the auth result
|
|
308
|
+
| **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result, on **both** transports; `undefined` and `null` mean "no opinion" and fall back | `auth.tenantId` |
|
|
309
309
|
| **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed` (fire-and-forget) | — |
|
|
310
310
|
| **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
|
|
311
311
|
| **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
|
|
312
|
-
| **presence** | `IPresenceStorage` —
|
|
312
|
+
| **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
|
|
313
313
|
| **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `maxConnectionsPerUser`, `emitConnectionEvent` | `/realtime/sse`, `30000`, `100`, `5`, `true` |
|
|
314
314
|
| **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults) |
|
|
315
315
|
| **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs` | `300`, `'disconnect'`, `60000` |
|
|
@@ -546,6 +546,46 @@ Read-side view of live connections — useful for admin endpoints and metrics.
|
|
|
546
546
|
|
|
547
547
|
Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePubSub`, `RedisOfflineQueue`.
|
|
548
548
|
|
|
549
|
+
#### Identity must be present or absent, never blank
|
|
550
|
+
|
|
551
|
+
`userId` must be a non-empty string, and `tenantId` must be either absent or a non-empty
|
|
552
|
+
string. A connection whose authenticator — or whose `tenantResolver` — yields a blank one is
|
|
553
|
+
**refused at bootstrap** rather than registered.
|
|
554
|
+
|
|
555
|
+
The reason is that blank is not missing. `userId` and `tenantId` key the connection registry
|
|
556
|
+
and compose the `user:` and `tenant:` rooms, so every connection carrying `''` lands under the
|
|
557
|
+
same key and joins the same room; a later emit to that key reaches all of them. On a long-lived
|
|
558
|
+
subscription that is not one wrong response but a stream that keeps delivering.
|
|
559
|
+
|
|
560
|
+
To place a connection in no tenant, the **authenticator omits `tenantId`** — that is indexed
|
|
561
|
+
under none and joins no tenant room, which an empty string is not. Whitespace counts as blank:
|
|
562
|
+
`' '` composes `user: ` just as `''` does.
|
|
563
|
+
|
|
564
|
+
Omission is the form to write, because it is the only one that compiles everywhere.
|
|
565
|
+
`AuthenticationResult` declares `tenantId?: string`; the runtime accepts an explicit `undefined`
|
|
566
|
+
or `null` too — an untyped claim spread into the result produces them routinely — but whether
|
|
567
|
+
either *type-checks* depends on the consuming project's `tsconfig`, which the published
|
|
568
|
+
declarations do not control:
|
|
569
|
+
|
|
570
|
+
| consumer's `tsconfig` | `tenantId: undefined` | `tenantId: null` |
|
|
571
|
+
| ----------------------------------------- | --------------------- | ---------------- |
|
|
572
|
+
| `strict` + `exactOptionalPropertyTypes` | `TS2375` | `TS2322` |
|
|
573
|
+
| `strict`, no `exactOptionalPropertyTypes` | compiles | `TS2322` |
|
|
574
|
+
| no `strictNullChecks` | compiles | compiles |
|
|
575
|
+
|
|
576
|
+
Omitting the key is correct in all three.
|
|
577
|
+
|
|
578
|
+
`tenantResolver` cannot clear a tenant, and this is the one asymmetry worth reading twice.
|
|
579
|
+
Resolution is `tenantResolver?.(auth) ?? auth.tenantId`, so a resolver returning `undefined` or
|
|
580
|
+
`null` means *no opinion* and falls back to the tenant the authenticator supplied. A resolver
|
|
581
|
+
written to place a connection in no tenant by returning `null` leaves it in `auth.tenantId`'s
|
|
582
|
+
room instead, still receiving that tenant's events. Decide the absent case in the
|
|
583
|
+
authenticator, where absence is what it looks like.
|
|
584
|
+
|
|
585
|
+
A blank identity surfaces as a server fault rather than a `401`, because the client's
|
|
586
|
+
credentials were accepted and the fault is in the authenticator. Return `null` to reject a
|
|
587
|
+
client.
|
|
588
|
+
|
|
549
589
|
#### Carrying handshake context into the hooks
|
|
550
590
|
|
|
551
591
|
`AuthenticationResult.metadata` is a free-form bag the library carries verbatim: it reaches
|
|
@@ -593,6 +633,21 @@ composeRoomId('TENANT', tenantId) // → "tenant:t_acme"
|
|
|
593
633
|
composeRoomId('RESOURCE', 'invoice', invoiceId) // → "resource:invoice:42"
|
|
594
634
|
```
|
|
595
635
|
|
|
636
|
+
`composeRoomId` joins its parts with `:` and escapes nothing, so a part must not contain `:`. The `encodeURIComponent` advice below holds for that `:` separator only, because it escapes `:` and leaves characters such as `-`, `.`, `_` and `~` alone.
|
|
637
|
+
`('a:b', 'c')` and `('a', 'b:c')` both give `resource:a:b:c` and land in the same room. When a
|
|
638
|
+
part comes from outside your code, encode it first:
|
|
639
|
+
`composeRoomId('RESOURCE', encodeURIComponent(type), encodeURIComponent(id))`.
|
|
640
|
+
|
|
641
|
+
A `resource:` room is not tenant-scoped: two tenants using the same type and id share it. When ids
|
|
642
|
+
are only unique within a tenant, pass the tenant as its own encoded part —
|
|
643
|
+
`composeRoomId('RESOURCE', 'invoice', encodeURIComponent(tenantId), encodeURIComponent(id))` —
|
|
644
|
+
because gluing them into one part with a separator that ids may contain, such as `-`, lets two
|
|
645
|
+
different pairs compose the same room.
|
|
646
|
+
|
|
647
|
+
Never pass client-supplied input to `joinRoom` or `emitToRoom` as a room id without checking that
|
|
648
|
+
it cannot start with the reserved `user:` or `tenant:` prefixes. The library does not guard them,
|
|
649
|
+
and joining `tenant:<other>` receives that tenant's events.
|
|
650
|
+
|
|
596
651
|
#### Role-scoped delivery
|
|
597
652
|
|
|
598
653
|
There is no `emitToRole`. Roles are the consumer's authorization vocabulary, not
|
|
@@ -692,16 +747,23 @@ const onConnect = joinRoleRoom({ get: () => ({ joinRoom }) }, 'admin', 'role:adm
|
|
|
692
747
|
|
|
693
748
|
### Reserved Events
|
|
694
749
|
|
|
695
|
-
|
|
750
|
+
These names belong to the library. Do not reuse them for application events.
|
|
751
|
+
|
|
752
|
+
**Emitted today**
|
|
753
|
+
|
|
754
|
+
| Event | Meaning |
|
|
755
|
+
| ------------------------------------ | ------------------------------------------------------- |
|
|
756
|
+
| `connection:established` | Handshake accepted (suppress via `emitConnectionEvent`) |
|
|
757
|
+
| `connection:reauthentication-failed` | Credentials no longer valid |
|
|
758
|
+
|
|
759
|
+
**Reserved, not emitted by the library.** An application may emit them itself; the library never does. The default SSE client subscribes to all of them except `error`. The browser dispatches a server-sent `error` event to the same handler as its own connection failures, so do not emit `error` over SSE: the client treats it as a dropped connection.
|
|
696
760
|
|
|
697
|
-
| Event | Meaning
|
|
698
|
-
| -------------------------------------- |
|
|
699
|
-
| `connection:
|
|
700
|
-
| `
|
|
701
|
-
| `
|
|
702
|
-
| `
|
|
703
|
-
| `error` | Transport-level error |
|
|
704
|
-
| `presence:online` / `presence:offline` | Presence changed (requires `IPresenceStorage`) |
|
|
761
|
+
| Event | Meaning |
|
|
762
|
+
| -------------------------------------- | -------------------------------------------------------------------- |
|
|
763
|
+
| `connection:credential-expiring` | Credential nearing expiry |
|
|
764
|
+
| `room:joined` / `room:left` | Room membership changed |
|
|
765
|
+
| `error` | Transport-level error |
|
|
766
|
+
| `presence:online` / `presence:offline` | Presence changed; emitted by your code, `IPresenceStorage` is a seam |
|
|
705
767
|
|
|
706
768
|
> [!NOTE]
|
|
707
769
|
> The SSE heartbeat is a `: keepalive` **comment line**, not a named event. It never appears in the `Last-Event-ID` id-space and never reaches a client listener.
|
package/dist/internal/index.cjs
CHANGED
|
@@ -177,6 +177,31 @@ var RESERVED_EVENT_NAMES = {
|
|
|
177
177
|
ERROR: "error"
|
|
178
178
|
};
|
|
179
179
|
|
|
180
|
+
// src/server/utils/assert-identity.ts
|
|
181
|
+
function isBlank(value) {
|
|
182
|
+
return typeof value !== "string" || value.trim().length === 0;
|
|
183
|
+
}
|
|
184
|
+
function resolveAuthTenant(options, auth) {
|
|
185
|
+
const resolved = options.tenantResolver?.(auth) ?? auth.tenantId;
|
|
186
|
+
if (resolved === void 0 || resolved === null) {
|
|
187
|
+
const { tenantId: _dropped, ...withoutTenant } = auth;
|
|
188
|
+
return withoutTenant;
|
|
189
|
+
}
|
|
190
|
+
return { ...auth, tenantId: resolved };
|
|
191
|
+
}
|
|
192
|
+
function assertIdentityIsNotBlank(auth) {
|
|
193
|
+
if (isBlank(auth.userId)) {
|
|
194
|
+
throw new Error(
|
|
195
|
+
`${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
if (auth.tenantId !== void 0 && isBlank(auth.tenantId)) {
|
|
199
|
+
throw new Error(
|
|
200
|
+
`${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
180
205
|
// src/server/utils/parse-cookie-header.ts
|
|
181
206
|
function parseCookieHeader(cookieHeader) {
|
|
182
207
|
const out = /* @__PURE__ */ Object.create(null);
|
|
@@ -786,6 +811,39 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
786
811
|
hooks;
|
|
787
812
|
offlineDelivery;
|
|
788
813
|
logger = new common.Logger(exports.SseSubscriptionHandler.name);
|
|
814
|
+
/**
|
|
815
|
+
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
816
|
+
*
|
|
817
|
+
* Both transports resolve the routing tenant through this one function, so a
|
|
818
|
+
* connection carries the same tenant whichever one opened it. The check runs on
|
|
819
|
+
* the resolved value rather than the raw one — validating what the server does not
|
|
820
|
+
* use would validate nothing.
|
|
821
|
+
*
|
|
822
|
+
* A blank identity is the consumer's configuration rather than the client's
|
|
823
|
+
* credentials, so it is deliberately not a 401: a 401 would tell a client its
|
|
824
|
+
* credentials were rejected when they were accepted, inviting a retry that cannot
|
|
825
|
+
* succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
|
|
826
|
+
* once, not an unhandled crash logging a stack on every reconnect.
|
|
827
|
+
*
|
|
828
|
+
* The reason names the operator's fix, so it goes to the server log and the client
|
|
829
|
+
* receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
|
|
830
|
+
* without a message.
|
|
831
|
+
*
|
|
832
|
+
* @param auth - The result the consumer's authenticator returned.
|
|
833
|
+
* @returns The same result with the routing tenant resolved.
|
|
834
|
+
* @throws InternalServerErrorException with the generic body when a trait is present
|
|
835
|
+
* but blank.
|
|
836
|
+
*/
|
|
837
|
+
resolveAndValidateIdentity(auth) {
|
|
838
|
+
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
839
|
+
try {
|
|
840
|
+
assertIdentityIsNotBlank(resolvedAuth);
|
|
841
|
+
} catch (err) {
|
|
842
|
+
this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
|
|
843
|
+
throw new common.InternalServerErrorException();
|
|
844
|
+
}
|
|
845
|
+
return resolvedAuth;
|
|
846
|
+
}
|
|
789
847
|
/**
|
|
790
848
|
* Handle an incoming SSE connection request end-to-end.
|
|
791
849
|
*
|
|
@@ -797,7 +855,15 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
797
855
|
* @param req - The incoming request (SSE GET).
|
|
798
856
|
* @param res - The response (passthrough for header mutations and heartbeat writes).
|
|
799
857
|
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
800
|
-
* @throws UnauthorizedException when authentication returns null
|
|
858
|
+
* @throws UnauthorizedException when authentication returns null — the client's
|
|
859
|
+
* credentials were rejected, which is a 401.
|
|
860
|
+
* @throws InternalServerErrorException when the authenticator, or the configured
|
|
861
|
+
* `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
|
|
862
|
+
* a 401: the credentials were accepted and the fault is the consumer's
|
|
863
|
+
* configuration, so it surfaces as a 500 rather than telling a client to retry
|
|
864
|
+
* something that cannot succeed. The exception carries no message, so the client
|
|
865
|
+
* gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
|
|
866
|
+
* written to the server log.
|
|
801
867
|
*/
|
|
802
868
|
async handle(req, res) {
|
|
803
869
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
@@ -805,8 +871,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
805
871
|
const context = buildAuthContext(req);
|
|
806
872
|
const auth = await this.transport.authenticate(context);
|
|
807
873
|
if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
808
|
-
const
|
|
809
|
-
const resolvedAuth = resolvedTenantId !== void 0 ? { ...auth, tenantId: resolvedTenantId } : auth;
|
|
874
|
+
const resolvedAuth = this.resolveAndValidateIdentity(auth);
|
|
810
875
|
const connectionId = crypto.randomUUID();
|
|
811
876
|
const subject = new rxjs.Subject();
|
|
812
877
|
const close$ = new rxjs.Subject();
|
|
@@ -1029,7 +1094,13 @@ exports.RealtimeService = class RealtimeService {
|
|
|
1029
1094
|
broadcast(event, data) {
|
|
1030
1095
|
return this.transport.broadcast(event, data);
|
|
1031
1096
|
}
|
|
1032
|
-
/**
|
|
1097
|
+
/**
|
|
1098
|
+
* Add a specific connection to a room.
|
|
1099
|
+
*
|
|
1100
|
+
* The room id is not checked. Never pass client-supplied input that could start
|
|
1101
|
+
* with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
|
|
1102
|
+
* receives that tenant's events.
|
|
1103
|
+
*/
|
|
1033
1104
|
joinRoom(connectionId, roomId) {
|
|
1034
1105
|
return this.transport.joinRoom(connectionId, roomId);
|
|
1035
1106
|
}
|
|
@@ -1099,7 +1170,7 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1099
1170
|
this.positiveCache.clear();
|
|
1100
1171
|
}
|
|
1101
1172
|
/**
|
|
1102
|
-
* Run one revalidation cycle over
|
|
1173
|
+
* Run one revalidation cycle over every active connection, SSE and WebSocket alike.
|
|
1103
1174
|
*
|
|
1104
1175
|
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
1105
1176
|
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
@@ -1109,7 +1180,11 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1109
1180
|
*/
|
|
1110
1181
|
async runCycle() {
|
|
1111
1182
|
const now = Date.now();
|
|
1112
|
-
|
|
1183
|
+
const connections = [
|
|
1184
|
+
...this.connections.allByTransport("sse"),
|
|
1185
|
+
...this.connections.allByTransport("websocket")
|
|
1186
|
+
];
|
|
1187
|
+
for (const conn of connections) {
|
|
1113
1188
|
try {
|
|
1114
1189
|
const lastValid = this.positiveCache.get(conn.connectionId);
|
|
1115
1190
|
if (lastValid !== void 0 && now - lastValid < this.policy.cacheTtlMs) continue;
|
|
@@ -1148,7 +1223,7 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1148
1223
|
tenantId: conn.tenantId,
|
|
1149
1224
|
roles: conn.originalAuth.roles,
|
|
1150
1225
|
metadata: conn.originalAuth.metadata,
|
|
1151
|
-
transport:
|
|
1226
|
+
transport: conn.transport,
|
|
1152
1227
|
ip: conn.ip,
|
|
1153
1228
|
userAgent: conn.userAgent,
|
|
1154
1229
|
connectedAt: conn.connectedAt
|
|
@@ -1678,9 +1753,11 @@ exports.RESERVED_EVENT_NAMES = RESERVED_EVENT_NAMES;
|
|
|
1678
1753
|
exports.ROOM_PREFIXES = ROOM_PREFIXES;
|
|
1679
1754
|
exports.RedisOfflineQueue = RedisOfflineQueue;
|
|
1680
1755
|
exports.RedisRealtimePubSub = RedisRealtimePubSub;
|
|
1756
|
+
exports.assertIdentityIsNotBlank = assertIdentityIsNotBlank;
|
|
1681
1757
|
exports.composeForRoot = composeForRoot;
|
|
1682
1758
|
exports.composeForRootAsync = composeForRootAsync;
|
|
1683
1759
|
exports.composeRoomId = composeRoomId;
|
|
1684
1760
|
exports.createSseController = createSseController;
|
|
1685
1761
|
exports.parseCookieHeader = parseCookieHeader;
|
|
1762
|
+
exports.resolveAuthTenant = resolveAuthTenant;
|
|
1686
1763
|
exports.sseWiring = sseWiring;
|
|
@@ -47,10 +47,10 @@ interface ConnectionAuthContext {
|
|
|
47
47
|
/**
|
|
48
48
|
* Query string parameters — useful for the ticket pattern.
|
|
49
49
|
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
50
|
+
* On WebSocket a repeated key (`?a=1&a=2`) arrives as a `string[]`, except the
|
|
51
|
+
* `ticket` parameter, which the gateway collapses to a single string. On SSE only
|
|
52
|
+
* a single string value is kept; a repeated key arrives as `undefined`.
|
|
53
|
+
* Authenticators that expect a single value should check `typeof value === 'string'`.
|
|
54
54
|
*/
|
|
55
55
|
readonly query: Record<string, string | string[] | undefined>;
|
|
56
56
|
/**
|
|
@@ -69,7 +69,20 @@ interface ConnectionAuthContext {
|
|
|
69
69
|
* may carry extra fields through the `metadata` bag.
|
|
70
70
|
*/
|
|
71
71
|
interface AuthenticationResult {
|
|
72
|
+
/**
|
|
73
|
+
* The authenticated account. Must be a non-empty string: a blank one indexes
|
|
74
|
+
* every such connection under a single key and joins them all to the room
|
|
75
|
+
* `user:`, so it is refused at connection bootstrap rather than registered.
|
|
76
|
+
*/
|
|
72
77
|
readonly userId: string;
|
|
78
|
+
/**
|
|
79
|
+
* The tenant this connection routes on, or absent when it belongs to none.
|
|
80
|
+
*
|
|
81
|
+
* Absent and empty are different. Omitting it — or returning `undefined` or
|
|
82
|
+
* `null` — means no tenant: indexed under none, joining no tenant room. An empty
|
|
83
|
+
* or whitespace-only string is refused, because it is a shared bucket rather than
|
|
84
|
+
* a missing value: every connection carrying `''` lands under the same key.
|
|
85
|
+
*/
|
|
73
86
|
readonly tenantId?: string;
|
|
74
87
|
readonly roles?: readonly string[];
|
|
75
88
|
/**
|
|
@@ -110,6 +123,12 @@ interface IConnectionAuthenticator {
|
|
|
110
123
|
*
|
|
111
124
|
* @returns the authenticated result, or `null` to reject the connection (the
|
|
112
125
|
* transport replies 401 / disconnects accordingly).
|
|
126
|
+
*
|
|
127
|
+
* Returning a result whose `userId` is blank, or whose `tenantId` is present but
|
|
128
|
+
* blank, is not a second way to reject: it is a contract violation. The connection
|
|
129
|
+
* is refused either way, but it surfaces as a server fault rather than a 401,
|
|
130
|
+
* because the credentials were accepted and the fault is in this method. Return
|
|
131
|
+
* `null` to reject a client.
|
|
113
132
|
*/
|
|
114
133
|
authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
|
|
115
134
|
/**
|
|
@@ -328,7 +347,17 @@ interface ReauthenticationPolicy {
|
|
|
328
347
|
interface BymaxRealtimeModuleOptions {
|
|
329
348
|
transport: TransportMode;
|
|
330
349
|
authenticator: IConnectionAuthenticator;
|
|
331
|
-
|
|
350
|
+
/**
|
|
351
|
+
* Derive the tenant a connection routes on from the authenticated result.
|
|
352
|
+
*
|
|
353
|
+
* Applied on **both** transports. `undefined` and `null` both mean "no opinion"
|
|
354
|
+
* and fall back to `auth.tenantId` rather than clearing it; to place a connection
|
|
355
|
+
* in no tenant, return a result without one from the authenticator. `null` is in
|
|
356
|
+
* the signature because the implementation accepts it and a type narrower than the
|
|
357
|
+
* behaviour forces a cast on anyone testing the boundary. A blank string is
|
|
358
|
+
* refused, on the same terms as `AuthenticationResult.tenantId`.
|
|
359
|
+
*/
|
|
360
|
+
tenantResolver?: (auth: AuthenticationResult) => string | undefined | null;
|
|
332
361
|
hooks?: IConnectionLifecycleHooks;
|
|
333
362
|
pubsub?: IRealtimePubSub;
|
|
334
363
|
offlineQueue?: IOfflineQueueStorage;
|
|
@@ -740,7 +769,13 @@ declare class RealtimeService {
|
|
|
740
769
|
emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
|
|
741
770
|
/** Send to every connected client. Use sparingly. */
|
|
742
771
|
broadcast(event: string, data: unknown): Promise<void>;
|
|
743
|
-
/**
|
|
772
|
+
/**
|
|
773
|
+
* Add a specific connection to a room.
|
|
774
|
+
*
|
|
775
|
+
* The room id is not checked. Never pass client-supplied input that could start
|
|
776
|
+
* with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
|
|
777
|
+
* receives that tenant's events.
|
|
778
|
+
*/
|
|
744
779
|
joinRoom(connectionId: string, roomId: string): Promise<void>;
|
|
745
780
|
/** Remove a specific connection from a room. */
|
|
746
781
|
leaveRoom(connectionId: string, roomId: string): Promise<void>;
|
|
@@ -754,8 +789,8 @@ declare class RealtimeService {
|
|
|
754
789
|
*/
|
|
755
790
|
|
|
756
791
|
/**
|
|
757
|
-
* Periodically revalidates active
|
|
758
|
-
* `IConnectionAuthenticator.revalidate` contract.
|
|
792
|
+
* Periodically revalidates every active connection, on both transports, through the
|
|
793
|
+
* consumer-provided `IConnectionAuthenticator.revalidate` contract.
|
|
759
794
|
*
|
|
760
795
|
* A short positive cache (default 60 s) avoids hammering the auth backend on every
|
|
761
796
|
* interval tick. On failure the service either disconnects immediately or first emits
|
|
@@ -791,7 +826,7 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
|
|
|
791
826
|
*/
|
|
792
827
|
onApplicationShutdown(): void;
|
|
793
828
|
/**
|
|
794
|
-
* Run one revalidation cycle over
|
|
829
|
+
* Run one revalidation cycle over every active connection, SSE and WebSocket alike.
|
|
795
830
|
*
|
|
796
831
|
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
797
832
|
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
@@ -1137,6 +1172,30 @@ declare class SseSubscriptionHandler {
|
|
|
1137
1172
|
private readonly offlineDelivery?;
|
|
1138
1173
|
private readonly logger;
|
|
1139
1174
|
constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined);
|
|
1175
|
+
/**
|
|
1176
|
+
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
1177
|
+
*
|
|
1178
|
+
* Both transports resolve the routing tenant through this one function, so a
|
|
1179
|
+
* connection carries the same tenant whichever one opened it. The check runs on
|
|
1180
|
+
* the resolved value rather than the raw one — validating what the server does not
|
|
1181
|
+
* use would validate nothing.
|
|
1182
|
+
*
|
|
1183
|
+
* A blank identity is the consumer's configuration rather than the client's
|
|
1184
|
+
* credentials, so it is deliberately not a 401: a 401 would tell a client its
|
|
1185
|
+
* credentials were rejected when they were accepted, inviting a retry that cannot
|
|
1186
|
+
* succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
|
|
1187
|
+
* once, not an unhandled crash logging a stack on every reconnect.
|
|
1188
|
+
*
|
|
1189
|
+
* The reason names the operator's fix, so it goes to the server log and the client
|
|
1190
|
+
* receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
|
|
1191
|
+
* without a message.
|
|
1192
|
+
*
|
|
1193
|
+
* @param auth - The result the consumer's authenticator returned.
|
|
1194
|
+
* @returns The same result with the routing tenant resolved.
|
|
1195
|
+
* @throws InternalServerErrorException with the generic body when a trait is present
|
|
1196
|
+
* but blank.
|
|
1197
|
+
*/
|
|
1198
|
+
private resolveAndValidateIdentity;
|
|
1140
1199
|
/**
|
|
1141
1200
|
* Handle an incoming SSE connection request end-to-end.
|
|
1142
1201
|
*
|
|
@@ -1148,7 +1207,15 @@ declare class SseSubscriptionHandler {
|
|
|
1148
1207
|
* @param req - The incoming request (SSE GET).
|
|
1149
1208
|
* @param res - The response (passthrough for header mutations and heartbeat writes).
|
|
1150
1209
|
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
1151
|
-
* @throws UnauthorizedException when authentication returns null
|
|
1210
|
+
* @throws UnauthorizedException when authentication returns null — the client's
|
|
1211
|
+
* credentials were rejected, which is a 401.
|
|
1212
|
+
* @throws InternalServerErrorException when the authenticator, or the configured
|
|
1213
|
+
* `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
|
|
1214
|
+
* a 401: the credentials were accepted and the fault is the consumer's
|
|
1215
|
+
* configuration, so it surfaces as a 500 rather than telling a client to retry
|
|
1216
|
+
* something that cannot succeed. The exception carries no message, so the client
|
|
1217
|
+
* gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
|
|
1218
|
+
* written to the server log.
|
|
1152
1219
|
*/
|
|
1153
1220
|
handle(req: SseRequest, res: SseResponse): Promise<Observable<MessageEvent>>;
|
|
1154
1221
|
/**
|
|
@@ -1376,6 +1443,45 @@ declare class RedisOfflineQueue implements IOfflineQueueStorage {
|
|
|
1376
1443
|
acknowledge(userId: string, upToId: string): Promise<void>;
|
|
1377
1444
|
}
|
|
1378
1445
|
|
|
1446
|
+
/**
|
|
1447
|
+
* Resolve the tenant a connection routes on, and normalize a nullish result.
|
|
1448
|
+
*
|
|
1449
|
+
* Both transports must resolve the routing tenant through this one function. Two
|
|
1450
|
+
* copies of the rule can disagree, and a connection routed on one tenant by SSE and
|
|
1451
|
+
* another by WebSocket is a delivery to the wrong audience.
|
|
1452
|
+
*
|
|
1453
|
+
* `null` normalizes to `undefined` rather than passing through. `ConnectionRegistry`
|
|
1454
|
+
* guards on `!== undefined`, so a `null` tenant would otherwise be indexed under
|
|
1455
|
+
* `null` and compose the room `tenant:null` — the same shared-bucket defect as the
|
|
1456
|
+
* empty string, in a value a JWT claim produces routinely.
|
|
1457
|
+
*
|
|
1458
|
+
* @param options - The module options, read for an optional `tenantResolver`.
|
|
1459
|
+
* @param auth - The authentication result the consumer's authenticator returned.
|
|
1460
|
+
* @returns The same result with `tenantId` resolved, or absent when there is none.
|
|
1461
|
+
*/
|
|
1462
|
+
declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'tenantResolver'>, auth: AuthenticationResult): AuthenticationResult;
|
|
1463
|
+
/**
|
|
1464
|
+
* Reject an authentication result whose identity traits are present but blank.
|
|
1465
|
+
*
|
|
1466
|
+
* `userId` and `tenantId` index the registry and compose the `user:` and `tenant:`
|
|
1467
|
+
* rooms, so a blank one is not a missing value — it is a shared bucket. Every
|
|
1468
|
+
* connection whose authenticator returned `''` lands under the same key and joins
|
|
1469
|
+
* the same room, and a later emit to that key reaches all of them. On a long-lived
|
|
1470
|
+
* subscription that is not one wrong response but a stream that keeps delivering
|
|
1471
|
+
* for the life of the connection.
|
|
1472
|
+
*
|
|
1473
|
+
* An absent `tenantId` stays valid and means exactly what it says: this connection
|
|
1474
|
+
* belongs to no tenant, so it is indexed under none and joins no tenant room. The
|
|
1475
|
+
* distinction drawn is between *absent* and *empty*, and only the second is refused.
|
|
1476
|
+
*
|
|
1477
|
+
* Whitespace counts as blank. `' '` composes `user: ` and indexes under `' '`, which
|
|
1478
|
+
* is the same defect wearing a different character.
|
|
1479
|
+
*
|
|
1480
|
+
* @param auth - The resolved authentication result, after `resolveAuthTenant`.
|
|
1481
|
+
* @throws Error carrying `REALTIME_AUTH_FAILED` when a trait is present but blank.
|
|
1482
|
+
*/
|
|
1483
|
+
declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
|
|
1484
|
+
|
|
1379
1485
|
/**
|
|
1380
1486
|
* @fileoverview Canonical room id prefixes for scoping emits and auto-join.
|
|
1381
1487
|
* @layer shared
|
|
@@ -1408,7 +1514,13 @@ type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
|
|
|
1408
1514
|
* Build a canonical room id following the library's prefix convention.
|
|
1409
1515
|
*
|
|
1410
1516
|
* Validation of the parts (e.g. non-empty ids) is the caller's responsibility —
|
|
1411
|
-
* this helper only joins the prefix and parts with
|
|
1517
|
+
* this helper only joins the prefix and parts with `:` and escapes nothing, so a
|
|
1518
|
+
* part must not contain `:`. `('a:b', 'c')` and `('a', 'b:c')` both give
|
|
1519
|
+
* `resource:a:b:c`; encode parts that come from outside with `encodeURIComponent`, which escapes `:` and so
|
|
1520
|
+
* is sound for this `:` separator only.
|
|
1521
|
+
*
|
|
1522
|
+
* A `RESOURCE` room carries no tenant. When ids are only unique within one, pass
|
|
1523
|
+
* the tenant as its own encoded part rather than gluing it to the id.
|
|
1412
1524
|
*
|
|
1413
1525
|
* @example
|
|
1414
1526
|
* ```ts
|
|
@@ -1539,4 +1651,4 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
1539
1651
|
/** Union of canonical error code values. */
|
|
1540
1652
|
type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
|
|
1541
1653
|
|
|
1542
|
-
export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, sseWiring };
|
|
1654
|
+
export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
|
package/dist/internal/index.d.ts
CHANGED
|
@@ -47,10 +47,10 @@ interface ConnectionAuthContext {
|
|
|
47
47
|
/**
|
|
48
48
|
* Query string parameters — useful for the ticket pattern.
|
|
49
49
|
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
50
|
+
* On WebSocket a repeated key (`?a=1&a=2`) arrives as a `string[]`, except the
|
|
51
|
+
* `ticket` parameter, which the gateway collapses to a single string. On SSE only
|
|
52
|
+
* a single string value is kept; a repeated key arrives as `undefined`.
|
|
53
|
+
* Authenticators that expect a single value should check `typeof value === 'string'`.
|
|
54
54
|
*/
|
|
55
55
|
readonly query: Record<string, string | string[] | undefined>;
|
|
56
56
|
/**
|
|
@@ -69,7 +69,20 @@ interface ConnectionAuthContext {
|
|
|
69
69
|
* may carry extra fields through the `metadata` bag.
|
|
70
70
|
*/
|
|
71
71
|
interface AuthenticationResult {
|
|
72
|
+
/**
|
|
73
|
+
* The authenticated account. Must be a non-empty string: a blank one indexes
|
|
74
|
+
* every such connection under a single key and joins them all to the room
|
|
75
|
+
* `user:`, so it is refused at connection bootstrap rather than registered.
|
|
76
|
+
*/
|
|
72
77
|
readonly userId: string;
|
|
78
|
+
/**
|
|
79
|
+
* The tenant this connection routes on, or absent when it belongs to none.
|
|
80
|
+
*
|
|
81
|
+
* Absent and empty are different. Omitting it — or returning `undefined` or
|
|
82
|
+
* `null` — means no tenant: indexed under none, joining no tenant room. An empty
|
|
83
|
+
* or whitespace-only string is refused, because it is a shared bucket rather than
|
|
84
|
+
* a missing value: every connection carrying `''` lands under the same key.
|
|
85
|
+
*/
|
|
73
86
|
readonly tenantId?: string;
|
|
74
87
|
readonly roles?: readonly string[];
|
|
75
88
|
/**
|
|
@@ -110,6 +123,12 @@ interface IConnectionAuthenticator {
|
|
|
110
123
|
*
|
|
111
124
|
* @returns the authenticated result, or `null` to reject the connection (the
|
|
112
125
|
* transport replies 401 / disconnects accordingly).
|
|
126
|
+
*
|
|
127
|
+
* Returning a result whose `userId` is blank, or whose `tenantId` is present but
|
|
128
|
+
* blank, is not a second way to reject: it is a contract violation. The connection
|
|
129
|
+
* is refused either way, but it surfaces as a server fault rather than a 401,
|
|
130
|
+
* because the credentials were accepted and the fault is in this method. Return
|
|
131
|
+
* `null` to reject a client.
|
|
113
132
|
*/
|
|
114
133
|
authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
|
|
115
134
|
/**
|
|
@@ -328,7 +347,17 @@ interface ReauthenticationPolicy {
|
|
|
328
347
|
interface BymaxRealtimeModuleOptions {
|
|
329
348
|
transport: TransportMode;
|
|
330
349
|
authenticator: IConnectionAuthenticator;
|
|
331
|
-
|
|
350
|
+
/**
|
|
351
|
+
* Derive the tenant a connection routes on from the authenticated result.
|
|
352
|
+
*
|
|
353
|
+
* Applied on **both** transports. `undefined` and `null` both mean "no opinion"
|
|
354
|
+
* and fall back to `auth.tenantId` rather than clearing it; to place a connection
|
|
355
|
+
* in no tenant, return a result without one from the authenticator. `null` is in
|
|
356
|
+
* the signature because the implementation accepts it and a type narrower than the
|
|
357
|
+
* behaviour forces a cast on anyone testing the boundary. A blank string is
|
|
358
|
+
* refused, on the same terms as `AuthenticationResult.tenantId`.
|
|
359
|
+
*/
|
|
360
|
+
tenantResolver?: (auth: AuthenticationResult) => string | undefined | null;
|
|
332
361
|
hooks?: IConnectionLifecycleHooks;
|
|
333
362
|
pubsub?: IRealtimePubSub;
|
|
334
363
|
offlineQueue?: IOfflineQueueStorage;
|
|
@@ -740,7 +769,13 @@ declare class RealtimeService {
|
|
|
740
769
|
emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
|
|
741
770
|
/** Send to every connected client. Use sparingly. */
|
|
742
771
|
broadcast(event: string, data: unknown): Promise<void>;
|
|
743
|
-
/**
|
|
772
|
+
/**
|
|
773
|
+
* Add a specific connection to a room.
|
|
774
|
+
*
|
|
775
|
+
* The room id is not checked. Never pass client-supplied input that could start
|
|
776
|
+
* with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
|
|
777
|
+
* receives that tenant's events.
|
|
778
|
+
*/
|
|
744
779
|
joinRoom(connectionId: string, roomId: string): Promise<void>;
|
|
745
780
|
/** Remove a specific connection from a room. */
|
|
746
781
|
leaveRoom(connectionId: string, roomId: string): Promise<void>;
|
|
@@ -754,8 +789,8 @@ declare class RealtimeService {
|
|
|
754
789
|
*/
|
|
755
790
|
|
|
756
791
|
/**
|
|
757
|
-
* Periodically revalidates active
|
|
758
|
-
* `IConnectionAuthenticator.revalidate` contract.
|
|
792
|
+
* Periodically revalidates every active connection, on both transports, through the
|
|
793
|
+
* consumer-provided `IConnectionAuthenticator.revalidate` contract.
|
|
759
794
|
*
|
|
760
795
|
* A short positive cache (default 60 s) avoids hammering the auth backend on every
|
|
761
796
|
* interval tick. On failure the service either disconnects immediately or first emits
|
|
@@ -791,7 +826,7 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
|
|
|
791
826
|
*/
|
|
792
827
|
onApplicationShutdown(): void;
|
|
793
828
|
/**
|
|
794
|
-
* Run one revalidation cycle over
|
|
829
|
+
* Run one revalidation cycle over every active connection, SSE and WebSocket alike.
|
|
795
830
|
*
|
|
796
831
|
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
797
832
|
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
@@ -1137,6 +1172,30 @@ declare class SseSubscriptionHandler {
|
|
|
1137
1172
|
private readonly offlineDelivery?;
|
|
1138
1173
|
private readonly logger;
|
|
1139
1174
|
constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined);
|
|
1175
|
+
/**
|
|
1176
|
+
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
1177
|
+
*
|
|
1178
|
+
* Both transports resolve the routing tenant through this one function, so a
|
|
1179
|
+
* connection carries the same tenant whichever one opened it. The check runs on
|
|
1180
|
+
* the resolved value rather than the raw one — validating what the server does not
|
|
1181
|
+
* use would validate nothing.
|
|
1182
|
+
*
|
|
1183
|
+
* A blank identity is the consumer's configuration rather than the client's
|
|
1184
|
+
* credentials, so it is deliberately not a 401: a 401 would tell a client its
|
|
1185
|
+
* credentials were rejected when they were accepted, inviting a retry that cannot
|
|
1186
|
+
* succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
|
|
1187
|
+
* once, not an unhandled crash logging a stack on every reconnect.
|
|
1188
|
+
*
|
|
1189
|
+
* The reason names the operator's fix, so it goes to the server log and the client
|
|
1190
|
+
* receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
|
|
1191
|
+
* without a message.
|
|
1192
|
+
*
|
|
1193
|
+
* @param auth - The result the consumer's authenticator returned.
|
|
1194
|
+
* @returns The same result with the routing tenant resolved.
|
|
1195
|
+
* @throws InternalServerErrorException with the generic body when a trait is present
|
|
1196
|
+
* but blank.
|
|
1197
|
+
*/
|
|
1198
|
+
private resolveAndValidateIdentity;
|
|
1140
1199
|
/**
|
|
1141
1200
|
* Handle an incoming SSE connection request end-to-end.
|
|
1142
1201
|
*
|
|
@@ -1148,7 +1207,15 @@ declare class SseSubscriptionHandler {
|
|
|
1148
1207
|
* @param req - The incoming request (SSE GET).
|
|
1149
1208
|
* @param res - The response (passthrough for header mutations and heartbeat writes).
|
|
1150
1209
|
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
1151
|
-
* @throws UnauthorizedException when authentication returns null
|
|
1210
|
+
* @throws UnauthorizedException when authentication returns null — the client's
|
|
1211
|
+
* credentials were rejected, which is a 401.
|
|
1212
|
+
* @throws InternalServerErrorException when the authenticator, or the configured
|
|
1213
|
+
* `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
|
|
1214
|
+
* a 401: the credentials were accepted and the fault is the consumer's
|
|
1215
|
+
* configuration, so it surfaces as a 500 rather than telling a client to retry
|
|
1216
|
+
* something that cannot succeed. The exception carries no message, so the client
|
|
1217
|
+
* gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
|
|
1218
|
+
* written to the server log.
|
|
1152
1219
|
*/
|
|
1153
1220
|
handle(req: SseRequest, res: SseResponse): Promise<Observable<MessageEvent>>;
|
|
1154
1221
|
/**
|
|
@@ -1376,6 +1443,45 @@ declare class RedisOfflineQueue implements IOfflineQueueStorage {
|
|
|
1376
1443
|
acknowledge(userId: string, upToId: string): Promise<void>;
|
|
1377
1444
|
}
|
|
1378
1445
|
|
|
1446
|
+
/**
|
|
1447
|
+
* Resolve the tenant a connection routes on, and normalize a nullish result.
|
|
1448
|
+
*
|
|
1449
|
+
* Both transports must resolve the routing tenant through this one function. Two
|
|
1450
|
+
* copies of the rule can disagree, and a connection routed on one tenant by SSE and
|
|
1451
|
+
* another by WebSocket is a delivery to the wrong audience.
|
|
1452
|
+
*
|
|
1453
|
+
* `null` normalizes to `undefined` rather than passing through. `ConnectionRegistry`
|
|
1454
|
+
* guards on `!== undefined`, so a `null` tenant would otherwise be indexed under
|
|
1455
|
+
* `null` and compose the room `tenant:null` — the same shared-bucket defect as the
|
|
1456
|
+
* empty string, in a value a JWT claim produces routinely.
|
|
1457
|
+
*
|
|
1458
|
+
* @param options - The module options, read for an optional `tenantResolver`.
|
|
1459
|
+
* @param auth - The authentication result the consumer's authenticator returned.
|
|
1460
|
+
* @returns The same result with `tenantId` resolved, or absent when there is none.
|
|
1461
|
+
*/
|
|
1462
|
+
declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'tenantResolver'>, auth: AuthenticationResult): AuthenticationResult;
|
|
1463
|
+
/**
|
|
1464
|
+
* Reject an authentication result whose identity traits are present but blank.
|
|
1465
|
+
*
|
|
1466
|
+
* `userId` and `tenantId` index the registry and compose the `user:` and `tenant:`
|
|
1467
|
+
* rooms, so a blank one is not a missing value — it is a shared bucket. Every
|
|
1468
|
+
* connection whose authenticator returned `''` lands under the same key and joins
|
|
1469
|
+
* the same room, and a later emit to that key reaches all of them. On a long-lived
|
|
1470
|
+
* subscription that is not one wrong response but a stream that keeps delivering
|
|
1471
|
+
* for the life of the connection.
|
|
1472
|
+
*
|
|
1473
|
+
* An absent `tenantId` stays valid and means exactly what it says: this connection
|
|
1474
|
+
* belongs to no tenant, so it is indexed under none and joins no tenant room. The
|
|
1475
|
+
* distinction drawn is between *absent* and *empty*, and only the second is refused.
|
|
1476
|
+
*
|
|
1477
|
+
* Whitespace counts as blank. `' '` composes `user: ` and indexes under `' '`, which
|
|
1478
|
+
* is the same defect wearing a different character.
|
|
1479
|
+
*
|
|
1480
|
+
* @param auth - The resolved authentication result, after `resolveAuthTenant`.
|
|
1481
|
+
* @throws Error carrying `REALTIME_AUTH_FAILED` when a trait is present but blank.
|
|
1482
|
+
*/
|
|
1483
|
+
declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
|
|
1484
|
+
|
|
1379
1485
|
/**
|
|
1380
1486
|
* @fileoverview Canonical room id prefixes for scoping emits and auto-join.
|
|
1381
1487
|
* @layer shared
|
|
@@ -1408,7 +1514,13 @@ type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
|
|
|
1408
1514
|
* Build a canonical room id following the library's prefix convention.
|
|
1409
1515
|
*
|
|
1410
1516
|
* Validation of the parts (e.g. non-empty ids) is the caller's responsibility —
|
|
1411
|
-
* this helper only joins the prefix and parts with
|
|
1517
|
+
* this helper only joins the prefix and parts with `:` and escapes nothing, so a
|
|
1518
|
+
* part must not contain `:`. `('a:b', 'c')` and `('a', 'b:c')` both give
|
|
1519
|
+
* `resource:a:b:c`; encode parts that come from outside with `encodeURIComponent`, which escapes `:` and so
|
|
1520
|
+
* is sound for this `:` separator only.
|
|
1521
|
+
*
|
|
1522
|
+
* A `RESOURCE` room carries no tenant. When ids are only unique within one, pass
|
|
1523
|
+
* the tenant as its own encoded part rather than gluing it to the id.
|
|
1412
1524
|
*
|
|
1413
1525
|
* @example
|
|
1414
1526
|
* ```ts
|
|
@@ -1539,4 +1651,4 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
1539
1651
|
/** Union of canonical error code values. */
|
|
1540
1652
|
type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
|
|
1541
1653
|
|
|
1542
|
-
export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, sseWiring };
|
|
1654
|
+
export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
|
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, UnauthorizedException } from '@nestjs/common';
|
|
2
|
+
import { Injectable, Optional, Inject, Logger, Global, Module, Sse, Req, Res, Controller, InternalServerErrorException, 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
|
|
|
@@ -175,6 +175,31 @@ var RESERVED_EVENT_NAMES = {
|
|
|
175
175
|
ERROR: "error"
|
|
176
176
|
};
|
|
177
177
|
|
|
178
|
+
// src/server/utils/assert-identity.ts
|
|
179
|
+
function isBlank(value) {
|
|
180
|
+
return typeof value !== "string" || value.trim().length === 0;
|
|
181
|
+
}
|
|
182
|
+
function resolveAuthTenant(options, auth) {
|
|
183
|
+
const resolved = options.tenantResolver?.(auth) ?? auth.tenantId;
|
|
184
|
+
if (resolved === void 0 || resolved === null) {
|
|
185
|
+
const { tenantId: _dropped, ...withoutTenant } = auth;
|
|
186
|
+
return withoutTenant;
|
|
187
|
+
}
|
|
188
|
+
return { ...auth, tenantId: resolved };
|
|
189
|
+
}
|
|
190
|
+
function assertIdentityIsNotBlank(auth) {
|
|
191
|
+
if (isBlank(auth.userId)) {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
if (auth.tenantId !== void 0 && isBlank(auth.tenantId)) {
|
|
197
|
+
throw new Error(
|
|
198
|
+
`${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
178
203
|
// src/server/utils/parse-cookie-header.ts
|
|
179
204
|
function parseCookieHeader(cookieHeader) {
|
|
180
205
|
const out = /* @__PURE__ */ Object.create(null);
|
|
@@ -784,6 +809,39 @@ var SseSubscriptionHandler = class {
|
|
|
784
809
|
hooks;
|
|
785
810
|
offlineDelivery;
|
|
786
811
|
logger = new Logger(SseSubscriptionHandler.name);
|
|
812
|
+
/**
|
|
813
|
+
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
814
|
+
*
|
|
815
|
+
* Both transports resolve the routing tenant through this one function, so a
|
|
816
|
+
* connection carries the same tenant whichever one opened it. The check runs on
|
|
817
|
+
* the resolved value rather than the raw one — validating what the server does not
|
|
818
|
+
* use would validate nothing.
|
|
819
|
+
*
|
|
820
|
+
* A blank identity is the consumer's configuration rather than the client's
|
|
821
|
+
* credentials, so it is deliberately not a 401: a 401 would tell a client its
|
|
822
|
+
* credentials were rejected when they were accepted, inviting a retry that cannot
|
|
823
|
+
* succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
|
|
824
|
+
* once, not an unhandled crash logging a stack on every reconnect.
|
|
825
|
+
*
|
|
826
|
+
* The reason names the operator's fix, so it goes to the server log and the client
|
|
827
|
+
* receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
|
|
828
|
+
* without a message.
|
|
829
|
+
*
|
|
830
|
+
* @param auth - The result the consumer's authenticator returned.
|
|
831
|
+
* @returns The same result with the routing tenant resolved.
|
|
832
|
+
* @throws InternalServerErrorException with the generic body when a trait is present
|
|
833
|
+
* but blank.
|
|
834
|
+
*/
|
|
835
|
+
resolveAndValidateIdentity(auth) {
|
|
836
|
+
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
837
|
+
try {
|
|
838
|
+
assertIdentityIsNotBlank(resolvedAuth);
|
|
839
|
+
} catch (err) {
|
|
840
|
+
this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
|
|
841
|
+
throw new InternalServerErrorException();
|
|
842
|
+
}
|
|
843
|
+
return resolvedAuth;
|
|
844
|
+
}
|
|
787
845
|
/**
|
|
788
846
|
* Handle an incoming SSE connection request end-to-end.
|
|
789
847
|
*
|
|
@@ -795,7 +853,15 @@ var SseSubscriptionHandler = class {
|
|
|
795
853
|
* @param req - The incoming request (SSE GET).
|
|
796
854
|
* @param res - The response (passthrough for header mutations and heartbeat writes).
|
|
797
855
|
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
798
|
-
* @throws UnauthorizedException when authentication returns null
|
|
856
|
+
* @throws UnauthorizedException when authentication returns null — the client's
|
|
857
|
+
* credentials were rejected, which is a 401.
|
|
858
|
+
* @throws InternalServerErrorException when the authenticator, or the configured
|
|
859
|
+
* `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
|
|
860
|
+
* a 401: the credentials were accepted and the fault is the consumer's
|
|
861
|
+
* configuration, so it surfaces as a 500 rather than telling a client to retry
|
|
862
|
+
* something that cannot succeed. The exception carries no message, so the client
|
|
863
|
+
* gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
|
|
864
|
+
* written to the server log.
|
|
799
865
|
*/
|
|
800
866
|
async handle(req, res) {
|
|
801
867
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
@@ -803,8 +869,7 @@ var SseSubscriptionHandler = class {
|
|
|
803
869
|
const context = buildAuthContext(req);
|
|
804
870
|
const auth = await this.transport.authenticate(context);
|
|
805
871
|
if (!auth) throw new UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
806
|
-
const
|
|
807
|
-
const resolvedAuth = resolvedTenantId !== void 0 ? { ...auth, tenantId: resolvedTenantId } : auth;
|
|
872
|
+
const resolvedAuth = this.resolveAndValidateIdentity(auth);
|
|
808
873
|
const connectionId = randomUUID();
|
|
809
874
|
const subject = new Subject();
|
|
810
875
|
const close$ = new Subject();
|
|
@@ -1027,7 +1092,13 @@ var RealtimeService = class {
|
|
|
1027
1092
|
broadcast(event, data) {
|
|
1028
1093
|
return this.transport.broadcast(event, data);
|
|
1029
1094
|
}
|
|
1030
|
-
/**
|
|
1095
|
+
/**
|
|
1096
|
+
* Add a specific connection to a room.
|
|
1097
|
+
*
|
|
1098
|
+
* The room id is not checked. Never pass client-supplied input that could start
|
|
1099
|
+
* with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
|
|
1100
|
+
* receives that tenant's events.
|
|
1101
|
+
*/
|
|
1031
1102
|
joinRoom(connectionId, roomId) {
|
|
1032
1103
|
return this.transport.joinRoom(connectionId, roomId);
|
|
1033
1104
|
}
|
|
@@ -1097,7 +1168,7 @@ var ReauthenticationService = class {
|
|
|
1097
1168
|
this.positiveCache.clear();
|
|
1098
1169
|
}
|
|
1099
1170
|
/**
|
|
1100
|
-
* Run one revalidation cycle over
|
|
1171
|
+
* Run one revalidation cycle over every active connection, SSE and WebSocket alike.
|
|
1101
1172
|
*
|
|
1102
1173
|
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
1103
1174
|
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
@@ -1107,7 +1178,11 @@ var ReauthenticationService = class {
|
|
|
1107
1178
|
*/
|
|
1108
1179
|
async runCycle() {
|
|
1109
1180
|
const now = Date.now();
|
|
1110
|
-
|
|
1181
|
+
const connections = [
|
|
1182
|
+
...this.connections.allByTransport("sse"),
|
|
1183
|
+
...this.connections.allByTransport("websocket")
|
|
1184
|
+
];
|
|
1185
|
+
for (const conn of connections) {
|
|
1111
1186
|
try {
|
|
1112
1187
|
const lastValid = this.positiveCache.get(conn.connectionId);
|
|
1113
1188
|
if (lastValid !== void 0 && now - lastValid < this.policy.cacheTtlMs) continue;
|
|
@@ -1146,7 +1221,7 @@ var ReauthenticationService = class {
|
|
|
1146
1221
|
tenantId: conn.tenantId,
|
|
1147
1222
|
roles: conn.originalAuth.roles,
|
|
1148
1223
|
metadata: conn.originalAuth.metadata,
|
|
1149
|
-
transport:
|
|
1224
|
+
transport: conn.transport,
|
|
1150
1225
|
ip: conn.ip,
|
|
1151
1226
|
userAgent: conn.userAgent,
|
|
1152
1227
|
connectedAt: conn.connectedAt
|
|
@@ -1663,4 +1738,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
1663
1738
|
}
|
|
1664
1739
|
};
|
|
1665
1740
|
|
|
1666
|
-
export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, sseWiring };
|
|
1741
|
+
export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
|
package/dist/websocket/index.cjs
CHANGED
|
@@ -430,34 +430,54 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
430
430
|
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
431
431
|
* linger in an unregistered state and receive broadcast events.
|
|
432
432
|
*/
|
|
433
|
+
/**
|
|
434
|
+
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
435
|
+
*
|
|
436
|
+
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
437
|
+
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
438
|
+
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
439
|
+
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
440
|
+
* expects a string is a bug at the far end.
|
|
441
|
+
*
|
|
442
|
+
* @param socket - The connecting Socket.IO socket.
|
|
443
|
+
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
444
|
+
*/
|
|
445
|
+
buildAuthContext(socket) {
|
|
446
|
+
const { handshake } = socket;
|
|
447
|
+
const headers = this.normalizeHeaders(handshake.headers);
|
|
448
|
+
const query = { ...handshake.query };
|
|
449
|
+
const handshakeAuth = handshake.auth;
|
|
450
|
+
if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
|
|
451
|
+
if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
|
|
452
|
+
const ticket = firstQueryValue(query["ticket"]);
|
|
453
|
+
if (ticket !== void 0) query["ticket"] = ticket;
|
|
454
|
+
return {
|
|
455
|
+
cookies: internal.parseCookieHeader(handshake.headers.cookie ?? ""),
|
|
456
|
+
headers,
|
|
457
|
+
query,
|
|
458
|
+
ip: handshake.address,
|
|
459
|
+
userAgent: handshake.headers["user-agent"],
|
|
460
|
+
transport: "websocket"
|
|
461
|
+
};
|
|
462
|
+
}
|
|
433
463
|
async handleConnection(socket) {
|
|
434
464
|
try {
|
|
435
|
-
const
|
|
436
|
-
const headers = this.normalizeHeaders(handshake.headers);
|
|
437
|
-
const query = { ...handshake.query };
|
|
438
|
-
const handshakeAuth = handshake.auth;
|
|
439
|
-
if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
|
|
440
|
-
if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
|
|
441
|
-
const ticket = firstQueryValue(query["ticket"]);
|
|
442
|
-
if (ticket !== void 0) query["ticket"] = ticket;
|
|
443
|
-
const ctx = {
|
|
444
|
-
cookies: internal.parseCookieHeader(handshake.headers.cookie ?? ""),
|
|
445
|
-
headers,
|
|
446
|
-
query,
|
|
447
|
-
ip: handshake.address,
|
|
448
|
-
userAgent: handshake.headers["user-agent"],
|
|
449
|
-
transport: "websocket"
|
|
450
|
-
};
|
|
451
|
-
const auth = await this.transport.authenticator().authenticate(ctx);
|
|
465
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
452
466
|
if (!auth) {
|
|
453
467
|
socket.disconnect(true);
|
|
454
468
|
return;
|
|
455
469
|
}
|
|
456
|
-
|
|
470
|
+
const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
471
|
+
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
472
|
+
await this.transport.registerSocket(socket, resolvedAuth);
|
|
457
473
|
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
458
474
|
socket.emit(internal.RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
|
|
459
475
|
connectionId: socket.id,
|
|
460
|
-
traits: {
|
|
476
|
+
traits: {
|
|
477
|
+
userId: resolvedAuth.userId,
|
|
478
|
+
tenantId: resolvedAuth.tenantId,
|
|
479
|
+
roles: resolvedAuth.roles
|
|
480
|
+
}
|
|
461
481
|
});
|
|
462
482
|
}
|
|
463
483
|
} catch (err) {
|
|
@@ -613,7 +633,7 @@ exports.BymaxRealtimeWebSocketModule = __decorateClass([
|
|
|
613
633
|
common.Module({})
|
|
614
634
|
], exports.BymaxRealtimeWebSocketModule);
|
|
615
635
|
var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
|
|
616
|
-
|
|
636
|
+
adapterLogger = new common.Logger(_RealtimeIoAdapter.name);
|
|
617
637
|
options;
|
|
618
638
|
constructor(app) {
|
|
619
639
|
super(app);
|
|
@@ -673,11 +693,11 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
|
|
|
673
693
|
const pub = pubClient;
|
|
674
694
|
const sub = pub.duplicate();
|
|
675
695
|
server.adapter(createAdapter(pub, sub));
|
|
676
|
-
this.
|
|
696
|
+
this.adapterLogger.log(
|
|
677
697
|
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
678
698
|
);
|
|
679
699
|
} catch (err) {
|
|
680
|
-
this.
|
|
700
|
+
this.adapterLogger.error(
|
|
681
701
|
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
682
702
|
);
|
|
683
703
|
}
|
|
@@ -248,6 +248,19 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
248
248
|
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
249
249
|
* linger in an unregistered state and receive broadcast events.
|
|
250
250
|
*/
|
|
251
|
+
/**
|
|
252
|
+
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
253
|
+
*
|
|
254
|
+
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
255
|
+
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
256
|
+
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
257
|
+
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
258
|
+
* expects a string is a bug at the far end.
|
|
259
|
+
*
|
|
260
|
+
* @param socket - The connecting Socket.IO socket.
|
|
261
|
+
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
262
|
+
*/
|
|
263
|
+
private buildAuthContext;
|
|
251
264
|
handleConnection(socket: Socket): Promise<void>;
|
|
252
265
|
/** Handle a WebSocket disconnection — unregister the connection. */
|
|
253
266
|
handleDisconnect(socket: Socket): Promise<void>;
|
|
@@ -285,7 +298,7 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
285
298
|
* (spec §11.5).
|
|
286
299
|
*/
|
|
287
300
|
declare class RealtimeIoAdapter extends IoAdapter {
|
|
288
|
-
private readonly
|
|
301
|
+
private readonly adapterLogger;
|
|
289
302
|
private readonly options;
|
|
290
303
|
constructor(app: INestApplicationContext);
|
|
291
304
|
/**
|
|
@@ -248,6 +248,19 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
248
248
|
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
249
249
|
* linger in an unregistered state and receive broadcast events.
|
|
250
250
|
*/
|
|
251
|
+
/**
|
|
252
|
+
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
253
|
+
*
|
|
254
|
+
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
255
|
+
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
256
|
+
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
257
|
+
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
258
|
+
* expects a string is a bug at the far end.
|
|
259
|
+
*
|
|
260
|
+
* @param socket - The connecting Socket.IO socket.
|
|
261
|
+
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
262
|
+
*/
|
|
263
|
+
private buildAuthContext;
|
|
251
264
|
handleConnection(socket: Socket): Promise<void>;
|
|
252
265
|
/** Handle a WebSocket disconnection — unregister the connection. */
|
|
253
266
|
handleDisconnect(socket: Socket): Promise<void>;
|
|
@@ -285,7 +298,7 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
285
298
|
* (spec §11.5).
|
|
286
299
|
*/
|
|
287
300
|
declare class RealtimeIoAdapter extends IoAdapter {
|
|
288
|
-
private readonly
|
|
301
|
+
private readonly adapterLogger;
|
|
289
302
|
private readonly options;
|
|
290
303
|
constructor(app: INestApplicationContext);
|
|
291
304
|
/**
|
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, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
|
|
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, parseCookieHeader, resolveAuthTenant, assertIdentityIsNotBlank, 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
|
|
|
@@ -428,34 +428,54 @@ var RealtimeGateway = class {
|
|
|
428
428
|
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
429
429
|
* linger in an unregistered state and receive broadcast events.
|
|
430
430
|
*/
|
|
431
|
+
/**
|
|
432
|
+
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
433
|
+
*
|
|
434
|
+
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
435
|
+
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
436
|
+
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
437
|
+
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
438
|
+
* expects a string is a bug at the far end.
|
|
439
|
+
*
|
|
440
|
+
* @param socket - The connecting Socket.IO socket.
|
|
441
|
+
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
442
|
+
*/
|
|
443
|
+
buildAuthContext(socket) {
|
|
444
|
+
const { handshake } = socket;
|
|
445
|
+
const headers = this.normalizeHeaders(handshake.headers);
|
|
446
|
+
const query = { ...handshake.query };
|
|
447
|
+
const handshakeAuth = handshake.auth;
|
|
448
|
+
if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
|
|
449
|
+
if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
|
|
450
|
+
const ticket = firstQueryValue(query["ticket"]);
|
|
451
|
+
if (ticket !== void 0) query["ticket"] = ticket;
|
|
452
|
+
return {
|
|
453
|
+
cookies: parseCookieHeader(handshake.headers.cookie ?? ""),
|
|
454
|
+
headers,
|
|
455
|
+
query,
|
|
456
|
+
ip: handshake.address,
|
|
457
|
+
userAgent: handshake.headers["user-agent"],
|
|
458
|
+
transport: "websocket"
|
|
459
|
+
};
|
|
460
|
+
}
|
|
431
461
|
async handleConnection(socket) {
|
|
432
462
|
try {
|
|
433
|
-
const
|
|
434
|
-
const headers = this.normalizeHeaders(handshake.headers);
|
|
435
|
-
const query = { ...handshake.query };
|
|
436
|
-
const handshakeAuth = handshake.auth;
|
|
437
|
-
if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
|
|
438
|
-
if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
|
|
439
|
-
const ticket = firstQueryValue(query["ticket"]);
|
|
440
|
-
if (ticket !== void 0) query["ticket"] = ticket;
|
|
441
|
-
const ctx = {
|
|
442
|
-
cookies: parseCookieHeader(handshake.headers.cookie ?? ""),
|
|
443
|
-
headers,
|
|
444
|
-
query,
|
|
445
|
-
ip: handshake.address,
|
|
446
|
-
userAgent: handshake.headers["user-agent"],
|
|
447
|
-
transport: "websocket"
|
|
448
|
-
};
|
|
449
|
-
const auth = await this.transport.authenticator().authenticate(ctx);
|
|
463
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
450
464
|
if (!auth) {
|
|
451
465
|
socket.disconnect(true);
|
|
452
466
|
return;
|
|
453
467
|
}
|
|
454
|
-
|
|
468
|
+
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
469
|
+
assertIdentityIsNotBlank(resolvedAuth);
|
|
470
|
+
await this.transport.registerSocket(socket, resolvedAuth);
|
|
455
471
|
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
456
472
|
socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
|
|
457
473
|
connectionId: socket.id,
|
|
458
|
-
traits: {
|
|
474
|
+
traits: {
|
|
475
|
+
userId: resolvedAuth.userId,
|
|
476
|
+
tenantId: resolvedAuth.tenantId,
|
|
477
|
+
roles: resolvedAuth.roles
|
|
478
|
+
}
|
|
459
479
|
});
|
|
460
480
|
}
|
|
461
481
|
} catch (err) {
|
|
@@ -611,7 +631,7 @@ BymaxRealtimeWebSocketModule = __decorateClass([
|
|
|
611
631
|
Module({})
|
|
612
632
|
], BymaxRealtimeWebSocketModule);
|
|
613
633
|
var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
614
|
-
|
|
634
|
+
adapterLogger = new Logger(_RealtimeIoAdapter.name);
|
|
615
635
|
options;
|
|
616
636
|
constructor(app) {
|
|
617
637
|
super(app);
|
|
@@ -671,11 +691,11 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
|
671
691
|
const pub = pubClient;
|
|
672
692
|
const sub = pub.duplicate();
|
|
673
693
|
server.adapter(createAdapter(pub, sub));
|
|
674
|
-
this.
|
|
694
|
+
this.adapterLogger.log(
|
|
675
695
|
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
676
696
|
);
|
|
677
697
|
} catch (err) {
|
|
678
|
-
this.
|
|
698
|
+
this.adapterLogger.error(
|
|
679
699
|
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
680
700
|
);
|
|
681
701
|
}
|
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.1",
|
|
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",
|