@bymax-one/nest-realtime 1.2.3 → 1.2.5

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,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.5] - 2026-11-01
11
+
12
+ ### Added
13
+
14
+ - **`ConnectionAuthContext.remoteAddress`, the TCP peer of the connection.** It is read from the
15
+ socket (`req.socket.remoteAddress` on SSE, `handshake.address` on WebSocket), never from a header,
16
+ so a client cannot forge it. It is distinct from `ip`, which on SSE comes from `X-Forwarded-For`.
17
+ An authenticator behind a reverse proxy can check it against its trusted proxies before believing
18
+ a forwarded header such as `X-Forwarded-Host`. It is `undefined` when the socket reports no
19
+ address. `SseRequest` gains an optional `socket` for it. Nothing existing changes.
20
+
21
+ ### Internal
22
+
23
+ - The `internal` bundle budget in `pnpm size` is raised to make room for the line that reads the
24
+ peer address.
25
+
26
+ ## [1.2.4] - 2026-11-01
27
+
28
+ ### Fixed
29
+
30
+ - **A rejection that is not an `Error` no longer makes the handler reporting it fail.** Handlers
31
+ that log a failure read `.message` from whatever was thrown, so a promise that rejected with
32
+ `null` or `undefined`, or with an object that has no prototype, made the `catch` itself throw. In
33
+ a fire-and-forget `.catch` that surfaced as an unhandled rejection. They now describe the reason
34
+ through one function that never throws, and a test fails if a source file goes back to the old
35
+ patterns. The text logged for an `Error` or a string reason is unchanged; a plain object with a
36
+ string `message` now logs that message instead of `[object Object]`.
37
+
38
+ ### Documentation
39
+
40
+ - A local benchmark (`pnpm benchmark`, in `scripts/benchmark/`, not a CI gate) measures connect
41
+ latency, fan-out latency for 1, 100 and 1000 clients, cross-instance latency through Redis, memory
42
+ per idle connection and Redis connections per instance, and writes its tables as Markdown. The
43
+ first results, with the machine, versions and run-to-run noise, are in
44
+ `docs/benchmark_results_2026-10-31.md`.
45
+
10
46
  ## [1.2.3] - 2026-10-31
11
47
 
12
48
  **Apply before upgrading, if you set `websocket.redisAdapter`:** make sure `@socket.io/redis-adapter`
@@ -205,7 +241,7 @@ were routed to a tenant that differed by transport.
205
241
  **Shipped as a minor, and two entries below are strictly speaking breaking.** Both are called
206
242
  out as such rather than hidden: removing the `service` option is a compile error for anyone who
207
243
  passed it, and the new required key on `ConnectionEventMeta` is a compile error for anyone who
208
- *constructs* one. Neither changes runtime behaviour for any working configuration — `service`
244
+ _constructs_ one. Neither changes runtime behaviour for any working configuration — `service`
209
245
  was never read by anything, and reading the meta (what a hook does) is unaffected. The precedent
210
246
  is 1.1.1, which added a required `roles` key to the same type and shipped as a patch. The third
211
247
  item, the new bootstrap throw on a disagreeing SSE endpoint, replaces a silent misconfiguration
@@ -263,7 +299,7 @@ configured.
263
299
  channel, and it is the reason the field was declared in the first place.
264
300
 
265
301
  **This adds a required key** to `ConnectionEventMeta`, exactly as `roles` did in 1.1.1.
266
- Reading the meta is unaffected, which is what a hook does; code that *constructs* one
302
+ Reading the meta is unaffected, which is what a hook does; code that _constructs_ one
267
303
  (typically a test fixture) must now supply `metadata`. `undefined` stays meaningful — an
268
304
  authenticator that returns no bag is not one that returns an empty object. Like `roles`, it is
269
305
  a connect-time snapshot that `revalidate` does not refresh, and the library never reads a key.
@@ -598,7 +634,9 @@ First published release.
598
634
  rather than by the manual sweep that raised the NestJS floors — that sweep
