@bymax-one/nest-auth 1.4.10 → 1.4.12

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,68 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.12] - 2026-11-01
22
+
23
+ ### Apply to a derived backend
24
+
25
+ - **The refresh cookie is `SameSite=Strict` unless you configure `cookies.sameSite: 'none'`.**
26
+ Until now it followed `cookies.sameSite`, so under the default (`lax`) it was issued `Lax`. It is
27
+ now `Strict` under `lax` and `strict`, and `None` only when `none` is configured, which is
28
+ unchanged. Only the attribute changes: the access and session-signal cookies still follow
29
+ `cookies.sameSite`, so the OAuth return trip is unaffected, and the cookie that ends a session
30
+ is cleared with the same attribute it was issued with. Nothing a user could do stops working:
31
+ the silent-refresh route already refused every caller stating a `Sec-Fetch-Site` other
32
+ than `same-origin` or `none`. Measured in Chromium 140 with the real proxy and route handler, a
33
+ `Lax` refresh cookie does reach that route on a cross-site link, and the route answers before
34
+ reading it, so a `Strict` cookie changes the outcome of no navigation. A deployment that
35
+ proxies the refresh call from a frontend on another site must already be on `none`.
36
+ - **A cross-site entry to the silent-refresh route now redirects to the login page.** A user
37
+ who follows a link into the app from another site (or from another origin on the same site)
38
+ after the access token expired used to land on a bare `403`. The route now answers `307` to
39
+ `loginPath?reason=expired`, the same target a failed refresh uses, so the login page can show
40
+ its expired-session message. The refusal keeps its property: no refresh is attempted and no
41
+ `Set-Cookie` is written, so a cross-site caller still causes nothing. The logout and
42
+ client-refresh routes are unchanged and still answer `403`. A page that treated a `403` from
43
+ the silent-refresh route as a signal sees a redirect instead.
44
+
45
+ ### Fixed
46
+
47
+ - **The refresh cookie was issued `Lax` under the default configuration.** See the Apply note
48
+ above.
49
+ - **A cross-site entry to the silent-refresh route showed a bare `403`.** See the Apply note
50
+ above.
51
+
52
+ ## [1.4.11] - 2026-11-01
53
+
54
+ ### Apply to a derived backend
55
+
56
+ - **New opt-in `isTrustedProxy`, for the tenant binding behind a proxy that rewrites `Host`.** With
57
+ `enforceTenantBinding` on, the hostname a `tenantIdResolver` sees on a WebSocket upgrade or a
58
+ verified stream was always the `Host` header, while Express resolves `req.hostname` from
59
+ `X-Forwarded-Host` when its `trust proxy` setting trusts the peer. Behind a proxy such as nginx
60
+ with its default `Host $proxy_host`, every stream was therefore refused. Set
61
+ `isTrustedProxy: (peer) => expressApp.get('trust proxy fn')(peer, 0)`, where `expressApp` is
62
+ `app.getHttpAdapter().getInstance()` (not `app.get()`, which resolves providers), and the first element of a single
63
+ `X-Forwarded-Host` is used when the TCP peer is trusted. The predicate receives the peer exactly
64
+ as the transport reported it (including `::ffff:` mapped forms). `AuthTokenVerifierService`
65
+ callers pass the peer as `request.remoteAddress`; `WsJwtGuard` reads Socket.IO's
66
+ `handshake.address` itself. **Nothing changes unless you set it**: unset, `X-Forwarded-Host` is
67
+ never read, and every uncertain case (no peer, a header handed over as separate values, an empty first element, a predicate that throws
68
+ or does not answer `true`) falls back to `Host`, so those cases can only refuse a stream, never
69
+ admit a tenant the client chose.
70
+ - **`afterMfaEnabled` and `afterMfaDisabled` now receive the account as the transition left it.**
71
+ Both hooks ran after the second factor was written, but the account they were handed was the
72
+ record read before the write, so "after MFA enabled" reported `mfaEnabled: false` and "after MFA
73
+ disabled" reported `true`, on both planes and for the administrative `resetMfa` as well. They now
74
+ report `true` and `false` respectively. A handler that branched on the old, inverted value (for
75
+ example to decide whether to send an alert) now sees the real one. The credential fields
76
+ (`passwordHash`, `mfaSecret`, `mfaRecoveryCodes`) are still absent from the payload, and nothing
77
+ else about it changes.
78
+
79
+ ### Fixed
80
+
81
+ - **The MFA hooks reported the state from before the transition.** See the Apply note above.
82
+
21
83
  ## [1.4.10] - 2026-11-01
22
84
 
23
85
  ### Apply to a derived backend
@@ -4123,7 +4185,9 @@ ever installable.
4123
4185
  - 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
4124
4186
  - 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
4125
4187
 
4126
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.10...HEAD
4188
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.12...HEAD
4189
+ [1.4.12]: https://github.com/bymaxone/nest-auth/compare/v1.4.11...v1.4.12
4190
+ [1.4.11]: https://github.com/bymaxone/nest-auth/compare/v1.4.10...v1.4.11
4127
4191
  [1.4.10]: https://github.com/bymaxone/nest-auth/compare/v1.4.9...v1.4.10
4128
4192
  [1.4.9]: https://github.com/bymaxone/nest-auth/compare/v1.4.8...v1.4.9
4129
4193
  [1.4.8]: https://github.com/bymaxone/nest-auth/compare/v1.4.6...v1.4.8
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
@@ -1415,8 +1461,10 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
1415
1461
  - `@MaxLength(128)` on password DTOs prevents algorithmic-DoS via oversized scrypt inputs
1416
1462
  - JWT algorithm pinning to HS256 prevents algorithm-confusion attacks
1417
1463
  - Constant-time comparisons via `crypto.timingSafeEqual` for all secret comparisons
