@bymax-one/nest-realtime 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,87 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.1.2] - 2026-08-21
9
+
10
+ **Documentation-only.** `dist/` is byte-identical to `1.1.1` — verified by diffing the
11
+ build against the published tarball, not asserted. No runtime path, exported type or
12
+ public surface changed. The release exists because `README.md` ships inside the package
13
+ and renders on npm, so a documentation defect there reaches consumers exactly as a code
14
+ one does.
15
+
16
+ ### Documentation
17
+
18
+ - **The role-scoped room snippet led a careful consumer into a wall.** It called
19
+ `moduleRef.get()` inside the `onConnect` hook, which is correct and runs — and which
20
+ means unit-testing that hook requires faking `ModuleRef`, in practice
21
+ `as unknown as ModuleRef`. That is a suppression many codebases block outright, so the
22
+ documented pattern was unusable for anyone whose policy forbids the cast. Found by a
23
+ consumer adopting `1.1.1`, not by us; "it works" was true and was the reason it
24
+ survived review.
25
+
26
+ The README now also documents the testable shape: give the hook the two capabilities
27
+ it uses, `RoomJoiner` and `ServiceResolver`. `ModuleRef` and `RealtimeService` satisfy
28
+ them structurally, so production passes the real objects and a test passes plain ones,
29
+ with no cast at either end. Both snippets are compiled and executed by
30
+ `realtime.module.documented-patterns.spec.ts` rather than left as prose.
31
+
32
+ - **Role matching is exact membership.** `roles?.includes('admin')` on a
33
+ `readonly string[]` compares whole elements. Reaching for
34
+ `roles?.some((r) => r.includes('admin'))` — for case-insensitivity, say — admits
35
+ `administrator`, `admin-readonly` and `superadmin`. That failure is an authorization
36
+ leak, it fails open, and it appears only for role names nobody declared.
37
+
38
+ ## [1.1.1] - 2026-08-21
39
+
40
+ ### Added
41
+
42
+ - **`ConnectionEventMeta` now carries `roles`.** `IConnectionAuthenticator.authenticate` returns
43
+ `roles` and `ConnectionRecord.originalAuth` stores them, but the meta the lifecycle hooks
44
+ receive dropped them — so a host authenticating by role could not act on the role at
45
+ `onConnect`, the one point that has a `connectionId` and knows the connection is new. With no
46
+ role-scoped fan-out and a registry indexed by id, userId and tenantId, a room is the only
47
+ mechanism for "these connections and not those", and a room could not be built on a value that
48
+ never arrived. Threaded through all five meta construction sites — SSE and WebSocket
49
+ `onConnect`/`onDisconnect` plus `onReauthenticationFailed` — because roles present at connect
50
+ and absent at disconnect would be a field that lies by omission exactly when a host cleans up.
51
+
52
+ **This adds a required key.** Reading the meta is unaffected, which is what a hook does; code
53
+ that _constructs_ a `ConnectionEventMeta` (typically a test fixture) must now supply `roles`.
54
+ `undefined` stays meaningful for an authenticator that returns none.
55
+
56
+ Roles are carried, never interpreted: there is deliberately no `emitToRole`. Indexing a
57
+ fan-out on a role would put the consumer's authorization vocabulary into the transport's API,
58
+ and `meta.roles` is a connect-time snapshot — a role-indexed emit would look authoritative
59
+ while reading state that can go stale. Room-plus-`onConnect` leaves that decision with the
60
+ host. The pattern is documented in the README and covered by an executable test.
61
+
62
+ ### Fixed
63
+
64
+ - **`forRootAsync` rejected typed factories and abstract `inject` tokens.** `useFactory` was an
65
+ arrow-property signature, so `strictFunctionTypes` checked it contravariantly and rejected
66
+ every factory whose parameters carried real provider types — including the
67
+ `useFactory: (cfg: ConfigService) => ...` example in this module's own JSDoc, which had never
68
+ typechecked for a consumer. Method shorthand is bivariant, which is what makes `inject` usable.
69
+ Separately, `inject` accepted only `Type<unknown>`, a non-abstract constructor type, which
70
+ excluded Nest's own abstract tokens — `ModuleRef` among them, and therefore the documented
71
+ role-scoped room pattern. Widened with `Abstract<unknown>`.
72
+
73
+ ### Documentation
74
+
75
+ - The README's Rooms section gains a **role-scoped delivery** subsection: how to build a
76
+ role room in `onConnect`, why there is no `emitToRole`, and the snapshot semantics of
77
+ `meta.roles` — a `revalidate` that keeps a connection alive does not refresh it.
78
+ - The `[Unreleased]` compare link pointed at `v1.0.5`, left behind when 1.1.0 shipped, so it
79
+ showed the whole 1.1.0 release as unreleased.
80
+
81
+ ### Tests
82
+
83
+ - The documented role-scoped room pattern is now an executable test rather than prose
84
+ (`realtime.module.documented-patterns.spec.ts`): it boots the module exactly as the README
85
+ shows and asserts both halves — the admin connection reaches `role:admin`, and a `viewer` and
86
+ a roles-`undefined` connection reach nothing. `pnpm typecheck` covers it, so reverting either
87
+ option-type change fails there.
88
+
8
89
  ## [1.1.0] - 2026-08-11