599
635
  asked about NestJS and never put the same question to the other ten peers.
600
636
 
601
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.3...HEAD
637
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.5...HEAD
638
+ [1.2.5]: https://github.com/bymaxone/nest-realtime/compare/v1.2.4...v1.2.5
639
+ [1.2.4]: https://github.com/bymaxone/nest-realtime/compare/v1.2.3...v1.2.4
602
640
  [1.2.3]: https://github.com/bymaxone/nest-realtime/compare/v1.2.2...v1.2.3
603
641
  [1.2.2]: https://github.com/bymaxone/nest-realtime/compare/v1.2.1...v1.2.2
604
642
  [1.2.1]: https://github.com/bymaxone/nest-realtime/compare/v1.2.0...v1.2.1
package/README.md CHANGED
@@ -668,6 +668,21 @@ const hooks: IConnectionLifecycleHooks = {
668
668
  Like `roles`, it is a **connect-time snapshot**: a `revalidate` that keeps the connection alive
669
669
  does not refresh it. The library never reads a key.
670
670
 
671
+ #### Client address versus peer address
672
+
673
+ `authenticate` receives two addresses, and only one of them can be trusted on its own:
674
+
675
+ | Field | SSE | WebSocket | Forgeable by the client |
676
+ | --------------- | -------------------------------------------- | ------------------- | --------------------------- |
677
+ | `ip` | `X-Forwarded-For` first value, else `req.ip` | `handshake.address` | Yes on SSE, no on WebSocket |
678
+ | `remoteAddress` | `req.socket.remoteAddress` | `handshake.address` | No |
679
+
680
+ `remoteAddress` is the TCP peer, read from the socket and never from a header. Behind a reverse
681
+ proxy it is the proxy's address. Use it to decide whether a forwarded header such as
682
+ `X-Forwarded-Host` may be believed: read it only when `remoteAddress` is one of your proxies. It is
683
+ `undefined` when the socket reports no address, and an IPv4 peer can arrive in its IPv4-mapped form
684
+ (`::ffff:10.0.0.1`), which is passed through as reported.
685
+
671
686
  ### Rooms
672
687
 
673
688
  | Room ID | Used for | Auto-joined |
@@ -105,6 +105,18 @@ var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
105
105
  var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
106
106
  var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
107
107
  var DEFAULT_HEARTBEAT_MS = 3e4;
108
+
109
+ // src/server/utils/describe-error.ts
110
+ function describeError(reason) {
111
+ try {
112
+ const message = reason?.message;
113
+ return typeof message === "string" ? message : String(reason);
114
+ } catch {
115
+ return "unprintable error";
116
+ }
117
+ }
118
+
119
+ // src/server/offline-queue/offline-queue-delivery.service.ts
108
120
  var RETRIEVE_LIMIT = 200;
109
121
  exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
110
122
  constructor(storage) {
@@ -131,7 +143,7 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
131
143
  try {
132
144
  events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
133
145
  } catch (err) {
134
- this.logger.warn(`Offline queue retrieve failed: ${err.message}`);
146
+ this.logger.warn(`Offline queue retrieve failed: ${describeError(err)}`);
135
147
  return [];
136
148
  }
137
149
  if (events.length === RETRIEVE_LIMIT) {
@@ -158,7 +170,7 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
158
170
  try {
159
171
  await this.storage.acknowledge(userId, lastId);
160
172
  } catch (err) {
161
- this.logger.warn(`Offline queue acknowledge failed: ${err.message}`);
173
+ this.logger.warn(`Offline queue acknowledge failed: ${describeError(err)}`);
162
174
  }
163
175
  }
164
176
  };
@@ -570,7 +582,7 @@ exports.SseTransport = class SseTransport {
570
582
  ...reason !== void 0 ? { reason } : {}
571
583
  });
572
584
  } catch (error) {
573
- this.logger.error(`onDisconnect hook failed: ${error.message}`);
585
+ this.logger.error(`onDisconnect hook failed: ${describeError(error)}`);
574
586
  }
575
587
  }