1418
- - HttpOnly cookies; `Secure` enforced in production; `SameSite=Lax` by default on every auth
1419
- cookie, so the OAuth provider's cross-site redirect back to your app still carries them.
1464
+ - HttpOnly cookies; `Secure` enforced in production; `SameSite=Lax` by default on the access and
1465
+ session-signal cookies, so the OAuth provider's cross-site redirect back to your app still
1466
+ carries them. The refresh cookie is `Strict` under `lax` and `strict`, and `None` only when
1467
+ you configure `cookies.sameSite: 'none'`.
1420
1468
  Deployments that do not need that redirect can take the stricter posture with
1421
1469
  `cookies.sameSite: 'strict'`. CSRF does not rest on this setting — `TrustedOriginGuard` is
1422
1470
  applied to every controller and runs before authentication.
@@ -1446,7 +1494,7 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
1446
1494
  | Token Generation | `crypto.randomBytes(32)` — 256 bits of entropy |
1447
1495
  | Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
1448
1496
  | JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
1449
- | Cookies | HttpOnly, Secure, SameSite=Lax (override to `strict`), path-scoped |
1497
+ | Cookies | HttpOnly, Secure, SameSite=Lax (override to `strict`), refresh cookie Strict, path-scoped |
1450
1498
  | Brute-Force | Redis atomic counters per HMAC(email, identifier key) |
1451
1499
  | CSRF (OAuth) | 64-char hex state nonce, single-use via `getdel()` |
1452
1500
  | Refresh Rotation | Single-use tokens with a grace window; a replay past it revokes that login's whole family lineage |
