@bymax-one/nest-auth 1.4.9 → 1.4.11

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
@@ -18,6 +18,65 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.11] - 2026-11-01
22
+
23
+ ### Apply to a derived backend
24
+
25
+ - **New opt-in `isTrustedProxy`, for the tenant binding behind a proxy that rewrites `Host`.** With
26
+ `enforceTenantBinding` on, the hostname a `tenantIdResolver` sees on a WebSocket upgrade or a
27
+ verified stream was always the `Host` header, while Express resolves `req.hostname` from
28
+ `X-Forwarded-Host` when its `trust proxy` setting trusts the peer. Behind a proxy such as nginx
29
+ with its default `Host $proxy_host`, every stream was therefore refused. Set
30
+ `isTrustedProxy: (peer) => expressApp.get('trust proxy fn')(peer, 0)`, where `expressApp` is
31
+ `app.getHttpAdapter().getInstance()` (not `app.get()`, which resolves providers), and the first element of a single
32
+ `X-Forwarded-Host` is used when the TCP peer is trusted. The predicate receives the peer exactly
33
+ as the transport reported it (including `::ffff:` mapped forms). `AuthTokenVerifierService`
34
+ callers pass the peer as `request.remoteAddress`; `WsJwtGuard` reads Socket.IO's
35
+ `handshake.address` itself. **Nothing changes unless you set it**: unset, `X-Forwarded-Host` is
36
+ never read, and every uncertain case (no peer, a header handed over as separate values, an empty first element, a predicate that throws
37
+ or does not answer `true`) falls back to `Host`, so those cases can only refuse a stream, never
38
+ admit a tenant the client chose.
39
+ - **`afterMfaEnabled` and `afterMfaDisabled` now receive the account as the transition left it.**
40
+ Both hooks ran after the second factor was written, but the account they were handed was the
41
+ record read before the write, so "after MFA enabled" reported `mfaEnabled: false` and "after MFA
42
+ disabled" reported `true`, on both planes and for the administrative `resetMfa` as well. They now
43
+ report `true` and `false` respectively. A handler that branched on the old, inverted value (for
44
+ example to decide whether to send an alert) now sees the real one. The credential fields
45
+ (`passwordHash`, `mfaSecret`, `mfaRecoveryCodes`) are still absent from the payload, and nothing
46
+ else about it changes.
47
+
48
+ ### Fixed
49
+
50
+ - **The MFA hooks reported the state from before the transition.** See the Apply note above.
51
+
52
+ ## [1.4.10] - 2026-11-01
53
+
54
+ ### Apply to a derived backend
55
+
56
+ - **The account-status cache keys no longer carry the tenant and user id.** The `us:` (status) and
57
+ `uev:` (email-verified) entries were keyed by the percent-encoded tenant and user id; they are now
58
+ keyed by `HMAC-SHA-256(hmacKey, userSubject)` of the tenant-scoped dashboard subject, like the
59
+ session index, the token epoch and every other key that names an account. Both entries are
60
+ TTL'd cache values, so nothing needs migrating: the first read after the change misses and
61
+ refills. **Do not name these keys yourself**; `AccountStatusService.invalidate` is the supported
62
+ way to drop them and it already derives the new shape. A deployment that runs the old and the new
63
+ release side by side (a rolling deploy, or another backend on the old shape sharing the store)
64
+ can serve a changed status stale for **up to `userStatusCacheTtlSeconds`** (60 s by default),
65
+ because an invalidation issued by one side deletes a key the other does not read, and pays one
66
+ extra repository read per account. Drain the old release before the new one serves to avoid even
67
+ that.
68
+
69
+ ### Security
70
+
71
+ - The status cache no longer writes account identifiers into Redis keys in the clear.
72
+
73
+ ### Documentation
74
+
75
+ - **The account-status cache is part of the shared wire contract.** `conformance/wire-contract.json`
76
+ declares the `us` and `uev` prefixes and a `userStatusCache` section: the key derivation, the
77
+ value forms, the TTL source and the invalidation order (verified entry first), with vectors for
78
+ delimiter-bearing and multi-byte ids. A conformance test pins the library's behaviour to it.
79
+
21
80
  ## [1.4.9] - 2026-11-01
22
81
 
23
82
  ### Apply to a derived backend
@@ -4095,7 +4154,9 @@ ever installable.
4095
4154
  - Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
4096
4155
  - Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
4097
4156
 
4098
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.9...HEAD
4157
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.11...HEAD
4158
+ [1.4.11]: https://github.com/bymaxone/nest-auth/compare/v1.4.10...v1.4.11
4159
+ [1.4.10]: https://github.com/bymaxone/nest-auth/compare/v1.4.9...v1.4.10
4099
4160
  [1.4.9]: https://github.com/bymaxone/nest-auth/compare/v1.4.8...v1.4.9
4100
4161
  [1.4.8]: https://github.com/bymaxone/nest-auth/compare/v1.4.6...v1.4.8
4101
4162
  [1.4.6]: https://github.com/bymaxone/nest-auth/compare/v1.4.5...v1.4.6
package/README.md CHANGED
@@ -820,21 +820,67 @@ tenant of the upgrade and refuses (`auth.token_invalid`, the same code HTTP answ
820
820
  token minted for another tenant, as `JwtAuthGuard` does on a mismatch. An upgrade has no Express request,
821
821
  so your `tenantIdResolver` is handed a request-like object with **only** these fields:
822
822
 
823
- | Field | Value |
824
- | ---------- | ------------------------------------------------------------------------------------------------- |
825
- | `headers` | The handshake headers, names lowercased |
826
- | `url` | The upgrade URL, `''` when the transport exposes none |
827
- | `hostname` | The `Host` header with the port cut (a bracketed IPv6 literal keeps its brackets), `''` if absent |
823
+ | Field | Value |
824
+ | ---------- | ----------------------------------------------------------------------------------------------------------------------------------- |
825
+ | `headers` | The handshake headers, names lowercased |
826
+ | `url` | The upgrade URL, `''` when the transport exposes none |
827
+ | `hostname` | The `Host` header with the port cut (a bracketed IPv6 literal keeps its brackets), `''` if absent; see below for `X-Forwarded-Host` |
828
828
 
829
829
  There is **no** `cookies` (the `Cookie` header is present in `headers`, but nothing parses it the way
830
- `cookie-parser` does on HTTP), no `ip` or `ips`, and no trust-proxy behaviour: `hostname` is the
831
- `Host` as received, never `X-Forwarded-Host`. The resolver's parameter is typed
830
+ `cookie-parser` does on HTTP) and no `ip` or `ips`. `hostname` is the `Host` as received unless you
831
+ set `isTrustedProxy` (below). The resolver's parameter is typed
832
832
  `TenantResolverRequest` (exported), so a resolver that reads one of the absent fields does not