576
588
  /** Replay the events a user missed after `lastEventId`. */
@@ -601,7 +613,7 @@ exports.SseTransport = class SseTransport {
601
613
  this.emitToUserLocal(userId, event, data, id);
602
614
  if (this.offlineQueue && this.connections.byUser(userId, "sse").length === 0) {
603
615
  void this.offlineQueue.append(userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }).catch(
604
- (error) => this.logger.warn(`Offline queue append failed: ${error.message}`)
616
+ (error) => this.logger.warn(`Offline queue append failed: ${describeError(error)}`)
605
617
  );
606
618
  }
607
619
  await this.publish({ op: "emitToUser", args: { userId, event, data, id } });
@@ -707,7 +719,7 @@ exports.SseTransport = class SseTransport {
707
719
  try {
708
720
  conn.subject?.next(message);
709
721
  } catch (error) {
710
- this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${error.message}`);
722
+ this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
711
723
  }
712
724
  }
713
725
  /** Publish once to the bus; pub/sub failures never affect the live emit path. */
@@ -715,7 +727,7 @@ exports.SseTransport = class SseTransport {
715
727
  try {
716
728
  await this.pubsub.publish({ ...message, origin: this.instanceId });
717
729
  } catch (error) {
718
- this.logger.warn(`pubsub.publish failed: ${error.message}`);
730
+ this.logger.warn(`pubsub.publish failed: ${describeError(error)}`);
719
731
  }
720
732
  }
721
733
  /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
@@ -777,6 +789,7 @@ function buildAuthContext(req) {
777
789
  headers,
778
790
  query: sanitizeQuery(req.query),
779
791
  ip: resolveIp(req),
792
+ remoteAddress: req.socket?.remoteAddress,
780
793
  userAgent: singleHeader(req.headers["user-agent"]),
781
794
  transport: "sse"
782
795
  };
@@ -849,7 +862,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
849
862
  try {
850
863
  assertIdentityIsNotBlank(resolvedAuth);
851
864
  } catch (err) {
852
- this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
865
+ this.logger.error(`SSE connection refused \u2014 responding 500: ${describeError(err)}`);
853
866
  throw new common.InternalServerErrorException();
854
867
  }
855
868
  return resolvedAuth;
@@ -932,9 +945,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
932
945
  return err instanceof common.HttpException ? err : this.serverError(err, what);
933
946
  }
934
947
  serverError(err, what) {
935
- this.logger.error(
936
- `${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
937
- );
948
+ this.logger.error(`${what} \u2014 responding 500: ${describeError(err)}`);
938
949
  return new common.InternalServerErrorException();
939
950
  }
940
951
  async authenticateRequest(req) {
@@ -1031,7 +1042,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1031
1042
  */
1032
1043
  fireHook(invoke) {
1033
1044
  void Promise.resolve(invoke()).catch((err) => {
1034
- this.logger.warn(`Lifecycle hook failed: ${err.message}`);
1045
+ this.logger.warn(`Lifecycle hook failed: ${describeError(err)}`);
1035
1046
  });
1036
1047
  }
1037
1048
  };
@@ -1265,9 +1276,7 @@ exports.ReauthenticationService = class ReauthenticationService {
1265
1276
  }
1266
1277
  await this.handleFailure(conn);
1267
1278
  } catch (err) {
1268
- this.logger.warn(
1269
- `Reauthentication errored for ${conn.connectionId}: ${err.message}`
1270
- );
1279
+ this.logger.warn(`Reauthentication errored for ${conn.connectionId}: ${describeError(err)}`);
1271
1280
  await this.handleFailure(conn);
1272
1281
  }
1273
1282
  }
@@ -1293,7 +1302,7 @@ exports.ReauthenticationService = class ReauthenticationService {
1293
1302
  connectedAt: conn.connectedAt
1294
1303
  })
1295
1304
  ).catch((err) => {
1296
- this.logger.warn(`onReauthenticationFailed hook failed: ${err.message}`);
1305
+ this.logger.warn(`onReauthenticationFailed hook failed: ${describeError(err)}`);
1297
1306
  });
