@bymax-one/nest-realtime 1.2.12 โ†’ 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.
Files changed (3) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/README.md +60 -214
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,18 @@ 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
+
10
22
  ## [1.2.12] - 2026-11-12
11
23
 
12
24
  ### Added
@@ -984,7 +996,8 @@ First published release.
984
996
  rather than by the manual sweep that raised the NestJS floors โ€” that sweep
985
997
  asked about NestJS and never put the same question to the other ten peers.
986
998
 
987
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.12...HEAD
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
988
1001
  [1.2.12]: https://github.com/bymaxone/nest-realtime/compare/v1.2.11...v1.2.12
989
1002
  [1.2.11]: https://github.com/bymaxone/nest-realtime/compare/v1.2.10...v1.2.11
990
1003
  [1.2.10]: https://github.com/bymaxone/nest-realtime/compare/v1.2.9...v1.2.10
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 **2.26 KB brotli** instead of ~80 KB.
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/` contains no reference to `@nestjs/jwt`, `passport-*`, or any auth package, verified in CI
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 `shared` subpath carries no Node or NestJS import, so the same event names and error codes are used on both sides of the wire without duplicating a constant.
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
- # Using pnpm (recommended)
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 an error at start-up that names this fix.
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 full reference, including `forRootAsync` with `useFactory` / `useClass` / `useExisting`, is in [docs/technical_specification.md](./docs/technical_specification.md) ยง4.
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 โ€” `src/` is audited in CI for any reference to `@bymax-one/nest-auth`, `@nestjs/jwt`, or `passport-*`:
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 consumer-supplied `IConnectionAuthenticator` |
502
- | Auth library imports | None โ€” enforced by a CI grep over `src/` |
503
- | Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result |
504
- | Connection revocation | `disconnect(connectionId)`, propagated cross-instance via `op: 'disconnect'`; rejects when it cannot reach the connection |
505
- | Credential expiry | Interval re-authentication with `disconnect` or event on failure |
506
- | Connection flooding | FIFO eviction per user โ€” oldest closed, new admitted, never a 429 |
507
- | SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform` by default |
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 (~15-25 min)
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 when the connection was closed on this instance or when the revocation was handed to the bus (`IRealtimePubSub`). It **rejects** when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish (`RedisRealtimePubSub` refuses it at once while its Redis client is anything but ready, and does not wait for the connection to return), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. The error carries that code as `error.code` (a `RealtimeErrorCode`), so branch on the property and not on the message text; it is a plain `Error`, not a class to test with `instanceof`. A rejection means the connection may still be connected, so retry. An emit is different: `emitToUser`, `emitToTenant`, `emitToRoom` and `broadcast` stay at-most-once, and **resolve even when the publish to the other instances failed**. That failure is not silent: it is logged with `REALTIME_PUBSUB_UNAVAILABLE` and the operation, and passed to the `onDeliveryFailure` hook, which is where to count it. `emitToUser` also resolves, reporting it the same way, when the offline queue could not keep an event for a user who is offline here, because another instance may have delivered it live. It rejects only when the event has no delivery path left: the user is offline here, the queue failed, and the bus failed or cannot reach another instance (the default in-memory bus). With `transport: 'both'`, an emit that fails on one transport is logged and resolves; one that fails on both rejects with `REALTIME_TRANSPORT_UNAVAILABLE`. A rejected emit is not proof that no client received it, so retry only where a duplicate is acceptable.
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` must be either absent or a non-empty
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.
641
-
642
- To place a connection in no tenant, the **authenticator omits `tenantId`** โ€” that is indexed
643
- under none and joins no tenant room, which an empty string is not. Whitespace counts as blank:
644
- `' '` composes `user: ` just as `''` does.
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.
645
608
 
646
- Omission is the form to write, because it is the only one that compiles everywhere.
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:
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.
651
610
 
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` is the exception and takes a narrower payload (`connectionId?`, `error`, `transport`):
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 {
@@ -716,12 +656,7 @@ class WorkspaceAuthenticator implements IConnectionAuthenticator {
716
656
  }
717
657
  ```
718
658
 
719
- Scope a connection here, not by calling `joinRoom` from `onConnect`. `onConnect` runs after the
720
- connection is live, so an event published to the room in between is missed, and room events have
721
- no replay. Measured with a publish made while the `onConnect` join was still pending: both SSE and
722
- WebSocket delivered the next event and not that one. On SSE `onConnect` is also not awaited, and a
723
- hook that throws is only logged as a warning, so a connection scoped from there can stay live
724
- without its room. Neither behaviour changes; `rooms` is the way around both.
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.
725
660
 
726
661
  A name must be a non-blank string of at most `ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH`
727
662
  characters and must not start with `user:`, `tenant:` or `connection:`; at most
@@ -769,20 +704,11 @@ composeRoomId('TENANT', tenantId) // โ†’ "tenant:t_acme"
769
704
  composeRoomId('RESOURCE', 'invoice', invoiceId) // โ†’ "resource:invoice:42"
770
705
  ```
771
706
 
772
- `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.
773
- `('a:b', 'c')` and `('a', 'b:c')` both give `resource:a:b:c` and land in the same room. When a
774
- part comes from outside your code, encode it first:
775
- `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))`.
776
708
 
777
- A `resource:` room is not tenant-scoped: two tenants using the same type and id share it. When ids
778
- are only unique within a tenant, pass the tenant as its own encoded part โ€”
779
- `composeRoomId('RESOURCE', 'invoice', encodeURIComponent(tenantId), encodeURIComponent(id))` โ€”
780
- because gluing them into one part with a separator that ids may contain, such as `-`, lets two
781
- 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 `-`.
782
710
 
783
- Never pass client-supplied input to `joinRoom` or `emitToRoom` as a room id without checking that
784
- it cannot start with the reserved `user:` or `tenant:` prefixes. The library does not guard them,
785
- 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.
786
712
 
787
713
  #### Role-scoped delivery
788
714
 
@@ -829,58 +755,8 @@ the connection alive does not refresh it. When a role can be revoked mid-session
829
755
  make `revalidate` return `false` so the connection is torn down and re-established
830
756
  with the new roles.
831
757
 
832
- ##### Make the hook testable: depend on the capability, not the injector
833
-
834
- The snippet above works, and it still walks a careful consumer into a wall: a
835
- `moduleRef.get()` call inside the hook means unit-testing that hook requires
836
- faking `ModuleRef`, which in practice means `as unknown as ModuleRef` โ€” a
837
- suppression many codebases block outright.
838
-
839
- Give the hook the two capabilities it actually uses instead. `ModuleRef` and
840
- `RealtimeService` satisfy these shapes **structurally**, so the module passes the
841
- real objects and a test passes plain ones, with no cast at either end:
842
-
843
- ```typescript
844
- interface RoomJoiner {
845
- joinRoom(connectionId: string, roomId: string): Promise<void>
846
- }
847
-
848
- interface ServiceResolver {
849
- get(token: typeof RealtimeService): RoomJoiner
850
- }
851
-
852
- function joinRoleRoom(resolver: ServiceResolver, role: string, roomId: string) {
853
- return async (meta: ConnectionEventMeta): Promise<void> => {
854
- if (!meta.roles?.includes(role)) return
855
- await resolver.get(RealtimeService).joinRoom(meta.connectionId, roomId)
856
- }
857
- }
858
- ```
859
-
860
- Wire it with the real injector:
861
-
862
- ```typescript
863
- inject: [ModuleRef],
864
- useFactory: (moduleRef: ModuleRef) => ({
865
- transport: 'sse' as const,
866
- authenticator: new CookieAuthenticator(),
867
- hooks: { onConnect: joinRoleRoom(moduleRef, 'admin', 'role:admin') },
868
- }),
869
- ```
870
-
871
- and test it without booting NestJS:
872
-
873
- ```typescript
874
- const joinRoom = jest.fn()
875
- const onConnect = joinRoleRoom({ get: () => ({ joinRoom }) }, 'admin', 'role:admin')
876
- ```
877
-
878
758
  > [!NOTE]
879
- > Match roles by exact membership. `roles?.includes('admin')` on a `readonly string[]`
880
- > compares whole elements; reaching for `roles?.some((r) => r.includes('admin'))` โ€”
881
- > for case-insensitivity, say โ€” admits `administrator`, `admin-readonly` and
882
- > `superadmin`. That failure is an authorization leak, it fails open, and it only
883
- > 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.
884
760
 
885
761
  ### Reserved Events
886
762
 
@@ -907,19 +783,23 @@ These names belong to the library. Do not reuse them for application events. The
907
783
 
908
784
  ### Error Codes
909
785
 
910
- | Code | Status |
911
- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
912
- | `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option |
913
- | `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
914
- | `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
915
- | `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
916
- | `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
917
- | `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
918
- | `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 |
919
- | `REALTIME_TRANSPORT_UNAVAILABLE` | Raised as the rejection of a disconnect, a join or a leave when the transport that holds the connection fails or has no server attached, and of an emit to an offline user that has no delivery path left. Also what a new SSE stream or WebSocket handshake is refused with once shutdown has begun: a 503 whose message is the code, and a connect_error whose data.code is the code. Shutdown begins, for this purpose, in the onModuleDestroy phase, ahead of every beforeApplicationShutdown hook, so a slow beforeApplicationShutdown in the host does not leave a window; a slow onModuleDestroy in a module nearer the root than the realtime module still runs first, and a connection is accepted until it returns. |
920
- | `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
921
- | `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
922
- | `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.
923
803
 
924
804
  ### DI Tokens
925
805
 
@@ -953,55 +833,21 @@ These names belong to the library. Do not reuse them for application events. The
953
833
 
954
834
  ---
955
835
 
956
- ## ๐Ÿšง Deployment Notes
957
-
958
- SSE connections are long-lived HTTP responses, and several common proxy defaults break them silently:
959
-
960
- | Concern | Fix |
961
- | ------------------------ | ------------------------------------------------------------------------------------------------------ |
962
- | **Response compression** | Disable on the SSE endpoint โ€” `Content-Encoding: gzip` buffers the body and defeats streaming |
963
- | **Proxy buffering** | Nginx `proxy_buffering off`. The library already sends `X-Accel-Buffering: no` |
964
- | **CDN caching** | `Cache-Control: no-cache, no-transform` โ€” set by the library on the SSE response |
965
- | **Idle timeout** | Must exceed `sse.heartbeatMs` (default 30 s). AWS ALB's 60 s default is compatible |
966
- | **WebSocket + polling** | Enable sticky sessions. The Redis adapter syncs messages between instances, but not handshake affinity |
836
+ ## ๐Ÿšซ What This Library Does NOT Do
967
837
 
968
- Platform-specific configuration is in [docs/proxies-cheat-sheet.md](./docs/proxies-cheat-sheet.md).
969
-
970
- ### Troubleshooting
971
-
972
- **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`:
973
-
974
- ```
975
- 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'.
976
- ```
977
-
978
- When `websocket` options are set, their names follow the words "the websocket options" in parentheses, for example `(cors, redisAdapter)`. The fix is the `main.ts` line in [step 7](#7-add-websocket-optional): `RealtimeIoAdapter` applies `cors`, `namespace`, `pingIntervalMs`, `pingTimeoutMs`, `maxHttpBufferSize` and `redisAdapter`, and until it is installed none of them takes effect.
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.
979
845
 
980
846
  ---
981
847
 
982
848
  ## ๐Ÿค Contributing
983
849
 
984
- Contributions are welcome! Please open an issue to discuss substantial changes before submitting a pull request.
985
-
986
- ```bash
987
- # Clone the repository
988
- git clone https://github.com/bymaxone/nest-realtime.git
989
- cd nest-realtime
990
-
991
- # Install dependencies
992
- pnpm install
993
-
994
- # Run tests
995
- pnpm test
996
-
997
- # Build
998
- pnpm build
999
-
1000
- # Type check
1001
- pnpm typecheck
1002
- ```
1003
-
1004
- 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:
1005
851
 
1006
852
  ```bash
1007
853
  pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm size
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.12",
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",