@bymax-one/nest-realtime 1.2.4 → 1.2.6

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,67 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.6] - 2026-11-01
11
+
12
+ ### Fixed
13
+
14
+ - **The SSE client address no longer comes from the leftmost `X-Forwarded-For` entry.** The
15
+ connection context's `ip` and the `ip` the hooks receive were the first raw entry of that header,
16
+ which the client writes, with no check that it was an address and no regard for the application's
17
+ `trust proxy` setting: with `trust proxy` set to `'loopback'` and the header `6.6.6.6, 203.0.113.9`,
18
+ Express reported `203.0.113.9` and the library reported `6.6.6.6`. On SSE `ip` is now the address `trust proxy` produced (`req.ip`, else an address from `req.ips`, else the socket
19
+ peer), `''` when no channel carries an address, and a header text that is not an address is never
20
+ returned. WebSocket is unchanged: it reads the handshake's peer address. `SseRequest` gains an
21
+ optional `ips`.
22
+
23
+ #### Apply to a derived backend
24
+
25
+ A hook or an authenticator that reads `ip` on SSE may now see a different value, and the new one is
26
+ the correct one: the address your `trust proxy` setting vouches for. Behind a reverse proxy, set
27
+ `trust proxy` on the application (for example `app.set('trust proxy', 'loopback')`), or `ip` is the
28
+ proxy's address, as it already was on WebSocket. An application that never set it sees the socket
29
+ peer where it used to see whatever the client put in the header. `ip` is `''` where it used to be
30
+ `'unknown'` when nothing carries an address. Compare against `remoteAddress` to tell the proxy from
31
+ the client.
32
+
33
+ ### Tests
34
+
35
+ - **The README Quick Start is executed, not only type-checked.** Specs take the Quick Start
36
+ blocks from the README text, compile them and run them against a real Nest application over HTTP,
37
+ a real Socket.IO handshake and jsdom. A wrong option shape, a route that is never mounted, a missing `eventNames` entry or a
38
+ `main.ts` without the adapter now fails a test instead of reaching a reader. No source or
39
+ published-surface change, so there is nothing to apply.
40
+
41
+ ### Internal
42
+
43
+ - The Release workflow takes the GitHub Release notes from the tag's CHANGELOG section before the
44
+ gates run, matching the heading literally, and fails the release when the section is missing or
45
+ blank instead of falling back to a pointer. The notes reach `gh release create` through a file.
46
+ - `pnpm check:api` compares the built `.d.ts` and `.d.cts` files, comments ignored, with the previous
47
+ published version, and the Release workflow runs it before the publish. It always prints what
48
+ differs. A difference passes only when the CHANGELOG section of the version being released holds
49
+ an "Apply to a derived backend" note (or the older "Apply to a consumer"). There is no override.
50
+ - A workflow runs the same check in a pull request that changes `package.json` and moves the version,
51
+ so a release that changes the declarations without the note fails before the tag. A pull request
52
+ that leaves the version alone skips it.
53
+ - The `internal` bundle budget in `pnpm size` is raised to fit the client-address validation.
54
+
55
+ ## [1.2.5] - 2026-11-01
56
+
57
+ ### Added
58
+
59
+ - **`ConnectionAuthContext.remoteAddress`, the TCP peer of the connection.** It is read from the
60
+ socket (`req.socket.remoteAddress` on SSE, `handshake.address` on WebSocket), never from a header,
61
+ so a client cannot forge it. It is distinct from `ip`, which on SSE comes from `X-Forwarded-For`.
62
+ An authenticator behind a reverse proxy can check it against its trusted proxies before believing
63
+ a forwarded header such as `X-Forwarded-Host`. It is `undefined` when the socket reports no
64
+ address. `SseRequest` gains an optional `socket` for it. Nothing existing changes.
65
+
66
+ ### Internal
67
+
68
+ - The `internal` bundle budget in `pnpm size` is raised to make room for the line that reads the
69
+ peer address.
70
+
10
71
  ## [1.2.4] - 2026-11-01
11
72
 
12
73
  ### Fixed
@@ -618,7 +679,9 @@ First published release.
618
679
  rather than by the manual sweep that raised the NestJS floors — that sweep