1298
1307
  await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
1299
1308
  }
@@ -1488,7 +1497,7 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
1488
1497
  this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1489
1498
  } catch (err) {
1490
1499
  this.logger.warn(
1491
- `Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1500
+ `Failed to subscribe to pub/sub: ${describeError(err)}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1492
1501
  );
1493
1502
  }
1494
1503
  }
@@ -1497,7 +1506,7 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
1497
1506
  try {
1498
1507
  await this.unsubscribe();
1499
1508
  } catch (err) {
1500
- this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
1509
+ this.logger.warn(`Pub/sub unsubscribe failed: ${describeError(err)}`);
1501
1510
  }
1502
1511
  this.unsubscribe = null;
1503
1512
  }
@@ -1537,7 +1546,7 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
1537
1546
  }
1538
1547
  }
1539
1548
  } catch (err) {
1540
- this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
1549
+ this.logger.warn(`Pub/sub message handling failed: ${describeError(err)}`);
1541
1550
  }
1542
1551
  }
1543
1552
  };
@@ -1822,6 +1831,7 @@ exports.composeForRoot = composeForRoot;
1822
1831
  exports.composeForRootAsync = composeForRootAsync;
1823
1832
  exports.composeRoomId = composeRoomId;
1824
1833
  exports.createSseController = createSseController;
1834
+ exports.describeError = describeError;
1825
1835
  exports.parseCookieHeader = parseCookieHeader;
1826
1836
  exports.resolveAuthTenant = resolveAuthTenant;
1827
1837
  exports.sseWiring = sseWiring;
@@ -59,6 +59,18 @@ interface ConnectionAuthContext {
59
59
  * without validating the proxy chain.
60
60
  */
61
61
  readonly ip: string;
62
+ /**
63
+ * The TCP peer address of the connection: the socket's own `remoteAddress`, never read
64
+ * from a header, so a client cannot forge it. It is the proxy's address when one sits
65
+ * in front of the application, and it is distinct from `ip`, which on SSE comes from
66
+ * `X-Forwarded-For`. Use it to decide whether a forwarded header such as
67
+ * `X-Forwarded-Host` may be believed, by checking it against the proxies you trust.
68
+ *
69
+ * `undefined` when the socket reports no address. A peer on IPv4 can arrive in its
70
+ * IPv4-mapped IPv6 form (`::ffff:10.0.0.1`); the value is passed through as the socket
71
+ * reports it.
72
+ */
73
+ readonly remoteAddress?: string | undefined;
62
74
  /** Raw User-Agent. */
63
75
  readonly userAgent: string | undefined;
64
76
  /** Transport kind initiating the connection. */
@@ -1014,6 +1026,14 @@ interface SseRequest {
1014
1026
  readonly headers: Readonly<Record<string, SseHeaderValue>>;
1015
1027
  /** Remote address as the HTTP framework resolved it, when it resolves one. */
1016
1028
  readonly ip?: string | undefined;
1029
+ /**
1030
+ * The underlying connection, when the framework exposes it (Express and Fastify do as
1031
+ * `req.socket`). Its `remoteAddress` is the TCP peer, unlike `ip`, which a trusted-proxy
1032
+ * setting can derive from a header.
1033
+ */
1034
+ readonly socket?: {
1035
+ readonly remoteAddress?: string | undefined;
1036
+ } | undefined;
1017
1037
  /** Parsed query string. Values are narrowed to strings by the caller. */
1018
1038
  readonly query: Readonly<Record<string, unknown>>;
1019
1039
  }
@@ -1549,6 +1569,13 @@ type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
1549
1569
  */
1550
1570
  declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: string[]): string;
1551
1571
 
