@bymax-one/nest-realtime 1.2.24 → 1.2.26

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
@@ -7,6 +7,30 @@ Versioning is **not** strict [SemVer](https://semver.org/spec/v2.0.0.html) while
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.26] - 2026-11-21
11
+
12
+ ### Fixed
13
+
14
+ - **An origin allowlist in `websocket.cors` is no longer dropped when it is defined as a class getter, a non-enumerable property or a prototype property.** The block was copied by its own enumerable keys, so `origin` went missing, Socket.IO fell back to its default and answered every origin with `Access-Control-Allow-Origin: *`. The block is now read by the names of `CorsConfig` whenever it is a non-array object, however it reports its type: a block with a `Symbol.toStringTag`, or a strict proxy, is read the same way. A block whose names cannot be read is refused with `REALTIME_INVALID_OPTIONS` and the host's error as the cause, never answered with a wildcard.
15
+ - **`roles` whose read throws is refused at admission.** A proxy or getter on `roles` was first read when the connection event or a hook needed it, so the host's error reached the framework raw. The array is now read once at admission into a frozen copy, and a read that throws is refused with `REALTIME_AUTH_FAILED` and the host's error as the cause. A `roles` value that is not an array is left as it is.
16
+ - **An `async` `tenantResolver` no longer leaves an unhandled rejection.** The resolver is synchronous; a promise is refused as a tenant that is not a string, and its rejection is now absorbed.
17
+
18
+ #### Apply to a derived backend
19
+
20
+ Nothing to change. A host that defined `websocket.cors.origin` as a getter, non-enumerable or on a prototype now gets the allowlist it wrote; check that it is the list you intend, since until now such a server answered every origin.
21
+
22
+ ## [1.2.25] - 2026-11-21
23
+
24
+ ### Fixed
25
+
26
+ - **A `tenantResolver` is given the authenticator's own result again, and the library keeps its own record.** From 1.2.22 to 1.2.24 the resolver received a copy of the result, and every shape of host object turned out to lose something in a copy: a hidden or symbol-keyed field, a field a class default or `Object.create` supplies from the prototype, an accessor that shadows one, a getter over a private field that throws on the copy. The resolver is now handed the object the authenticator returned, so none of that applies. The record the library keeps is built by name (`userId`, `tenantId`, `roles`, `rooms`, `metadata`), each field read once, before the resolver runs; what a resolver writes to the result does not change it, and `roles`, `rooms` and `metadata` stay shared. What the resolver returns is what routes, so the tenant that was tested and the tenant that is used stay one value.
27
+ - **The entries of `extraProviders` are read under the guard, and a value whose type cannot be read says so.** An entry that throws when its type or its `provide` is read raised the host's own error or a refusal without it; it is now refused with the library's code and the error as the `cause`. A refusal of the options, a group or an entry whose type could not be read says `received an object that could not be read`, where it said `a built-in object` or `an object` according to a second read of the value.
28
+ - **A log field named `service` or `version` can no longer reach a log line.** A logger that stamps those on every line would have been given two answers; `logEvent` drops them with the other names it reserves.
29
+
30
+ #### Apply to a derived backend
31
+
32
+ A `tenantResolver` now receives the authenticator's original result, not a copy: it sees a `null` or absent `tenantId` as the authenticator returned it, and a resolver that wrote to the copy it was given from 1.2.22 to 1.2.24 now writes to the authenticator's object. The record the library keeps is built by name from `userId`, `tenantId`, `roles`, `rooms` and `metadata`, and is read the way JavaScript reads a property: a field supplied by a class default, `Object.create` or an accessor on the prototype is now honoured, where 1.2.22 to 1.2.24 dropped it, so a result whose `userId` exists only on its prototype is admitted, and a blank one is still refused. Properties of the result beyond those five were never exposed to hooks and are not kept.
33
+
10
34
  ## [1.2.24] - 2026-11-20
11
35
 
12
36
  ### Fixed
@@ -1274,7 +1298,9 @@ First published release.
1274
1298
  rather than by the manual sweep that raised the NestJS floors — that sweep
1275
1299
  asked about NestJS and never put the same question to the other ten peers.
1276
1300
 
1277
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.24...HEAD
1301
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.26...HEAD
1302
+ [1.2.26]: https://github.com/bymaxone/nest-realtime/compare/v1.2.25...v1.2.26
1303
+ [1.2.25]: https://github.com/bymaxone/nest-realtime/compare/v1.2.24...v1.2.25
1278
1304
  [1.2.24]: https://github.com/bymaxone/nest-realtime/compare/v1.2.23...v1.2.24
1279
1305
  [1.2.23]: https://github.com/bymaxone/nest-realtime/compare/v1.2.22...v1.2.23
1280
1306
  [1.2.22]: https://github.com/bymaxone/nest-realtime/compare/v1.2.21...v1.2.22
package/README.md CHANGED
@@ -342,23 +342,23 @@ With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls
342
342
 