619
680
  asked about NestJS and never put the same question to the other ten peers.
620
681
 
621
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.4...HEAD
682
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.6...HEAD
683
+ [1.2.6]: https://github.com/bymaxone/nest-realtime/compare/v1.2.5...v1.2.6
684
+ [1.2.5]: https://github.com/bymaxone/nest-realtime/compare/v1.2.4...v1.2.5
622
685
  [1.2.4]: https://github.com/bymaxone/nest-realtime/compare/v1.2.3...v1.2.4
623
686
  [1.2.3]: https://github.com/bymaxone/nest-realtime/compare/v1.2.2...v1.2.3
624
687
  [1.2.2]: https://github.com/bymaxone/nest-realtime/compare/v1.2.1...v1.2.2
package/README.md CHANGED
@@ -668,6 +668,25 @@ 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. On SSE `ip` is the address your application's
674
+ `trust proxy` setting produced, validated: `X-Forwarded-For` is never read directly, a header text
675
+ that is not an address is never returned, and `ip` is `''` when no channel carries an address.
676
+ Without `trust proxy` it is the peer. Only `remoteAddress` can be trusted without knowing that
677
+ setting:
678
+
679
+ | Field | SSE | WebSocket | Forgeable by the client |
680
+ | --------------- | ----------------------------------------------------- | ------------------- | ------------------------------------------------- |
681
+ | `ip` | `req.ip`, which follows the app's `trust proxy` value | `handshake.address` | Only as far as `trust proxy` believes the header |
682
+ | `remoteAddress` | `req.socket.remoteAddress` | `handshake.address` | No |
683
+
684
+ `remoteAddress` is the TCP peer, read from the socket and never from a header. Behind a reverse
685
+ proxy it is the proxy's address. Use it to decide whether a forwarded header such as
686
+ `X-Forwarded-Host` may be believed: read it only when `remoteAddress` is one of your proxies. It is
687
+ `undefined` when the socket reports no address, and an IPv4 peer can arrive in its IPv4-mapped form
688
+ (`::ffff:10.0.0.1`), which is passed through as reported.
689
+
671
690
  ### Rooms
672
691
 
673
692
  | Room ID | Used for | Auto-joined |
@@ -4,6 +4,7 @@ var crypto = require('crypto');
4
4
  var common = require('@nestjs/common');
5
5
  var rxjs = require('rxjs');
6
6
  var operators = require('rxjs/operators');
7
+ var net = require('net');
7
8
 
8
9
  var __defProp = Object.defineProperty;
9
10
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -228,6 +229,25 @@ function parseCookieHeader(cookieHeader) {
228
229
  }
229
230
  return out;
230
231
  }