9
90
 
10
91
  ### Changed
@@ -242,7 +323,9 @@ First published release.
242
323
  rather than by the manual sweep that raised the NestJS floors — that sweep
243
324
  asked about NestJS and never put the same question to the other ten peers.
244
325
 
245
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.0.5...HEAD
326
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.1.2...HEAD
327
+ [1.1.2]: https://github.com/bymaxone/nest-realtime/compare/v1.1.1...v1.1.2
328
+ [1.1.1]: https://github.com/bymaxone/nest-realtime/compare/v1.1.0...v1.1.1
246
329
  [1.1.0]: https://github.com/bymaxone/nest-realtime/compare/v1.0.6...v1.1.0
247
330
  [1.0.6]: https://github.com/bymaxone/nest-realtime/compare/v1.0.5...v1.0.6
248
331
  [1.0.5]: https://github.com/bymaxone/nest-realtime/compare/v1.0.4...v1.0.5
package/README.md CHANGED
@@ -544,6 +544,103 @@ composeRoomId('TENANT', tenantId) // → "tenant:t_acme"
544
544
  composeRoomId('RESOURCE', 'invoice', invoiceId) // → "resource:invoice:42"
545
545
  ```
546
546
 
547
+ #### Role-scoped delivery
548
+
549
+ There is no `emitToRole`. Roles are the consumer's authorization vocabulary, not
550
+ the transport's — the library carries them through without interpreting them (see
551
+ [Auth Inversion](#auth-inversion)). To deliver to a subset of connections by role,
552
+ build a room for it in `onConnect`, where `ConnectionEventMeta.roles` carries the
553
+ snapshot the authenticator produced:
554
+
555
+ ```typescript
556
+ import { ModuleRef } from '@nestjs/core'
557
+ import { BymaxRealtimeModule, RealtimeService } from '@bymax-one/nest-realtime'
558
+
559
+ BymaxRealtimeModule.forRootAsync({
560
+ transport: 'sse',
561
+ inject: [ModuleRef],
562
+ useFactory: (moduleRef: ModuleRef) => ({
563
+ transport: 'sse' as const,
564
+ authenticator: new CookieAuthenticator(),
565
+ hooks: {
566
+ onConnect: async (meta) => {
567
+ if (!meta.roles?.includes('admin')) return
568
+ // Resolved lazily: the hook runs per connection, long after bootstrap, so
569
+ // `RealtimeService` — provided by this very module — cannot be injected
570
+ // into the factory that configures it.
571
+ const realtime = moduleRef.get(RealtimeService)
572
+ await realtime.joinRoom(meta.connectionId, 'role:admin')
573
+ },
574
+ },
575
+ }),
576
+ })
577
+ ```
578
+
579
+ Then deliver to exactly those connections from any provider that injects
580
+ `RealtimeService`:
581
+
582
+ ```typescript
583
+ await this.realtime.emitToRoom('role:admin', 'audit.log', entry)
584
+ ```
585
+
586
+ `meta.roles` is a snapshot taken at connect time; a later `revalidate` that keeps
587
+ the connection alive does not refresh it. When a role can be revoked mid-session,
588
+ make `revalidate` return `false` so the connection is torn down and re-established
589
+ with the new roles.
590
+
591
+ ##### Make the hook testable: depend on the capability, not the injector
592
+
593
+ The snippet above works, and it still walks a careful consumer into a wall: a
594
+ `moduleRef.get()` call inside the hook means unit-testing that hook requires
595
+ faking `ModuleRef`, which in practice means `as unknown as ModuleRef` — a
596
+ suppression many codebases block outright.
597
+
598
+ Give the hook the two capabilities it actually uses instead. `ModuleRef` and
599
+ `RealtimeService` satisfy these shapes **structurally**, so the module passes the
600
+ real objects and a test passes plain ones, with no cast at either end:
601
+
602
+ ```typescript
603
+ interface RoomJoiner {
604
+ joinRoom(connectionId: string, roomId: string): Promise<void>
605
+ }
606
+
607
+ interface ServiceResolver {
608
+ get(token: typeof RealtimeService): RoomJoiner
609
+ }
610
+
611
+ function joinRoleRoom(resolver: ServiceResolver, role: string, roomId: string) {
612
+ return async (meta: ConnectionEventMeta): Promise<void> => {
613
+ if (!meta.roles?.includes(role)) return
614
+ await resolver.get(RealtimeService).joinRoom(meta.connectionId, roomId)
615
+ }
616
+ }
617
+ ```
618
+
619
+ Wire it with the real injector:
620
+
621
+ ```typescript
622
+ inject: [ModuleRef],
623
+ useFactory: (moduleRef: ModuleRef) => ({
624
+ transport: 'sse' as const,
625
+ authenticator: new CookieAuthenticator(),
626
+ hooks: { onConnect: joinRoleRoom(moduleRef, 'admin', 'role:admin') },
627
+ }),
628
+ ```
629
+
630
+ and test it without booting NestJS:
631
+
632
+ ```typescript
633
+ const joinRoom = jest.fn()
634
+ const onConnect = joinRoleRoom({ get: () => ({ joinRoom }) }, 'admin', 'role:admin')
635
+ ```
636
+
637
+ > [!NOTE]
638
+ > Match roles by exact membership. `roles?.includes('admin')` on a `readonly string[]`
639
+ > compares whole elements; reaching for `roles?.some((r) => r.includes('admin'))` —
640
+ > for case-insensitivity, say — admits `administrator`, `admin-readonly` and
641
+ > `superadmin`. That failure is an authorization leak, it fails open, and it only
642
+ > shows up for role names nobody declared.
643
+
547
644
  ### Reserved Events
548
645
 
549
646
  Emitted by the library. Do not reuse these names for application events.
@@ -525,6 +525,7 @@ exports.SseTransport = class SseTransport {
525
525
  connectionId: record.connectionId,
526
526
  userId: record.userId,
527
527
  tenantId: record.tenantId,
528
+ roles: record.originalAuth.roles,
528
529
  transport: "sse",
529
530
  ip: record.ip,
530
531
  userAgent: record.userAgent,
@@ -761,6 +762,7 @@ function buildMeta(record) {
761
762
  connectionId: record.connectionId,
762
763
  userId: record.userId,
763
764
  tenantId: record.tenantId,
765
+ roles: record.originalAuth.roles,
764
766
  transport: "sse",
765
767
  ip: record.ip,
766
768
  userAgent: record.userAgent,
@@ -1135,6 +1137,7 @@ exports.ReauthenticationService = class ReauthenticationService {
1135
1137
  connectionId: conn.connectionId,
1136
1138
  userId: conn.userId,
1137
1139
  tenantId: conn.tenantId,
1140
+ roles: conn.originalAuth.roles,
1138
1141
  transport: "sse",
1139
1142
  ip: conn.ip,
1140
1143
  userAgent: conn.userAgent,
@@ -1,4 +1,4 @@
1
- import { ModuleMetadata, Type, Provider, Logger, DynamicModule, MessageEvent, OnModuleInit, OnApplicationShutdown } from '@nestjs/common';
1
+ import { ModuleMetadata, Type, Abstract, Provider, Logger, DynamicModule, MessageEvent, OnModuleInit, OnApplicationShutdown } from '@nestjs/common';
2
2
  import { Subject, Observable } from 'rxjs';
3
3
  import { Redis } from 'ioredis';
4
4
 
@@ -121,6 +121,16 @@ interface ConnectionEventMeta {
121
121
  readonly connectionId: string;
122
122
  readonly userId: string;
123
123
  readonly tenantId: string | undefined;
124
+ /**
125
+ * Roles the authenticator returned for this connection, as a snapshot taken at
126
+ * connect time — `undefined` when the authenticator returned none.
127
+ *
128
+ * The library never interprets a role; it carries the consumer's own
129
+ * authorization vocabulary through so `onConnect` can act on it (typically by
130
+ * joining the connection to a role-scoped room). A later `revalidate` that
131
+ * keeps the connection alive does not refresh this snapshot.
132
+ */
133
+ readonly roles: readonly string[] | undefined;
124
134
  readonly transport: 'sse' | 'websocket';
125
135
  readonly ip: string;
126
136
  readonly userAgent: string | undefined;
@@ -324,8 +334,24 @@ interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'
324
334
  * `transport` the factory resolves; a mismatch fails fast at bootstrap.
325
335
  */
326
336
  transport: TransportMode;
327
- useFactory?: (...args: unknown[]) => BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
328
- inject?: readonly (string | symbol | Type<unknown>)[];
337
+ /**
338
+ * Factory producing the options, receiving whatever `inject` resolves.
339
+ *
340
+ * Declared in method shorthand on purpose: that signature is bivariant, so a
341
+ * consumer can annotate the parameters with the real provider types
342
+ * (`(cfg: ConfigService) => ...`) instead of `unknown`. An arrow-property
343
+ * signature would be checked contravariantly under `strictFunctionTypes` and
344
+ * reject every typed factory, which is the whole point of `inject`.
345
+ */
346
+ useFactory?(...args: unknown[]): BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
347
+ /**
348
+ * Providers to resolve and pass to `useFactory`, positionally.
349
+ *
350
+ * `Abstract<unknown>` is included because Nest's own injectable tokens are
351
+ * abstract classes — `ModuleRef` among them — and `Type<unknown>` alone is a
352
+ * non-abstract constructor type that excludes them.
353
+ */
354
+ inject?: readonly (string | symbol | Type<unknown> | Abstract<unknown>)[];
329
355
  useExisting?: Type<BymaxRealtimeModuleOptionsFactory>;
330
356
  useClass?: Type<BymaxRealtimeModuleOptionsFactory>;
331
357
  /**
@@ -1,4 +1,4 @@
1
- import { ModuleMetadata, Type, Provider, Logger, DynamicModule, MessageEvent, OnModuleInit, OnApplicationShutdown } from '@nestjs/common';
1
+ import { ModuleMetadata, Type, Abstract, Provider, Logger, DynamicModule, MessageEvent, OnModuleInit, OnApplicationShutdown } from '@nestjs/common';
2
2
  import { Subject, Observable } from 'rxjs';
3
3
  import { Redis } from 'ioredis';
4
4
 
@@ -121,6 +121,16 @@ interface ConnectionEventMeta {
121
121
  readonly connectionId: string;
122
122
  readonly userId: string;
123
123
  readonly tenantId: string | undefined;
124
+ /**
125
+ * Roles the authenticator returned for this connection, as a snapshot taken at
126
+ * connect time — `undefined` when the authenticator returned none.
127
+ *
128
+ * The library never interprets a role; it carries the consumer's own
129
+ * authorization vocabulary through so `onConnect` can act on it (typically by
130
+ * joining the connection to a role-scoped room). A later `revalidate` that
131
+ * keeps the connection alive does not refresh this snapshot.
132
+ */
133
+ readonly roles: readonly string[] | undefined;
124
134
  readonly transport: 'sse' | 'websocket';
125
135
  readonly ip: string;
126
136
  readonly userAgent: string | undefined;
@@ -324,8 +334,24 @@ interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'
324
334
  * `transport` the factory resolves; a mismatch fails fast at bootstrap.
325
335
  */
326
336
  transport: TransportMode;
327
- useFactory?: (...args: unknown[]) => BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
328
- inject?: readonly (string | symbol | Type<unknown>)[];
337
+ /**
338
+ * Factory producing the options, receiving whatever `inject` resolves.
339
+ *
340
+ * Declared in method shorthand on purpose: that signature is bivariant, so a
341
+ * consumer can annotate the parameters with the real provider types
342
+ * (`(cfg: ConfigService) => ...`) instead of `unknown`. An arrow-property
343
+ * signature would be checked contravariantly under `strictFunctionTypes` and
344
+ * reject every typed factory, which is the whole point of `inject`.
345
+ */
346
+ useFactory?(...args: unknown[]): BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
347
+ /**
348
+ * Providers to resolve and pass to `useFactory`, positionally.
349
+ *
350
+ * `Abstract<unknown>` is included because Nest's own injectable tokens are
351
+ * abstract classes — `ModuleRef` among them — and `Type<unknown>` alone is a
352
+ * non-abstract constructor type that excludes them.
353
+ */
354
+ inject?: readonly (string | symbol | Type<unknown> | Abstract<unknown>)[];
329
355
  useExisting?: Type<BymaxRealtimeModuleOptionsFactory>;
330
356
  useClass?: Type<BymaxRealtimeModuleOptionsFactory>;
331
357
  /**
@@ -523,6 +523,7 @@ var SseTransport = class {
523
523
  connectionId: record.connectionId,
524
524
  userId: record.userId,
525
525
  tenantId: record.tenantId,
526
+ roles: record.originalAuth.roles,
526
527
  transport: "sse",
527
528
  ip: record.ip,
528
529
  userAgent: record.userAgent,
@@ -759,6 +760,7 @@ function buildMeta(record) {
759
760
  connectionId: record.connectionId,
760
761
  userId: record.userId,
761
762
  tenantId: record.tenantId,
763
+ roles: record.originalAuth.roles,
762
764
  transport: "sse",
763
765
  ip: record.ip,
764
766
  userAgent: record.userAgent,
@@ -1133,6 +1135,7 @@ var ReauthenticationService = class {
1133
1135
  connectionId: conn.connectionId,
1134
1136
  userId: conn.userId,
1135
1137
  tenantId: conn.tenantId,
1138
+ roles: conn.originalAuth.roles,
1136
1139
  transport: "sse",
1137
1140
  ip: conn.ip,
1138
1141
  userAgent: conn.userAgent,
@@ -118,6 +118,7 @@ exports.WebSocketTransport = class WebSocketTransport {
118
118
  connectionId: socket.id,
119
119
  userId: auth.userId,
120
120
  tenantId: auth.tenantId,
121
+ roles: auth.roles,
121
122
  transport: "websocket",
122
123
  ip: socket.handshake.address,
123
124
  userAgent: socket.handshake.headers["user-agent"],
@@ -142,6 +143,7 @@ exports.WebSocketTransport = class WebSocketTransport {
142
143
  connectionId,
143
144
  userId: record.userId,
144
145
  tenantId: record.tenantId,
146
+ roles: record.originalAuth.roles,
145
147
  transport: "websocket",
146
148
  ip: record.ip,
147
149
  userAgent: record.userAgent,
@@ -116,6 +116,7 @@ var WebSocketTransport = class {
116
116
  connectionId: socket.id,
117
117
  userId: auth.userId,
118
118
  tenantId: auth.tenantId,
119
+ roles: auth.roles,
119
120
  transport: "websocket",
120
121
  ip: socket.handshake.address,
121
122
  userAgent: socket.handshake.headers["user-agent"],
@@ -140,6 +141,7 @@ var WebSocketTransport = class {
140
141
  connectionId,
141
142
  userId: record.userId,
142
143
  tenantId: record.tenantId,
144
+ roles: record.originalAuth.roles,
143
145
  transport: "websocket",
144
146
  ip: record.ip,
145
147
  userAgent: record.userAgent,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "Realtime backend → frontend communication for NestJS — dual-transport SSE (default) and WebSocket (opt-in) with a unified server-side API.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -187,7 +187,7 @@
187
187
  "eslint-plugin-prettier": "^5.0.0",
188
188
  "eslint-plugin-react-hooks": "^7.1.1",
189
189
  "eslint-plugin-security": "^4.0.1",
190
- "eventsource": "^4.1.0",
190
+ "eventsource": "^5.1.0",
191
191
  "ioredis": "^6.0.0",
192
192
  "ioredis-mock": "^8.0.0",
193
193
  "jest": "^30.0.0",