@@ -936,12 +936,7 @@ function createSilentRefreshHandler(config) {
936
936
  const refreshUrl = buildRefreshUrl(config.apiBase, config.refreshPath);
937
937
  return /* @__PURE__ */ __name(async function silentRefreshHandler(request) {
938
938
  if (isCrossSiteRequest(request)) {
939
- return new server.NextResponse(null, {
940
- status: 403,
941
- headers: {
942
- "Cache-Control": "no-store, no-cache"
943
- }
944
- });
939
+ return buildLoginRedirect(config);
945
940
  }
946
941
  const origin = request.nextUrl.origin;
947
942
  const rawDestination = request.nextUrl.searchParams.get("redirect");
@@ -1005,8 +1000,7 @@ function buildSuccessRedirect(destination, rawSetCookies) {
1005
1000
  }
1006
1001
  __name(buildSuccessRedirect, "buildSuccessRedirect");
1007
1002
  function buildLogoutRedirect(config) {
1008
- const response = redirectToPath(withQueryParam(config.loginPath, "reason", "expired"));
1009
- response.headers.set("Cache-Control", "no-store, no-cache");
1003
+ const response = buildLoginRedirect(config);
1010
1004
  const clearCookies = [
1011
1005
  serializeClearCookie(config.cookieNames.access, "/", config.cookieDomain),
1012
1006
  serializeClearCookie(config.cookieNames.refresh, config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH, config.cookieDomain),
@@ -1018,6 +1012,12 @@ function buildLogoutRedirect(config) {
1018
1012
  return response;
1019
1013
  }
1020
1014
  __name(buildLogoutRedirect, "buildLogoutRedirect");
1015
+ function buildLoginRedirect(config) {
1016
+ const response = redirectToPath(withQueryParam(config.loginPath, "reason", "expired"));
1017
+ response.headers.set("Cache-Control", "no-store, no-cache");
1018
+ return response;
1019
+ }
1020
+ __name(buildLoginRedirect, "buildLoginRedirect");
1021
1021
  var SILENT_REFRESH_ROUTE = shared.AUTH_PROXY_ROUTES.silentRefresh;
1022
1022
  function createClientRefreshHandler(config) {
1023
1023
  assertValidApiBase(config.apiBase, "createClientRefreshHandler");
@@ -862,6 +862,8 @@ type SilentRefreshHandler = (request: NextRequest) => Promise<NextResponse>;
862
862
  * Create a GET handler for `/api/auth/silent-refresh`.
863
863
  *
864
864
  * The returned handler:
865
+ * 0. Redirects a caller whose `Sec-Fetch-Site` is not `same-origin` or `none` to
866
+ * `loginPath?reason=expired` with no refresh and no `Set-Cookie`.
865
867
  * 1. Resolves a safe `redirect` destination (see open-redirect
866
868
  * defence above).
867
869
  * 2. Forwards the incoming cookies to the upstream refresh endpoint.
@@ -862,6 +862,8 @@ type SilentRefreshHandler = (request: NextRequest) => Promise<NextResponse>;
862
862
  * Create a GET handler for `/api/auth/silent-refresh`.
863
863
  *
864
864
  * The returned handler:
865
+ * 0. Redirects a caller whose `Sec-Fetch-Site` is not `same-origin` or `none` to
866
+ * `loginPath?reason=expired` with no refresh and no `Set-Cookie`.
865
867
  * 1. Resolves a safe `redirect` destination (see open-redirect
866
868
  * defence above).
867
869
  * 2. Forwards the incoming cookies to the upstream refresh endpoint.
@@ -934,12 +934,7 @@ function createSilentRefreshHandler(config) {
934
934
  const refreshUrl = buildRefreshUrl(config.apiBase, config.refreshPath);
935
935
  return /* @__PURE__ */ __name(async function silentRefreshHandler(request) {
936
936
  if (isCrossSiteRequest(request)) {
937
- return new NextResponse(null, {
938
- status: 403,
939
- headers: {
940
- "Cache-Control": "no-store, no-cache"
941
- }
942
- });
937
+ return buildLoginRedirect(config);
943
938
  }
944
939
  const origin = request.nextUrl.origin;
945
940
  const rawDestination = request.nextUrl.searchParams.get("redirect");
@@ -1003,8 +998,7 @@ function buildSuccessRedirect(destination, rawSetCookies) {
1003
998
  }
1004
999
  __name(buildSuccessRedirect, "buildSuccessRedirect");
1005
1000
  function buildLogoutRedirect(config) {
1006
- const response = redirectToPath(withQueryParam(config.loginPath, "reason", "expired"));
1007
- response.headers.set("Cache-Control", "no-store, no-cache");
1001
+ const response = buildLoginRedirect(config);
1008
1002
  const clearCookies = [
1009
1003
  serializeClearCookie(config.cookieNames.access, "/", config.cookieDomain),
1010
1004
  serializeClearCookie(config.cookieNames.refresh, config.refreshCookiePath ?? DEFAULT_REFRESH_COOKIE_PATH, config.cookieDomain),
@@ -1016,6 +1010,12 @@ function buildLogoutRedirect(config) {
1016
1010
  return response;
1017
1011
  }
1018
1012
  __name(buildLogoutRedirect, "buildLogoutRedirect");
1013
+ function buildLoginRedirect(config) {
1014
+ const response = redirectToPath(withQueryParam(config.loginPath, "reason", "expired"));
1015
+ response.headers.set("Cache-Control", "no-store, no-cache");
1016
+ return response;
1017
+ }
1018
+ __name(buildLoginRedirect, "buildLoginRedirect");
1019
1019
  var SILENT_REFRESH_ROUTE = AUTH_PROXY_ROUTES.silentRefresh;
1020
1020
  function createClientRefreshHandler(config) {
1021
1021
  assertValidApiBase(config.apiBase, "createClientRefreshHandler");
@@ -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}$/;
@@ -3508,6 +3511,7 @@ exports.TokenDeliveryService = class TokenDeliveryService {
3508
3511
  res.clearCookie(this.options.cookies.accessTokenName, cookieOpts);
3509
3512
  res.clearCookie(this.options.cookies.refreshTokenName, {
3510
3513
  ...cookieOpts,
3514
+ sameSite: this.refreshSameSite(),
3511
3515
  path: this.options.cookies.refreshCookiePath
3512
3516
  });
3513
3517
  res.clearCookie(this.options.cookies.sessionSignalName, {
@@ -3574,6 +3578,7 @@ exports.TokenDeliveryService = class TokenDeliveryService {
3574
3578
  });
3575
3579
  res.cookie(this.options.cookies.refreshTokenName, rawRefreshToken, {
3576
3580
  ...base,
3581
+ sameSite: this.refreshSameSite(),
3577
3582
  httpOnly: true,
3578
3583
  secure: isProd,
3579
3584
  path: this.options.cookies.refreshCookiePath,
@@ -3586,6 +3591,18 @@ exports.TokenDeliveryService = class TokenDeliveryService {
3586
3591
  maxAge: refreshMaxAge
3587
3592
  });
3588
3593
  }
3594
+ /**
3595
+ * `SameSite` of the refresh cookie: Strict unless the deployment is cross-site (`none`).
3596
+ *
3597
+ * Only the refresh route reads this cookie, and a browser sends it there on the app's own
3598
+ * requests; withholding it from every cross-site request costs nothing, whereas the access and
3599
+ * session-signal cookies follow `cookies.sameSite` because the OAuth return trip needs them on
3600
+ * a cross-site top-level navigation. A `none` deployment must keep `none`, or its refresh call
3601
+ * would carry no credential.
3602
+ */
3603
+ refreshSameSite() {
3604
+ return this.options.cookies.sameSite === "none" ? "none" : "strict";
3605
+ }
3589
3606
  /** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
3590
3607
  baseCookieOptions(domain) {
3591
3608
  return {
@@ -10090,6 +10107,28 @@ exports.MfaService = class _MfaService {
10090
10107
  emailVerified: true
10091
10108
  };
10092
10109
  }
10110
+ /**
10111
+ * The account a hook is handed after an MFA transition, projected from the state the transition
10112
+ * wrote.
10113
+ *
10114
+ * The record in hand was read before the transition, so its `mfaEnabled` still describes the
10115
+ * state the transition replaced; the hooks run after the write and must be told what it
10116
+ * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
10117
+ * the same projections every other hook payload uses, and the repository's own record is not
10118
+ * modified.
10119
+ *
10120
+ * @param context - The identity plane the account belongs to.
10121
+ * @param user - The record read before the transition.
10122
+ * @param mfaEnabled - Whether the transition left the second factor enabled.
10123
+ * @returns The projection for the plane, with `mfaEnabled` as written.
10124
+ */
10125
+ committedSafeUser(context, user, mfaEnabled) {
10126
+ const committed = {
10127
+ ...user,
10128
+ mfaEnabled
10129
+ };
10130
+ return context === "platform" ? this.platformUserAsSafeUser(committed) : this.toSafeUser(committed);
10131
+ }
10093
10132
  // ---------------------------------------------------------------------------
10094
10133
  // setup — TOTP secret generation, idempotent key reservation, recovery codes
10095
10134
  // ---------------------------------------------------------------------------
@@ -10227,7 +10266,7 @@ exports.MfaService = class _MfaService {
10227
10266
  this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
10228
10267
  this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
10229
10268
  if (this.hooks.afterMfaEnabled) {
10230
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10269
+ const safeUser = this.committedSafeUser(context, user, true);
10231
10270
  void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
10232
10271
  // The plane, because the tenant cannot carry it: a platform admin is rendered with the
10233
10272
  // sentinel `tenantId: ''` while a platform token has no tenant claim at all.
@@ -10420,7 +10459,7 @@ exports.MfaService = class _MfaService {
10420
10459
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10421
10460
  this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
10422
10461
  this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10423
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10462
+ const safeUser = this.committedSafeUser(context, user, false);
10424
10463
  if (this.hooks.afterMfaDisabled) {
10425
10464
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10426
10465
  plane: context,
@@ -10488,7 +10527,7 @@ exports.MfaService = class _MfaService {
10488
10527
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10489
10528
  this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
10490
10529
  this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10491
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10530
+ const safeUser = this.committedSafeUser(context, user, false);
10492
10531
  if (this.hooks.afterMfaDisabled) {
10493
10532
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10494
10533
  plane: context,
@@ -16915,18 +16954,32 @@ function validation(field, message) {
16915
16954
  __name(validation, "validation");
16916
16955
 
16917
16956
  // src/server/utils/handshake-request.ts
16918
- function handshakeRequest(handshake) {
16957
+ function handshakeRequest(handshake, isTrustedProxy) {
16919
16958
  const headers = {};
16920
16959
  for (const [name, value] of Object.entries(handshake.headers)) {
16921
16960
  headers[name.toLowerCase()] = value;
16922
16961
  }
16962
+ const forwarded = trustedForwardedHost(headers["x-forwarded-host"], handshake.remoteAddress, isTrustedProxy);
16923
16963
  return {
16924
16964
  headers,
16925
16965
  url: handshake.url ?? "",
16926
- hostname: hostnameOf(headers["host"])
16966
+ hostname: hostnameOf(forwarded ?? headers["host"])
16927
16967
  };
16928
16968
  }
16929
16969
  __name(handshakeRequest, "handshakeRequest");
16970
+ function trustedForwardedHost(forwarded, peer, isTrustedProxy) {
16971
+ if (isTrustedProxy === void 0 || typeof forwarded !== "string") return void 0;
16972
+ if (peer === void 0 || peer.trim() === "") return void 0;
16973
+ try {
16974
+ if (isTrustedProxy(peer) !== true) return void 0;
16975
+ } catch {
16976
+ return void 0;
16977
+ }
16978
+ const comma = forwarded.indexOf(",");
16979
+ const first = (comma === -1 ? forwarded : forwarded.slice(0, comma)).trim();
16980
+ return first === "" ? void 0 : first;
16981
+ }
16982
+ __name(trustedForwardedHost, "trustedForwardedHost");
16930
16983
  function hostnameOf(host) {
16931
16984
  if (typeof host !== "string") return "";
16932
16985
  const offset = host.startsWith("[") ? host.indexOf("]") + 1 : 0;
@@ -16945,7 +16998,7 @@ async function assertTenantBinding(options, handshake, tenantId) {
16945
16998
  if (options.enforceTenantBinding !== true || !resolver) return;
16946
16999
  let requestTenant;
16947
17000
  try {
16948
- requestTenant = await resolver(handshakeRequest(handshake));
17001
+ requestTenant = await resolver(handshakeRequest(handshake, options.isTrustedProxy));
16949
17002
  } catch {
16950
17003
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16951
17004
  }
@@ -18169,7 +18222,7 @@ exports.WsJwtGuard = class WsJwtGuard {
18169
18222
  if (ticket !== void 0) {
18170
18223
  const snapshot = await this.wsTickets.redeem(ticket);
18171
18224
  assertDashboardSnapshot(snapshot);
18172
- await assertTenantBinding(this.options, handshake, snapshot.tenantId);
18225
+ await assertTenantBinding(this.options, bindingInput(handshake), snapshot.tenantId);
18173
18226
  client.data.user = snapshot;
18174
18227
  return true;
18175
18228
  }
@@ -18192,7 +18245,7 @@ exports.WsJwtGuard = class WsJwtGuard {
18192
18245
  if (await this.revocation.isAccessTokenRevoked(payload)) {
18193
18246
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
18194
18247
  }
18195
- await assertTenantBinding(this.options, handshake, payload.tenantId);
18248
+ await assertTenantBinding(this.options, bindingInput(handshake), payload.tenantId);
18196
18249
  client.data.user = payload;
18197
18250
  return true;
18198
18251
  }
@@ -18237,6 +18290,13 @@ function readUpgradeTicket(handshake) {
18237
18290
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
18238
18291
  }
18239
18292
  __name(readUpgradeTicket, "readUpgradeTicket");
18293
+ function bindingInput(handshake) {
18294
+ return handshake.address === void 0 ? handshake : {
18295
+ ...handshake,
18296
+ remoteAddress: handshake.address
18297
+ };
18298
+ }
18299
+ __name(bindingInput, "bindingInput");
18240
18300
  function _ts_decorate74(decorators, target, key, desc) {
18241
18301
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
18242
18302
  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 {
@@ -819,8 +820,13 @@ interface BymaxAuthModuleOptions {
819
820
  */
820
821
  resolveDomains?: (requestDomain: string) => string[];
821
822
  /**
822
- * `SameSite` attribute applied to every cookie issued by the module
823
- * (access token, refresh token, session signal). Default: `'lax'`.
823
+ * `SameSite` attribute applied to the access-token and session-signal cookies issued by
824
+ * the module. Default: `'lax'`.
825
+ *
826
+ * The refresh-token cookie does not follow this value except for `'none'`: it is issued
827
+ * `Strict` under `'lax'` and `'strict'`, because only the refresh route reads it and no
828
+ * cross-site request needs it. Under `'none'` it is `None` too, since a cross-site
829
+ * frontend's refresh call would otherwise carry no credential.
824
830
  *
825
831
  * Trade-offs:
826
832
  * - `'lax'` (default): cookies travel on top-level cross-site GET navigations.
@@ -1346,6 +1352,33 @@ interface BymaxAuthModuleOptions {
1346
1352
  * tenant are *meant* to differ.
1347
1353
  */
1348
1354
  enforceTenantBinding?: boolean;
1355
+ /**
1356
+ * Whether the immediate TCP peer of a WebSocket upgrade or a stream is a proxy whose
1357
+ * `X-Forwarded-Host` may be believed.
1358
+ *
1359
+ * It matters when the tenant is decided by the host name and a proxy rewrites `Host` on the way
1360
+ * in (nginx's default `proxy_set_header Host $proxy_host` does). Over HTTP, Express resolves
1361
+ * `req.hostname` from `X-Forwarded-Host` when its `trust proxy` setting trusts the peer; a
1362
+ * stream has no Express request, so without this the {@link tenantIdResolver} would see the
1363
+ * upstream host and {@link enforceTenantBinding} would refuse every stream.
1364
+ *
1365
+ * The predicate receives the peer address **exactly as the transport reported it**, so an
1366
+ * IPv4-mapped form such as `::ffff:10.0.0.1` reaches it unchanged. Express's compiled setting
1367
+ * understands that form, so the usual recipe is
1368
+ * `(peer) => expressApp.get('trust proxy fn')(peer, 0)`, where `expressApp` is
1369
+ * `app.getHttpAdapter().getInstance()`: `app.get()` on a Nest application resolves a provider and
1370
+ * does not read an Express setting. Only the exact boolean `true` trusts a peer.
1371
+ *
1372
+ * Unset, which is the default, `X-Forwarded-Host` is never read. A missing peer address, a
1373
+ * header handed over as separate values, an empty first element, a predicate that throws and a
1374
+ * predicate that answers anything other than `true` all fall back to `Host`, so those cases can
1375
+ * only make the binding stricter, never admit a tenant the client chose. Node joins a header
1376
+ * repeated on the wire into one comma-separated string, whose first element is used, as Express
1377
+ * does. A predicate that answers `true` for a peer it
1378
+ * should not trust does let that peer choose the host, exactly as a wrong Express `trust proxy`
1379
+ * setting would, so the policy must be no wider than the one given to Express.
1380
+ */
1381
+ isTrustedProxy?: (peerAddress: string) => boolean;
1349
1382
  /**
1350
1383
  * Granular control over which controllers are registered.
1351
1384
  * Allows disabling endpoints that are not needed for a specific application.
@@ -3171,7 +3204,8 @@ interface IAuthHooks {
3171
3204
  * Use this hook to send security notifications (via `IEmailProvider`),
3172
3205
  * update audit logs, or propagate the change to downstream systems.
3173
3206
  *
3174
- * @param user - The user who enabled MFA (credential fields omitted).
3207
+ * @param user - The user who enabled MFA, as the enrolment left it: `mfaEnabled` is `true`
3208
+ * (credential fields omitted).
3175
3209
  * @param context - Request metadata (IP, user agent, sanitized headers).
3176
3210
  */
3177
3211
  afterMfaEnabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
@@ -3181,7 +3215,9 @@ interface IAuthHooks {
3181
3215
  * Use this hook to send security alerts, update audit logs, or enforce
3182
3216
  * organizational policies that require MFA.
3183
3217
  *
3184
- * @param user - The user who disabled MFA (credential fields omitted).
3218
+ * @param user - The user whose MFA was disabled, as the removal left it: `mfaEnabled` is
3219
+ * `false` (credential fields omitted). Fired for a user-initiated disable and for an
3220
+ * administrative `resetMfa` alike.
3185
3221
  * @param context - Request metadata (IP, user agent, sanitized headers).
3186
3222
  */
3187
3223
  afterMfaDisabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
@@ -5157,7 +5193,8 @@ interface PlatformBearerAuthResponse {
5157
5193
  * set. Use this for mobile/native clients or SPA with cross-origin APIs.
5158
5194
  * - `'both'`: Tokens are set as cookies AND returned in the response body.
5159
5195
  *
5160
- * Cookie security: HttpOnly, Secure (production), SameSite=Strict.
5196
+ * Cookie security: HttpOnly, Secure (production). The access and session-signal cookies follow
5197
+ * `cookies.sameSite`; the refresh cookie is SameSite=Strict unless `none` is configured.
5161
5198
  * Refresh cookies use the configured `cookies.refreshCookiePath`.
5162
5199
  *
5163
5200
  * @layer Service
@@ -5283,6 +5320,16 @@ declare class TokenDeliveryService {
5283
5320
  */
5284
5321
  extractDomain(req: Request): string | undefined;
5285
5322
  private setAuthCookies;
5323
+ /**
5324
+ * `SameSite` of the refresh cookie: Strict unless the deployment is cross-site (`none`).
5325
+ *
5326
+ * Only the refresh route reads this cookie, and a browser sends it there on the app's own
5327
+ * requests; withholding it from every cross-site request costs nothing, whereas the access and
5328
+ * session-signal cookies follow `cookies.sameSite` because the OAuth return trip needs them on
5329
+ * a cross-site top-level navigation. A `none` deployment must keep `none`, or its refresh call
5330
+ * would carry no credential.
5331
+ */
5332
+ private refreshSameSite;
5286
5333
  /** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
5287
5334
  private baseCookieOptions;
5288
5335
  /** Reads the value of the cookie identified by `name` from the request. */
@@ -8861,6 +8908,22 @@ declare class MfaService {
8861
8908
  * provisioned directly and do not participate in the tenant/email-verification flow.
8862
8909
  */
8863
8910
  private platformUserAsSafeUser;
8911
+ /**
8912
+ * The account a hook is handed after an MFA transition, projected from the state the transition
8913
+ * wrote.
8914
+ *
8915
+ * The record in hand was read before the transition, so its `mfaEnabled` still describes the
8916
+ * state the transition replaced; the hooks run after the write and must be told what it
8917
+ * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
8918
+ * the same projections every other hook payload uses, and the repository's own record is not
8919
+ * modified.
8920
+ *
8921
+ * @param context - The identity plane the account belongs to.
8922
+ * @param user - The record read before the transition.
8923
+ * @param mfaEnabled - Whether the transition left the second factor enabled.
8924
+ * @returns The projection for the plane, with `mfaEnabled` as written.
8925
+ */
8926
+ private committedSafeUser;
8864
8927
  /**
8865
8928
  * Initiates the MFA setup flow for a dashboard user or platform administrator.
8866
8929
  *
@@ -9831,6 +9894,11 @@ declare class PlatformAuthService {
9831
9894
  interface HandshakeLike {
9832
9895
  headers: Record<string, string | string[] | undefined>;
9833
9896
  url?: string;
9897
+ /**
9898
+ * The TCP peer, as the transport reported it, never a header. Read only to decide whether
9899
+ * `X-Forwarded-Host` may be believed; absent or empty means it may not.
9900
+ */
9901
+ remoteAddress?: string;
9834
9902
  }
9835
9903
 
9836
9904
  /**
@@ -9910,9 +9978,14 @@ interface VerifyAccessTokenOptions {
9910
9978
  * The binding needs the request the host's `tenantIdResolver` reads, which a token alone does
9911
9979
  * not carry. With `enforceTenantBinding` on and a request passed, the resolver runs on the
9912
9980
  * 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.
9981
+ * (lowercased), `url` and `hostname` — no `cookies`, `ip` or `ips` — and a resolver that throws
9982
+ * on that, or answers another tenant, refuses the token with `TOKEN_INVALID`. The platform plane
9983
+ * has no tenant and ignores it.
9984
+ *
9985
+ * `hostname` is the `Host` header with the port cut. When the host configured `isTrustedProxy`,
9986
+ * pass the TCP peer as `request.remoteAddress` (never a header value): if the predicate trusts
9987
+ * it, the first element of a single `X-Forwarded-Host` is used instead, as Express does over
9988
+ * HTTP. Without a peer the `Host` header stands.
9916
9989
  *
9917
9990
  * **Omit it and the binding is not applied for that call.** With `enforceTenantBinding` on,
9918
9991
  * 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 {
@@ -819,8 +820,13 @@ interface BymaxAuthModuleOptions {
819
820
  */
820
821
  resolveDomains?: (requestDomain: string) => string[];
821
822
  /**
822
- * `SameSite` attribute applied to every cookie issued by the module
823
- * (access token, refresh token, session signal). Default: `'lax'`.
823
+ * `SameSite` attribute applied to the access-token and session-signal cookies issued by
824
+ * the module. Default: `'lax'`.
825
+ *
826
+ * The refresh-token cookie does not follow this value except for `'none'`: it is issued
827
+ * `Strict` under `'lax'` and `'strict'`, because only the refresh route reads it and no
828
+ * cross-site request needs it. Under `'none'` it is `None` too, since a cross-site
829
+ * frontend's refresh call would otherwise carry no credential.
824
830
  *
825
831
  * Trade-offs:
826
832
  * - `'lax'` (default): cookies travel on top-level cross-site GET navigations.
@@ -1346,6 +1352,33 @@ interface BymaxAuthModuleOptions {
1346
1352
  * tenant are *meant* to differ.
1347
1353
  */
1348
1354
  enforceTenantBinding?: boolean;
1355
+ /**
1356
+ * Whether the immediate TCP peer of a WebSocket upgrade or a stream is a proxy whose
1357
+ * `X-Forwarded-Host` may be believed.
1358
+ *
1359
+ * It matters when the tenant is decided by the host name and a proxy rewrites `Host` on the way
1360
+ * in (nginx's default `proxy_set_header Host $proxy_host` does). Over HTTP, Express resolves
1361
+ * `req.hostname` from `X-Forwarded-Host` when its `trust proxy` setting trusts the peer; a
1362
+ * stream has no Express request, so without this the {@link tenantIdResolver} would see the
1363
+ * upstream host and {@link enforceTenantBinding} would refuse every stream.
1364
+ *
1365
+ * The predicate receives the peer address **exactly as the transport reported it**, so an
1366
+ * IPv4-mapped form such as `::ffff:10.0.0.1` reaches it unchanged. Express's compiled setting
1367
+ * understands that form, so the usual recipe is
1368
+ * `(peer) => expressApp.get('trust proxy fn')(peer, 0)`, where `expressApp` is
1369
+ * `app.getHttpAdapter().getInstance()`: `app.get()` on a Nest application resolves a provider and
1370
+ * does not read an Express setting. Only the exact boolean `true` trusts a peer.
1371
+ *
1372
+ * Unset, which is the default, `X-Forwarded-Host` is never read. A missing peer address, a
1373
+ * header handed over as separate values, an empty first element, a predicate that throws and a
1374
+ * predicate that answers anything other than `true` all fall back to `Host`, so those cases can
1375
+ * only make the binding stricter, never admit a tenant the client chose. Node joins a header
1376
+ * repeated on the wire into one comma-separated string, whose first element is used, as Express
1377
+ * does. A predicate that answers `true` for a peer it
1378
+ * should not trust does let that peer choose the host, exactly as a wrong Express `trust proxy`
1379
+ * setting would, so the policy must be no wider than the one given to Express.
1380
+ */
1381
+ isTrustedProxy?: (peerAddress: string) => boolean;
1349
1382
  /**
1350
1383
  * Granular control over which controllers are registered.
1351
1384
  * Allows disabling endpoints that are not needed for a specific application.
@@ -3171,7 +3204,8 @@ interface IAuthHooks {
3171
3204
  * Use this hook to send security notifications (via `IEmailProvider`),
3172
3205
  * update audit logs, or propagate the change to downstream systems.
3173
3206
  *
3174
- * @param user - The user who enabled MFA (credential fields omitted).
3207
+ * @param user - The user who enabled MFA, as the enrolment left it: `mfaEnabled` is `true`
3208
+ * (credential fields omitted).
3175
3209
  * @param context - Request metadata (IP, user agent, sanitized headers).
3176
3210
  */
3177
3211
  afterMfaEnabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
@@ -3181,7 +3215,9 @@ interface IAuthHooks {
3181
3215
  * Use this hook to send security alerts, update audit logs, or enforce
3182
3216
  * organizational policies that require MFA.
3183
3217
  *
3184
- * @param user - The user who disabled MFA (credential fields omitted).
3218
+ * @param user - The user whose MFA was disabled, as the removal left it: `mfaEnabled` is
3219
+ * `false` (credential fields omitted). Fired for a user-initiated disable and for an
3220
+ * administrative `resetMfa` alike.
3185
3221
  * @param context - Request metadata (IP, user agent, sanitized headers).
3186
3222
  */
3187
3223
  afterMfaDisabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
@@ -5157,7 +5193,8 @@ interface PlatformBearerAuthResponse {
5157
5193
  * set. Use this for mobile/native clients or SPA with cross-origin APIs.
5158
5194
  * - `'both'`: Tokens are set as cookies AND returned in the response body.
5159
5195
  *
5160
- * Cookie security: HttpOnly, Secure (production), SameSite=Strict.
5196
+ * Cookie security: HttpOnly, Secure (production). The access and session-signal cookies follow
5197
+ * `cookies.sameSite`; the refresh cookie is SameSite=Strict unless `none` is configured.
5161
5198
  * Refresh cookies use the configured `cookies.refreshCookiePath`.
5162
5199
  *
5163
5200
  * @layer Service
@@ -5283,6 +5320,16 @@ declare class TokenDeliveryService {
5283
5320
  */
5284
5321
  extractDomain(req: Request): string | undefined;
5285
5322
  private setAuthCookies;
5323
+ /**
5324
+ * `SameSite` of the refresh cookie: Strict unless the deployment is cross-site (`none`).
5325
+ *
5326
+ * Only the refresh route reads this cookie, and a browser sends it there on the app's own
5327
+ * requests; withholding it from every cross-site request costs nothing, whereas the access and
5328
+ * session-signal cookies follow `cookies.sameSite` because the OAuth return trip needs them on
5329
+ * a cross-site top-level navigation. A `none` deployment must keep `none`, or its refresh call
5330
+ * would carry no credential.
5331
+ */
5332
+ private refreshSameSite;
5286
5333
  /** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
5287
5334
  private baseCookieOptions;
5288
5335
  /** Reads the value of the cookie identified by `name` from the request. */
@@ -8861,6 +8908,22 @@ declare class MfaService {
8861
8908
  * provisioned directly and do not participate in the tenant/email-verification flow.
8862
8909
  */
8863
8910
  private platformUserAsSafeUser;
8911
+ /**
8912
+ * The account a hook is handed after an MFA transition, projected from the state the transition
8913
+ * wrote.
8914
+ *
8915
+ * The record in hand was read before the transition, so its `mfaEnabled` still describes the
8916
+ * state the transition replaced; the hooks run after the write and must be told what it
8917
+ * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
8918
+ * the same projections every other hook payload uses, and the repository's own record is not
8919
+ * modified.
8920
+ *
8921
+ * @param context - The identity plane the account belongs to.
8922
+ * @param user - The record read before the transition.
8923
+ * @param mfaEnabled - Whether the transition left the second factor enabled.
8924
+ * @returns The projection for the plane, with `mfaEnabled` as written.
8925
+ */
8926
+ private committedSafeUser;
8864
8927
  /**
8865
8928
  * Initiates the MFA setup flow for a dashboard user or platform administrator.
8866
8929
  *
@@ -9831,6 +9894,11 @@ declare class PlatformAuthService {
9831
9894
  interface HandshakeLike {
9832
9895
  headers: Record<string, string | string[] | undefined>;
9833
9896
  url?: string;
9897
+ /**
9898
+ * The TCP peer, as the transport reported it, never a header. Read only to decide whether
9899
+ * `X-Forwarded-Host` may be believed; absent or empty means it may not.
9900
+ */
9901
+ remoteAddress?: string;
9834
9902
  }
9835
9903
 
9836
9904
  /**
@@ -9910,9 +9978,14 @@ interface VerifyAccessTokenOptions {
9910
9978
  * The binding needs the request the host's `tenantIdResolver` reads, which a token alone does
9911
9979
  * not carry. With `enforceTenantBinding` on and a request passed, the resolver runs on the
9912
9980
  * 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.
9981
+ * (lowercased), `url` and `hostname` — no `cookies`, `ip` or `ips` — and a resolver that throws
9982
+ * on that, or answers another tenant, refuses the token with `TOKEN_INVALID`. The platform plane
9983
+ * has no tenant and ignores it.
9984
+ *
9985
+ * `hostname` is the `Host` header with the port cut. When the host configured `isTrustedProxy`,
9986
+ * pass the TCP peer as `request.remoteAddress` (never a header value): if the predicate trusts
9987
+ * it, the first element of a single `X-Forwarded-Host` is used instead, as Express does over
9988
+ * HTTP. Without a peer the `Host` header stands.
9916
9989
  *
9917
9990
  * **Omit it and the binding is not applied for that call.** With `enforceTenantBinding` on,
9918
9991
  * 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}$/;
@@ -3506,6 +3509,7 @@ var TokenDeliveryService = class {
3506
3509
  res.clearCookie(this.options.cookies.accessTokenName, cookieOpts);
3507
3510
  res.clearCookie(this.options.cookies.refreshTokenName, {
3508
3511
  ...cookieOpts,
3512
+ sameSite: this.refreshSameSite(),
3509
3513
  path: this.options.cookies.refreshCookiePath
3510
3514
  });
3511
3515
  res.clearCookie(this.options.cookies.sessionSignalName, {
@@ -3572,6 +3576,7 @@ var TokenDeliveryService = class {
3572
3576
  });
3573
3577
  res.cookie(this.options.cookies.refreshTokenName, rawRefreshToken, {
3574
3578
  ...base,
3579
+ sameSite: this.refreshSameSite(),
3575
3580
  httpOnly: true,
3576
3581
  secure: isProd,
3577
3582
  path: this.options.cookies.refreshCookiePath,
@@ -3584,6 +3589,18 @@ var TokenDeliveryService = class {
3584
3589
  maxAge: refreshMaxAge
3585
3590
  });
3586
3591
  }
3592
+ /**
3593
+ * `SameSite` of the refresh cookie: Strict unless the deployment is cross-site (`none`).
3594
+ *
3595
+ * Only the refresh route reads this cookie, and a browser sends it there on the app's own
3596
+ * requests; withholding it from every cross-site request costs nothing, whereas the access and
3597
+ * session-signal cookies follow `cookies.sameSite` because the OAuth return trip needs them on
3598
+ * a cross-site top-level navigation. A `none` deployment must keep `none`, or its refresh call
3599
+ * would carry no credential.
3600
+ */
3601
+ refreshSameSite() {
3602
+ return this.options.cookies.sameSite === "none" ? "none" : "strict";
3603
+ }
3587
3604
  /** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
3588
3605
  baseCookieOptions(domain) {
3589
3606
  return {
@@ -10088,6 +10105,28 @@ var MfaService = class _MfaService {
10088
10105
  emailVerified: true
10089
10106
  };
10090
10107
  }
10108
+ /**
10109
+ * The account a hook is handed after an MFA transition, projected from the state the transition
10110
+ * wrote.
10111
+ *
10112
+ * The record in hand was read before the transition, so its `mfaEnabled` still describes the
10113
+ * state the transition replaced; the hooks run after the write and must be told what it
10114
+ * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
10115
+ * the same projections every other hook payload uses, and the repository's own record is not
10116
+ * modified.
10117
+ *
10118
+ * @param context - The identity plane the account belongs to.
10119
+ * @param user - The record read before the transition.
10120
+ * @param mfaEnabled - Whether the transition left the second factor enabled.
10121
+ * @returns The projection for the plane, with `mfaEnabled` as written.
10122
+ */
10123
+ committedSafeUser(context, user, mfaEnabled) {
10124
+ const committed = {
10125
+ ...user,
10126
+ mfaEnabled
10127
+ };
10128
+ return context === "platform" ? this.platformUserAsSafeUser(committed) : this.toSafeUser(committed);
10129
+ }
10091
10130
  // ---------------------------------------------------------------------------
10092
10131
  // setup — TOTP secret generation, idempotent key reservation, recovery codes
10093
10132
  // ---------------------------------------------------------------------------
@@ -10225,7 +10264,7 @@ var MfaService = class _MfaService {
10225
10264
  this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
10226
10265
  this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
10227
10266
  if (this.hooks.afterMfaEnabled) {
10228
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10267
+ const safeUser = this.committedSafeUser(context, user, true);
10229
10268
  void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
10230
10269
  // The plane, because the tenant cannot carry it: a platform admin is rendered with the
10231
10270
  // sentinel `tenantId: ''` while a platform token has no tenant claim at all.
@@ -10418,7 +10457,7 @@ var MfaService = class _MfaService {
10418
10457
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10419
10458
  this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
10420
10459
  this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10421
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10460
+ const safeUser = this.committedSafeUser(context, user, false);
10422
10461
  if (this.hooks.afterMfaDisabled) {
10423
10462
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10424
10463
  plane: context,
@@ -10486,7 +10525,7 @@ var MfaService = class _MfaService {
10486
10525
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10487
10526
  this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
10488
10527
  this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10489
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10528
+ const safeUser = this.committedSafeUser(context, user, false);
10490
10529
  if (this.hooks.afterMfaDisabled) {
10491
10530
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10492
10531
  plane: context,
@@ -16913,18 +16952,32 @@ function validation(field, message) {
16913
16952
  __name(validation, "validation");
16914
16953
 
16915
16954
  // src/server/utils/handshake-request.ts
16916
- function handshakeRequest(handshake) {
16955
+ function handshakeRequest(handshake, isTrustedProxy) {
16917
16956
  const headers = {};
16918
16957
  for (const [name, value] of Object.entries(handshake.headers)) {
16919
16958
  headers[name.toLowerCase()] = value;
16920
16959
  }
16960
+ const forwarded = trustedForwardedHost(headers["x-forwarded-host"], handshake.remoteAddress, isTrustedProxy);
16921
16961
  return {
16922
16962
  headers,
16923
16963
  url: handshake.url ?? "",
16924
- hostname: hostnameOf(headers["host"])
16964
+ hostname: hostnameOf(forwarded ?? headers["host"])
16925
16965
  };
16926
16966
  }
16927
16967
  __name(handshakeRequest, "handshakeRequest");
16968
+ function trustedForwardedHost(forwarded, peer, isTrustedProxy) {
16969
+ if (isTrustedProxy === void 0 || typeof forwarded !== "string") return void 0;
16970
+ if (peer === void 0 || peer.trim() === "") return void 0;
16971
+ try {
16972
+ if (isTrustedProxy(peer) !== true) return void 0;
16973
+ } catch {
16974
+ return void 0;
16975
+ }
16976
+ const comma = forwarded.indexOf(",");
16977
+ const first = (comma === -1 ? forwarded : forwarded.slice(0, comma)).trim();
16978
+ return first === "" ? void 0 : first;
16979
+ }
16980
+ __name(trustedForwardedHost, "trustedForwardedHost");
16928
16981
  function hostnameOf(host) {
16929
16982
  if (typeof host !== "string") return "";
16930
16983
  const offset = host.startsWith("[") ? host.indexOf("]") + 1 : 0;
@@ -16943,7 +16996,7 @@ async function assertTenantBinding(options, handshake, tenantId) {
16943
16996
  if (options.enforceTenantBinding !== true || !resolver) return;
16944
16997
  let requestTenant;
16945
16998
  try {
16946
- requestTenant = await resolver(handshakeRequest(handshake));
16999
+ requestTenant = await resolver(handshakeRequest(handshake, options.isTrustedProxy));
16947
17000
  } catch {
16948
17001
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16949
17002
  }
@@ -18167,7 +18220,7 @@ var WsJwtGuard = class {
18167
18220
  if (ticket !== void 0) {
18168
18221
  const snapshot = await this.wsTickets.redeem(ticket);
18169
18222
  assertDashboardSnapshot(snapshot);
18170
- await assertTenantBinding(this.options, handshake, snapshot.tenantId);
18223
+ await assertTenantBinding(this.options, bindingInput(handshake), snapshot.tenantId);
18171
18224
  client.data.user = snapshot;
18172
18225
  return true;
18173
18226
  }
@@ -18190,7 +18243,7 @@ var WsJwtGuard = class {
18190
18243
  if (await this.revocation.isAccessTokenRevoked(payload)) {
18191
18244
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
18192
18245
  }
18193
- await assertTenantBinding(this.options, handshake, payload.tenantId);
18246
+ await assertTenantBinding(this.options, bindingInput(handshake), payload.tenantId);
18194
18247
  client.data.user = payload;
18195
18248
  return true;
18196
18249
  }
@@ -18235,6 +18288,13 @@ function readUpgradeTicket(handshake) {
18235
18288
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
18236
18289
  }
18237
18290
  __name(readUpgradeTicket, "readUpgradeTicket");
18291
+ function bindingInput(handshake) {
18292
+ return handshake.address === void 0 ? handshake : {
18293
+ ...handshake,
18294
+ remoteAddress: handshake.address
18295
+ };
18296
+ }
18297
+ __name(bindingInput, "bindingInput");
18238
18298
  function _ts_decorate74(decorators, target, key, desc) {
18239
18299
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
18240
18300
  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.10",
3
+ "version": "1.4.12",
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",