833
833
  compile. If a resolver still throws at runtime, or returns anything other than the credential's
834
834
  tenant, the connection is **refused**, never bound to the wrong tenant. Resolve from `headers` or
835
835
  `hostname` so one resolver
836
836
  serves both HTTP and sockets.
837
837
 
838
+ **Behind a proxy that rewrites `Host`.** nginx's default `proxy_set_header Host $proxy_host` presents
839
+ the upstream name in `Host` and the public one in `X-Forwarded-Host`. Over HTTP, Express resolves
840
+ `req.hostname` from the forwarded header when its `trust proxy` setting trusts the peer; a socket has
841
+ no Express request, so without more the resolver sees the upstream host and the binding refuses every
842
+ stream. Declare the same trust decision once with `isTrustedProxy`, a function that takes the TCP peer
843
+ address and answers a boolean:
844
+
845
+ ```typescript
846
+ // The module factory runs before the app exists, so it reads the policy per connection.
847
+ // Until main.ts fills it in, no peer is trusted.
848
+ export const proxyPolicy = { trusts: (_peer: string): boolean => false }
849
+
850
+ BymaxAuthModule.registerAsync({
851
+ useFactory: () => ({
852
+ // ...
853
+ enforceTenantBinding: true,
854
+ tenantIdResolver: (req) => req.hostname.split('.')[0] ?? '',
855
+ isTrustedProxy: (peer) => proxyPolicy.trusts(peer)
856
+ })
857
+ })
858
+
859
+ // main.ts
860
+ import { proxyPolicy } from './app.module' // wherever the module is configured
861
+
862
+ const app = await NestFactory.create<NestExpressApplication>(AppModule)
863
+ const expressApp = app.getHttpAdapter().getInstance()
864
+ expressApp.set('trust proxy', 'loopback, 10.0.0.0/8')
865
+ proxyPolicy.trusts = (peer) => expressApp.get('trust proxy fn')(peer, 0)
866
+ ```
867
+
868
+ Read the compiled policy from the **Express instance**, `app.getHttpAdapter().getInstance()`. On a
869
+ Nest application, `app.get()` resolves a provider from the container and does not read an Express
870
+ setting, so `app.get('trust proxy fn')` looks for a provider of that name and fails.
871
+
872
+ The predicate receives the peer **exactly as the transport reported it**, so an IPv4-mapped form such
873
+ as `::ffff:10.0.0.1` reaches it unchanged; Express's compiled setting understands that form, which
874
+ is why the recipe delegates to it. When it answers `true`, the first element of a single
875
+ `X-Forwarded-Host` is used, with the port cut like `Host`. Unset, which is the default,
876
+ `X-Forwarded-Host` is never read. Every other case falls back to `Host`: no peer address, a header handed
877
+ over as separate values, an empty first element, a predicate that throws or answers anything but
878
+ `true`. (Node joins a header repeated on the wire into one comma-separated string, and its first
879
+ element is used, as in Express.) Those cases can therefore only make the binding stricter, never
880
+ admit a tenant the client chose. The
881
+ peer address comes from `WsJwtGuard` itself (Socket.IO's `handshake.address`); a caller of
882
+ `AuthTokenVerifierService.verifyAccessToken` passes it as `request.remoteAddress`.
883
+
838
884
  Both channels live on the client's `handshake`, and only a **Socket.IO** client has one — with
839
885
  `@nestjs/platform-ws` the gateway receives the raw `ws` socket, which carries no `handshake` and
840
886
  does not retain the upgrade request. `WsJwtGuard` refuses such a connection with
@@ -506,6 +506,9 @@ function validateTenantBinding(userOptions) {
506
506
  if (userOptions.enforceTenantBinding === true && !userOptions.tenantIdResolver) {
507
507
  throw new Error(`[BymaxAuthModule] enforceTenantBinding is true but no tenantIdResolver is set. The binding check re-resolves the request's tenant and refuses a token minted for a different one, so with no resolver there is nothing to compare against and every token is accepted \u2014 the control reports success while enforcing nothing. Provide a tenantIdResolver (typically the same host-to-tenant function used on the credential flows), or remove enforceTenantBinding.`);
508
508
  }
509
+ if (userOptions.isTrustedProxy !== void 0 && typeof userOptions.isTrustedProxy !== "function") {
510
+ throw new Error(`[BymaxAuthModule] isTrustedProxy must be a function that takes the peer address and answers a boolean. Pass \`(peer) => expressApp.get('trust proxy fn')(peer, 0)\` with \`expressApp = app.getHttpAdapter().getInstance()\`, or remove it.`);
511
+ }
509
512
  }
510
513
  __name(validateTenantBinding, "validateTenantBinding");
511
514
  var API_KEY_SCOPE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,63}$/;
@@ -3872,11 +3875,11 @@ function _ts_param7(paramIndex, decorator) {
3872
3875
  };
3873
3876
  }
3874
3877
  __name(_ts_param7, "_ts_param");