1572
+ /**
1573
+ * @fileoverview Printable text for whatever a `catch` or a rejected promise delivered.
1574
+ * @layer utils
1575
+ */
1576
+ /** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
1577
+ declare function describeError(reason: unknown): string;
1578
+
1552
1579
  /**
1553
1580
  * @fileoverview Parser turning a raw HTTP `Cookie` header into a plain object.
1554
1581
  * @layer utils
@@ -1670,4 +1697,4 @@ declare const REALTIME_ERROR_CODES: {
1670
1697
  /** Union of canonical error code values. */
1671
1698
  type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
1672
1699
 
1673
- export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
1700
+ export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, resolveAuthTenant, sseWiring };
@@ -59,6 +59,18 @@ interface ConnectionAuthContext {
59
59
  * without validating the proxy chain.
60
60
  */
61
61
  readonly ip: string;
62
+ /**
63
+ * The TCP peer address of the connection: the socket's own `remoteAddress`, never read
64
+ * from a header, so a client cannot forge it. It is the proxy's address when one sits
65
+ * in front of the application, and it is distinct from `ip`, which on SSE comes from
66
+ * `X-Forwarded-For`. Use it to decide whether a forwarded header such as
67
+ * `X-Forwarded-Host` may be believed, by checking it against the proxies you trust.
68
+ *
69
+ * `undefined` when the socket reports no address. A peer on IPv4 can arrive in its
70
+ * IPv4-mapped IPv6 form (`::ffff:10.0.0.1`); the value is passed through as the socket
71
+ * reports it.
72
+ */
73
+ readonly remoteAddress?: string | undefined;
62
74
  /** Raw User-Agent. */
63
75
  readonly userAgent: string | undefined;
64
76
  /** Transport kind initiating the connection. */
@@ -1014,6 +1026,14 @@ interface SseRequest {
1014
1026
  readonly headers: Readonly<Record<string, SseHeaderValue>>;
1015
1027
  /** Remote address as the HTTP framework resolved it, when it resolves one. */
1016
1028
  readonly ip?: string | undefined;
1029
+ /**
1030
+ * The underlying connection, when the framework exposes it (Express and Fastify do as
1031
+ * `req.socket`). Its `remoteAddress` is the TCP peer, unlike `ip`, which a trusted-proxy
1032
+ * setting can derive from a header.
1033
+ */
1034
+ readonly socket?: {
1035
+ readonly remoteAddress?: string | undefined;
1036
+ } | undefined;
1017
1037
  /** Parsed query string. Values are narrowed to strings by the caller. */
1018
1038
  readonly query: Readonly<Record<string, unknown>>;
1019
1039
  }
@@ -1549,6 +1569,13 @@ type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
1549
1569
  */
1550
1570
  declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: string[]): string;
1551
1571
 
1572
+ /**
1573
+ * @fileoverview Printable text for whatever a `catch` or a rejected promise delivered.
1574
+ * @layer utils
1575
+ */
1576
+ /** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
1577
+ declare function describeError(reason: unknown): string;
1578
+
1552
1579
  /**
1553
1580
  * @fileoverview Parser turning a raw HTTP `Cookie` header into a plain object.
1554
1581
  * @layer utils
@@ -1670,4 +1697,4 @@ declare const REALTIME_ERROR_CODES: {
1670
1697
  /** Union of canonical error code values. */
1671
1698
  type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
1672
1699
 
1673
- export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
1700
+ export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, resolveAuthTenant, sseWiring };
@@ -103,6 +103,18 @@ var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
103
103
  var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
104
104
  var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
105
105
  var DEFAULT_HEARTBEAT_MS = 3e4;
106
+
107
+ // src/server/utils/describe-error.ts
108
+ function describeError(reason) {
109
+ try {
110
+ const message = reason?.message;
111
+ return typeof message === "string" ? message : String(reason);
112
+ } catch {
113
+ return "unprintable error";
114
+ }
115
+ }
116
+
117
+ // src/server/offline-queue/offline-queue-delivery.service.ts
106
118
  var RETRIEVE_LIMIT = 200;
