@bymax-one/nest-realtime 1.2.11 â 1.2.13
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 +44 -1
- package/README.md +91 -209
- package/dist/internal/index.cjs +50 -7
- package/dist/internal/index.d.cts +63 -5
- package/dist/internal/index.d.ts +63 -5
- package/dist/internal/index.mjs +49 -8
- package/dist/server/index.cjs +4 -0
- package/dist/server/index.d.cts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.mjs +1 -1
- package/dist/shared/index.cjs +7 -0
- package/dist/shared/index.d.cts +22 -1
- package/dist/shared/index.d.ts +22 -1
- package/dist/shared/index.mjs +7 -1
- package/dist/websocket/index.cjs +5 -0
- package/dist/websocket/index.d.cts +4 -4
- package/dist/websocket/index.d.ts +4 -4
- package/dist/websocket/index.mjs +6 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.13] - 2026-11-13
|
|
11
|
+
|
|
12
|
+
No change to the published package: `dist/` is the same as in 1.2.12.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- **An ESLint rule now enforces the auth-import rule.** A string literal under `src/` that names `@bymax-one/nest-auth`, `@nestjs/jwt`, `passport` or `passport-*` fails the lint step, so a literal specifier is refused in every form of `import` and `require`. It is covered by `src/eslint-auth-gate.spec.ts`.
|
|
17
|
+
|
|
18
|
+
### Documentation
|
|
19
|
+
|
|
20
|
+
- The README is audited and shortened. Shutdown has its own section, "What This Library Does NOT Do" replaces the deployment notes, and a compact Security Table and Tech Stack stay.
|
|
21
|
+
|
|
22
|
+
## [1.2.12] - 2026-11-12
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
26
|
+
- **`AuthenticationResult.rooms`: rooms joined at admission.** An authenticator can return extra
|
|
27
|
+
rooms (a workspace, a project) that are joined before the connection is announced,
|
|
28
|
+
on both transports. Joining from `onConnect` leaves a window: the connection is already live, so an
|
|
29
|
+
event published to the room in between is missed, and room events have no replay. On SSE `onConnect`
|
|
30
|
+
is not awaited and a hook that throws is only logged, so a connection scoped there can stay
|
|
31
|
+
live without its room. A name must be a non-blank string of at most
|
|
32
|
+
`ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH` characters and must not start with `user:`,
|
|
33
|
+
`tenant:` or `connection:`; at most `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates
|
|
34
|
+
join once. A result that breaks a rule is refused like a blank `userId`. The limits are bounds
|
|
35
|
+
against abuse, not measurements, and apply to this field only; `joinRoom` is unchanged. The rooms
|
|
36
|
+
are fixed at admission: `revalidate` receives them, and a different set returned later is not
|
|
37
|
+
re-synchronized. `ADMISSION_ROOM_LIMITS` is exported from the root and `./shared` entries.
|
|
38
|
+
|
|
39
|
+
#### Apply to a derived backend
|
|
40
|
+
|
|
41
|
+
`ConnectionRecord.originalAuth` gains an optional `rooms`. A custom `IConnectionAuthenticator` is
|
|
42
|
+
unaffected; one that wants a scoped room returns it in `rooms` instead of joining it from
|
|
43
|
+
`onConnect`. A subclass of `SseTransport` or `WebSocketTransport` that overrides
|
|
44
|
+
`registerConnection` or `registerSocket` has to join `auth.rooms` itself.
|
|
45
|
+
|
|
46
|
+
### Fixed
|
|
47
|
+
|
|
48
|
+
- The JSDoc of `onModuleDestroy` on both transports now opens with its limit: a slow
|
|
49
|
+
`onModuleDestroy` in a module nearer the root than the realtime module still runs first.
|
|
50
|
+
|
|
10
51
|
## [1.2.11] - 2026-11-09
|
|
11
52
|
|
|
12
53
|
### Fixed
|
|
@@ -955,7 +996,9 @@ First published release.
|
|
|
955
996
|
rather than by the manual sweep that raised the NestJS floors â that sweep
|
|
956
997
|
asked about NestJS and never put the same question to the other ten peers.
|
|
957
998
|
|
|
958
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
999
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.13...HEAD
|
|
1000
|
+
[1.2.13]: https://github.com/bymaxone/nest-realtime/compare/v1.2.12...v1.2.13
|
|
1001
|
+
[1.2.12]: https://github.com/bymaxone/nest-realtime/compare/v1.2.11...v1.2.12
|
|
959
1002
|
[1.2.11]: https://github.com/bymaxone/nest-realtime/compare/v1.2.10...v1.2.11
|
|
960
1003
|
[1.2.10]: https://github.com/bymaxone/nest-realtime/compare/v1.2.9...v1.2.10
|
|
961
1004
|
[1.2.9]: https://github.com/bymaxone/nest-realtime/compare/v1.2.8...v1.2.9
|
package/README.md
CHANGED
|
@@ -43,11 +43,7 @@ The default transport is **Server-Sent Events**: browser-native, plain HTTP, no
|
|
|
43
43
|
- **ðĄ SSE first, and that is the point** â SSE reconnects natively, replays through `Last-Event-ID`, and traverses proxies as ordinary HTTP. Most apps only push server â client, and for those WebSocket is a dependency you pay for without using.
|
|
44
44
|
- **ð Auth stays yours** â The library never verifies a JWT, never imports an auth package. You implement `IConnectionAuthenticator`; cookie, ticket, and bearer patterns are all supported. This is enforced structurally, not by convention.
|
|
45
45
|
- **ðĒ Multi-tenant by construction** â Every connection auto-joins `user:{id}` and, when present, `tenant:{id}`. Tenant scoping is a room convention, not an afterthought bolted onto a chat library.
|
|
46
|
-
- **ðŠķ Nothing in your bundle you didn't ask for** â `"dependencies": {}` on the server, and `socket.io-client` is reached through `await import()` so an SSE-only frontend ships
|
|
47
|
-
|
|
48
|
-
```
|
|
49
|
-
pnpm add @bymax-one/nest-realtime
|
|
50
|
-
```
|
|
46
|
+
- **ðŠķ Nothing in your bundle you didn't ask for** â `"dependencies": {}` on the server, and `socket.io-client` is reached through `await import()` so an SSE-only frontend ships about 2 KB brotli and never loads it.
|
|
51
47
|
|
|
52
48
|
---
|
|
53
49
|
|
|
@@ -63,7 +59,7 @@ pnpm add @bymax-one/nest-realtime
|
|
|
63
59
|
### ð Security & Auth
|
|
64
60
|
|
|
65
61
|
- â
**Auth inversion** â the consumer plugs `IConnectionAuthenticator`; the library owns no credentials
|
|
66
|
-
- â
**Zero auth imports** â `src/`
|
|
62
|
+
- â
**Zero auth imports** â `src/` imports no auth package (`@nestjs/jwt`, `passport-*`, `@bymax-one/nest-auth`), and a lint rule fails the build if one appears
|
|
67
63
|
- â
**Three handshake patterns** â HttpOnly cookie (SSE-safe), one-time ticket, and bearer header (WebSocket only)
|
|
68
64
|
- â
**Periodic re-authentication** â revalidate credentials on an interval, with a positive-result cache
|
|
69
65
|
- â
**Tenant from the token, never the body** â `tenantId` comes from the authenticated result via `tenantResolver`
|
|
@@ -78,11 +74,9 @@ pnpm add @bymax-one/nest-realtime
|
|
|
78
74
|
|
|
79
75
|
### ð§Đ Developer Experience
|
|
80
76
|
|
|
81
|
-
- â
**4 subpath exports** â server, WebSocket, shared types, and React; tree-shakeable, ESM + CJS dual output
|
|
82
77
|
- â
**Dynamic module** â `forRoot()` and `forRootAsync()` with `useFactory` / `useClass` / `useExisting`
|
|
83
78
|
- â
**Strict TypeScript, zero `any`** â `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` enabled
|
|
84
79
|
- â
**Horizontal scaling** â `IRealtimePubSub` for SSE fan-out, `@socket.io/redis-adapter` for WebSocket
|
|
85
|
-
- â
**Bundle gate in CI** â the SSE-only React bundle is measured on every build and fails over budget
|
|
86
80
|
|
|
87
81
|
---
|
|
88
82
|
|
|
@@ -105,9 +99,7 @@ One package, four entry points â import only what your app needs:
|
|
|
105
99
|
|
|
106
100
|
`/websocket` also exports `RealtimeGateway`, `WebSocketTransport` and `CompositeTransport`. They are exported for the module's own wiring and for tests: applications register `BymaxRealtimeWebSocketModule` and install `RealtimeIoAdapter`, and do not construct them.
|
|
107
101
|
|
|
108
|
-
The `
|
|
109
|
-
|
|
110
|
-
**The `websocket` subpath exists so the server one costs nothing extra.** Everything that touches `@nestjs/websockets`, `@nestjs/platform-socket.io` and `socket.io` is reachable only through it, so an application on SSE â the default transport â never installs the Socket.IO stack. Importing it is what opts in, in the install as much as in the configuration.
|
|
102
|
+
**The `websocket` subpath exists so the server one costs nothing extra.** Everything that touches `@nestjs/websockets`, `@nestjs/platform-socket.io` and `socket.io` is reachable only through it, so an SSE application never installs the Socket.IO stack. Importing it is what opts in.
|
|
111
103
|
|
|
112
104
|
The package also exposes `@bymax-one/nest-realtime/internal`. It is **not public API** and carries no compatibility promise â it is the shared runtime the two server subpaths import so that a service registered through one and injected through the other is the same class. Import the four above; nothing you need is only there.
|
|
113
105
|
|
|
@@ -121,14 +113,7 @@ The package also exposes `@bymax-one/nest-realtime/internal`. It is **not public
|
|
|
121
113
|
### 1. Install
|
|
122
114
|
|
|
123
115
|
```bash
|
|
124
|
-
#
|
|
125
|
-
pnpm add @bymax-one/nest-realtime
|
|
126
|
-
|
|
127
|
-
# Using npm
|
|
128
|
-
npm install @bymax-one/nest-realtime
|
|
129
|
-
|
|
130
|
-
# Using yarn
|
|
131
|
-
yarn add @bymax-one/nest-realtime
|
|
116
|
+
pnpm add @bymax-one/nest-realtime # or npm install / yarn add
|
|
132
117
|
```
|
|
133
118
|
|
|
134
119
|
> [!IMPORTANT]
|
|
@@ -340,7 +325,11 @@ bootstrap()
|
|
|
340
325
|
```
|
|
341
326
|
|
|
342
327
|
> [!IMPORTANT]
|
|
343
|
-
> The `main.ts` line is not optional. `RealtimeIoAdapter` is what applies `websocket.cors`, `namespace`, `pingIntervalMs`, `pingTimeoutMs`, `maxHttpBufferSize` and `redisAdapter`. Without it those options are ignored, the gateway's own CORS stays closed (`origin: false`) so a browser on another origin cannot connect, and the module logs
|
|
328
|
+
> The `main.ts` line is not optional. `RealtimeIoAdapter` is what applies `websocket.cors`, `namespace`, `pingIntervalMs`, `pingTimeoutMs`, `maxHttpBufferSize` and `redisAdapter`. Without it those options are ignored, the gateway's own CORS stays closed (`origin: false`) so a browser on another origin cannot connect, and the module logs this error once at start-up:
|
|
329
|
+
|
|
330
|
+
```
|
|
331
|
+
RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options are ignored and the gateway CORS stays closed (origin: false): browsers on another origin cannot connect. Add app.useWebSocketAdapter(new RealtimeIoAdapter(app)) in main.ts, importing it from '@bymax-one/nest-realtime/websocket'.
|
|
332
|
+
```
|
|
344
333
|
|
|
345
334
|
With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls `pubClient.duplicate()` for the subscriber; the library never opens its own Redis connection. If it cannot be installed (the package is missing, the client has no `duplicate()`), the boot fails with `REALTIME_REDIS_ADAPTER_FAILED` instead of serving a single instance; a Redis that is merely unreachable does not fail the boot. Socket.IO's polling fallback needs sticky sessions even then â see [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md). On the frontend, a `ws://` or `wss://` `url` selects WebSocket in `RealtimeProvider`. Replay through `Last-Event-ID` and the offline queue are SSE features: a WebSocket connection has neither.
|
|
346
335
|
|
|
@@ -389,7 +378,7 @@ The options are typed per entry point: `SseRealtimeModuleOptions` and `SseRealti
|
|
|
389
378
|
> `REALTIME_OPTIONS_TOKEN` reports the route that was actually bound â so a health check or an
|
|
390
379
|
> OpenAPI document built from the options names the path that exists.
|
|
391
380
|
|
|
392
|
-
The
|
|
381
|
+
The design specification, [docs/technical_specification.md](./docs/technical_specification.md) §4, covers the options in depth. It was written against v0.1.0, so where it differs from this README or the CHANGELOG, those are current.
|
|
393
382
|
|
|
394
383
|
---
|
|
395
384
|
|
|
@@ -423,16 +412,6 @@ The package runs **inside** your NestJS application as a dynamic module â not
|
|
|
423
412
|
ââââââââââ Browser âââââââ
|
|
424
413
|
```
|
|
425
414
|
|
|
426
|
-
### Design Principles
|
|
427
|
-
|
|
428
|
-
| Principle | Description |
|
|
429
|
-
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
|
430
|
-
| **ð Interface-Driven** | Authentication, pub/sub, offline queue, and presence are contracts you implement â Redis reference implementations ship, none are forced |
|
|
431
|
-
| **ð Transport-Agnostic** | `RealtimeService` talks to `ITransport`; adding or swapping a transport never touches application code |
|
|
432
|
-
| **ðĄïļ Auth Inversion** | The library holds no credential logic, so an auth vulnerability cannot originate here |
|
|
433
|
-
| **ðŠķ Zero Runtime Deps** | `"dependencies": {}` â every dependency is a peer, and optional ones are marked in `peerDependenciesMeta` |
|
|
434
|
-
| **ðģ Tree-Shakeable** | `sideEffects: false`, subpath exports, and a dynamic `import()` that keeps `socket.io-client` out of the SSE bundle |
|
|
435
|
-
|
|
436
415
|
### Cross-Instance Emit Flow
|
|
437
416
|
|
|
438
417
|
An emit delivers locally **and** publishes once. Every other instance's subscriber re-emits through local-only paths (`emitToUserLocal`, âĶ), so a message is never republished and cannot loop. Connection revocation crosses instances as an `op: 'disconnect'` message on the same channel.
|
|
@@ -447,11 +426,7 @@ Sizing guidance and adapter trade-offs are in [docs/architecture/scaling-cheatsh
|
|
|
447
426
|
|
|
448
427
|
This library **never** verifies a JWT, hashes a password, or imports an authentication package. It calls `IConnectionAuthenticator.authenticate()` once per connection and trusts the `AuthenticationResult` you return.
|
|
449
428
|
|
|
450
|
-
This is a **structural guarantee**, not a guideline
|
|
451
|
-
|
|
452
|
-
```bash
|
|
453
|
-
grep -rE "@nestjs/jwt|@bymax-one/nest-auth|passport" src/ # must return zero
|
|
454
|
-
```
|
|
429
|
+
This is a **structural guarantee**, not a guideline: an ESLint rule fails the lint step on any string literal under `src/` that names `@bymax-one/nest-auth`, `@nestjs/jwt`, `passport` or `passport-*`, so a literal specifier is refused in every form of `import` and `require`.
|
|
455
430
|
|
|
456
431
|
The consequence is worth stating plainly: a credential-handling vulnerability cannot originate in this package, because the code that would contain it does not exist here. It also means **you** are responsible for the bridge â vulnerabilities in a bridge implementation belong to that project, as [SECURITY.md](./SECURITY.md) records.
|
|
457
432
|
|
|
@@ -496,19 +471,16 @@ When integrating `@bymax-one/nest-realtime` in production, verify each of the fo
|
|
|
496
471
|
|
|
497
472
|
## ðĄïļ Security Table
|
|
498
473
|
|
|
499
|
-
| Layer | Implementation
|
|
500
|
-
| --------------------- |
|
|
501
|
-
| Credential validation | Delegated entirely to
|
|
502
|
-
| Auth library imports | None
|
|
503
|
-
| Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result
|
|
504
|
-
| Connection revocation | `disconnect(connectionId)`,
|
|
505
|
-
| Credential expiry | Interval re-authentication
|
|
506
|
-
| Connection flooding | FIFO eviction per user
|
|
507
|
-
| SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform`
|
|
508
|
-
| WebSocket origin | Explicit `cors` config passed straight to Socket.IO
|
|
509
|
-
|
|
510
|
-
> [!IMPORTANT]
|
|
511
|
-
> 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.
|
|
474
|
+
| Layer | Implementation |
|
|
475
|
+
| --------------------- | -------------------------------------------------------------------------------------------------- |
|
|
476
|
+
| Credential validation | Delegated entirely to your `IConnectionAuthenticator` |
|
|
477
|
+
| Auth library imports | None: an ESLint rule fails lint on a string literal naming an auth package in `src` |
|
|
478
|
+
| Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result |
|
|
479
|
+
| Connection revocation | `disconnect(connectionId)`, cross-instance; rejects if it cannot reach it |
|
|
480
|
+
| Credential expiry | Interval re-authentication; a failure drops the connection, after an event if `onFailure: 'event'` |
|
|
481
|
+
| Connection flooding | FIFO eviction per user: oldest closed, new admitted, never a 429 |
|
|
482
|
+
| SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform` |
|
|
483
|
+
| WebSocket origin | Explicit `cors` config passed straight to Socket.IO |
|
|
512
484
|
|
|
513
485
|
---
|
|
514
486
|
|
|
@@ -541,7 +513,7 @@ A realtime channel fails in ways that are hard to reproduce â dropped streams,
|
|
|
541
513
|
pnpm test # unit + integration
|
|
542
514
|
pnpm test:e2e # end-to-end (single instance, no Redis needed)
|
|
543
515
|
pnpm test:cov:all # 100% coverage gate
|
|
544
|
-
pnpm mutation # Stryker mutation testing
|
|
516
|
+
pnpm mutation # Stryker mutation testing
|
|
545
517
|
pnpm build && pnpm size
|
|
546
518
|
```
|
|
547
519
|
|
|
@@ -574,7 +546,9 @@ The unified emit API. Identical on every transport.
|
|
|
574
546
|
|
|
575
547
|
All methods return `Promise<void>`.
|
|
576
548
|
|
|
577
|
-
**Revocation is never best-effort.** `disconnect(connectionId)` resolves
|
|
549
|
+
**Revocation is never best-effort.** `disconnect(connectionId)` resolves once the connection was closed on this instance or the revocation was handed to the bus (`IRealtimePubSub`). It **rejects**, with `error.code` set to a `RealtimeErrorCode`, when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish (`RedisRealtimePubSub` refuses at once while its Redis client is not ready), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. Branch on the code, not the message; the error is a plain `Error`, not a class for `instanceof`. A rejection means the connection may still be connected, so retry.
|
|
550
|
+
|
|
551
|
+
**Emits are at-most-once.** `emitToUser`, `emitToTenant`, `emitToRoom` and `broadcast` **resolve even when the publish to the other instances failed**; that failure is logged with `REALTIME_PUBSUB_UNAVAILABLE` and passed to the `onDeliveryFailure` hook, which is where to count it. An offline queue that could not keep an event for a user who is offline here is reported the same way, since another instance may have delivered it live; a failure on one transport of `'both'` is only logged. An emit rejects only when the event has no delivery path left: for `emitToUser`, the user is offline here, the queue failed, and the bus failed or cannot reach another instance (the default in-memory bus); with `'both'`, a failure on both transports rejects with `REALTIME_TRANSPORT_UNAVAILABLE`. A rejected emit is not proof that no client received it, so retry only where a duplicate is acceptable.
|
|
578
552
|
|
|
579
553
|
`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.
|
|
580
554
|
|
|
@@ -630,43 +604,11 @@ Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePub
|
|
|
630
604
|
|
|
631
605
|
#### Identity must be present or absent, never blank
|
|
632
606
|
|
|
633
|
-
`userId` must be a non-empty string, and `tenantId`
|
|
634
|
-
string. A connection whose authenticator â or whose `tenantResolver` â yields a blank one is
|
|
635
|
-
**refused at bootstrap** rather than registered.
|
|
636
|
-
|
|
637
|
-
The reason is that blank is not missing. `userId` and `tenantId` key the connection registry
|
|
638
|
-
and compose the `user:` and `tenant:` rooms, so every connection carrying `''` lands under the
|
|
639
|
-
same key and joins the same room; a later emit to that key reaches all of them. On a long-lived
|
|
640
|
-
subscription that is not one wrong response but a stream that keeps delivering.
|
|
607
|
+
`userId` must be a non-empty string, and `tenantId` either absent or a non-empty string. A connection whose authenticator, or whose `tenantResolver`, yields a blank one is **refused at bootstrap** as a server fault, not a `401`: blank is not missing. Every connection carrying `''` lands under the same registry key and joins the same `user:` or `tenant:` room, and a later emit reaches all of them. Whitespace counts as blank.
|
|
641
608
|
|
|
642
|
-
To place a connection in no tenant, the
|
|
643
|
-
under none and joins no tenant room, which an empty string is not. Whitespace counts as blank:
|
|
644
|
-
`' '` composes `user: ` just as `''` does.
|
|
609
|
+
To place a connection in no tenant, **omit `tenantId`**. The runtime also accepts `undefined` or `null`, but whether those type-check depends on the consumer's `tsconfig` (`exactOptionalPropertyTypes` rejects `undefined`, `strictNullChecks` rejects `null`), so omission is the only form that compiles everywhere.
|
|
645
610
|
|
|
646
|
-
|
|
647
|
-
`AuthenticationResult` declares `tenantId?: string`; the runtime accepts an explicit `undefined`
|
|
648
|
-
or `null` too â an untyped claim spread into the result produces them routinely â but whether
|
|
649
|
-
either _type-checks_ depends on the consuming project's `tsconfig`, which the published
|
|
650
|
-
declarations do not control:
|
|
651
|
-
|
|
652
|
-
| consumer's `tsconfig` | `tenantId: undefined` | `tenantId: null` |
|
|
653
|
-
| ----------------------------------------- | --------------------- | ---------------- |
|
|
654
|
-
| `strict` + `exactOptionalPropertyTypes` | `TS2375` | `TS2322` |
|
|
655
|
-
| `strict`, no `exactOptionalPropertyTypes` | compiles | `TS2322` |
|
|
656
|
-
| no `strictNullChecks` | compiles | compiles |
|
|
657
|
-
|
|
658
|
-
Omitting the key is correct in all three.
|
|
659
|
-
|
|
660
|
-
`tenantResolver` cannot clear a tenant, and this is the one asymmetry worth reading twice.
|
|
661
|
-
Resolution is `tenantResolver?.(auth) ?? auth.tenantId`, so a resolver returning `undefined` or
|
|
662
|
-
`null` means _no opinion_ and falls back to the tenant the authenticator supplied. A resolver
|
|
663
|
-
written to place a connection in no tenant by returning `null` leaves it in `auth.tenantId`'s
|
|
664
|
-
room instead, still receiving that tenant's events. Decide the absent case in the
|
|
665
|
-
authenticator, where absence is what it looks like.
|
|
666
|
-
|
|
667
|
-
A blank identity surfaces as a server fault rather than a `401`, because the client's
|
|
668
|
-
credentials were accepted and the fault is in the authenticator. Return `null` to reject a
|
|
669
|
-
client.
|
|
611
|
+
`tenantResolver` cannot clear a tenant. Resolution is `tenantResolver?.(auth) ?? auth.tenantId`, so a resolver returning `undefined` or `null` means "no opinion" and the authenticator's tenant stays. Decide the absent case in the authenticator.
|
|
670
612
|
|
|
671
613
|
#### Carrying handshake context into the hooks
|
|
672
614
|
|
|
@@ -677,9 +619,7 @@ the original result. It is the only channel that crosses that boundary â `auth
|
|
|
677
619
|
the request headers but no `connectionId` yet, and those hooks see the `connectionId` but not
|
|
678
620
|
the headers.
|
|
679
621
|
|
|
680
|
-
`onError`
|
|
681
|
-
it can fire before authentication resolves, so there may be no connection to describe, which is
|
|
682
|
-
also why its `connectionId` is optional. It carries neither `roles` nor `metadata`.
|
|
622
|
+
`onError` takes a narrower payload (`connectionId?`, `error`, `transport`) with neither `roles` nor `metadata`, because it can fire before authentication resolves.
|
|
683
623
|
|
|
684
624
|
```typescript
|
|
685
625
|
class TracingAuthenticator implements IConnectionAuthenticator {
|
|
@@ -699,6 +639,36 @@ const hooks: IConnectionLifecycleHooks = {
|
|
|
699
639
|
Like `roles`, it is a **connect-time snapshot**: a `revalidate` that keeps the connection alive
|
|
700
640
|
does not refresh it. The library never reads a key.
|
|
701
641
|
|
|
642
|
+
#### Joining rooms at admission
|
|
643
|
+
|
|
644
|
+
`AuthenticationResult.rooms` lists extra rooms (a workspace, a project) that the library joins
|
|
645
|
+
beside `user:` and `tenant:`, **before** the connection is announced:
|
|
646
|
+
|
|
647
|
+
```typescript
|
|
648
|
+
class WorkspaceAuthenticator implements IConnectionAuthenticator {
|
|
649
|
+
constructor(private readonly sessions: SessionStore) {}
|
|
650
|
+
|
|
651
|
+
async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
|
|
652
|
+
const session = await this.sessions.find(ctx.cookies['sid'])
|
|
653
|
+
if (!session) return null
|
|
654
|
+
return { userId: session.userId, rooms: [`workspace:${session.workspaceId}`] }
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
Scope a connection here, not by calling `joinRoom` from `onConnect`. On **SSE** the connection is live before `onConnect` runs and the hook is not awaited, so an event published to the room in that window is missed (room events have no replay), and a hook that throws is only logged as a warning, leaving the connection live and unscoped. On **WebSocket** the hook is awaited before `connection:established`, so no window is observable once the client is ready; `rooms` is still the right place. Neither hook behaviour changes.
|
|
660
|
+
|
|
661
|
+
A name must be a non-blank string of at most `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH`
|
|
662
|
+
characters and must not start with `user:`, `tenant:` or `connection:`; at most
|
|
663
|
+
`ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once. A result that breaks a rule
|
|
664
|
+
is refused like a blank `userId` â a server fault (500 on SSE, a generic `connect_error` on
|
|
665
|
+
WebSocket), not a 401 â and nothing is registered. The two limits are bounds against abuse, not
|
|
666
|
+
measurements, and they apply to this field only: `joinRoom` stays free-form.
|
|
667
|
+
|
|
668
|
+
The rooms are fixed at admission and handed back to `revalidate` in the original result. A
|
|
669
|
+
different set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for changes
|
|
670
|
+
during the connection.
|
|
671
|
+
|
|
702
672
|
#### Client address versus peer address
|
|
703
673
|
|
|
704
674
|
`authenticate` receives two addresses. On SSE `ip` is the address your application's
|
|
@@ -734,27 +704,19 @@ composeRoomId('TENANT', tenantId) // â "tenant:t_acme"
|
|
|
734
704
|
composeRoomId('RESOURCE', 'invoice', invoiceId) // â "resource:invoice:42"
|
|
735
705
|
```
|
|
736
706
|
|
|
737
|
-
`composeRoomId` joins its parts with `:` and escapes nothing, so a
|
|
738
|
-
`('a:b', 'c')` and `('a', 'b:c')` both give `resource:a:b:c` and land in the same room. When a
|
|
739
|
-
part comes from outside your code, encode it first:
|
|
740
|
-
`composeRoomId('RESOURCE', encodeURIComponent(type), encodeURIComponent(id))`.
|
|
707
|
+
`composeRoomId` joins its parts with `:` and escapes nothing, so `('a:b', 'c')` and `('a', 'b:c')` both give `resource:a:b:c` and land in the same room. Encode a part that comes from outside your code with `encodeURIComponent`, which escapes `:` and is sound for this separator only: `composeRoomId('RESOURCE', encodeURIComponent(type), encodeURIComponent(id))`.
|
|
741
708
|
|
|
742
|
-
A `resource:` room is not tenant-scoped: two tenants using the same type and id share it. When ids
|
|
743
|
-
are only unique within a tenant, pass the tenant as its own encoded part â
|
|
744
|
-
`composeRoomId('RESOURCE', 'invoice', encodeURIComponent(tenantId), encodeURIComponent(id))` â
|
|
745
|
-
because gluing them into one part with a separator that ids may contain, such as `-`, lets two
|
|
746
|
-
different pairs compose the same room.
|
|
709
|
+
A `resource:` room is not tenant-scoped: two tenants using the same type and id share it. When ids are only unique within a tenant, pass the tenant as its own encoded part rather than gluing it to the id with a separator that ids may contain, such as `-`.
|
|
747
710
|
|
|
748
|
-
Never pass client-supplied input to `joinRoom` or `emitToRoom` as a room id without checking that
|
|
749
|
-
it cannot start with the reserved `user:` or `tenant:` prefixes. The library does not guard them,
|
|
750
|
-
and joining `tenant:<other>` receives that tenant's events.
|
|
711
|
+
Never pass client-supplied input to `joinRoom` or `emitToRoom` as a room id without checking that it cannot start with `user:` or `tenant:`. `joinRoom` is not guarded (only the `rooms` field is validated), and joining `tenant:<other>` receives that tenant's events.
|
|
751
712
|
|
|
752
713
|
#### Role-scoped delivery
|
|
753
714
|
|
|
754
715
|
There is no `emitToRole`. Roles are the consumer's authorization vocabulary, not
|
|
755
716
|
the transport's â the library carries them through without interpreting them (see
|
|
756
717
|
[Auth Inversion](#auth-inversion)). To deliver to a subset of connections by role,
|
|
757
|
-
build a room for it in `onConnect
|
|
718
|
+
build a room for it in `onConnect` (a room that must hold from the first event belongs in
|
|
719
|
+
[`rooms`](#joining-rooms-at-admission) instead), where `ConnectionEventMeta.roles` carries the
|
|
758
720
|
snapshot the authenticator produced:
|
|
759
721
|
|
|
760
722
|
```typescript
|
|
@@ -793,58 +755,8 @@ the connection alive does not refresh it. When a role can be revoked mid-session
|
|
|
793
755
|
make `revalidate` return `false` so the connection is torn down and re-established
|
|
794
756
|
with the new roles.
|
|
795
757
|
|
|
796
|
-
##### Make the hook testable: depend on the capability, not the injector
|
|
797
|
-
|
|
798
|
-
The snippet above works, and it still walks a careful consumer into a wall: a
|
|
799
|
-
`moduleRef.get()` call inside the hook means unit-testing that hook requires
|
|
800
|
-
faking `ModuleRef`, which in practice means `as unknown as ModuleRef` â a
|
|
801
|
-
suppression many codebases block outright.
|
|
802
|
-
|
|
803
|
-
Give the hook the two capabilities it actually uses instead. `ModuleRef` and
|
|
804
|
-
`RealtimeService` satisfy these shapes **structurally**, so the module passes the
|
|
805
|
-
real objects and a test passes plain ones, with no cast at either end:
|
|
806
|
-
|
|
807
|
-
```typescript
|
|
808
|
-
interface RoomJoiner {
|
|
809
|
-
joinRoom(connectionId: string, roomId: string): Promise<void>
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
interface ServiceResolver {
|
|
813
|
-
get(token: typeof RealtimeService): RoomJoiner
|
|
814
|
-
}
|
|
815
|
-
|
|
816
|
-
function joinRoleRoom(resolver: ServiceResolver, role: string, roomId: string) {
|
|
817
|
-
return async (meta: ConnectionEventMeta): Promise<void> => {
|
|
818
|
-
if (!meta.roles?.includes(role)) return
|
|
819
|
-
await resolver.get(RealtimeService).joinRoom(meta.connectionId, roomId)
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
```
|
|
823
|
-
|
|
824
|
-
Wire it with the real injector:
|
|
825
|
-
|
|
826
|
-
```typescript
|
|
827
|
-
inject: [ModuleRef],
|
|
828
|
-
useFactory: (moduleRef: ModuleRef) => ({
|
|
829
|
-
transport: 'sse' as const,
|
|
830
|
-
authenticator: new CookieAuthenticator(),
|
|
831
|
-
hooks: { onConnect: joinRoleRoom(moduleRef, 'admin', 'role:admin') },
|
|
832
|
-
}),
|
|
833
|
-
```
|
|
834
|
-
|
|
835
|
-
and test it without booting NestJS:
|
|
836
|
-
|
|
837
|
-
```typescript
|
|
838
|
-
const joinRoom = jest.fn()
|
|
839
|
-
const onConnect = joinRoleRoom({ get: () => ({ joinRoom }) }, 'admin', 'role:admin')
|
|
840
|
-
```
|
|
841
|
-
|
|
842
758
|
> [!NOTE]
|
|
843
|
-
> Match roles by exact membership. `roles?.includes('admin')`
|
|
844
|
-
> compares whole elements; reaching for `roles?.some((r) => r.includes('admin'))` â
|
|
845
|
-
> for case-insensitivity, say â admits `administrator`, `admin-readonly` and
|
|
846
|
-
> `superadmin`. That failure is an authorization leak, it fails open, and it only
|
|
847
|
-
> shows up for role names nobody declared.
|
|
759
|
+
> Match roles by exact membership. `roles?.some((r) => r.includes('admin'))` admits `administrator` and `superadmin`, which fails open as an authorization leak.
|
|
848
760
|
|
|
849
761
|
### Reserved Events
|
|
850
762
|
|
|
@@ -871,19 +783,23 @@ These names belong to the library. Do not reuse them for application events. The
|
|
|
871
783
|
|
|
872
784
|
### Error Codes
|
|
873
785
|
|
|
874
|
-
| Code | Status
|
|
875
|
-
| ---------------------------------- |
|
|
876
|
-
| `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option
|
|
877
|
-
| `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid
|
|
878
|
-
| `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal
|
|
879
|
-
| `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails
|
|
880
|
-
| `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed
|
|
881
|
-
| `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write
|
|
882
|
-
| `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
|
|
883
|
-
| `REALTIME_TRANSPORT_UNAVAILABLE` | Raised as the rejection of a disconnect
|
|
884
|
-
| `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed
|
|
885
|
-
| `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today
|
|
886
|
-
| `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today
|
|
786
|
+
| Code | Status |
|
|
787
|
+
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
788
|
+
| `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option |
|
|
789
|
+
| `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
|
|
790
|
+
| `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
|
|
791
|
+
| `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
|
|
792
|
+
| `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
|
|
793
|
+
| `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
|
|
794
|
+
| `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 |
|
|
795
|
+
| `REALTIME_TRANSPORT_UNAVAILABLE` | Raised as the rejection of a disconnect when the WebSocket transport fails or has no server attached, and of an emit that has no delivery path left. Also what a stream or handshake that arrives during shutdown is refused with, below |
|
|
796
|
+
| `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
|
|
797
|
+
| `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
|
|
798
|
+
| `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
|
|
799
|
+
|
|
800
|
+
### Shutdown
|
|
801
|
+
|
|
802
|
+
From the `onModuleDestroy` phase on, which runs ahead of every `beforeApplicationShutdown`, a new SSE stream gets a 503 whose message is `REALTIME_TRANSPORT_UNAVAILABLE` and a new WebSocket handshake gets a `connect_error` whose `data.code` is that code. A slow `onModuleDestroy` in a module nearer the root than the realtime module still runs first, and until it returns a connection is accepted.
|
|
887
803
|
|
|
888
804
|
### DI Tokens
|
|
889
805
|
|
|
@@ -917,55 +833,21 @@ These names belong to the library. Do not reuse them for application events. The
|
|
|
917
833
|
|
|
918
834
|
---
|
|
919
835
|
|
|
920
|
-
##
|
|
921
|
-
|
|
922
|
-
SSE connections are long-lived HTTP responses, and several common proxy defaults break them silently:
|
|
923
|
-
|
|
924
|
-
| Concern | Fix |
|
|
925
|
-
| ------------------------ | ------------------------------------------------------------------------------------------------------ |
|
|
926
|
-
| **Response compression** | Disable on the SSE endpoint â `Content-Encoding: gzip` buffers the body and defeats streaming |
|
|
927
|
-
| **Proxy buffering** | Nginx `proxy_buffering off`. The library already sends `X-Accel-Buffering: no` |
|
|
928
|
-
| **CDN caching** | `Cache-Control: no-cache, no-transform` â set by the library on the SSE response |
|
|
929
|
-
| **Idle timeout** | Must exceed `sse.heartbeatMs` (default 30 s). AWS ALB's 60 s default is compatible |
|
|
930
|
-
| **WebSocket + polling** | Enable sticky sessions. The Redis adapter syncs messages between instances, but not handshake affinity |
|
|
931
|
-
|
|
932
|
-
Platform-specific configuration is in [docs/proxies-cheat-sheet.md](./docs/proxies-cheat-sheet.md).
|
|
933
|
-
|
|
934
|
-
### Troubleshooting
|
|
935
|
-
|
|
936
|
-
**The log shows `RealtimeIoAdapter is not the active WebSocket adapter`.** The gateway logs this once at start-up, as an error, when its Socket.IO server was not created by `RealtimeIoAdapter`:
|
|
937
|
-
|
|
938
|
-
```
|
|
939
|
-
RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options are ignored and the gateway CORS stays closed (origin: false): browsers on another origin cannot connect. Add app.useWebSocketAdapter(new RealtimeIoAdapter(app)) in main.ts, importing it from '@bymax-one/nest-realtime/websocket'.
|
|
940
|
-
```
|
|
836
|
+
## ðŦ What This Library Does NOT Do
|
|
941
837
|
|
|
942
|
-
|
|
838
|
+
- **Authenticate.** It holds no credential logic. The strength of your realtime auth is the strength of the `IConnectionAuthenticator` you plug in.
|
|
839
|
+
- **Guarantee delivery.** Emits are at-most-once, with no acknowledgement. `Last-Event-ID` replay and the offline queue are SSE-only and bounded.
|
|
840
|
+
- **Track presence.** `IPresenceStorage` is a seam the library never calls, and `presence:*` events are emitted by your code.
|
|
841
|
+
- **Receive client messages.** `RealtimeGateway` registers no message handlers, so a WebSocket client's `emit` is ignored unless you write a gateway.
|
|
842
|
+
- **Route by role.** There is no `emitToRole`; build a room from `ConnectionEventMeta.roles` (see [Role-scoped delivery](#role-scoped-delivery)).
|
|
843
|
+
- **Configure your proxy.** SSE needs response compression and proxy buffering off and an idle timeout above `sse.heartbeatMs`; the library sends `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform`. WebSocket with the polling fallback needs sticky sessions. See [docs/proxies-cheat-sheet.md](./docs/proxies-cheat-sheet.md).
|
|
844
|
+
- **Run a separate server.** It runs inside your NestJS application.
|
|
943
845
|
|
|
944
846
|
---
|
|
945
847
|
|
|
946
848
|
## ðĪ Contributing
|
|
947
849
|
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
```bash
|
|
951
|
-
# Clone the repository
|
|
952
|
-
git clone https://github.com/bymaxone/nest-realtime.git
|
|
953
|
-
cd nest-realtime
|
|
954
|
-
|
|
955
|
-
# Install dependencies
|
|
956
|
-
pnpm install
|
|
957
|
-
|
|
958
|
-
# Run tests
|
|
959
|
-
pnpm test
|
|
960
|
-
|
|
961
|
-
# Build
|
|
962
|
-
pnpm build
|
|
963
|
-
|
|
964
|
-
# Type check
|
|
965
|
-
pnpm typecheck
|
|
966
|
-
```
|
|
967
|
-
|
|
968
|
-
Every change must keep the full gate green:
|
|
850
|
+
Please open an issue to discuss substantial changes before a pull request. Clone the repository, run `pnpm install`, and keep the full gate green:
|
|
969
851
|
|
|
970
852
|
```bash
|
|
971
853
|
pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm size
|
package/dist/internal/index.cjs
CHANGED
|
@@ -225,6 +225,50 @@ var RESERVED_EVENT_NAMES = {
|
|
|
225
225
|
ERROR: "error"
|
|
226
226
|
};
|
|
227
227
|
|
|
228
|
+
// src/shared/constants/admission-rooms.constants.ts
|
|
229
|
+
var ADMISSION_ROOM_LIMITS = {
|
|
230
|
+
MAX_ROOMS: 32,
|
|
231
|
+
MAX_ROOM_NAME_LENGTH: 256
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
// src/shared/constants/room-prefixes.constants.ts
|
|
235
|
+
var ROOM_PREFIXES = {
|
|
236
|
+
USER: "user",
|
|
237
|
+
TENANT: "tenant",
|
|
238
|
+
RESOURCE: "resource"
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
// src/server/utils/assert-admission-rooms.ts
|
|
242
|
+
var RESERVED_ROOM_PREFIXES = [
|
|
243
|
+
`${ROOM_PREFIXES.USER}:`,
|
|
244
|
+
`${ROOM_PREFIXES.TENANT}:`,
|
|
245
|
+
"connection:"
|
|
246
|
+
];
|
|
247
|
+
function refuse(detail) {
|
|
248
|
+
throw realtimeError(
|
|
249
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
250
|
+
`the authenticator returned rooms that are not valid: ${detail}. Fix the authenticator; the limits are bounds against abuse and apply to this field only.`
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
function assertAdmissionRooms(auth) {
|
|
254
|
+
const { rooms } = auth;
|
|
255
|
+
if (rooms === void 0) return;
|
|
256
|
+
if (!Array.isArray(rooms)) refuse("`rooms` is not an array");
|
|
257
|
+
if (rooms.length > ADMISSION_ROOM_LIMITS.MAX_ROOMS) {
|
|
258
|
+
refuse(`${rooms.length} rooms exceeds the limit of ${ADMISSION_ROOM_LIMITS.MAX_ROOMS}`);
|
|
259
|
+
}
|
|
260
|
+
for (const room of rooms) {
|
|
261
|
+
if (typeof room !== "string" || room.trim().length === 0) {
|
|
262
|
+
refuse("every room must be a non-blank string");
|
|
263
|
+
}
|
|
264
|
+
if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
|
|
265
|
+
refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
|
|
266
|
+
}
|
|
267
|
+
const reserved = RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
|
|
268
|
+
if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
228
272
|
// src/server/utils/assert-identity.ts
|
|
229
273
|
function isBlank(value) {
|
|
230
274
|
return typeof value !== "string" || value.trim().length === 0;
|
|
@@ -418,13 +462,6 @@ exports.RoomRegistry = __decorateClass([
|
|
|
418
462
|
common.Injectable()
|
|
419
463
|
], exports.RoomRegistry);
|
|
420
464
|
|
|
421
|
-
// src/shared/constants/room-prefixes.constants.ts
|
|
422
|
-
var ROOM_PREFIXES = {
|
|
423
|
-
USER: "user",
|
|
424
|
-
TENANT: "tenant",
|
|
425
|
-
RESOURCE: "resource"
|
|
426
|
-
};
|
|
427
|
-
|
|
428
465
|
// src/server/utils/compose-room-id.ts
|
|
429
466
|
function composeRoomId(prefix, ...parts) {
|
|
430
467
|
return [ROOM_PREFIXES[prefix], ...parts].join(":");
|
|
@@ -591,6 +628,7 @@ exports.SseTransport = class SseTransport {
|
|
|
591
628
|
userId: params.auth.userId,
|
|
592
629
|
tenantId: params.auth.tenantId,
|
|
593
630
|
roles: params.auth.roles,
|
|
631
|
+
rooms: params.auth.rooms,
|
|
594
632
|
metadata: params.auth.metadata
|
|
595
633
|
}
|
|
596
634
|
};
|
|
@@ -599,6 +637,7 @@ exports.SseTransport = class SseTransport {
|
|
|
599
637
|
if (params.auth.tenantId !== void 0) {
|
|
600
638
|
this.rooms.join(params.connectionId, composeRoomId("TENANT", params.auth.tenantId));
|
|
601
639
|
}
|
|
640
|
+
for (const room of params.auth.rooms ?? []) this.rooms.join(params.connectionId, room);
|
|
602
641
|
await this.evictBeyondLimit(params.auth.userId);
|
|
603
642
|
}
|
|
604
643
|
async unregisterConnection(connectionId, reason) {
|
|
@@ -879,6 +918,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
879
918
|
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
880
919
|
try {
|
|
881
920
|
assertIdentityIsNotBlank(resolvedAuth);
|
|
921
|
+
assertAdmissionRooms(resolvedAuth);
|
|
882
922
|
} catch (err) {
|
|
883
923
|
this.logger.error(`SSE connection refused \u2014 responding 500: ${describeError(err)}`);
|
|
884
924
|
throw new common.InternalServerErrorException();
|
|
@@ -1165,6 +1205,7 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1165
1205
|
userId: conn.originalAuth.userId,
|
|
1166
1206
|
...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
|
|
1167
1207
|
...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {},
|
|
1208
|
+
...conn.originalAuth.rooms !== void 0 ? { rooms: conn.originalAuth.rooms } : {},
|
|
1168
1209
|
...conn.originalAuth.metadata !== void 0 ? { metadata: conn.originalAuth.metadata } : {}
|
|
1169
1210
|
};
|
|
1170
1211
|
const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
|
|
@@ -1801,6 +1842,7 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
1801
1842
|
}
|
|
1802
1843
|
};
|
|
1803
1844
|
|
|
1845
|
+
exports.ADMISSION_ROOM_LIMITS = ADMISSION_ROOM_LIMITS;
|
|
1804
1846
|
exports.REALTIME_AUTHENTICATOR_TOKEN = REALTIME_AUTHENTICATOR_TOKEN;
|
|
1805
1847
|
exports.REALTIME_ERROR_CODES = REALTIME_ERROR_CODES;
|
|
1806
1848
|
exports.REALTIME_HOOKS_TOKEN = REALTIME_HOOKS_TOKEN;
|
|
@@ -1814,6 +1856,7 @@ exports.RESERVED_EVENT_NAMES = RESERVED_EVENT_NAMES;
|
|
|
1814
1856
|
exports.ROOM_PREFIXES = ROOM_PREFIXES;
|
|
1815
1857
|
exports.RedisOfflineQueue = RedisOfflineQueue;
|
|
1816
1858
|
exports.RedisRealtimePubSub = RedisRealtimePubSub;
|
|
1859
|
+
exports.assertAdmissionRooms = assertAdmissionRooms;
|
|
1817
1860
|
exports.assertIdentityIsNotBlank = assertIdentityIsNotBlank;
|
|
1818
1861
|
exports.composeForRoot = composeForRoot;
|
|
1819
1862
|
exports.composeForRootAsync = composeForRootAsync;
|
|
@@ -99,6 +99,28 @@ interface AuthenticationResult {
|
|
|
99
99
|
*/
|
|
100
100
|
readonly tenantId?: string;
|
|
101
101
|
readonly roles?: readonly string[];
|
|
102
|
+
/**
|
|
103
|
+
* Extra rooms to join this connection to at admission, beside `user:` and `tenant:`.
|
|
104
|
+
*
|
|
105
|
+
* They are joined before the connection is announced or `onConnect` runs, so no event
|
|
106
|
+
* published to one of them can fall between admission and a later `joinRoom` â the
|
|
107
|
+
* window a join from `onConnect` leaves open. On SSE `onConnect` is not awaited
|
|
108
|
+
* and a hook that throws is only logged, so a connection scoped from there can go
|
|
109
|
+
* live, and stay, without its room; scope in `rooms`, not in `onConnect`.
|
|
110
|
+
*
|
|
111
|
+
* Each name must be a non-blank string of at most `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH`
|
|
112
|
+
* characters, must not start with `user:`, `tenant:` or `connection:` (the library
|
|
113
|
+
* composes those from the identity it resolved, or reserves them), and the list may
|
|
114
|
+
* hold at most `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once.
|
|
115
|
+
* A result that breaks a rule is a contract violation, refused like a blank `userId`:
|
|
116
|
+
* a server fault, not a 401. The limits are bounds against abuse, not measurements.
|
|
117
|
+
* They apply to this field only; `joinRoom` stays free-form.
|
|
118
|
+
*
|
|
119
|
+
* The rooms are fixed at admission. `revalidate` is handed them back, but a different
|
|
120
|
+
* set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for
|
|
121
|
+
* changes during the connection.
|
|
122
|
+
*/
|
|
123
|
+
readonly rooms?: readonly string[];
|
|
102
124
|
/**
|
|
103
125
|
* Free-form extras for downstream code (e.g. feature flags, plan tier, a
|
|
104
126
|
* correlation id read off the handshake headers).
|
|
@@ -709,6 +731,8 @@ interface ConnectionRecord {
|
|
|
709
731
|
userId: string;
|
|
710
732
|
tenantId: string | undefined;
|
|
711
733
|
roles: readonly string[] | undefined;
|
|
734
|
+
/** The rooms the authenticator joined at admission, as returned. */
|
|
735
|
+
rooms?: readonly string[] | undefined;
|
|
712
736
|
/** The authenticator's free-form bag, carried through verbatim and never read. */
|
|
713
737
|
metadata: Record<string, unknown> | undefined;
|
|
714
738
|
};
|
|
@@ -1216,10 +1240,10 @@ declare class SseTransport implements ITransport {
|
|
|
1216
1240
|
private readonly logger;
|
|
1217
1241
|
constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, auth: IConnectionAuthenticator, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined);
|
|
1218
1242
|
/**
|
|
1219
|
-
* Mark shutdown as begun at the first hook Nest runs on close
|
|
1220
|
-
*
|
|
1221
|
-
*
|
|
1222
|
-
*
|
|
1243
|
+
* Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
|
|
1244
|
+
* nearer the root than the realtime module still runs first, and until it returns a stream is
|
|
1245
|
+
* accepted; nothing the library owns runs earlier. A slow `beforeApplicationShutdown` in such a
|
|
1246
|
+
* module runs before this transport's own, which is why the flag is set here.
|
|
1223
1247
|
*/
|
|
1224
1248
|
onModuleDestroy(): void;
|
|
1225
1249
|
/**
|
|
@@ -1739,6 +1763,19 @@ declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'te
|
|
|
1739
1763
|
*/
|
|
1740
1764
|
declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
|
|
1741
1765
|
|
|
1766
|
+
/**
|
|
1767
|
+
* Refuse an authentication result whose `rooms` break the admission rules.
|
|
1768
|
+
*
|
|
1769
|
+
* Like a blank identity, a bad room is a contract violation by the authenticator, so it
|
|
1770
|
+
* is refused at admission rather than trimmed or skipped: a connection quietly missing a
|
|
1771
|
+
* room it was meant to join would be live and unscoped. Every check is on the runtime
|
|
1772
|
+
* value, because the declared type is a promise, not a fact.
|
|
1773
|
+
*
|
|
1774
|
+
* @param auth - The resolved authentication result.
|
|
1775
|
+
* @throws Error carrying `REALTIME_AUTH_FAILED` when `rooms` is present and invalid.
|
|
1776
|
+
*/
|
|
1777
|
+
declare function assertAdmissionRooms(auth: AuthenticationResult): void;
|
|
1778
|
+
|
|
1742
1779
|
/**
|
|
1743
1780
|
* @fileoverview Canonical room id prefixes for scoping emits and auto-join.
|
|
1744
1781
|
* @layer shared
|
|
@@ -1925,6 +1962,27 @@ interface PublicConnectionMeta {
|
|
|
1925
1962
|
readonly connectedAt: Date;
|
|
1926
1963
|
}
|
|
1927
1964
|
|
|
1965
|
+
/**
|
|
1966
|
+
* @fileoverview Bounds on the rooms an authenticator may join a connection to at admission.
|
|
1967
|
+
* @layer shared
|
|
1968
|
+
*/
|
|
1969
|
+
/**
|
|
1970
|
+
* Bounds applied to `AuthenticationResult.rooms`.
|
|
1971
|
+
*
|
|
1972
|
+
* Both values are bounds against abuse, not measurements: they keep a buggy or
|
|
1973
|
+
* hostile authenticator from joining a connection to an unbounded set of rooms or to
|
|
1974
|
+
* a room whose name is a payload. Neither was derived from a benchmark or from a
|
|
1975
|
+
* limit of Socket.IO or of the registries, and neither is a recommendation â a host
|
|
1976
|
+
* that needs few rooms should use far fewer. They apply only to the `rooms` field;
|
|
1977
|
+
* `joinRoom` accepts any room name.
|
|
1978
|
+
*/
|
|
1979
|
+
declare const ADMISSION_ROOM_LIMITS: {
|
|
1980
|
+
/** The most rooms one authentication result may carry. */
|
|
1981
|
+
readonly MAX_ROOMS: 32;
|
|
1982
|
+
/** The longest room name, in UTF-16 code units (`String.prototype.length`). */
|
|
1983
|
+
readonly MAX_ROOM_NAME_LENGTH: 256;
|
|
1984
|
+
};
|
|
1985
|
+
|
|
1928
1986
|
/**
|
|
1929
1987
|
* @fileoverview Event names reserved by the library (the §13 catalog).
|
|
1930
1988
|
* @layer shared
|
|
@@ -1950,5 +2008,5 @@ declare const RESERVED_EVENT_NAMES: {
|
|
|
1950
2008
|
/** Union of reserved event name values. */
|
|
1951
2009
|
type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
|
|
1952
2010
|
|
|
1953
|
-
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, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
|
|
2011
|
+
export { ADMISSION_ROOM_LIMITS, 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, assertAdmissionRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
|
|
1954
2012
|
export type { AuthenticationResult, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
|
package/dist/internal/index.d.ts
CHANGED
|
@@ -99,6 +99,28 @@ interface AuthenticationResult {
|
|
|
99
99
|
*/
|
|
100
100
|
readonly tenantId?: string;
|
|
101
101
|
readonly roles?: readonly string[];
|
|
102
|
+
/**
|
|
103
|
+
* Extra rooms to join this connection to at admission, beside `user:` and `tenant:`.
|
|
104
|
+
*
|
|
105
|
+
* They are joined before the connection is announced or `onConnect` runs, so no event
|
|
106
|
+
* published to one of them can fall between admission and a later `joinRoom` â the
|
|
107
|
+
* window a join from `onConnect` leaves open. On SSE `onConnect` is not awaited
|
|
108
|
+
* and a hook that throws is only logged, so a connection scoped from there can go
|
|
109
|
+
* live, and stay, without its room; scope in `rooms`, not in `onConnect`.
|
|
110
|
+
*
|
|
111
|
+
* Each name must be a non-blank string of at most `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH`
|
|
112
|
+
* characters, must not start with `user:`, `tenant:` or `connection:` (the library
|
|
113
|
+
* composes those from the identity it resolved, or reserves them), and the list may
|
|
114
|
+
* hold at most `ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once.
|
|
115
|
+
* A result that breaks a rule is a contract violation, refused like a blank `userId`:
|
|
116
|
+
* a server fault, not a 401. The limits are bounds against abuse, not measurements.
|
|
117
|
+
* They apply to this field only; `joinRoom` stays free-form.
|
|
118
|
+
*
|
|
119
|
+
* The rooms are fixed at admission. `revalidate` is handed them back, but a different
|
|
120
|
+
* set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for
|
|
121
|
+
* changes during the connection.
|
|
122
|
+
*/
|
|
123
|
+
readonly rooms?: readonly string[];
|
|
102
124
|
/**
|
|
103
125
|
* Free-form extras for downstream code (e.g. feature flags, plan tier, a
|
|
104
126
|
* correlation id read off the handshake headers).
|
|
@@ -709,6 +731,8 @@ interface ConnectionRecord {
|
|
|
709
731
|
userId: string;
|
|
710
732
|
tenantId: string | undefined;
|
|
711
733
|
roles: readonly string[] | undefined;
|
|
734
|
+
/** The rooms the authenticator joined at admission, as returned. */
|
|
735
|
+
rooms?: readonly string[] | undefined;
|
|
712
736
|
/** The authenticator's free-form bag, carried through verbatim and never read. */
|
|
713
737
|
metadata: Record<string, unknown> | undefined;
|
|
714
738
|
};
|
|
@@ -1216,10 +1240,10 @@ declare class SseTransport implements ITransport {
|
|
|
1216
1240
|
private readonly logger;
|
|
1217
1241
|
constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, auth: IConnectionAuthenticator, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined);
|
|
1218
1242
|
/**
|
|
1219
|
-
* Mark shutdown as begun at the first hook Nest runs on close
|
|
1220
|
-
*
|
|
1221
|
-
*
|
|
1222
|
-
*
|
|
1243
|
+
* Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
|
|
1244
|
+
* nearer the root than the realtime module still runs first, and until it returns a stream is
|
|
1245
|
+
* accepted; nothing the library owns runs earlier. A slow `beforeApplicationShutdown` in such a
|
|
1246
|
+
* module runs before this transport's own, which is why the flag is set here.
|
|
1223
1247
|
*/
|
|
1224
1248
|
onModuleDestroy(): void;
|
|
1225
1249
|
/**
|
|
@@ -1739,6 +1763,19 @@ declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'te
|
|
|
1739
1763
|
*/
|
|
1740
1764
|
declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
|
|
1741
1765
|
|
|
1766
|
+
/**
|
|
1767
|
+
* Refuse an authentication result whose `rooms` break the admission rules.
|
|
1768
|
+
*
|
|
1769
|
+
* Like a blank identity, a bad room is a contract violation by the authenticator, so it
|
|
1770
|
+
* is refused at admission rather than trimmed or skipped: a connection quietly missing a
|
|
1771
|
+
* room it was meant to join would be live and unscoped. Every check is on the runtime
|
|
1772
|
+
* value, because the declared type is a promise, not a fact.
|
|
1773
|
+
*
|
|
1774
|
+
* @param auth - The resolved authentication result.
|
|
1775
|
+
* @throws Error carrying `REALTIME_AUTH_FAILED` when `rooms` is present and invalid.
|
|
1776
|
+
*/
|
|
1777
|
+
declare function assertAdmissionRooms(auth: AuthenticationResult): void;
|
|
1778
|
+
|
|
1742
1779
|
/**
|
|
1743
1780
|
* @fileoverview Canonical room id prefixes for scoping emits and auto-join.
|
|
1744
1781
|
* @layer shared
|
|
@@ -1925,6 +1962,27 @@ interface PublicConnectionMeta {
|
|
|
1925
1962
|
readonly connectedAt: Date;
|
|
1926
1963
|
}
|
|
1927
1964
|
|
|
1965
|
+
/**
|
|
1966
|
+
* @fileoverview Bounds on the rooms an authenticator may join a connection to at admission.
|
|
1967
|
+
* @layer shared
|
|
1968
|
+
*/
|
|
1969
|
+
/**
|
|
1970
|
+
* Bounds applied to `AuthenticationResult.rooms`.
|
|
1971
|
+
*
|
|
1972
|
+
* Both values are bounds against abuse, not measurements: they keep a buggy or
|
|
1973
|
+
* hostile authenticator from joining a connection to an unbounded set of rooms or to
|
|
1974
|
+
* a room whose name is a payload. Neither was derived from a benchmark or from a
|
|
1975
|
+
* limit of Socket.IO or of the registries, and neither is a recommendation â a host
|
|
1976
|
+
* that needs few rooms should use far fewer. They apply only to the `rooms` field;
|
|
1977
|
+
* `joinRoom` accepts any room name.
|
|
1978
|
+
*/
|
|
1979
|
+
declare const ADMISSION_ROOM_LIMITS: {
|
|
1980
|
+
/** The most rooms one authentication result may carry. */
|
|
1981
|
+
readonly MAX_ROOMS: 32;
|
|
1982
|
+
/** The longest room name, in UTF-16 code units (`String.prototype.length`). */
|
|
1983
|
+
readonly MAX_ROOM_NAME_LENGTH: 256;
|
|
1984
|
+
};
|
|
1985
|
+
|
|
1928
1986
|
/**
|
|
1929
1987
|
* @fileoverview Event names reserved by the library (the §13 catalog).
|
|
1930
1988
|
* @layer shared
|
|
@@ -1950,5 +2008,5 @@ declare const RESERVED_EVENT_NAMES: {
|
|
|
1950
2008
|
/** Union of reserved event name values. */
|
|
1951
2009
|
type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
|
|
1952
2010
|
|
|
1953
|
-
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, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
|
|
2011
|
+
export { ADMISSION_ROOM_LIMITS, 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, assertAdmissionRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
|
|
1954
2012
|
export type { AuthenticationResult, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
|
package/dist/internal/index.mjs
CHANGED
|
@@ -223,6 +223,50 @@ var RESERVED_EVENT_NAMES = {
|
|
|
223
223
|
ERROR: "error"
|
|
224
224
|
};
|
|
225
225
|
|
|
226
|
+
// src/shared/constants/admission-rooms.constants.ts
|
|
227
|
+
var ADMISSION_ROOM_LIMITS = {
|
|
228
|
+
MAX_ROOMS: 32,
|
|
229
|
+
MAX_ROOM_NAME_LENGTH: 256
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
// src/shared/constants/room-prefixes.constants.ts
|
|
233
|
+
var ROOM_PREFIXES = {
|
|
234
|
+
USER: "user",
|
|
235
|
+
TENANT: "tenant",
|
|
236
|
+
RESOURCE: "resource"
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
// src/server/utils/assert-admission-rooms.ts
|
|
240
|
+
var RESERVED_ROOM_PREFIXES = [
|
|
241
|
+
`${ROOM_PREFIXES.USER}:`,
|
|
242
|
+
`${ROOM_PREFIXES.TENANT}:`,
|
|
243
|
+
"connection:"
|
|
244
|
+
];
|
|
245
|
+
function refuse(detail) {
|
|
246
|
+
throw realtimeError(
|
|
247
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
248
|
+
`the authenticator returned rooms that are not valid: ${detail}. Fix the authenticator; the limits are bounds against abuse and apply to this field only.`
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
function assertAdmissionRooms(auth) {
|
|
252
|
+
const { rooms } = auth;
|
|
253
|
+
if (rooms === void 0) return;
|
|
254
|
+
if (!Array.isArray(rooms)) refuse("`rooms` is not an array");
|
|
255
|
+
if (rooms.length > ADMISSION_ROOM_LIMITS.MAX_ROOMS) {
|
|
256
|
+
refuse(`${rooms.length} rooms exceeds the limit of ${ADMISSION_ROOM_LIMITS.MAX_ROOMS}`);
|
|
257
|
+
}
|
|
258
|
+
for (const room of rooms) {
|
|
259
|
+
if (typeof room !== "string" || room.trim().length === 0) {
|
|
260
|
+
refuse("every room must be a non-blank string");
|
|
261
|
+
}
|
|
262
|
+
if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
|
|
263
|
+
refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
|
|
264
|
+
}
|
|
265
|
+
const reserved = RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
|
|
266
|
+
if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
226
270
|
// src/server/utils/assert-identity.ts
|
|
227
271
|
function isBlank(value) {
|
|
228
272
|
return typeof value !== "string" || value.trim().length === 0;
|
|
@@ -416,13 +460,6 @@ RoomRegistry = __decorateClass([
|
|
|
416
460
|
Injectable()
|
|
417
461
|
], RoomRegistry);
|
|
418
462
|
|
|
419
|
-
// src/shared/constants/room-prefixes.constants.ts
|
|
420
|
-
var ROOM_PREFIXES = {
|
|
421
|
-
USER: "user",
|
|
422
|
-
TENANT: "tenant",
|
|
423
|
-
RESOURCE: "resource"
|
|
424
|
-
};
|
|
425
|
-
|
|
426
463
|
// src/server/utils/compose-room-id.ts
|
|
427
464
|
function composeRoomId(prefix, ...parts) {
|
|
428
465
|
return [ROOM_PREFIXES[prefix], ...parts].join(":");
|
|
@@ -589,6 +626,7 @@ var SseTransport = class {
|
|
|
589
626
|
userId: params.auth.userId,
|
|
590
627
|
tenantId: params.auth.tenantId,
|
|
591
628
|
roles: params.auth.roles,
|
|
629
|
+
rooms: params.auth.rooms,
|
|
592
630
|
metadata: params.auth.metadata
|
|
593
631
|
}
|
|
594
632
|
};
|
|
@@ -597,6 +635,7 @@ var SseTransport = class {
|
|
|
597
635
|
if (params.auth.tenantId !== void 0) {
|
|
598
636
|
this.rooms.join(params.connectionId, composeRoomId("TENANT", params.auth.tenantId));
|
|
599
637
|
}
|
|
638
|
+
for (const room of params.auth.rooms ?? []) this.rooms.join(params.connectionId, room);
|
|
600
639
|
await this.evictBeyondLimit(params.auth.userId);
|
|
601
640
|
}
|
|
602
641
|
async unregisterConnection(connectionId, reason) {
|
|
@@ -877,6 +916,7 @@ var SseSubscriptionHandler = class {
|
|
|
877
916
|
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
878
917
|
try {
|
|
879
918
|
assertIdentityIsNotBlank(resolvedAuth);
|
|
919
|
+
assertAdmissionRooms(resolvedAuth);
|
|
880
920
|
} catch (err) {
|
|
881
921
|
this.logger.error(`SSE connection refused \u2014 responding 500: ${describeError(err)}`);
|
|
882
922
|
throw new InternalServerErrorException();
|
|
@@ -1163,6 +1203,7 @@ var ReauthenticationService = class {
|
|
|
1163
1203
|
userId: conn.originalAuth.userId,
|
|
1164
1204
|
...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
|
|
1165
1205
|
...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {},
|
|
1206
|
+
...conn.originalAuth.rooms !== void 0 ? { rooms: conn.originalAuth.rooms } : {},
|
|
1166
1207
|
...conn.originalAuth.metadata !== void 0 ? { metadata: conn.originalAuth.metadata } : {}
|
|
1167
1208
|
};
|
|
1168
1209
|
const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
|
|
@@ -1799,4 +1840,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
1799
1840
|
}
|
|
1800
1841
|
};
|
|
1801
1842
|
|
|
1802
|
-
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, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
|
|
1843
|
+
export { ADMISSION_ROOM_LIMITS, 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, assertAdmissionRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
|
package/dist/server/index.cjs
CHANGED
|
@@ -4,6 +4,10 @@ var internal = require('@bymax-one/nest-realtime/internal');
|
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
7
|
+
Object.defineProperty(exports, "ADMISSION_ROOM_LIMITS", {
|
|
8
|
+
enumerable: true,
|
|
9
|
+
get: function () { return internal.ADMISSION_ROOM_LIMITS; }
|
|
10
|
+
});
|
|
7
11
|
Object.defineProperty(exports, "BymaxRealtimeModule", {
|
|
8
12
|
enumerable: true,
|
|
9
13
|
get: function () { return internal.BymaxRealtimeModule; }
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
|
1
|
+
export { ADMISSION_ROOM_LIMITS, AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
|
1
|
+
export { ADMISSION_ROOM_LIMITS, AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
package/dist/server/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { BymaxRealtimeModule, ConnectionRegistry, InMemoryPubSub, 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, RealtimeService, RedisOfflineQueue, RedisRealtimePubSub, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
|
1
|
+
export { ADMISSION_ROOM_LIMITS, BymaxRealtimeModule, ConnectionRegistry, InMemoryPubSub, 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, RealtimeService, RedisOfflineQueue, RedisRealtimePubSub, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
package/dist/shared/index.cjs
CHANGED
|
@@ -7,6 +7,12 @@ var ROOM_PREFIXES = {
|
|
|
7
7
|
RESOURCE: "resource"
|
|
8
8
|
};
|
|
9
9
|
|
|
10
|
+
// src/shared/constants/admission-rooms.constants.ts
|
|
11
|
+
var ADMISSION_ROOM_LIMITS = {
|
|
12
|
+
MAX_ROOMS: 32,
|
|
13
|
+
MAX_ROOM_NAME_LENGTH: 256
|
|
14
|
+
};
|
|
15
|
+
|
|
10
16
|
// src/shared/constants/reserved-events.constants.ts
|
|
11
17
|
var RESERVED_EVENT_NAMES = {
|
|
12
18
|
CONNECTION_ESTABLISHED: "connection:established",
|
|
@@ -36,6 +42,7 @@ var REALTIME_ERROR_CODES = {
|
|
|
36
42
|
REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
|
|
37
43
|
};
|
|
38
44
|
|
|
45
|
+
exports.ADMISSION_ROOM_LIMITS = ADMISSION_ROOM_LIMITS;
|
|
39
46
|
exports.PRESENCE_EVENT_NAMES = PRESENCE_EVENT_NAMES;
|
|
40
47
|
exports.REALTIME_ERROR_CODES = REALTIME_ERROR_CODES;
|
|
41
48
|
exports.RESERVED_EVENT_NAMES = RESERVED_EVENT_NAMES;
|
package/dist/shared/index.d.cts
CHANGED
|
@@ -93,6 +93,27 @@ declare const ROOM_PREFIXES: {
|
|
|
93
93
|
/** Union of canonical room prefix values (`'user' | 'tenant' | 'resource'`). */
|
|
94
94
|
type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
|
|
95
95
|
|
|
96
|
+
/**
|
|
97
|
+
* @fileoverview Bounds on the rooms an authenticator may join a connection to at admission.
|
|
98
|
+
* @layer shared
|
|
99
|
+
*/
|
|
100
|
+
/**
|
|
101
|
+
* Bounds applied to `AuthenticationResult.rooms`.
|
|
102
|
+
*
|
|
103
|
+
* Both values are bounds against abuse, not measurements: they keep a buggy or
|
|
104
|
+
* hostile authenticator from joining a connection to an unbounded set of rooms or to
|
|
105
|
+
* a room whose name is a payload. Neither was derived from a benchmark or from a
|
|
106
|
+
* limit of Socket.IO or of the registries, and neither is a recommendation â a host
|
|
107
|
+
* that needs few rooms should use far fewer. They apply only to the `rooms` field;
|
|
108
|
+
* `joinRoom` accepts any room name.
|
|
109
|
+
*/
|
|
110
|
+
declare const ADMISSION_ROOM_LIMITS: {
|
|
111
|
+
/** The most rooms one authentication result may carry. */
|
|
112
|
+
readonly MAX_ROOMS: 32;
|
|
113
|
+
/** The longest room name, in UTF-16 code units (`String.prototype.length`). */
|
|
114
|
+
readonly MAX_ROOM_NAME_LENGTH: 256;
|
|
115
|
+
};
|
|
116
|
+
|
|
96
117
|
/**
|
|
97
118
|
* @fileoverview Event names reserved by the library (the §13 catalog).
|
|
98
119
|
* @layer shared
|
|
@@ -161,5 +182,5 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
161
182
|
/** Union of canonical error code values. */
|
|
162
183
|
type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
|
|
163
184
|
|
|
164
|
-
export { PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
|
|
185
|
+
export { ADMISSION_ROOM_LIMITS, PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
|
|
165
186
|
export type { PresenceEventName, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, ReservedEventName, RoomPrefix, TransportMode };
|
package/dist/shared/index.d.ts
CHANGED
|
@@ -93,6 +93,27 @@ declare const ROOM_PREFIXES: {
|
|
|
93
93
|
/** Union of canonical room prefix values (`'user' | 'tenant' | 'resource'`). */
|
|
94
94
|
type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
|
|
95
95
|
|
|
96
|
+
/**
|
|
97
|
+
* @fileoverview Bounds on the rooms an authenticator may join a connection to at admission.
|
|
98
|
+
* @layer shared
|
|
99
|
+
*/
|
|
100
|
+
/**
|
|
101
|
+
* Bounds applied to `AuthenticationResult.rooms`.
|
|
102
|
+
*
|
|
103
|
+
* Both values are bounds against abuse, not measurements: they keep a buggy or
|
|
104
|
+
* hostile authenticator from joining a connection to an unbounded set of rooms or to
|
|
105
|
+
* a room whose name is a payload. Neither was derived from a benchmark or from a
|
|
106
|
+
* limit of Socket.IO or of the registries, and neither is a recommendation â a host
|
|
107
|
+
* that needs few rooms should use far fewer. They apply only to the `rooms` field;
|
|
108
|
+
* `joinRoom` accepts any room name.
|
|
109
|
+
*/
|
|
110
|
+
declare const ADMISSION_ROOM_LIMITS: {
|
|
111
|
+
/** The most rooms one authentication result may carry. */
|
|
112
|
+
readonly MAX_ROOMS: 32;
|
|
113
|
+
/** The longest room name, in UTF-16 code units (`String.prototype.length`). */
|
|
114
|
+
readonly MAX_ROOM_NAME_LENGTH: 256;
|
|
115
|
+
};
|
|
116
|
+
|
|
96
117
|
/**
|
|
97
118
|
* @fileoverview Event names reserved by the library (the §13 catalog).
|
|
98
119
|
* @layer shared
|
|
@@ -161,5 +182,5 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
161
182
|
/** Union of canonical error code values. */
|
|
162
183
|
type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
|
|
163
184
|
|
|
164
|
-
export { PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
|
|
185
|
+
export { ADMISSION_ROOM_LIMITS, PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
|
|
165
186
|
export type { PresenceEventName, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, ReservedEventName, RoomPrefix, TransportMode };
|
package/dist/shared/index.mjs
CHANGED
|
@@ -5,6 +5,12 @@ var ROOM_PREFIXES = {
|
|
|
5
5
|
RESOURCE: "resource"
|
|
6
6
|
};
|
|
7
7
|
|
|
8
|
+
// src/shared/constants/admission-rooms.constants.ts
|
|
9
|
+
var ADMISSION_ROOM_LIMITS = {
|
|
10
|
+
MAX_ROOMS: 32,
|
|
11
|
+
MAX_ROOM_NAME_LENGTH: 256
|
|
12
|
+
};
|
|
13
|
+
|
|
8
14
|
// src/shared/constants/reserved-events.constants.ts
|
|
9
15
|
var RESERVED_EVENT_NAMES = {
|
|
10
16
|
CONNECTION_ESTABLISHED: "connection:established",
|
|
@@ -34,4 +40,4 @@ var REALTIME_ERROR_CODES = {
|
|
|
34
40
|
REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
|
|
35
41
|
};
|
|
36
42
|
|
|
37
|
-
export { PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
|
|
43
|
+
export { ADMISSION_ROOM_LIMITS, PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
|
package/dist/websocket/index.cjs
CHANGED
|
@@ -98,14 +98,17 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
98
98
|
userId: auth.userId,
|
|
99
99
|
tenantId: auth.tenantId,
|
|
100
100
|
roles: auth.roles,
|
|
101
|
+
rooms: auth.rooms,
|
|
101
102
|
metadata: auth.metadata
|
|
102
103
|
}
|
|
103
104
|
});
|
|
104
105
|
await socket.join(`${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
|
|
105
106
|
if (auth.tenantId) await socket.join(`${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
|
|
106
107
|
await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
|
|
108
|
+
for (const room of auth.rooms ?? []) await socket.join(room);
|
|
107
109
|
this.rooms.join(socket.id, `${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
|
|
108
110
|
if (auth.tenantId) this.rooms.join(socket.id, `${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
|
|
111
|
+
for (const room of auth.rooms ?? []) this.rooms.join(socket.id, room);
|
|
109
112
|
await this.evictBeyondLimit(auth.userId);
|
|
110
113
|
await this.hooks.onConnect?.({
|
|
111
114
|
connectionId: socket.id,
|
|
@@ -389,6 +392,7 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
389
392
|
}
|
|
390
393
|
const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
391
394
|
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
395
|
+
internal.assertAdmissionRooms(resolvedAuth);
|
|
392
396
|
this.authenticated.set(socket, resolvedAuth);
|
|
393
397
|
next();
|
|
394
398
|
} catch (err) {
|
|
@@ -448,6 +452,7 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
448
452
|
}
|
|
449
453
|
resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
450
454
|
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
455
|
+
internal.assertAdmissionRooms(resolvedAuth);
|
|
451
456
|
}
|
|
452
457
|
await this.transport.registerSocket(socket, resolvedAuth);
|
|
453
458
|
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
@@ -85,13 +85,13 @@ declare class WebSocketTransport implements ITransport {
|
|
|
85
85
|
private warnedUnattached;
|
|
86
86
|
constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
|
|
87
87
|
/**
|
|
88
|
-
* Mark shutdown as begun at the first hook Nest runs on close
|
|
89
|
-
*
|
|
88
|
+
* Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
|
|
89
|
+
* nearer the root than the realtime module still runs first, and until it returns a handshake is
|
|
90
|
+
* accepted; nothing the library owns runs earlier.
|
|
90
91
|
*
|
|
91
92
|
* Nest runs every module's `onModuleDestroy` before any `beforeApplicationShutdown`, and within a
|
|
92
93
|
* phase it runs a module nearer the root before one it imports, so a slow `beforeApplicationShutdown`
|
|
93
|
-
* in the host's root module runs before this transport's own
|
|
94
|
-
* nearer the root than the realtime module still runs first; nothing the library owns runs earlier.
|
|
94
|
+
* in the host's root module runs before this transport's own, which is why the flag is set here.
|
|
95
95
|
*/
|
|
96
96
|
onModuleDestroy(): void;
|
|
97
97
|
/**
|
|
@@ -85,13 +85,13 @@ declare class WebSocketTransport implements ITransport {
|
|
|
85
85
|
private warnedUnattached;
|
|
86
86
|
constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
|
|
87
87
|
/**
|
|
88
|
-
* Mark shutdown as begun at the first hook Nest runs on close
|
|
89
|
-
*
|
|
88
|
+
* Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
|
|
89
|
+
* nearer the root than the realtime module still runs first, and until it returns a handshake is
|
|
90
|
+
* accepted; nothing the library owns runs earlier.
|
|
90
91
|
*
|
|
91
92
|
* Nest runs every module's `onModuleDestroy` before any `beforeApplicationShutdown`, and within a
|
|
92
93
|
* phase it runs a module nearer the root before one it imports, so a slow `beforeApplicationShutdown`
|
|
93
|
-
* in the host's root module runs before this transport's own
|
|
94
|
-
* nearer the root than the realtime module still runs first; nothing the library owns runs earlier.
|
|
94
|
+
* in the host's root module runs before this transport's own, which is why the flag is set here.
|
|
95
95
|
*/
|
|
96
96
|
onModuleDestroy(): void;
|
|
97
97
|
/**
|
package/dist/websocket/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
|
|
3
|
-
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, describeError, parseCookieHeader, RESERVED_EVENT_NAMES, realtimeError } from '@bymax-one/nest-realtime/internal';
|
|
3
|
+
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, assertAdmissionRooms, describeError, parseCookieHeader, RESERVED_EVENT_NAMES, realtimeError } from '@bymax-one/nest-realtime/internal';
|
|
4
4
|
import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
|
|
5
5
|
import { IoAdapter } from '@nestjs/platform-socket.io';
|
|
6
6
|
|
|
@@ -98,14 +98,17 @@ var WebSocketTransport = class {
|
|
|
98
98
|
userId: auth.userId,
|
|
99
99
|
tenantId: auth.tenantId,
|
|
100
100
|
roles: auth.roles,
|
|
101
|
+
rooms: auth.rooms,
|
|
101
102
|
metadata: auth.metadata
|
|
102
103
|
}
|
|
103
104
|
});
|
|
104
105
|
await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
|
|
105
106
|
if (auth.tenantId) await socket.join(`${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
|
|
106
107
|
await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
|
|
108
|
+
for (const room of auth.rooms ?? []) await socket.join(room);
|
|
107
109
|
this.rooms.join(socket.id, `${ROOM_PREFIXES.USER}:${auth.userId}`);
|
|
108
110
|
if (auth.tenantId) this.rooms.join(socket.id, `${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
|
|
111
|
+
for (const room of auth.rooms ?? []) this.rooms.join(socket.id, room);
|
|
109
112
|
await this.evictBeyondLimit(auth.userId);
|
|
110
113
|
await this.hooks.onConnect?.({
|
|
111
114
|
connectionId: socket.id,
|
|
@@ -389,6 +392,7 @@ var RealtimeGateway = class {
|
|
|
389
392
|
}
|
|
390
393
|
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
391
394
|
assertIdentityIsNotBlank(resolvedAuth);
|
|
395
|
+
assertAdmissionRooms(resolvedAuth);
|
|
392
396
|
this.authenticated.set(socket, resolvedAuth);
|
|
393
397
|
next();
|
|
394
398
|
} catch (err) {
|
|
@@ -448,6 +452,7 @@ var RealtimeGateway = class {
|
|
|
448
452
|
}
|
|
449
453
|
resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
450
454
|
assertIdentityIsNotBlank(resolvedAuth);
|
|
455
|
+
assertAdmissionRooms(resolvedAuth);
|
|
451
456
|
}
|
|
452
457
|
await this.transport.registerSocket(socket, resolvedAuth);
|
|
453
458
|
if (this.options.websocket?.emitConnectionEvent !== false) {
|
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.13",
|
|
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",
|