343
343
  All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `authenticator` are required.
344
344
 
345
- | Group | Key Options | Default |
346
- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- |
347
- | **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
348
- | **authenticator** | `IConnectionAuthenticator` | — (**required**) |
349
- | **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result (it receives a plain copy of that result, which has no `tenantId` when the tenant is absent or `null`), on **both** transports; `undefined` and `null` mean "no opinion" and fall back | `auth.tenantId` |
350
- | **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget) | — |
351
- | **hookTimeoutMs** | How long the library waits for a hook it awaits (`onDisconnect` on both transports, WebSocket `onConnect`) before giving up on it; integer from 1 to 2147483647 | `5000` |
352
- | **onConnectFailure** | What a failing `onConnect` does to its connection: `'ignore'` logs it and keeps the connection, `'close'` logs it and closes the connection on both transports, after the hook has run; anything else is refused at start-up | `'ignore'` |
353
- | **authenticateTimeoutMs** | How long a handshake waits for `authenticate` before it is refused (SSE `503`, WebSocket the generic error); integer from 1 to 2147483647 | `10000` |
354
- | **maxPendingHandshakes** | How many calls to `authenticate` may be waiting at once, across both transports; over it a handshake is refused at once without calling it; integer >= 1 | `1000` |
355
- | **maxConnections** | How many connections one instance holds, both transports together; a handshake past it is refused before `authenticate` is called (SSE `503`, WebSocket the generic error); integer >= 1, no way to switch it off | `10000` |
356
- | **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
357
- | **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
358
- | **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
359
- | **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `replayTtlMs`, `replayMaxIdleUsers`, `maxConnectionsPerUser`, `emitConnectionEvent`, `maxQueuedBytes`, `maxQueuedEvents`, `stallHeartbeats` | `/realtime/sse`, `30000`, `100`, `300000`, `1000`, `5`, `true`, `2097152`, `1000`, `3` |
360
- | **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults), `5` for `maxConnectionsPerUser` |
361
- | **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`, `revalidateTimeoutMs`, `concurrency` | `300`, `'disconnect'`, `60000`, `10000`, `8` |
345
+ | Group | Key Options | Default |
346
+ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
347
+ | **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
348
+ | **authenticator** | `IConnectionAuthenticator` | — (**required**) |
349
+ | **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result (it receives the authenticator's own result, not a copy), on **both** transports; `undefined` and `null` mean "no opinion" and fall back | `auth.tenantId` |
350
+ | **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget) | — |
351
+ | **hookTimeoutMs** | How long the library waits for a hook it awaits (`onDisconnect` on both transports, WebSocket `onConnect`) before giving up on it; integer from 1 to 2147483647 | `5000` |
352
+ | **onConnectFailure** | What a failing `onConnect` does to its connection: `'ignore'` logs it and keeps the connection, `'close'` logs it and closes the connection on both transports, after the hook has run; anything else is refused at start-up | `'ignore'` |
353
+ | **authenticateTimeoutMs** | How long a handshake waits for `authenticate` before it is refused (SSE `503`, WebSocket the generic error); integer from 1 to 2147483647 | `10000` |
354
+ | **maxPendingHandshakes** | How many calls to `authenticate` may be waiting at once, across both transports; over it a handshake is refused at once without calling it; integer >= 1 | `1000` |
355
+ | **maxConnections** | How many connections one instance holds, both transports together; a handshake past it is refused before `authenticate` is called (SSE `503`, WebSocket the generic error); integer >= 1, no way to switch it off | `10000` |
356
+ | **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
357
+ | **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
358
+ | **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
359
+ | **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `replayTtlMs`, `replayMaxIdleUsers`, `maxConnectionsPerUser`, `emitConnectionEvent`, `maxQueuedBytes`, `maxQueuedEvents`, `stallHeartbeats` | `/realtime/sse`, `30000`, `100`, `300000`, `1000`, `5`, `true`, `2097152`, `1000`, `3` |
360
+ | **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults), `5` for `maxConnectionsPerUser` |
361
+ | **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`, `revalidateTimeoutMs`, `concurrency` | `300`, `'disconnect'`, `60000`, `10000`, `8` |
362
362
 
363
363
  `sse.heartbeatMs` must be between 5,000 and 90,000 ms. Any other value, including `NaN` and a non-number, stops the application at start-up with `REALTIME_INVALID_OPTIONS`. `websocket.pingIntervalMs` and `websocket.pingTimeoutMs` must be integers from 1 to 2147483647 (Socket.IO runs both as timers, and Node runs a longer one as 1 ms). `sse.replayTtlMs` must be an integer from 1 to 2147483647 and `sse.replayMaxIdleUsers` an integer of 1 or more. `sse.maxQueuedBytes`, `sse.maxQueuedEvents` and `sse.stallHeartbeats` must be integers of 0 or more, and `0` switches that bound off.
364
364
 
@@ -412,7 +412,7 @@ An option that holds `undefined` or `null` is read as unset: it takes its defaul
412
412
 