3875
- function cacheKeysFor(ref) {
3876
- const scope = `${encodeURIComponent(ref.tenantId)}:${encodeURIComponent(ref.userId)}`;
3878
+ function cacheKeysFor(ref, hmacKey) {
3879
+ const digest = hmacSha256(userSubject("dashboard", ref.userId, ref.tenantId), hmacKey);
3877
3880
  return {
3878
- statusKey: `us:${scope}`,
3879
- verifiedKey: `uev:${scope}`
3881
+ statusKey: `us:${digest}`,
3882
+ verifiedKey: `uev:${digest}`
3880
3883
  };
3881
3884
  }
3882
3885
  __name(cacheKeysFor, "cacheKeysFor");
@@ -3934,7 +3937,7 @@ exports.AccountStatusService = class AccountStatusService {
3934
3937
  *
3935
3938
  * @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
3936
3939
  * @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
3937
- * tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
3940
+ * tenant derives a subject no read ever wrote, so the delete would
3938
3941
  * remove nothing and resolve normally — the caller's admin surface reports the suspension
3939
3942
  * applied while the cached `active` survives its full TTL. That is the exact silent failure
3940
3943
  * this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
@@ -3944,7 +3947,7 @@ exports.AccountStatusService = class AccountStatusService {
3944
3947
  if (ref.userId.trim() === "" || ref.tenantId.trim() === "") {
3945
3948
  throw new TypeError("invalidate: userId and tenantId must both be non-empty");
3946
3949
  }
3947
- const { statusKey, verifiedKey } = cacheKeysFor(ref);
3950
+ const { statusKey, verifiedKey } = cacheKeysFor(ref, this.options.hmacKey);
3948
3951
  await this.redis.del(verifiedKey);
3949
3952
  await this.redis.del(statusKey);
3950
3953
  }
@@ -3961,7 +3964,7 @@ exports.AccountStatusService = class AccountStatusService {
3961
3964
  */
3962
3965
  async assertDashboardAccountUsable(ref) {
3963
3966
  const { userId, tenantId } = ref;
3964
- const { statusKey, verifiedKey } = cacheKeysFor(ref);
3967
+ const { statusKey, verifiedKey } = cacheKeysFor(ref, this.options.hmacKey);
3965
3968
  const cacheTtl = this.options.userStatusCacheTtlSeconds;
3966
3969
  const requireVerified = this.options.emailVerification.required;
3967
3970
  let status = await this.redis.get(statusKey);
@@ -10090,6 +10093,28 @@ exports.MfaService = class _MfaService {
10090
10093
  emailVerified: true
10091
10094
  };
10092
10095
  }
10096
+ /**
10097
+ * The account a hook is handed after an MFA transition, projected from the state the transition
10098
+ * wrote.
10099
+ *
10100
+ * The record in hand was read before the transition, so its `mfaEnabled` still describes the
10101
+ * state the transition replaced; the hooks run after the write and must be told what it
10102
+ * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
10103
+ * the same projections every other hook payload uses, and the repository's own record is not
10104
+ * modified.
10105
+ *
10106
+ * @param context - The identity plane the account belongs to.
10107
+ * @param user - The record read before the transition.
10108
+ * @param mfaEnabled - Whether the transition left the second factor enabled.
10109
+ * @returns The projection for the plane, with `mfaEnabled` as written.
10110
+ */
10111
+ committedSafeUser(context, user, mfaEnabled) {
10112
+ const committed = {
10113
+ ...user,
10114
+ mfaEnabled
10115
+ };
10116
+ return context === "platform" ? this.platformUserAsSafeUser(committed) : this.toSafeUser(committed);
10117
+ }
10093
10118
  // ---------------------------------------------------------------------------
10094
10119
  // setup — TOTP secret generation, idempotent key reservation, recovery codes
10095
10120
  // ---------------------------------------------------------------------------
@@ -10227,7 +10252,7 @@ exports.MfaService = class _MfaService {
10227
10252
  this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
10228
10253
  this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
10229
10254
  if (this.hooks.afterMfaEnabled) {
10230
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10255
+ const safeUser = this.committedSafeUser(context, user, true);
10231
10256
  void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
10232
10257
  // The plane, because the tenant cannot carry it: a platform admin is rendered with the
10233
10258
  // sentinel `tenantId: ''` while a platform token has no tenant claim at all.
@@ -10420,7 +10445,7 @@ exports.MfaService = class _MfaService {
10420
10445
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10421
10446
  this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
10422
10447
  this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10423
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10448
+ const safeUser = this.committedSafeUser(context, user, false);
10424
10449
  if (this.hooks.afterMfaDisabled) {
10425
10450
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10426
10451
  plane: context,
@@ -10488,7 +10513,7 @@ exports.MfaService = class _MfaService {
10488
10513
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10489
10514
  this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
10490
10515
  this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10491
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10516
+ const safeUser = this.committedSafeUser(context, user, false);
10492
10517
  if (this.hooks.afterMfaDisabled) {
10493
10518
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10494
10519
  plane: context,
@@ -16915,18 +16940,32 @@ function validation(field, message) {
16915
16940
  __name(validation, "validation");
16916
16941
 
16917
16942
  // src/server/utils/handshake-request.ts
16918
- function handshakeRequest(handshake) {
16943
+ function handshakeRequest(handshake, isTrustedProxy) {
16919
16944
  const headers = {};
16920
16945
  for (const [name, value] of Object.entries(handshake.headers)) {
16921
16946
  headers[name.toLowerCase()] = value;
16922
16947
  }
16948
+ const forwarded = trustedForwardedHost(headers["x-forwarded-host"], handshake.remoteAddress, isTrustedProxy);
16923
16949
  return {
16924
16950
  headers,
16925
16951
  url: handshake.url ?? "",
16926
- hostname: hostnameOf(headers["host"])
16952
+ hostname: hostnameOf(forwarded ?? headers["host"])
16927
16953
  };
16928
16954
  }
16929
16955
  __name(handshakeRequest, "handshakeRequest");
16956
+ function trustedForwardedHost(forwarded, peer, isTrustedProxy) {
16957
+ if (isTrustedProxy === void 0 || typeof forwarded !== "string") return void 0;
16958
+ if (peer === void 0 || peer.trim() === "") return void 0;
16959
+ try {
16960
+ if (isTrustedProxy(peer) !== true) return void 0;
16961
+ } catch {
16962
+ return void 0;
16963
+ }
16964
+ const comma = forwarded.indexOf(",");
16965
+ const first = (comma === -1 ? forwarded : forwarded.slice(0, comma)).trim();
16966
+ return first === "" ? void 0 : first;
16967
+ }
16968
+ __name(trustedForwardedHost, "trustedForwardedHost");
16930
16969
  function hostnameOf(host) {
16931
16970
  if (typeof host !== "string") return "";
16932
16971
  const offset = host.startsWith("[") ? host.indexOf("]") + 1 : 0;
@@ -16945,7 +16984,7 @@ async function assertTenantBinding(options, handshake, tenantId) {
16945
16984
  if (options.enforceTenantBinding !== true || !resolver) return;
16946
16985
  let requestTenant;
16947
16986
  try {
16948
- requestTenant = await resolver(handshakeRequest(handshake));
16987
+ requestTenant = await resolver(handshakeRequest(handshake, options.isTrustedProxy));
16949
16988
  } catch {
16950
16989
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16951
16990
  }
@@ -18169,7 +18208,7 @@ exports.WsJwtGuard = class WsJwtGuard {
18169
18208
  if (ticket !== void 0) {
18170
18209
  const snapshot = await this.wsTickets.redeem(ticket);
18171
18210
  assertDashboardSnapshot(snapshot);
18172
- await assertTenantBinding(this.options, handshake, snapshot.tenantId);
18211
+ await assertTenantBinding(this.options, bindingInput(handshake), snapshot.tenantId);
18173
18212
  client.data.user = snapshot;
18174
18213
  return true;
18175
18214
  }
@@ -18192,7 +18231,7 @@ exports.WsJwtGuard = class WsJwtGuard {
18192
18231
  if (await this.revocation.isAccessTokenRevoked(payload)) {
18193
18232
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
18194
18233
  }
18195
- await assertTenantBinding(this.options, handshake, payload.tenantId);
18234
+ await assertTenantBinding(this.options, bindingInput(handshake), payload.tenantId);
18196
18235
  client.data.user = payload;
18197
18236
  return true;
18198
18237
  }
@@ -18237,6 +18276,13 @@ function readUpgradeTicket(handshake) {
18237
18276
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
18238
18277
  }
18239
18278
  __name(readUpgradeTicket, "readUpgradeTicket");
18279
+ function bindingInput(handshake) {
18280
+ return handshake.address === void 0 ? handshake : {
18281
+ ...handshake,
18282
+ remoteAddress: handshake.address
18283
+ };
18284
+ }
18285
+ __name(bindingInput, "bindingInput");
18240
18286
  function _ts_decorate74(decorators, target, key, desc) {
18241
18287
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
18242
18288
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -505,7 +505,8 @@ type BymaxAuthRateLimitOptions = {
505
505
  * the fields an upgrade lacks — instead of leaving that to a runtime refusal of every socket.
506
506
  *
507
507
  * `hostname` is the `Host` header with the port cut (a bracketed IPv6 literal keeps its brackets),
508
- * `''` when an upgrade carries none or repeats it; it never reads `X-Forwarded-Host`. `url` is `''` when the
508
+ * `''` when an upgrade carries none or repeats it. It reads `X-Forwarded-Host` instead only when
509
+ * {@link BymaxAuthModuleOptions.isTrustedProxy} approves the TCP peer. `url` is `''` when the
509
510
  * transport exposes none.
510
511
  */
511
512
  interface TenantResolverRequest {
@@ -1346,6 +1347,33 @@ interface BymaxAuthModuleOptions {
1346
1347
  * tenant are *meant* to differ.
1347
1348
  */
1348
1349
  enforceTenantBinding?: boolean;
1350
+ /**
1351
+ * Whether the immediate TCP peer of a WebSocket upgrade or a stream is a proxy whose
1352
+ * `X-Forwarded-Host` may be believed.
1353
+ *
1354
+ * It matters when the tenant is decided by the host name and a proxy rewrites `Host` on the way
1355
+ * in (nginx's default `proxy_set_header Host $proxy_host` does). Over HTTP, Express resolves
1356
+ * `req.hostname` from `X-Forwarded-Host` when its `trust proxy` setting trusts the peer; a
1357
+ * stream has no Express request, so without this the {@link tenantIdResolver} would see the
1358
+ * upstream host and {@link enforceTenantBinding} would refuse every stream.
1359
+ *
1360
+ * The predicate receives the peer address **exactly as the transport reported it**, so an
1361
+ * IPv4-mapped form such as `::ffff:10.0.0.1` reaches it unchanged. Express's compiled setting
1362
+ * understands that form, so the usual recipe is
1363
+ * `(peer) => expressApp.get('trust proxy fn')(peer, 0)`, where `expressApp` is
1364
+ * `app.getHttpAdapter().getInstance()`: `app.get()` on a Nest application resolves a provider and
1365
+ * does not read an Express setting. Only the exact boolean `true` trusts a peer.
1366
+ *
1367
+ * Unset, which is the default, `X-Forwarded-Host` is never read. A missing peer address, a
1368
+ * header handed over as separate values, an empty first element, a predicate that throws and a
1369
+ * predicate that answers anything other than `true` all fall back to `Host`, so those cases can
1370
+ * only make the binding stricter, never admit a tenant the client chose. Node joins a header
1371
+ * repeated on the wire into one comma-separated string, whose first element is used, as Express
1372
+ * does. A predicate that answers `true` for a peer it
1373
+ * should not trust does let that peer choose the host, exactly as a wrong Express `trust proxy`
1374
+ * setting would, so the policy must be no wider than the one given to Express.
1375
+ */
1376
+ isTrustedProxy?: (peerAddress: string) => boolean;
1349
1377
  /**
1350
1378
  * Granular control over which controllers are registered.
1351
1379
  * Allows disabling endpoints that are not needed for a specific application.
@@ -3171,7 +3199,8 @@ interface IAuthHooks {
3171
3199
  * Use this hook to send security notifications (via `IEmailProvider`),
3172
3200
  * update audit logs, or propagate the change to downstream systems.
3173
3201
  *
3174
- * @param user - The user who enabled MFA (credential fields omitted).
3202
+ * @param user - The user who enabled MFA, as the enrolment left it: `mfaEnabled` is `true`
3203
+ * (credential fields omitted).
3175
3204
  * @param context - Request metadata (IP, user agent, sanitized headers).
3176
3205
  */
3177
3206
  afterMfaEnabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
@@ -3181,7 +3210,9 @@ interface IAuthHooks {
3181
3210
  * Use this hook to send security alerts, update audit logs, or enforce
3182
3211
  * organizational policies that require MFA.
3183
3212
  *
3184
- * @param user - The user who disabled MFA (credential fields omitted).
3213
+ * @param user - The user whose MFA was disabled, as the removal left it: `mfaEnabled` is
3214
+ * `false` (credential fields omitted). Fired for a user-initiated disable and for an
3215
+ * administrative `resetMfa` alike.
3185
3216
  * @param context - Request metadata (IP, user agent, sanitized headers).
3186
3217
  */
3187
3218
  afterMfaDisabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
@@ -5674,7 +5705,7 @@ declare class TrustedOriginGuard implements CanActivate {
5674
5705
  * request — an access token's whole lifetime, a stream held open for hours — therefore has to ask
5675
5706
  * again, which is what this service exists to do.
5676
5707
  *
5677
- * It reads through a Redis cache (`us:{tenantId}:{userId}`, and `uev:` for the verified flag)
5708
+ * It reads through a Redis cache (`us:` for the status and `uev:` for the verified flag, each keyed by the account)
5678
5709
  * rather than the repository, so asking on every request or on every reconnect costs one `get`
5679
5710
  * rather than a database round trip. A miss resolves both facts from a single tenant-scoped read
5680
5711
  * and writes both back for `userStatusCacheTtlSeconds`.
@@ -5731,7 +5762,7 @@ declare class AccountStatusService {
5731
5762
  *
5732
5763
  * @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
5733
5764
  * @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
5734
- * tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
5765
+ * tenant derives a subject no read ever wrote, so the delete would
5735
5766
  * remove nothing and resolve normally — the caller's admin surface reports the suspension
5736
5767
  * applied while the cached `active` survives its full TTL. That is the exact silent failure
5737
5768
  * this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
@@ -8861,6 +8892,22 @@ declare class MfaService {
8861
8892
  * provisioned directly and do not participate in the tenant/email-verification flow.
8862
8893
  */
8863
8894
  private platformUserAsSafeUser;
8895
+ /**
8896
+ * The account a hook is handed after an MFA transition, projected from the state the transition
8897
+ * wrote.
8898
+ *
8899
+ * The record in hand was read before the transition, so its `mfaEnabled` still describes the
8900
+ * state the transition replaced; the hooks run after the write and must be told what it
8901
+ * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
8902
+ * the same projections every other hook payload uses, and the repository's own record is not
8903
+ * modified.
8904
+ *
8905
+ * @param context - The identity plane the account belongs to.
8906
+ * @param user - The record read before the transition.
8907
+ * @param mfaEnabled - Whether the transition left the second factor enabled.
8908
+ * @returns The projection for the plane, with `mfaEnabled` as written.
8909
+ */
8910
+ private committedSafeUser;
8864
8911
  /**
8865
8912
  * Initiates the MFA setup flow for a dashboard user or platform administrator.
8866
8913
  *
@@ -9831,6 +9878,11 @@ declare class PlatformAuthService {
9831
9878
  interface HandshakeLike {
9832
9879
  headers: Record<string, string | string[] | undefined>;
9833
9880
  url?: string;
9881
+ /**
9882
+ * The TCP peer, as the transport reported it, never a header. Read only to decide whether
9883
+ * `X-Forwarded-Host` may be believed; absent or empty means it may not.
9884
+ */
9885
+ remoteAddress?: string;
9834
9886
  }
9835
9887
 
9836
9888
  /**
@@ -9910,9 +9962,14 @@ interface VerifyAccessTokenOptions {
9910
9962
  * The binding needs the request the host's `tenantIdResolver` reads, which a token alone does
9911
9963
  * not carry. With `enforceTenantBinding` on and a request passed, the resolver runs on the
9912
9964
  * dashboard plane exactly as it does in `WsJwtGuard`: it receives an object with only `headers`
9913
- * (lowercased), `url` and `hostname` (the `Host` header, port cut) — no `cookies`, `ip`, `ips`
9914
- * or trust-proxy behaviour — and a resolver that throws on that, or answers another tenant,
9915
- * refuses the token with `TOKEN_INVALID`. The platform plane has no tenant and ignores it.
9965
+ * (lowercased), `url` and `hostname` — no `cookies`, `ip` or `ips` — and a resolver that throws
9966
+ * on that, or answers another tenant, refuses the token with `TOKEN_INVALID`. The platform plane
9967
+ * has no tenant and ignores it.
9968
+ *
9969
+ * `hostname` is the `Host` header with the port cut. When the host configured `isTrustedProxy`,
9970
+ * pass the TCP peer as `request.remoteAddress` (never a header value): if the predicate trusts
9971
+ * it, the first element of a single `X-Forwarded-Host` is used instead, as Express does over
9972
+ * HTTP. Without a peer the `Host` header stands.
9916
9973
  *
9917
9974
  * **Omit it and the binding is not applied for that call.** With `enforceTenantBinding` on,
9918
9975
  * that is logged once per service instance, because a caller that never passes it has a
@@ -505,7 +505,8 @@ type BymaxAuthRateLimitOptions = {
505
505
  * the fields an upgrade lacks — instead of leaving that to a runtime refusal of every socket.
506
506
  *
507
507
  * `hostname` is the `Host` header with the port cut (a bracketed IPv6 literal keeps its brackets),
508
- * `''` when an upgrade carries none or repeats it; it never reads `X-Forwarded-Host`. `url` is `''` when the
508
+ * `''` when an upgrade carries none or repeats it. It reads `X-Forwarded-Host` instead only when
509
+ * {@link BymaxAuthModuleOptions.isTrustedProxy} approves the TCP peer. `url` is `''` when the
509
510
  * transport exposes none.
510
511
  */
511
512
  interface TenantResolverRequest {
@@ -1346,6 +1347,33 @@ interface BymaxAuthModuleOptions {
1346
1347
  * tenant are *meant* to differ.
1347
1348
  */
1348
1349
  enforceTenantBinding?: boolean;
1350
+ /**
1351
+ * Whether the immediate TCP peer of a WebSocket upgrade or a stream is a proxy whose
1352
+ * `X-Forwarded-Host` may be believed.
1353
+ *
1354
+ * It matters when the tenant is decided by the host name and a proxy rewrites `Host` on the way
1355
+ * in (nginx's default `proxy_set_header Host $proxy_host` does). Over HTTP, Express resolves
1356
+ * `req.hostname` from `X-Forwarded-Host` when its `trust proxy` setting trusts the peer; a
1357
+ * stream has no Express request, so without this the {@link tenantIdResolver} would see the
1358
+ * upstream host and {@link enforceTenantBinding} would refuse every stream.
1359
+ *
1360
+ * The predicate receives the peer address **exactly as the transport reported it**, so an
1361
+ * IPv4-mapped form such as `::ffff:10.0.0.1` reaches it unchanged. Express's compiled setting
1362
+ * understands that form, so the usual recipe is
1363
+ * `(peer) => expressApp.get('trust proxy fn')(peer, 0)`, where `expressApp` is
1364
+ * `app.getHttpAdapter().getInstance()`: `app.get()` on a Nest application resolves a provider and
1365
+ * does not read an Express setting. Only the exact boolean `true` trusts a peer.
1366
+ *
1367
+ * Unset, which is the default, `X-Forwarded-Host` is never read. A missing peer address, a
1368
+ * header handed over as separate values, an empty first element, a predicate that throws and a
1369
+ * predicate that answers anything other than `true` all fall back to `Host`, so those cases can
1370
+ * only make the binding stricter, never admit a tenant the client chose. Node joins a header
1371
+ * repeated on the wire into one comma-separated string, whose first element is used, as Express
1372
+ * does. A predicate that answers `true` for a peer it
1373
+ * should not trust does let that peer choose the host, exactly as a wrong Express `trust proxy`
1374
+ * setting would, so the policy must be no wider than the one given to Express.
1375
+ */
1376
+ isTrustedProxy?: (peerAddress: string) => boolean;
1349
1377
  /**
1350
1378
  * Granular control over which controllers are registered.
1351
1379
  * Allows disabling endpoints that are not needed for a specific application.
@@ -3171,7 +3199,8 @@ interface IAuthHooks {
3171
3199
  * Use this hook to send security notifications (via `IEmailProvider`),
3172
3200
  * update audit logs, or propagate the change to downstream systems.
3173
3201
  *
3174
- * @param user - The user who enabled MFA (credential fields omitted).
3202
+ * @param user - The user who enabled MFA, as the enrolment left it: `mfaEnabled` is `true`
3203
+ * (credential fields omitted).
3175
3204
  * @param context - Request metadata (IP, user agent, sanitized headers).
3176
3205
  */
3177
3206
  afterMfaEnabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
@@ -3181,7 +3210,9 @@ interface IAuthHooks {
3181
3210
  * Use this hook to send security alerts, update audit logs, or enforce
3182
3211
  * organizational policies that require MFA.
3183
3212
  *
3184
- * @param user - The user who disabled MFA (credential fields omitted).
3213
+ * @param user - The user whose MFA was disabled, as the removal left it: `mfaEnabled` is
3214
+ * `false` (credential fields omitted). Fired for a user-initiated disable and for an
3215
+ * administrative `resetMfa` alike.
3185
3216
  * @param context - Request metadata (IP, user agent, sanitized headers).
3186
3217
  */
3187
3218
  afterMfaDisabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
@@ -5674,7 +5705,7 @@ declare class TrustedOriginGuard implements CanActivate {
5674
5705
  * request — an access token's whole lifetime, a stream held open for hours — therefore has to ask
5675
5706
  * again, which is what this service exists to do.
5676
5707
  *
5677
- * It reads through a Redis cache (`us:{tenantId}:{userId}`, and `uev:` for the verified flag)
5708
+ * It reads through a Redis cache (`us:` for the status and `uev:` for the verified flag, each keyed by the account)
5678
5709
  * rather than the repository, so asking on every request or on every reconnect costs one `get`
5679
5710
  * rather than a database round trip. A miss resolves both facts from a single tenant-scoped read
5680
5711
  * and writes both back for `userStatusCacheTtlSeconds`.
@@ -5731,7 +5762,7 @@ declare class AccountStatusService {
5731
5762
  *
5732
5763
  * @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
5733
5764
  * @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
5734
- * tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
5765
+ * tenant derives a subject no read ever wrote, so the delete would
5735
5766
  * remove nothing and resolve normally — the caller's admin surface reports the suspension
5736
5767
  * applied while the cached `active` survives its full TTL. That is the exact silent failure
5737
5768
  * this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
@@ -8861,6 +8892,22 @@ declare class MfaService {
8861
8892
  * provisioned directly and do not participate in the tenant/email-verification flow.
8862
8893
  */
8863
8894
  private platformUserAsSafeUser;
8895
+ /**
8896
+ * The account a hook is handed after an MFA transition, projected from the state the transition
8897
+ * wrote.
8898
+ *
8899
+ * The record in hand was read before the transition, so its `mfaEnabled` still describes the
8900
+ * state the transition replaced; the hooks run after the write and must be told what it
8901
+ * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
8902
+ * the same projections every other hook payload uses, and the repository's own record is not
8903
+ * modified.
8904
+ *
8905
+ * @param context - The identity plane the account belongs to.
8906
+ * @param user - The record read before the transition.
8907
+ * @param mfaEnabled - Whether the transition left the second factor enabled.
8908
+ * @returns The projection for the plane, with `mfaEnabled` as written.
8909
+ */
8910
+ private committedSafeUser;
8864
8911
  /**
8865
8912
  * Initiates the MFA setup flow for a dashboard user or platform administrator.
8866
8913
  *
@@ -9831,6 +9878,11 @@ declare class PlatformAuthService {
9831
9878
  interface HandshakeLike {
9832
9879
  headers: Record<string, string | string[] | undefined>;
9833
9880
  url?: string;
9881
+ /**
9882
+ * The TCP peer, as the transport reported it, never a header. Read only to decide whether
9883
+ * `X-Forwarded-Host` may be believed; absent or empty means it may not.
9884
+ */
9885
+ remoteAddress?: string;
9834
9886
  }
9835
9887
 
9836
9888
  /**
@@ -9910,9 +9962,14 @@ interface VerifyAccessTokenOptions {
9910
9962
  * The binding needs the request the host's `tenantIdResolver` reads, which a token alone does
9911
9963
  * not carry. With `enforceTenantBinding` on and a request passed, the resolver runs on the
9912
9964
  * dashboard plane exactly as it does in `WsJwtGuard`: it receives an object with only `headers`
9913
- * (lowercased), `url` and `hostname` (the `Host` header, port cut) — no `cookies`, `ip`, `ips`
9914
- * or trust-proxy behaviour — and a resolver that throws on that, or answers another tenant,
9915
- * refuses the token with `TOKEN_INVALID`. The platform plane has no tenant and ignores it.
9965
+ * (lowercased), `url` and `hostname` — no `cookies`, `ip` or `ips` — and a resolver that throws
9966
+ * on that, or answers another tenant, refuses the token with `TOKEN_INVALID`. The platform plane
9967
+ * has no tenant and ignores it.
9968
+ *
9969
+ * `hostname` is the `Host` header with the port cut. When the host configured `isTrustedProxy`,
9970
+ * pass the TCP peer as `request.remoteAddress` (never a header value): if the predicate trusts
9971
+ * it, the first element of a single `X-Forwarded-Host` is used instead, as Express does over
9972
+ * HTTP. Without a peer the `Host` header stands.
9916
9973
  *
9917
9974
  * **Omit it and the binding is not applied for that call.** With `enforceTenantBinding` on,
9918
9975
  * that is logged once per service instance, because a caller that never passes it has a
@@ -504,6 +504,9 @@ function validateTenantBinding(userOptions) {
504
504
  if (userOptions.enforceTenantBinding === true && !userOptions.tenantIdResolver) {
505
505
  throw new Error(`[BymaxAuthModule] enforceTenantBinding is true but no tenantIdResolver is set. The binding check re-resolves the request's tenant and refuses a token minted for a different one, so with no resolver there is nothing to compare against and every token is accepted \u2014 the control reports success while enforcing nothing. Provide a tenantIdResolver (typically the same host-to-tenant function used on the credential flows), or remove enforceTenantBinding.`);
506
506
  }
507
+ if (userOptions.isTrustedProxy !== void 0 && typeof userOptions.isTrustedProxy !== "function") {
508
+ throw new Error(`[BymaxAuthModule] isTrustedProxy must be a function that takes the peer address and answers a boolean. Pass \`(peer) => expressApp.get('trust proxy fn')(peer, 0)\` with \`expressApp = app.getHttpAdapter().getInstance()\`, or remove it.`);
509
+ }
507
510
  }
508
511
  __name(validateTenantBinding, "validateTenantBinding");
509
512
  var API_KEY_SCOPE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,63}$/;
@@ -3870,11 +3873,11 @@ function _ts_param7(paramIndex, decorator) {
3870
3873
  };
3871
3874
  }
3872
3875
  __name(_ts_param7, "_ts_param");
3873
- function cacheKeysFor(ref) {
3874
- const scope = `${encodeURIComponent(ref.tenantId)}:${encodeURIComponent(ref.userId)}`;
3876
+ function cacheKeysFor(ref, hmacKey) {
3877
+ const digest = hmacSha256(userSubject("dashboard", ref.userId, ref.tenantId), hmacKey);
3875
3878
  return {
3876
- statusKey: `us:${scope}`,
3877
- verifiedKey: `uev:${scope}`
3879
+ statusKey: `us:${digest}`,
3880
+ verifiedKey: `uev:${digest}`
3878
3881
  };
3879
3882
  }
3880
3883
  __name(cacheKeysFor, "cacheKeysFor");
@@ -3932,7 +3935,7 @@ var AccountStatusService = class {
3932
3935
  *
3933
3936
  * @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
3934
3937
  * @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
3935
- * tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
3938
+ * tenant derives a subject no read ever wrote, so the delete would
3936
3939
  * remove nothing and resolve normally — the caller's admin surface reports the suspension
3937
3940
  * applied while the cached `active` survives its full TTL. That is the exact silent failure
3938
3941
  * this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
@@ -3942,7 +3945,7 @@ var AccountStatusService = class {
3942
3945
  if (ref.userId.trim() === "" || ref.tenantId.trim() === "") {
3943
3946
  throw new TypeError("invalidate: userId and tenantId must both be non-empty");
3944
3947
  }
3945
- const { statusKey, verifiedKey } = cacheKeysFor(ref);
3948
+ const { statusKey, verifiedKey } = cacheKeysFor(ref, this.options.hmacKey);
3946
3949
  await this.redis.del(verifiedKey);
3947
3950
  await this.redis.del(statusKey);
3948
3951
  }
@@ -3959,7 +3962,7 @@ var AccountStatusService = class {
3959
3962
  */
3960
3963
  async assertDashboardAccountUsable(ref) {
3961
3964
  const { userId, tenantId } = ref;
3962
- const { statusKey, verifiedKey } = cacheKeysFor(ref);
3965
+ const { statusKey, verifiedKey } = cacheKeysFor(ref, this.options.hmacKey);
3963
3966
  const cacheTtl = this.options.userStatusCacheTtlSeconds;
3964
3967
  const requireVerified = this.options.emailVerification.required;
3965
3968
  let status = await this.redis.get(statusKey);
@@ -10088,6 +10091,28 @@ var MfaService = class _MfaService {
10088
10091
  emailVerified: true
10089
10092
  };
10090
10093
  }
10094
+ /**
10095
+ * The account a hook is handed after an MFA transition, projected from the state the transition
10096
+ * wrote.
10097
+ *
10098
+ * The record in hand was read before the transition, so its `mfaEnabled` still describes the
10099
+ * state the transition replaced; the hooks run after the write and must be told what it
10100
+ * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
10101
+ * the same projections every other hook payload uses, and the repository's own record is not
10102
+ * modified.
10103
+ *
10104
+ * @param context - The identity plane the account belongs to.
10105
+ * @param user - The record read before the transition.
10106
+ * @param mfaEnabled - Whether the transition left the second factor enabled.
10107
+ * @returns The projection for the plane, with `mfaEnabled` as written.
10108
+ */
10109
+ committedSafeUser(context, user, mfaEnabled) {
10110
+ const committed = {
10111
+ ...user,
10112
+ mfaEnabled
10113
+ };
10114
+ return context === "platform" ? this.platformUserAsSafeUser(committed) : this.toSafeUser(committed);
10115
+ }
10091
10116
  // ---------------------------------------------------------------------------
10092
10117
  // setup — TOTP secret generation, idempotent key reservation, recovery codes
10093
10118
  // ---------------------------------------------------------------------------
@@ -10225,7 +10250,7 @@ var MfaService = class _MfaService {
10225
10250
  this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
10226
10251
  this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
10227
10252
  if (this.hooks.afterMfaEnabled) {
10228
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10253
+ const safeUser = this.committedSafeUser(context, user, true);
10229
10254
  void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
10230
10255
  // The plane, because the tenant cannot carry it: a platform admin is rendered with the
10231
10256
  // sentinel `tenantId: ''` while a platform token has no tenant claim at all.
@@ -10418,7 +10443,7 @@ var MfaService = class _MfaService {
10418
10443
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10419
10444
  this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
10420
10445
  this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10421
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10446
+ const safeUser = this.committedSafeUser(context, user, false);
10422
10447
  if (this.hooks.afterMfaDisabled) {
10423
10448
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10424
10449
  plane: context,
@@ -10486,7 +10511,7 @@ var MfaService = class _MfaService {
10486
10511
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10487
10512
  this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
10488
10513
  this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10489
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10514
+ const safeUser = this.committedSafeUser(context, user, false);
10490
10515
  if (this.hooks.afterMfaDisabled) {
10491
10516
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10492
10517
  plane: context,
@@ -16913,18 +16938,32 @@ function validation(field, message) {
16913
16938
  __name(validation, "validation");
16914
16939
 
16915
16940
  // src/server/utils/handshake-request.ts
16916
- function handshakeRequest(handshake) {
16941
+ function handshakeRequest(handshake, isTrustedProxy) {
16917
16942
  const headers = {};
16918
16943
  for (const [name, value] of Object.entries(handshake.headers)) {
16919
16944
  headers[name.toLowerCase()] = value;
16920
16945
  }
16946
+ const forwarded = trustedForwardedHost(headers["x-forwarded-host"], handshake.remoteAddress, isTrustedProxy);
16921
16947
  return {
16922
16948
  headers,
16923
16949
  url: handshake.url ?? "",
16924
- hostname: hostnameOf(headers["host"])
16950
+ hostname: hostnameOf(forwarded ?? headers["host"])
16925
16951
  };
16926
16952
  }
16927
16953
  __name(handshakeRequest, "handshakeRequest");
16954
+ function trustedForwardedHost(forwarded, peer, isTrustedProxy) {
16955
+ if (isTrustedProxy === void 0 || typeof forwarded !== "string") return void 0;
16956
+ if (peer === void 0 || peer.trim() === "") return void 0;
16957
+ try {
16958
+ if (isTrustedProxy(peer) !== true) return void 0;
16959
+ } catch {
16960
+ return void 0;
16961
+ }
16962
+ const comma = forwarded.indexOf(",");
16963
+ const first = (comma === -1 ? forwarded : forwarded.slice(0, comma)).trim();
16964
+ return first === "" ? void 0 : first;
16965
+ }
16966
+ __name(trustedForwardedHost, "trustedForwardedHost");
16928
16967
  function hostnameOf(host) {
16929
16968
  if (typeof host !== "string") return "";
16930
16969
  const offset = host.startsWith("[") ? host.indexOf("]") + 1 : 0;
@@ -16943,7 +16982,7 @@ async function assertTenantBinding(options, handshake, tenantId) {
16943
16982
  if (options.enforceTenantBinding !== true || !resolver) return;
16944
16983
  let requestTenant;
16945
16984
  try {
16946
- requestTenant = await resolver(handshakeRequest(handshake));
16985
+ requestTenant = await resolver(handshakeRequest(handshake, options.isTrustedProxy));
16947
16986
  } catch {
16948
16987
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16949
16988
  }
@@ -18167,7 +18206,7 @@ var WsJwtGuard = class {
18167
18206
  if (ticket !== void 0) {
18168
18207
  const snapshot = await this.wsTickets.redeem(ticket);
18169
18208
  assertDashboardSnapshot(snapshot);
18170
- await assertTenantBinding(this.options, handshake, snapshot.tenantId);
18209
+ await assertTenantBinding(this.options, bindingInput(handshake), snapshot.tenantId);
18171
18210
  client.data.user = snapshot;
18172
18211
  return true;
18173
18212
  }
@@ -18190,7 +18229,7 @@ var WsJwtGuard = class {
18190
18229
  if (await this.revocation.isAccessTokenRevoked(payload)) {
18191
18230
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
18192
18231
  }
18193
- await assertTenantBinding(this.options, handshake, payload.tenantId);
18232
+ await assertTenantBinding(this.options, bindingInput(handshake), payload.tenantId);
18194
18233
  client.data.user = payload;
18195
18234
  return true;
18196
18235
  }
@@ -18235,6 +18274,13 @@ function readUpgradeTicket(handshake) {
18235
18274
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
18236
18275
  }
18237
18276
  __name(readUpgradeTicket, "readUpgradeTicket");
18277
+ function bindingInput(handshake) {
18278
+ return handshake.address === void 0 ? handshake : {
18279
+ ...handshake,
18280
+ remoteAddress: handshake.address
18281
+ };
18282
+ }
18283
+ __name(bindingInput, "bindingInput");
18238
18284
  function _ts_decorate74(decorators, target, key, desc) {
18239
18285
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
18240
18286
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.4.9",
3
+ "version": "1.4.11",
4
4
  "description": "Full-stack authentication and authorization package for NestJS, React and Next.js — JWT, MFA, OAuth, sessions, multi-tenant SaaS ready",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",