107
119
  var OfflineQueueDeliveryService = class {
108
120
  constructor(storage) {
@@ -129,7 +141,7 @@ var OfflineQueueDeliveryService = class {
129
141
  try {
130
142
  events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
131
143
  } catch (err) {
132
- this.logger.warn(`Offline queue retrieve failed: ${err.message}`);
144
+ this.logger.warn(`Offline queue retrieve failed: ${describeError(err)}`);
133
145
  return [];
134
146
  }
135
147
  if (events.length === RETRIEVE_LIMIT) {
@@ -156,7 +168,7 @@ var OfflineQueueDeliveryService = class {
156
168
  try {
157
169
  await this.storage.acknowledge(userId, lastId);
158
170
  } catch (err) {
159
- this.logger.warn(`Offline queue acknowledge failed: ${err.message}`);
171
+ this.logger.warn(`Offline queue acknowledge failed: ${describeError(err)}`);
160
172
  }
161
173
  }
162
174
  };
@@ -568,7 +580,7 @@ var SseTransport = class {
568
580
  ...reason !== void 0 ? { reason } : {}
569
581
  });
570
582
  } catch (error) {
571
- this.logger.error(`onDisconnect hook failed: ${error.message}`);
583
+ this.logger.error(`onDisconnect hook failed: ${describeError(error)}`);
572
584
  }
573
585
  }
574
586
  /** Replay the events a user missed after `lastEventId`. */
@@ -599,7 +611,7 @@ var SseTransport = class {
599
611
  this.emitToUserLocal(userId, event, data, id);
600
612
  if (this.offlineQueue && this.connections.byUser(userId, "sse").length === 0) {
601
613
  void this.offlineQueue.append(userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }).catch(
602
- (error) => this.logger.warn(`Offline queue append failed: ${error.message}`)
614
+ (error) => this.logger.warn(`Offline queue append failed: ${describeError(error)}`)
603
615
  );
604
616
  }
605
617
  await this.publish({ op: "emitToUser", args: { userId, event, data, id } });
@@ -705,7 +717,7 @@ var SseTransport = class {
705
717
  try {
706
718
  conn.subject?.next(message);
707
719
  } catch (error) {
708
- this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${error.message}`);
720
+ this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
709
721
  }
710
722
  }
711
723
  /** Publish once to the bus; pub/sub failures never affect the live emit path. */
@@ -713,7 +725,7 @@ var SseTransport = class {
713
725
  try {
714
726
  await this.pubsub.publish({ ...message, origin: this.instanceId });
715
727
  } catch (error) {
716
- this.logger.warn(`pubsub.publish failed: ${error.message}`);
728
+ this.logger.warn(`pubsub.publish failed: ${describeError(error)}`);
717
729
  }
718
730
  }
719
731
  /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
@@ -775,6 +787,7 @@ function buildAuthContext(req) {
775
787
  headers,
776
788
  query: sanitizeQuery(req.query),
777
789
  ip: resolveIp(req),
790
+ remoteAddress: req.socket?.remoteAddress,
778
791
  userAgent: singleHeader(req.headers["user-agent"]),
779
792
  transport: "sse"
780
793
  };
@@ -847,7 +860,7 @@ var SseSubscriptionHandler = class {
847
860
  try {
848
861
  assertIdentityIsNotBlank(resolvedAuth);
849
862
  } catch (err) {
850
- this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
863
+ this.logger.error(`SSE connection refused \u2014 responding 500: ${describeError(err)}`);
851
864
  throw new InternalServerErrorException();
852
865
  }
853
866
  return resolvedAuth;
@@ -930,9 +943,7 @@ var SseSubscriptionHandler = class {
930
943
  return err instanceof HttpException ? err : this.serverError(err, what);
931
944
  }
932
945
  serverError(err, what) {
933
- this.logger.error(
934
- `${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
935
- );
946
+ this.logger.error(`${what} \u2014 responding 500: ${describeError(err)}`);
936
947
  return new InternalServerErrorException();
937
948
  }
938
949
  async authenticateRequest(req) {
@@ -1029,7 +1040,7 @@ var SseSubscriptionHandler = class {
1029
1040
  */
1030
1041
  fireHook(invoke) {
1031
1042
  void Promise.resolve(invoke()).catch((err) => {
1032
- this.logger.warn(`Lifecycle hook failed: ${err.message}`);
1043
+ this.logger.warn(`Lifecycle hook failed: ${describeError(err)}`);
1033
1044
  });
1034
1045
  }
1035
1046
  };
@@ -1263,9 +1274,7 @@ var ReauthenticationService = class {
1263
1274
  }
1264
1275
  await this.handleFailure(conn);
1265
1276
  } catch (err) {
1266
- this.logger.warn(
1267
- `Reauthentication errored for ${conn.connectionId}: ${err.message}`
1268
- );
1277
+ this.logger.warn(`Reauthentication errored for ${conn.connectionId}: ${describeError(err)}`);
1269
1278
  await this.handleFailure(conn);
1270
1279
  }
1271
1280
  }