413
413
  The shape of what you pass is checked at start-up too, and refused with `REALTIME_INVALID_OPTIONS`: `sse`, `websocket`, `reauthenticationPolicy` and `hooks` must be objects; `pubsub`, `offlineQueue` and `presence` must have every function of their interface (`IRealtimePubSub`, `IOfflineQueueStorage`, `IPresenceStorage`), on the object or its prototype; each hook that is set and `tenantResolver` must be a function; `sse.emitConnectionEvent` and `websocket.emitConnectionEvent` must be booleans; `sse.endpoint` must be a non-blank string, with or without a leading slash. An endpoint holds no whitespace, because no request can reach it, and the `sseEndpoint` of `forRootAsync` gets the same check. The options argument must be an object, and so must what a `forRootAsync` factory returns; an array, a `Date` or a `Map` is refused there and where a group is expected, while an instance of your own class is read by its keys. `new RedisOfflineQueue(options)` refuses options that are not an object and a `client` that is not one.
414
414
 
415
- The options are typed per entry point: `SseRealtimeModuleOptions` and `SseRealtimeModuleAsyncOptions` fix `transport: 'sse'`, and `WebSocketRealtimeModuleOptions` and `WebSocketRealtimeModuleAsyncOptions` (from `/websocket`) fix `'websocket' | 'both'`. `forRootAsync` takes `useFactory`, `useClass` (a `BymaxRealtimeModuleOptionsFactory`) or `useExisting`. A `useClass` or `useExisting` provider implements `createRealtimeOptions()`, which returns the options or a promise of them; a provider that does not is refused with `REALTIME_INVALID_OPTIONS`, as is an `extraProviders` that is not an array of providers (a class, or an object with `provide`). An options object, a group, a pluggable piece or a provider whose read throws, such as a getter or a proxy, is refused the same way, with the error it threw as the `cause`. The same holds for the keys of a `forRootAsync` registration and for an object that throws when its type is read, such as a proxy whose every read throws: it is refused as a built-in object, with the error it threw as the `cause`. A factory that returns the object itself is covered, including a proxy that throws on `then` or was revoked; one written as an `async` function rejects its own promise with the object's error, which reaches the application as that factory's failure. A refusal is recognised by its stable code, so an error of your own that carries a `REALTIME_` code is not wrapped.
415
+ The options are typed per entry point: `SseRealtimeModuleOptions` and `SseRealtimeModuleAsyncOptions` fix `transport: 'sse'`, and `WebSocketRealtimeModuleOptions` and `WebSocketRealtimeModuleAsyncOptions` (from `/websocket`) fix `'websocket' | 'both'`. `forRootAsync` takes `useFactory`, `useClass` (a `BymaxRealtimeModuleOptionsFactory`) or `useExisting`. A `useClass` or `useExisting` provider implements `createRealtimeOptions()`, which returns the options or a promise of them; a provider that does not is refused with `REALTIME_INVALID_OPTIONS`, as is an `extraProviders` that is not an array of providers (a class, or an object with `provide`). An options object, a group, a pluggable piece or a provider whose read throws, such as a getter or a proxy, is refused the same way, with the error it threw as the `cause`. The same holds for the keys of a `forRootAsync` registration and for an object that throws when its type is read, such as a proxy whose every read throws: it is refused as an object that could not be read, with the error it threw as the `cause`. A factory that returns the object itself is covered, including a proxy that throws on `then` or was revoked; one written as an `async` function rejects its own promise with the object's error, which reaches the application as that factory's failure. A refusal is recognised by its stable code, so an error of your own that carries a `REALTIME_` code is not wrapped.
416
416
 
417
417
  > [!IMPORTANT]
418
418
  > **`forRootAsync` takes the SSE route on the registration, not from the factory.** NestJS
@@ -638,16 +638,16 @@ When integrating `@bymax-one/nest-realtime` in production, verify each of the fo
638
638
 
639
639
  ## 🛡️ Security Table
640
640
 
641
- | Layer | Implementation |
642
- | --------------------- | -------------------------------------------------------------------------------------------------- |
643
- | Credential validation | Delegated entirely to your `IConnectionAuthenticator` |
644
- | Auth library imports | None: an ESLint rule fails lint on a string literal naming an auth package in `src` |
645
- | Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result |
646
- | Connection revocation | `disconnect(connectionId)`, cross-instance; rejects if it cannot reach it |
647
- | Credential expiry | Interval re-authentication; a failure drops the connection, after an event if `onFailure: 'event'` |
648
- | Connection flooding | FIFO eviction per user: oldest closed, new admitted, never a 429 |
649
- | SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform` |
650
- | WebSocket origin | Explicit `cors` config passed straight to Socket.IO |
641
+ | Layer | Implementation |
642
+ | --------------------- | ----------------------------------------------------------------------------------------------------- |
643
+ | Credential validation | Delegated entirely to your `IConnectionAuthenticator` |
644
+ | Auth library imports | None: an ESLint rule fails lint on a string literal naming an auth package in `src` |
645
+ | Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result |
646
+ | Connection revocation | `disconnect(connectionId)`, cross-instance; rejects if it cannot reach it |
647
+ | Credential expiry | Interval re-authentication; a failure drops the connection, after an event if `onFailure: 'event'` |
648
+ | Connection flooding | FIFO eviction per user: oldest closed, new admitted, never a 429 |
649
+ | SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform` |
650
+ | WebSocket origin | Explicit `cors` config: `origin`, `credentials` and `methods` are read by name and given to Socket.IO |
651
651
 