232
+ var IPV6 = 6;
233
+ function isHeaderAddress(candidate) {
234
+ return typeof candidate === "string" && !candidate.includes("%") && net.isIP(candidate) !== 0;
235
+ }
236
+ function peerAddress(remoteAddress) {
237
+ if (typeof remoteAddress !== "string") return "";
238
+ const zoneIndex = remoteAddress.indexOf("%");
239
+ const bare = zoneIndex === -1 ? remoteAddress : remoteAddress.slice(0, zoneIndex);
240
+ const family = net.isIP(bare);
241
+ if (zoneIndex !== -1) return family === IPV6 ? bare : "";
242
+ return family === 0 ? "" : bare;
243
+ }
244
+ function resolveClientAddress(request) {
245
+ const hops = request.ips ?? [];
246
+ for (const candidate of [request.ip, ...hops]) {
247
+ if (isHeaderAddress(candidate)) return candidate;
248
+ }
249
+ return peerAddress(request.socket?.remoteAddress);
250
+ }
231
251
  exports.ConnectionRegistry = class ConnectionRegistry {
232
252
  byId = /* @__PURE__ */ new Map();
233
253
  byUserId = /* @__PURE__ */ new Map();
@@ -762,11 +782,6 @@ exports.SseTransport = __decorateClass([
762
782
  function singleHeader(value) {
763
783
  return typeof value === "string" ? value : void 0;
764
784
  }
765
- function resolveIp(req) {
766
- const forwarded = req.headers["x-forwarded-for"];
767
- const candidate = (typeof forwarded === "string" ? forwarded.split(",")[0] : void 0) ?? "";
768
- return candidate.trim() || req.ip || "unknown";
769
- }
770
785
  function normalizeHeaders(headers) {
771
786
  const out = /* @__PURE__ */ Object.create(null);
772
787
  for (const [key, value] of Object.entries(headers)) {
@@ -788,7 +803,8 @@ function buildAuthContext(req) {
788
803
  cookies: parseCookieHeader(singleHeader(req.headers["cookie"]) ?? ""),
789
804
  headers,
790
805
  query: sanitizeQuery(req.query),
791
- ip: resolveIp(req),
806
+ ip: resolveClientAddress(req),
807
+ remoteAddress: req.socket?.remoteAddress,
792
808
  userAgent: singleHeader(req.headers["user-agent"]),
793
809
  transport: "sse"
794
810
  };
@@ -54,11 +54,25 @@ interface ConnectionAuthContext {
54
54
  */
55
55
  readonly query: Record<string, string | string[] | undefined>;
56
56
  /**
57
- * Client IP — best-effort. Derived from `X-Forwarded-For` when present, which is
58
- * spoofable unless set by a trusted proxy; do not use it for security decisions
59
- * without validating the proxy chain.
57
+ * Client IP. On SSE it is the address the application's `trust proxy` setting produced
58
+ * (`req.ip`, else the nearest trusted hop, else the socket peer), so `X-Forwarded-For` is
59
+ * believed only as far as that setting reaches and is never read directly. On WebSocket
60
+ * it is the handshake's peer address, which behind a proxy is the proxy's. `''` when no
61
+ * channel carries an address; a header text that is not an address is never returned.
60
62
  */
61
63
  readonly ip: string;
64
+ /**
65
+ * The TCP peer address of the connection: the socket's own `remoteAddress`, never read
66
+ * from a header, so a client cannot forge it. It is the proxy's address when one sits
67
+ * in front of the application, and it is distinct from `ip`, which on SSE follows the
68
+ * application's `trust proxy` setting. Use it to decide whether a forwarded header such as
69
+ * `X-Forwarded-Host` may be believed, by checking it against the proxies you trust.
70
+ *
71
+ * `undefined` when the socket reports no address. A peer on IPv4 can arrive in its
72
+ * IPv4-mapped IPv6 form (`::ffff:10.0.0.1`); the value is passed through as the socket
73
+ * reports it.
74
+ */
75
+ readonly remoteAddress?: string | undefined;
62
76
  /** Raw User-Agent. */
63
77
  readonly userAgent: string | undefined;
64
78
  /** Transport kind initiating the connection. */
@@ -1007,13 +1021,30 @@ interface SseRequest {
1007
1021
  /**
1008
1022
  * Request headers, keyed as the HTTP framework delivers them. Node lowercases
1009
1023
  * incoming header names, and the endpoint looks them up lowercase — `cookie`,
1010
- * `user-agent`, `x-forwarded-for` and `last-event-id` — so an adapter that
1024
+ * `user-agent` and `last-event-id` — so an adapter that
1011
1025
  * preserves the client's casing has to lowercase the keys before it gets here,
1012
1026
  * or those lookups miss.
1013
1027
  */
1014
1028
  readonly headers: Readonly<Record<string, SseHeaderValue>>;
1015
- /** Remote address as the HTTP framework resolved it, when it resolves one. */
1029
+ /**
1030
+ * Client address as the HTTP framework resolved it under the application's trusted-proxy
1031
+ * setting, when it resolves one. The endpoint validates it before using it.
1032
+ */
1016
1033
  readonly ip?: string | undefined;
1034
+ /**
1035
+ * The addresses behind `ip`, from the client end toward the socket, when the framework reports
1036
+ * them (Express and Fastify do under a trusted-proxy setting). Each entry after the first is a
1037
+ * hop that setting already vouched for.
1038
+ */
1039
+ readonly ips?: readonly string[] | undefined;
1040
+ /**
1041
+ * The underlying connection, when the framework exposes it (Express and Fastify do as
1042
+ * `req.socket`). Its `remoteAddress` is the TCP peer, unlike `ip`, which a trusted-proxy
1043
+ * setting can derive from a header.
1044
+ */
1045
+ readonly socket?: {
1046
+ readonly remoteAddress?: string | undefined;
1047
+ } | undefined;
1017
1048
  /** Parsed query string. Values are narrowed to strings by the caller. */
1018
1049
  readonly query: Readonly<Record<string, unknown>>;
1019
1050
  }
@@ -54,11 +54,25 @@ interface ConnectionAuthContext {
54
54
  */
55
55
  readonly query: Record<string, string | string[] | undefined>;
56
56
  /**
57
- * Client IP — best-effort. Derived from `X-Forwarded-For` when present, which is
58
- * spoofable unless set by a trusted proxy; do not use it for security decisions
59
- * without validating the proxy chain.
57
+ * Client IP. On SSE it is the address the application's `trust proxy` setting produced
58
+ * (`req.ip`, else the nearest trusted hop, else the socket peer), so `X-Forwarded-For` is
59
+ * believed only as far as that setting reaches and is never read directly. On WebSocket
60
+ * it is the handshake's peer address, which behind a proxy is the proxy's. `''` when no
61
+ * channel carries an address; a header text that is not an address is never returned.
60
62
  */
61
63
  readonly ip: string;
64
+ /**
65
+ * The TCP peer address of the connection: the socket's own `remoteAddress`, never read
66
+ * from a header, so a client cannot forge it. It is the proxy's address when one sits
67
+ * in front of the application, and it is distinct from `ip`, which on SSE follows the
68
+ * application's `trust proxy` setting. Use it to decide whether a forwarded header such as
69
+ * `X-Forwarded-Host` may be believed, by checking it against the proxies you trust.
70
+ *
71
+ * `undefined` when the socket reports no address. A peer on IPv4 can arrive in its
72
+ * IPv4-mapped IPv6 form (`::ffff:10.0.0.1`); the value is passed through as the socket
73
+ * reports it.
74
+ */
75
+ readonly remoteAddress?: string | undefined;
62
76
  /** Raw User-Agent. */
63
77
  readonly userAgent: string | undefined;
64
78
  /** Transport kind initiating the connection. */
@@ -1007,13 +1021,30 @@ interface SseRequest {
1007
1021
  /**
1008
1022
  * Request headers, keyed as the HTTP framework delivers them. Node lowercases
1009
1023
  * incoming header names, and the endpoint looks them up lowercase — `cookie`,
1010
- * `user-agent`, `x-forwarded-for` and `last-event-id` — so an adapter that
1024
+ * `user-agent` and `last-event-id` — so an adapter that
1011
1025
  * preserves the client's casing has to lowercase the keys before it gets here,
1012
1026
  * or those lookups miss.
1013
1027
  */
1014
1028
  readonly headers: Readonly<Record<string, SseHeaderValue>>;
1015
- /** Remote address as the HTTP framework resolved it, when it resolves one. */
1029
+ /**
1030
+ * Client address as the HTTP framework resolved it under the application's trusted-proxy
1031
+ * setting, when it resolves one. The endpoint validates it before using it.
1032
+ */
1016
1033
  readonly ip?: string | undefined;
1034
+ /**
1035
+ * The addresses behind `ip`, from the client end toward the socket, when the framework reports
1036
+ * them (Express and Fastify do under a trusted-proxy setting). Each entry after the first is a
1037
+ * hop that setting already vouched for.
1038
+ */
1039
+ readonly ips?: readonly string[] | undefined;
1040
+ /**
1041
+ * The underlying connection, when the framework exposes it (Express and Fastify do as
1042
+ * `req.socket`). Its `remoteAddress` is the TCP peer, unlike `ip`, which a trusted-proxy
1043
+ * setting can derive from a header.
1044
+ */
1045
+ readonly socket?: {
1046
+ readonly remoteAddress?: string | undefined;
1047
+ } | undefined;
1017
1048
  /** Parsed query string. Values are narrowed to strings by the caller. */
1018
1049
  readonly query: Readonly<Record<string, unknown>>;
1019
1050
  }
@@ -2,6 +2,7 @@ import { randomUUID } from 'crypto';
2
2
  import { Injectable, Optional, Inject, Logger, Global, Module, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, HttpException, UnauthorizedException } from '@nestjs/common';
3
3
  import { Subject, of, EMPTY, Observable, merge } from 'rxjs';
4
4
  import { takeUntil, catchError, finalize } from 'rxjs/operators';
5
+ import { isIP } from 'net';
5
6
 
6
7
  var __defProp = Object.defineProperty;
7
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -226,6 +227,25 @@ function parseCookieHeader(cookieHeader) {
226
227
  }
227
228
  return out;
228
229
  }
230
+ var IPV6 = 6;
231
+ function isHeaderAddress(candidate) {
232
+ return typeof candidate === "string" && !candidate.includes("%") && isIP(candidate) !== 0;
233
+ }
234
+ function peerAddress(remoteAddress) {
235
+ if (typeof remoteAddress !== "string") return "";
236
+ const zoneIndex = remoteAddress.indexOf("%");
237
+ const bare = zoneIndex === -1 ? remoteAddress : remoteAddress.slice(0, zoneIndex);
238
+ const family = isIP(bare);
239
+ if (zoneIndex !== -1) return family === IPV6 ? bare : "";
240
+ return family === 0 ? "" : bare;
241
+ }
242
+ function resolveClientAddress(request) {
243
+ const hops = request.ips ?? [];
244
+ for (const candidate of [request.ip, ...hops]) {
245
+ if (isHeaderAddress(candidate)) return candidate;
246
+ }
247
+ return peerAddress(request.socket?.remoteAddress);
248
+ }
229
249
  var ConnectionRegistry = class {
230
250
  byId = /* @__PURE__ */ new Map();
231
251
  byUserId = /* @__PURE__ */ new Map();
@@ -760,11 +780,6 @@ SseTransport = __decorateClass([
760
780
  function singleHeader(value) {
761
781
  return typeof value === "string" ? value : void 0;
762
782
  }
763
- function resolveIp(req) {
764
- const forwarded = req.headers["x-forwarded-for"];
765
- const candidate = (typeof forwarded === "string" ? forwarded.split(",")[0] : void 0) ?? "";
766
- return candidate.trim() || req.ip || "unknown";
767
- }
768
783
  function normalizeHeaders(headers) {
769
784
  const out = /* @__PURE__ */ Object.create(null);
770
785
  for (const [key, value] of Object.entries(headers)) {
@@ -786,7 +801,8 @@ function buildAuthContext(req) {
786
801
  cookies: parseCookieHeader(singleHeader(req.headers["cookie"]) ?? ""),
787
802
  headers,
788
803
  query: sanitizeQuery(req.query),
789
- ip: resolveIp(req),
804
+ ip: resolveClientAddress(req),
805
+ remoteAddress: req.socket?.remoteAddress,
790
806
  userAgent: singleHeader(req.headers["user-agent"]),
791
807
  transport: "sse"
792
808
  };
@@ -568,6 +568,7 @@ exports.RealtimeGateway = class RealtimeGateway {
568
568
  headers,
569
569
  query,
570
570
  ip: handshake.address,
571
+ remoteAddress: handshake.address,
571
572
  userAgent: handshake.headers["user-agent"],
572
573
  transport: "websocket"
573
574
  };
@@ -568,6 +568,7 @@ var RealtimeGateway = class {
568
568
  headers,
569
569
  query,
570
570
  ip: handshake.address,
571
+ remoteAddress: handshake.address,
571
572
  userAgent: handshake.headers["user-agent"],
572
573
  transport: "websocket"
573
574
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.4",
3
+ "version": "1.2.6",
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",
@@ -96,6 +96,7 @@
96
96
  "build": "pnpm clean && tsup",
97
97
  "check:exports": "attw --pack . --profile strict",
98
98
  "check:mutants": "node scripts/check-mutation-directives.mjs",
99
+ "check:api": "node scripts/check-api-surface.mjs",
99
100
  "check:published": "node scripts/check-published-surface.mjs",
100
101
  "check:runtime": "node scripts/check-consumer-runtime.mjs",
101
102
  "benchmark": "node scripts/benchmark/run.mjs",