@@ -1291,7 +1300,7 @@ var ReauthenticationService = class {
1291
1300
  connectedAt: conn.connectedAt
1292
1301
  })
1293
1302
  ).catch((err) => {
1294
- this.logger.warn(`onReauthenticationFailed hook failed: ${err.message}`);
1303
+ this.logger.warn(`onReauthenticationFailed hook failed: ${describeError(err)}`);
1295
1304
  });
1296
1305
  await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
1297
1306
  }
@@ -1486,7 +1495,7 @@ var RealtimePubSubSubscriber = class {
1486
1495
  this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1487
1496
  } catch (err) {
1488
1497
  this.logger.warn(
1489
- `Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1498
+ `Failed to subscribe to pub/sub: ${describeError(err)}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1490
1499
  );
1491
1500
  }
1492
1501
  }
@@ -1495,7 +1504,7 @@ var RealtimePubSubSubscriber = class {
1495
1504
  try {
1496
1505
  await this.unsubscribe();
1497
1506
  } catch (err) {
1498
- this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
1507
+ this.logger.warn(`Pub/sub unsubscribe failed: ${describeError(err)}`);
1499
1508
  }
1500
1509
  this.unsubscribe = null;
1501
1510
  }
@@ -1535,7 +1544,7 @@ var RealtimePubSubSubscriber = class {
1535
1544
  }
1536
1545
  }
1537
1546
  } catch (err) {
1538
- this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
1547
+ this.logger.warn(`Pub/sub message handling failed: ${describeError(err)}`);
1539
1548
  }
1540
1549
  }
1541
1550
  };
@@ -1802,4 +1811,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1802
1811
  }
1803
1812
  };
1804
1813
 
1805
- export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
1814
+ export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, resolveAuthTenant, sseWiring };
@@ -381,9 +381,7 @@ exports.CompositeTransport = class CompositeTransport {
381
381
  const results = await Promise.allSettled(tasks.map((t) => t()));
382
382
  for (const result of results) {
383
383
  if (result.status === "rejected") {
384
- this.logger.warn(
385
- `Composite ${op} partially failed: ${result.reason.message ?? result.reason}`
386
- );
384
+ this.logger.warn(`Composite ${op} partially failed: ${internal.describeError(result.reason)}`);
387
385
  }
388
386
  }
389
387
  }
@@ -464,7 +462,7 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
464
462
  const sub = pub.duplicate();
465
463
  server.adapter(createAdapter(pub, sub));