652
652
  ---
653
653
 
@@ -777,7 +777,7 @@ Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePub
777
777
 
778
778
  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.
779
779
 
780
- `tenantResolver` cannot clear a tenant. It receives a plain copy of the authentication result, not the authenticator's original object: the result's own enumerable properties, and the `tenantId` as the library read it, which counts when an accessor on the prototype supplies it and is missing when the tenant is absent or `null`. The copy is its own object and is shallow: a resolver that assigns to one of its top-level properties changes nothing the library keeps, while nested objects are shared with the original, so a write inside them changes what the library keeps. 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.
780
+ `tenantResolver` cannot clear a tenant. It receives the authenticator's own result, the object it returned and not a copy, so everything on it works as it does for the authenticator's code. The library keeps its own record of `userId`, `tenantId`, `roles`, `rooms` and `metadata`, built by name before the resolver runs and read the way JavaScript reads a property, so a field that a class default, `Object.create` or an accessor on the prototype supplies counts. What a resolver writes to the result does not change that record, which is another object; `roles`, `rooms` and `metadata` are shared, so a write inside them changes what the library keeps. Resolution is `tenantResolver?.(auth) ?? tenantId`, where `tenantId` is what the result held before the resolver ran, so a resolver returning `undefined` or `null` means "no opinion" and the authenticator's tenant stays. Decide the absent case in the authenticator.
781
781
 
782
782
  #### Carrying handshake context into the hooks
783
783
 
@@ -79,6 +79,11 @@ var WEBSOCKET_KEYS = {
79
79
  emitConnectionEvent: true,
80
80
  redisAdapter: true
81
81
  };
82
+ var CORS_KEYS = {
83
+ origin: true,
84
+ credentials: true,
85
+ methods: true
86
+ };
82
87
  var REAUTHENTICATION_KEYS = {
83
88
  intervalSeconds: true,
84
89
  onFailure: true,
@@ -122,6 +127,13 @@ function dropUnset(options) {
122
127
  const value = kept[group];
123
128
  if (isPlainObject(value)) kept[group] = readSet(value, keys);
124
129
  }
130
+ const websocket = kept.websocket;
131
+ if (isPlainObject(websocket)) {
132
+ const cors = websocket.cors;
133
+ if (typeof cors === "object" && cors !== null && !Array.isArray(cors)) {
134
+ websocket.cors = readSet(cors, CORS_KEYS);
135
+ }
136
+ }
125
137
  return kept;
126
138
  }
127
139
 
@@ -221,7 +233,7 @@ function describeReceived(value) {
221
233
  function refuseObject(who, path, value, cause) {
222
234
  throw realtimeError(
223
235
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
224
- `${path} must be an object, received ${describeReceived(value)}`,
236
+ `${path} must be an object, received ${cause === void 0 ? describeReceived(value) : "an object that could not be read"}`,
225
237
  cause === void 0 ? { who } : { who, cause: cause.error }
226
238
  );
227
239
  }
@@ -240,10 +252,11 @@ var HOOK_NAMES = [
240
252
  "onDeliveryFailure"
241
253
  ];
242
254
  var GROUP_NAMES = ["sse", "websocket", "reauthenticationPolicy"];
255
+ var UNREADABLE = "an object that could not be read";
243
256
  function refuse(path, expected, received, cause) {
244
257
  throw realtimeError(
245
258
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
246
- `options.${path} must be ${expected}, received ${describeReceived(received)}`,
259
+ `options.${path} must be ${expected}, received ${cause === void 0 ? describeReceived(received) : UNREADABLE}`,
247
260
  cause === void 0 ? { who: "BymaxRealtimeModule" } : { who: "BymaxRealtimeModule", cause: cause.error }
248
261
  );
249
262
  }
@@ -308,14 +321,14 @@ function assertExtraProviders(value) {
308
321
  );
309
322
  }
310
323
  value.forEach((entry, index) => {
311
- const isClass = typeof entry === "function";
312
- const hasProvide = isPlainObject(entry) && "provide" in entry;
313
- if (isClass || hasProvide) return;
314
- const received = isPlainObject(entry) && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
324
+ if (typeof entry === "function") return;
325
+ const read = readPlainObject(entry);
326
+ if (read.plain && "provide" in entry) return;
327
+ const received = read.threw ? UNREADABLE : read.plain && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
315
328
  throw realtimeError(
316
329
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
317
330
  `extraProviders[${index}] must be a provider (a class or an object with provide), received ${received}`,
318
- { who: "BymaxRealtimeModule" }
331
+ read.threw ? { who: "BymaxRealtimeModule", cause: read.error } : { who: "BymaxRealtimeModule" }
319
332
  );
320
333
  });
321
334
  }
@@ -587,7 +600,9 @@ var RESERVED_KEYS = [
587
600
  "name",
588
601
  "v",
589
602
  "req",
590
- "res"
603
+ "res",
604
+ "service",
605
+ "version"
591
606
  ];
592
607
  function logEvent(logger, level, event, message, fields = {}, error) {
593
608
  try {
@@ -851,9 +866,23 @@ function refuse2(detail) {
851
866
  `the authenticator returned rooms that are not valid: ${detail}. Fix the authenticator; the limits are bounds against abuse and apply to this field only.`
852
867
  );
853
868
  }
869
+ function admitRoles(roles) {
870
+ if (!Array.isArray(roles)) return roles;
871
+ try {
872
+ return Object.freeze([...roles]);
873
+ } catch (error) {
874
+ throw realtimeError(
875
+ REALTIME_ERROR_CODES.AUTH_FAILED,
876
+ "the authenticator returned roles that could not be read: a getter or a proxy on them throws",
877
+ { cause: error }
878
+ );
879
+ }
880
+ }
854
881
  function admitRooms(auth) {
882
+ const roles = admitRoles(auth.roles);
855
883
  const { rooms } = auth;
856
- if (rooms === void 0) return auth;
884
+ const kept = roles === auth.roles ? auth : { ...auth, roles };
885
+ if (rooms === void 0) return kept;
857
886
  if (!Array.isArray(rooms)) refuse2("`rooms` is not an array");
858
887
  const admitted = [];
859
888
  for (const room of rooms) {
@@ -874,7 +903,7 @@ function admitRooms(auth) {
874
903
  const reserved = reservedRoomPrefix(room);
875
904
  if (reserved !== void 0) refuse2(`a room name starts with the reserved prefix "${reserved}"`);
876
905
  }
877
- return { ...auth, rooms: Object.freeze(admitted) };
906
+ return { ...kept, rooms: Object.freeze(admitted) };
878
907
  }
879
908
 
880
909
  // src/server/utils/assert-identity.ts
@@ -882,12 +911,26 @@ function isBlank(value) {
882
911
  return typeof value !== "string" || value.trim().length === 0;
883
912
  }
884
913
  function resolveAuthTenant(options, auth) {
885
- const { tenantId: own, ...rest } = auth;
886
- const resolved = options.tenantResolver?.(
887
- own === void 0 || own === null ? { ...rest } : { ...rest, tenantId: own }
888
- ) ?? own;
889
- if (resolved === void 0 || resolved === null) return rest;
890
- return { ...rest, tenantId: resolved };
914
+ const own = auth.tenantId;
915
+ const kept = keepByName(auth);
916
+ const resolved = options.tenantResolver?.(auth) ?? own;
917
+ if (resolved instanceof Promise) resolved.catch(() => void 0);
918
+ if (resolved === void 0 || resolved === null) return kept;
919
+ return { ...kept, tenantId: resolved };
920
+ }
921
+ function keepByName(auth) {
922
+ const kept = {};
923
+ for (const key of ["userId", "roles", "rooms", "metadata"]) {
924
+ const value = auth[key];
925
+ if (value === void 0) continue;
926
+ Object.defineProperty(kept, key, {
927
+ value,
928
+ enumerable: true,
929
+ writable: true,
930
+ configurable: true
931
+ });
932
+ }
933
+ return kept;
891
934
  }
892
935
  function assertIdentityIsNotBlank(auth) {
893
936
  if (isBlank(auth.userId)) {
@@ -2781,7 +2824,7 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2781
2824
  assertModeSupported(wiring, registration.transport, moduleName);
2782
2825
  assertSseEndpoint("sseEndpoint", registration.sseEndpoint);
2783
2826
  assertSseEndpointApplies(registration, moduleName);
2784
- assertExtraProviders(registration.extraProviders);
2827
+ guardHostReads("the registration", () => assertExtraProviders(registration.extraProviders));
2785
2828
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2786
2829
  const instanceId = crypto.randomUUID();
2787
2830
  const boundSseEndpoint = registration.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
@@ -479,14 +479,15 @@ interface BymaxRealtimeModuleOptions {
479
479
  /**
480
480
  * Derive the tenant a connection routes on from the authenticated result.
481
481
  *
482
- * Applied on **both** transports. It receives a plain copy of the authentication
483
- * result, not the authenticator's original object: the result's own enumerable
484
- * properties and the `tenantId` as the library read it, which counts when an accessor
485
- * on the prototype supplies it and is missing when the tenant is absent or `null`.
486
- * The copy is its own object and is shallow: a resolver that assigns to one of its
487
- * top-level properties changes nothing the library keeps, while `roles`, `rooms` and
488
- * `metadata` are shared with the original, so a write inside them changes what the
489
- * library keeps. `undefined` and
482
+ * Applied on **both** transports. It receives the authenticator's own result, the
483
+ * object it returned and not a copy, so everything on it works as it does for the
484
+ * authenticator's code. The library keeps its own record of `userId`, `tenantId`,
485
+ * `roles`, `rooms` and `metadata`, built by name before the resolver runs and read the
486
+ * way JavaScript reads a property, so a field that a class default, `Object.create` or
487
+ * an accessor on the prototype supplies counts. What a resolver writes to the result
488
+ * does not change that record, which is another object; `roles`, `rooms` and
489
+ * `metadata` are shared, so a write inside them changes what the library keeps.
490
+ * `undefined` and
490
491
  * `null` both mean "no opinion"
491
492
  * and fall back to `auth.tenantId` rather than clearing it; to place a connection
492
493
  * in no tenant, return a result without one from the authenticator. `null` is in
@@ -2186,7 +2187,7 @@ declare class RedisOfflineQueue implements IOfflineQueueStorage {
2186
2187
  *
2187
2188
  * @param options - The module options, read for an optional `tenantResolver`.
2188
2189
  * @param auth - The authentication result the consumer's authenticator returned.
2189
- * @returns The same result with `tenantId` resolved, or absent when there is none.
2190
+ * @returns A copy of the result with `tenantId` resolved, or absent when there is none.
2190
2191
  */
2191
2192
  declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'tenantResolver'>, auth: AuthenticationResult): AuthenticationResult;
2192
2193
  /**
@@ -2226,9 +2227,9 @@ declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
2226
2227
  * await, so reading the original there would join whatever it holds by then.
2227
2228
  *
2228
2229
  * @param auth - The resolved authentication result.
2229
- * @returns `auth` itself when it has no `rooms`; otherwise a result with the same fields and a
2230
- * frozen copy of its `rooms`.
2231
- * @throws Error carrying `REALTIME_AUTH_FAILED` when `rooms` is present and invalid.
2230
+ * @returns `auth` itself when it has no `rooms` and no array `roles`; otherwise a result with the
2231
+ * same fields and a frozen copy of each of those it has.
2232
+ * @throws Error carrying `REALTIME_AUTH_FAILED` when `rooms` is present and invalid, or `roles` cannot be read.
2232
2233
  */
2233
2234
  declare function admitRooms(auth: AuthenticationResult): AuthenticationResult;
2234
2235
 
@@ -2314,7 +2315,7 @@ type LogFields = Readonly<Record<string, string | number | boolean>>;
2314
2315
  * @param event - The stable code of the condition.
2315
2316
  * @param message - Human text; the library's own wording, with no host-supplied value in it.
2316
2317
  * @param fields - Closed or numeric fields, built by the library. A key named `event` or `message` is replaced by the
2317
- * library's own value, and one named `err`, `msg`, `level`, `time`, `pid`, `hostname`, `name`, `v`, `req` or `res` is dropped, and a field whose read throws, such as a getter, loses the line like any other
2318
+ * library's own value, and one named `err`, `msg`, `level`, `time`, `pid`, `hostname`, `name`, `v`, `req`, `res`, `service` or `version` is dropped, and a field whose read throws, such as a getter, loses the line like any other
2318
2319
  * throw while writing.
2319
2320
  * @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
2320
2321
  * as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
@@ -479,14 +479,15 @@ interface BymaxRealtimeModuleOptions {
479
479
  /**
480
480
  * Derive the tenant a connection routes on from the authenticated result.
481
481
  *
482
- * Applied on **both** transports. It receives a plain copy of the authentication
483
- * result, not the authenticator's original object: the result's own enumerable
484
- * properties and the `tenantId` as the library read it, which counts when an accessor
485
- * on the prototype supplies it and is missing when the tenant is absent or `null`.
486
- * The copy is its own object and is shallow: a resolver that assigns to one of its
487
- * top-level properties changes nothing the library keeps, while `roles`, `rooms` and
488
- * `metadata` are shared with the original, so a write inside them changes what the
489
- * library keeps. `undefined` and
482
+ * Applied on **both** transports. It receives the authenticator's own result, the
483
+ * object it returned and not a copy, so everything on it works as it does for the
484
+ * authenticator's code. The library keeps its own record of `userId`, `tenantId`,
485
+ * `roles`, `rooms` and `metadata`, built by name before the resolver runs and read the
486
+ * way JavaScript reads a property, so a field that a class default, `Object.create` or
487
+ * an accessor on the prototype supplies counts. What a resolver writes to the result
488
+ * does not change that record, which is another object; `roles`, `rooms` and
489
+ * `metadata` are shared, so a write inside them changes what the library keeps.
490
+ * `undefined` and
490
491
  * `null` both mean "no opinion"
491
492
  * and fall back to `auth.tenantId` rather than clearing it; to place a connection
492
493
  * in no tenant, return a result without one from the authenticator. `null` is in
@@ -2186,7 +2187,7 @@ declare class RedisOfflineQueue implements IOfflineQueueStorage {
2186
2187
  *
2187
2188
  * @param options - The module options, read for an optional `tenantResolver`.
2188
2189
  * @param auth - The authentication result the consumer's authenticator returned.
2189
- * @returns The same result with `tenantId` resolved, or absent when there is none.
2190
+ * @returns A copy of the result with `tenantId` resolved, or absent when there is none.
2190
2191
  */
2191
2192
  declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'tenantResolver'>, auth: AuthenticationResult): AuthenticationResult;
2192
2193
  /**
@@ -2226,9 +2227,9 @@ declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
2226
2227
  * await, so reading the original there would join whatever it holds by then.
2227
2228
  *
2228
2229
  * @param auth - The resolved authentication result.
2229
- * @returns `auth` itself when it has no `rooms`; otherwise a result with the same fields and a
2230
- * frozen copy of its `rooms`.
2231
- * @throws Error carrying `REALTIME_AUTH_FAILED` when `rooms` is present and invalid.
2230
+ * @returns `auth` itself when it has no `rooms` and no array `roles`; otherwise a result with the
2231
+ * same fields and a frozen copy of each of those it has.
2232
+ * @throws Error carrying `REALTIME_AUTH_FAILED` when `rooms` is present and invalid, or `roles` cannot be read.
2232
2233
  */
2233
2234
  declare function admitRooms(auth: AuthenticationResult): AuthenticationResult;
2234
2235
 
@@ -2314,7 +2315,7 @@ type LogFields = Readonly<Record<string, string | number | boolean>>;
2314
2315
  * @param event - The stable code of the condition.
2315
2316
  * @param message - Human text; the library's own wording, with no host-supplied value in it.
2316
2317
  * @param fields - Closed or numeric fields, built by the library. A key named `event` or `message` is replaced by the
2317
- * library's own value, and one named `err`, `msg`, `level`, `time`, `pid`, `hostname`, `name`, `v`, `req` or `res` is dropped, and a field whose read throws, such as a getter, loses the line like any other
2318
+ * library's own value, and one named `err`, `msg`, `level`, `time`, `pid`, `hostname`, `name`, `v`, `req`, `res`, `service` or `version` is dropped, and a field whose read throws, such as a getter, loses the line like any other
2318
2319
  * throw while writing.
2319
2320
  * @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
2320
2321
  * as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
@@ -77,6 +77,11 @@ var WEBSOCKET_KEYS = {
77
77
  emitConnectionEvent: true,
78
78
  redisAdapter: true
79
79
  };
80
+ var CORS_KEYS = {
81
+ origin: true,
82
+ credentials: true,
83
+ methods: true
84
+ };
80
85
  var REAUTHENTICATION_KEYS = {
81
86
  intervalSeconds: true,
82
87
  onFailure: true,
@@ -120,6 +125,13 @@ function dropUnset(options) {
120
125
  const value = kept[group];
121
126
  if (isPlainObject(value)) kept[group] = readSet(value, keys);
122
127
  }
128
+ const websocket = kept.websocket;
129
+ if (isPlainObject(websocket)) {
130
+ const cors = websocket.cors;
131
+ if (typeof cors === "object" && cors !== null && !Array.isArray(cors)) {
132
+ websocket.cors = readSet(cors, CORS_KEYS);
133
+ }
134
+ }
123
135
  return kept;
124
136
  }
125
137
 
@@ -219,7 +231,7 @@ function describeReceived(value) {
219
231
  function refuseObject(who, path, value, cause) {
220
232
  throw realtimeError(
221
233
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
222
- `${path} must be an object, received ${describeReceived(value)}`,
234
+ `${path} must be an object, received ${cause === void 0 ? describeReceived(value) : "an object that could not be read"}`,
223
235
  cause === void 0 ? { who } : { who, cause: cause.error }
224
236
  );
225
237
  }
@@ -238,10 +250,11 @@ var HOOK_NAMES = [
238
250
  "onDeliveryFailure"
239
251
  ];
240
252
  var GROUP_NAMES = ["sse", "websocket", "reauthenticationPolicy"];
253
+ var UNREADABLE = "an object that could not be read";
241
254
  function refuse(path, expected, received, cause) {
242
255
  throw realtimeError(
243
256
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
244
- `options.${path} must be ${expected}, received ${describeReceived(received)}`,
257
+ `options.${path} must be ${expected}, received ${cause === void 0 ? describeReceived(received) : UNREADABLE}`,
245
258
  cause === void 0 ? { who: "BymaxRealtimeModule" } : { who: "BymaxRealtimeModule", cause: cause.error }
246
259
  );
247
260
  }
@@ -306,14 +319,14 @@ function assertExtraProviders(value) {
306
319
  );
307
320
  }
308
321
  value.forEach((entry, index) => {
309
- const isClass = typeof entry === "function";
310
- const hasProvide = isPlainObject(entry) && "provide" in entry;
311
- if (isClass || hasProvide) return;
312
- const received = isPlainObject(entry) && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
322
+ if (typeof entry === "function") return;
323
+ const read = readPlainObject(entry);
324
+ if (read.plain && "provide" in entry) return;
325
+ const received = read.threw ? UNREADABLE : read.plain && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
313
326
  throw realtimeError(
314
327
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
315
328
  `extraProviders[${index}] must be a provider (a class or an object with provide), received ${received}`,
316
- { who: "BymaxRealtimeModule" }
329
+ read.threw ? { who: "BymaxRealtimeModule", cause: read.error } : { who: "BymaxRealtimeModule" }
317
330
  );
318
331
  });
319
332
  }
@@ -585,7 +598,9 @@ var RESERVED_KEYS = [
585
598
  "name",
586
599
  "v",
587
600
  "req",
588
- "res"
601
+ "res",
602
+ "service",
603
+ "version"
589
604
  ];
590
605
  function logEvent(logger, level, event, message, fields = {}, error) {
591
606
  try {
@@ -849,9 +864,23 @@ function refuse2(detail) {
849
864
  `the authenticator returned rooms that are not valid: ${detail}. Fix the authenticator; the limits are bounds against abuse and apply to this field only.`
850
865
  );
851
866
  }
867
+ function admitRoles(roles) {
868
+ if (!Array.isArray(roles)) return roles;
869
+ try {
870
+ return Object.freeze([...roles]);
871
+ } catch (error) {
872
+ throw realtimeError(
873
+ REALTIME_ERROR_CODES.AUTH_FAILED,
874
+ "the authenticator returned roles that could not be read: a getter or a proxy on them throws",
875
+ { cause: error }
876
+ );
877
+ }
878
+ }
852
879
  function admitRooms(auth) {
880
+ const roles = admitRoles(auth.roles);
853
881
  const { rooms } = auth;
854
- if (rooms === void 0) return auth;
882
+ const kept = roles === auth.roles ? auth : { ...auth, roles };
883
+ if (rooms === void 0) return kept;
855
884
  if (!Array.isArray(rooms)) refuse2("`rooms` is not an array");
856
885
  const admitted = [];
857
886
  for (const room of rooms) {
@@ -872,7 +901,7 @@ function admitRooms(auth) {
872
901
  const reserved = reservedRoomPrefix(room);
873
902
  if (reserved !== void 0) refuse2(`a room name starts with the reserved prefix "${reserved}"`);
874
903
  }
875
- return { ...auth, rooms: Object.freeze(admitted) };
904
+ return { ...kept, rooms: Object.freeze(admitted) };
876
905
  }
877
906
 
878
907
  // src/server/utils/assert-identity.ts
@@ -880,12 +909,26 @@ function isBlank(value) {
880
909
  return typeof value !== "string" || value.trim().length === 0;
881
910
  }
882
911
  function resolveAuthTenant(options, auth) {
883
- const { tenantId: own, ...rest } = auth;
884
- const resolved = options.tenantResolver?.(
885
- own === void 0 || own === null ? { ...rest } : { ...rest, tenantId: own }
886
- ) ?? own;
887
- if (resolved === void 0 || resolved === null) return rest;
888
- return { ...rest, tenantId: resolved };
912
+ const own = auth.tenantId;
913
+ const kept = keepByName(auth);
914
+ const resolved = options.tenantResolver?.(auth) ?? own;
915
+ if (resolved instanceof Promise) resolved.catch(() => void 0);
916
+ if (resolved === void 0 || resolved === null) return kept;
917
+ return { ...kept, tenantId: resolved };
918
+ }
919
+ function keepByName(auth) {
920
+ const kept = {};
921
+ for (const key of ["userId", "roles", "rooms", "metadata"]) {
922
+ const value = auth[key];
923
+ if (value === void 0) continue;
924
+ Object.defineProperty(kept, key, {
925
+ value,
926
+ enumerable: true,
927
+ writable: true,
928
+ configurable: true
929
+ });
930
+ }
931
+ return kept;
889
932
  }
890
933
  function assertIdentityIsNotBlank(auth) {
891
934
  if (isBlank(auth.userId)) {
@@ -2779,7 +2822,7 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2779
2822
  assertModeSupported(wiring, registration.transport, moduleName);
2780
2823
  assertSseEndpoint("sseEndpoint", registration.sseEndpoint);
2781
2824
  assertSseEndpointApplies(registration, moduleName);
2782
- assertExtraProviders(registration.extraProviders);
2825
+ guardHostReads("the registration", () => assertExtraProviders(registration.extraProviders));
2783
2826
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2784
2827
  const instanceId = randomUUID();
2785
2828
  const boundSseEndpoint = registration.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.24",
3
+ "version": "1.2.26",
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",