466
464
  } catch (err) {
467
- const reason = err instanceof Error ? err.message : String(err);
465
+ const reason = internal.describeError(err);
468
466
  throw new Error(
469
467
  `[${_RealtimeIoAdapter.name}] ${internal.REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED}: websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed (${reason}). Install @socket.io/redis-adapter and pass an ioredis client as pubClient.`,
470
468
  { cause: err }
@@ -506,9 +504,7 @@ exports.RealtimeGateway = class RealtimeGateway {
506
504
  this.authenticated.set(socket, resolvedAuth);
507
505
  next();
508
506
  } catch (err) {
509
- this.logger.error(
510
- `handshake refused for socket ${socket.id}: ${err instanceof Error ? err.message : String(err)}`
511
- );
507
+ this.logger.error(`handshake refused for socket ${socket.id}: ${internal.describeError(err)}`);
512
508
  next(new Error("Internal Server Error"));
513
509
  }
514
510
  };
@@ -572,6 +568,7 @@ exports.RealtimeGateway = class RealtimeGateway {
572
568
  headers,
573
569
  query,
574
570
  ip: handshake.address,
571
+ remoteAddress: handshake.address,
575
572
  userAgent: handshake.headers["user-agent"],
576
573
  transport: "websocket"
577
574
  };
@@ -602,7 +599,7 @@ exports.RealtimeGateway = class RealtimeGateway {
602
599
  }
603
600
  } catch (err) {
604
601
  this.logger.error(
605
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err instanceof Error ? err.message : String(err)}`
602
+ `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${internal.describeError(err)}`
606
603
  );
607
604
  socket.disconnect(true);
608
605
  }
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
3
- import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES, REALTIME_ERROR_CODES, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
3
+ import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES, REALTIME_ERROR_CODES, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, describeError, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
4
4
  import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
5
5
  import { IoAdapter } from '@nestjs/platform-socket.io';
6
6
 
@@ -381,9 +381,7 @@ var CompositeTransport = class {
381
381
  const results = await Promise.allSettled(tasks.map((t) => t()));
382
382
  for (const result of results) {
383
383
  if (result.status === "rejected") {
384
- this.logger.warn(
385
- `Composite ${op} partially failed: ${result.reason.message ?? result.reason}`
386
- );
384
+ this.logger.warn(`Composite ${op} partially failed: ${describeError(result.reason)}`);
387
385
  }
388
386
  }
389
387
  }
@@ -464,7 +462,7 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
464
462
  const sub = pub.duplicate();
465
463
  server.adapter(createAdapter(pub, sub));
466
464
  } catch (err) {
467
- const reason = err instanceof Error ? err.message : String(err);
465
+ const reason = describeError(err);
468
466
  throw new Error(
469
467
  `[${_RealtimeIoAdapter.name}] ${REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED}: websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed (${reason}). Install @socket.io/redis-adapter and pass an ioredis client as pubClient.`,
470
468
  { cause: err }
@@ -506,9 +504,7 @@ var RealtimeGateway = class {
506
504
  this.authenticated.set(socket, resolvedAuth);
507
505
  next();
508
506
  } catch (err) {
509
- this.logger.error(
510
- `handshake refused for socket ${socket.id}: ${err instanceof Error ? err.message : String(err)}`
511
- );
507
+ this.logger.error(`handshake refused for socket ${socket.id}: ${describeError(err)}`);
512
508
  next(new Error("Internal Server Error"));
513
509
  }
514
510
  };
@@ -572,6 +568,7 @@ var RealtimeGateway = class {
572
568
  headers,
573
569
  query,
574
570
  ip: handshake.address,
571
+ remoteAddress: handshake.address,
575
572
  userAgent: handshake.headers["user-agent"],
576
573
  transport: "websocket"
577
574
  };
@@ -602,7 +599,7 @@ var RealtimeGateway = class {
602
599
  }
603
600
  } catch (err) {
604
601
  this.logger.error(
605
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err instanceof Error ? err.message : String(err)}`
602
+ `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${describeError(err)}`
606
603
  );
607
604
  socket.disconnect(true);
608
605
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.3",
3
+ "version": "1.2.5",
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",
@@ -98,6 +98,7 @@
98
98
  "check:mutants": "node scripts/check-mutation-directives.mjs",
99
99
  "check:published": "node scripts/check-published-surface.mjs",
100
100
  "check:runtime": "node scripts/check-consumer-runtime.mjs",
101
+ "benchmark": "node scripts/benchmark/run.mjs",
101
102
  "check:surface": "node scripts/check-public-surface.mjs",
102
103
  "clean": "rm -rf dist coverage",
103
104
  "lint": "eslint src",