@bymax-one/nest-auth 1.4.11 → 1.4.13

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,73 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.13] - 2026-11-01
22
+
23
+ ### Apply to a derived backend
24
+
25
+ - **A client address that is not an address is no longer a rate-limit key, and no longer reaches a
26
+ hook, a session or an audit event.** With `rateLimit.clientIpSource: 'trusted-proxy'` the limiter
27
+ keyed on `req.ip`, and behind a hop that forwards the client's own `X-Forwarded-For` unchanged
28
+ Express returns the first entry its `trust proxy` setting does not trust, which is an arbitrary
29
+ string when that entry is not an address. A client that varied it on every request got a fresh
30
+ budget each time. One function now resolves
31
+ the address for the limiter and for every place that records it: `req.ip`, then the rest of
32
+ `req.ips` (the trusted hops, nearest the client first), then the socket peer, taking the first
33
+ that is an address. A header entry that carries an IPv6 zone index is not one, while the socket peer's zone,
34
+ which a link-local peer reports, is cut. An unparsable client entry is therefore
35
+ charged to the nearest trusted hop, so every caller that sends one shares that hop's bucket; a
36
+ chain with no address in it at all falls back to the shared unknown bucket, as before.
37
+ **What consumers see differently:** `HookContext.ip`, which every hook receives, and the `ip` of
38
+ the `onApiKeyRequest` audit event used to carry the raw `req.ip`; they now carry an address, or an empty string when none can be read. The `ip`
39
+ stored on a session and shown by the sessions list and the new-session email follows the same
40
+ value. In `clientIpSource: 'peer'` the limiter still keys on the socket; the recorded address
41
+ still comes from `req.ip` when the application sets `trust proxy`, and is validated the same
42
+ way.
43
+ **Not changed:**
44
+ `'trusted-proxy'` is only as honest as the hops in front of the app. Behind such a proxy each hop
45
+ appends the address it saw, so the client is the rightmost entry that is not itself a trusted
46
+ proxy. A hop that forwards the client's own `X-Forwarded-For` unchanged lets the client choose
47
+ its address even when every entry is a valid one, and a client that varies a valid address still
48
+ gets a fresh budget each time. Behind
49
+ such a hop use `'peer'`, or make the hop append or overwrite the header.
50
+
51
+ ### Fixed
52
+
53
+ - **The per-address rate limit could be bypassed behind a proxy that forwards `X-Forwarded-For`
54
+ unchanged.** See the Apply note above.
55
+ - **A client-written non-address string could reach hook payloads and API-key audit events.** See the Apply note above.
56
+
57
+ ## [1.4.12] - 2026-11-01
58
+
59
+ ### Apply to a derived backend
60
+
61
+ - **The refresh cookie is `SameSite=Strict` unless you configure `cookies.sameSite: 'none'`.**
62
+ Until now it followed `cookies.sameSite`, so under the default (`lax`) it was issued `Lax`. It is
63
+ now `Strict` under `lax` and `strict`, and `None` only when `none` is configured, which is
64
+ unchanged. Only the attribute changes: the access and session-signal cookies still follow
65
+ `cookies.sameSite`, so the OAuth return trip is unaffected, and the cookie that ends a session
66
+ is cleared with the same attribute it was issued with. Nothing a user could do stops working:
67
+ the silent-refresh route already refused every caller stating a `Sec-Fetch-Site` other
68
+ than `same-origin` or `none`. Measured in Chromium 140 with the real proxy and route handler, a
69
+ `Lax` refresh cookie does reach that route on a cross-site link, and the route answers before
70
+ reading it, so a `Strict` cookie changes the outcome of no navigation. A deployment that
71
+ proxies the refresh call from a frontend on another site must already be on `none`.
72
+ - **A cross-site entry to the silent-refresh route now redirects to the login page.** A user
73
+ who follows a link into the app from another site (or from another origin on the same site)
74
+ after the access token expired used to land on a bare `403`. The route now answers `307` to
75
+ `loginPath?reason=expired`, the same target a failed refresh uses, so the login page can show
76
+ its expired-session message. The refusal keeps its property: no refresh is attempted and no
77
+ `Set-Cookie` is written, so a cross-site caller still causes nothing. The logout and
78
+ client-refresh routes are unchanged and still answer `403`. A page that treated a `403` from
79
+ the silent-refresh route as a signal sees a redirect instead.
80
+
81
+ ### Fixed
82
+
83
+ - **The refresh cookie was issued `Lax` under the default configuration.** See the Apply note
84
+ above.
85
+ - **A cross-site entry to the silent-refresh route showed a bare `403`.** See the Apply note
86
+ above.
87
+
21
88
  ## [1.4.11] - 2026-11-01
22
89
 
23
90
  ### Apply to a derived backend
@@ -4154,7 +4221,9 @@ ever installable.
4154
4221
  - 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
4155
4222
  - 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
4156
4223
 
4157
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.11...HEAD
4224
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.13...HEAD
4225
+ [1.4.13]: https://github.com/bymaxone/nest-auth/compare/v1.4.12...v1.4.13
4226
+ [1.4.12]: https://github.com/bymaxone/nest-auth/compare/v1.4.11...v1.4.12
4158
4227
  [1.4.11]: https://github.com/bymaxone/nest-auth/compare/v1.4.10...v1.4.11
4159
4228
  [1.4.10]: https://github.com/bymaxone/nest-auth/compare/v1.4.9...v1.4.10
4160
4229
  [1.4.9]: https://github.com/bymaxone/nest-auth/compare/v1.4.8...v1.4.9
package/README.md CHANGED
@@ -961,6 +961,13 @@ All options are configurable via `registerAsync()`. Here are the key configurati
961
961
  > `'trusted-proxy'` without a proxy lets the caller choose their own key. Both look like a
962
962
  > working limiter at runtime. Pass `rateLimit.enabled: false` if the limits are enforced at the
963
963
  > edge instead.
964
+ >
965
+ > `'trusted-proxy'` is only as honest as the hops in front of the app. Behind such a proxy each
966
+ > hop appends the address it saw, so the client is the rightmost entry that is not itself a
967
+ > trusted proxy. A hop that forwards the client's own `X-Forwarded-For` unchanged lets the client
968
+ > choose its address, so a client that varies it gets a fresh budget every time; behind such a hop
969
+ > use `'peer'`, or make the hop append or overwrite the header. An entry that is not an address at
970
+ > all is never a key: the limit is charged to the nearest trusted hop instead.
964
971
 
965
972
  > [!TIP]
966
973
  > **Binding tokens to an issuer and an audience.** `jwt.issuer` and `jwt.audience` are off by
@@ -1461,8 +1468,10 @@ When integrating `@bymax-one/nest-auth` in production, verify each of the follow
1461
1468
  - `@MaxLength(128)` on password DTOs prevents algorithmic-DoS via oversized scrypt inputs
1462
1469
  - JWT algorithm pinning to HS256 prevents algorithm-confusion attacks
1463
1470
  - Constant-time comparisons via `crypto.timingSafeEqual` for all secret comparisons
1464
- - HttpOnly cookies; `Secure` enforced in production; `SameSite=Lax` by default on every auth
1465
- cookie, so the OAuth provider's cross-site redirect back to your app still carries them.
1471
+ - HttpOnly cookies; `Secure` enforced in production; `SameSite=Lax` by default on the access and
1472
+ session-signal cookies, so the OAuth provider's cross-site redirect back to your app still
1473
+ carries them. The refresh cookie is `Strict` under `lax` and `strict`, and `None` only when
1474
+ you configure `cookies.sameSite: 'none'`.
1466
1475
  Deployments that do not need that redirect can take the stricter posture with
1467
1476
  `cookies.sameSite: 'strict'`. CSRF does not rest on this setting — `TrustedOriginGuard` is
1468
1477
  applied to every controller and runs before authentication.
@@ -1492,7 +1501,7 @@ it is the one guarantee cookie delivery exists for and the one no server-side te
1492
1501
  | Token Generation | `crypto.randomBytes(32)` — 256 bits of entropy |
1493
1502
  | Secret Comparison | `crypto.timingSafeEqual` (constant-time) |
1494
1503
  | JWT | HS256 via `@nestjs/jwt`, JTI blacklist via Redis |
1495
- | Cookies | HttpOnly, Secure, SameSite=Lax (override to `strict`), path-scoped |
1504
+ | Cookies | HttpOnly, Secure, SameSite=Lax (override to `strict`), refresh cookie Strict, path-scoped |
1496
1505
  | Brute-Force | Redis atomic counters per HMAC(email, identifier key) |
1497
1506
  | CSRF (OAuth) | 64-char hex state nonce, single-use via `getdel()` |
1498
1507
  | 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");
@@ -2889,6 +2889,31 @@ function isWsTicketSnapshot(value) {
2889
2889
  return typeof record["sub"] === "string" && typeof record["role"] === "string" && typeof record["status"] === "string" && typeof record["mfaEnabled"] === "boolean" && typeof record["mfaVerified"] === "boolean" && typeof record["jti"] === "string" && record["jti"] !== "" && typeof record["epoch"] === "number" && Number.isSafeInteger(record["epoch"]) && record["epoch"] >= 0 && (record["tenantId"] === void 0 || typeof record["tenantId"] === "string");
2890
2890
  }
2891
2891
  __name(isWsTicketSnapshot, "isWsTicketSnapshot");
2892
+ var IPV6 = 6;
2893
+ function isHeaderAddress(candidate) {
2894
+ return typeof candidate === "string" && !candidate.includes("%") && net.isIP(candidate) !== 0;
2895
+ }
2896
+ __name(isHeaderAddress, "isHeaderAddress");
2897
+ function peerAddress(remoteAddress) {
2898
+ if (typeof remoteAddress !== "string") return "";
2899
+ const zoneIndex = remoteAddress.indexOf("%");
2900
+ const bare = zoneIndex === -1 ? remoteAddress : remoteAddress.slice(0, zoneIndex);
2901
+ const family = net.isIP(bare);
2902
+ if (zoneIndex !== -1) return family === IPV6 ? bare : "";
2903
+ return family === 0 ? "" : bare;
2904
+ }
2905
+ __name(peerAddress, "peerAddress");
2906
+ function resolveClientAddress(request) {
2907
+ const hops = request.ips ?? [];
2908
+ for (const candidate of [
2909
+ request.ip,
2910
+ ...hops
2911
+ ]) {
2912
+ if (isHeaderAddress(candidate)) return candidate;
2913
+ }
2914
+ return peerAddress(request.socket?.remoteAddress);
2915
+ }
2916
+ __name(resolveClientAddress, "resolveClientAddress");
2892
2917
  var IPV6_GROUPS = 8;
2893
2918
  var IPV6_PREFIX_GROUPS = 4;
2894
2919
  function rateLimitBucket(address) {
@@ -3009,8 +3034,9 @@ exports.AuthRateLimitGuard = class AuthRateLimitGuard {
3009
3034
  * The address this request is counted against.
3010
3035
  *
3011
3036
  * `'peer'` — the default — reads the socket directly, so `X-Forwarded-For` cannot influence
3012
- * it. `'trusted-proxy'` uses `req.ip`, which honours the app's `trust proxy` setting and the
3013
- * forwarding headers it admits.
3037
+ * it. `'trusted-proxy'` uses the resolved client address, which starts from `req.ip` (honouring
3038
+ * the app's `trust proxy` setting and the forwarding headers it admits) and never returns a
3039
+ * string that is not an address, so a caller cannot mint a bucket by writing one.
3014
3040
  *
3015
3041
  * The default is the strict one because the two failure modes are not symmetric: keying on
3016
3042
  * the peer address behind a proxy over-counts, which is visible and recoverable, while
@@ -3023,7 +3049,7 @@ exports.AuthRateLimitGuard = class AuthRateLimitGuard {
3023
3049
  */
3024
3050
  clientIp(request) {
3025
3051
  if (this.options.rateLimit.clientIpSource === "trusted-proxy") {
3026
- return typeof request.ip === "string" && request.ip !== "" ? request.ip : UNKNOWN_CLIENT;
3052
+ return resolveClientAddress(request) || UNKNOWN_CLIENT;
3027
3053
  }
3028
3054
  const peer = request.socket?.remoteAddress;
3029
3055
  return typeof peer === "string" && peer !== "" ? peer : UNKNOWN_CLIENT;
@@ -3511,6 +3537,7 @@ exports.TokenDeliveryService = class TokenDeliveryService {
3511
3537
  res.clearCookie(this.options.cookies.accessTokenName, cookieOpts);
3512
3538
  res.clearCookie(this.options.cookies.refreshTokenName, {
3513
3539
  ...cookieOpts,
3540
+ sameSite: this.refreshSameSite(),
3514
3541
  path: this.options.cookies.refreshCookiePath
3515
3542
  });
3516
3543
  res.clearCookie(this.options.cookies.sessionSignalName, {
@@ -3577,6 +3604,7 @@ exports.TokenDeliveryService = class TokenDeliveryService {
3577
3604
  });
3578
3605
  res.cookie(this.options.cookies.refreshTokenName, rawRefreshToken, {
3579
3606
  ...base,
3607
+ sameSite: this.refreshSameSite(),
3580
3608
  httpOnly: true,
3581
3609
  secure: isProd,
3582
3610
  path: this.options.cookies.refreshCookiePath,
@@ -3589,6 +3617,18 @@ exports.TokenDeliveryService = class TokenDeliveryService {
3589
3617
  maxAge: refreshMaxAge
3590
3618
  });
3591
3619
  }
3620
+ /**
3621
+ * `SameSite` of the refresh cookie: Strict unless the deployment is cross-site (`none`).
3622
+ *
3623
+ * Only the refresh route reads this cookie, and a browser sends it there on the app's own
3624
+ * requests; withholding it from every cross-site request costs nothing, whereas the access and
3625
+ * session-signal cookies follow `cookies.sameSite` because the OAuth return trip needs them on
3626
+ * a cross-site top-level navigation. A `none` deployment must keep `none`, or its refresh call
3627
+ * would carry no credential.
3628
+ */
3629
+ refreshSameSite() {
3630
+ return this.options.cookies.sameSite === "none" ? "none" : "strict";
3631
+ }
3592
3632
  /** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
3593
3633
  baseCookieOptions(domain) {
3594
3634
  return {
@@ -6608,7 +6648,7 @@ exports.AuthService = class _AuthService {
6608
6648
  */
6609
6649
  async register(dto, req) {
6610
6650
  const tenantId = await this.resolveTenantId(dto.tenantId, req);
6611
- const ip = req.ip ?? "";
6651
+ const ip = resolveClientAddress(req);
6612
6652
  const userAgent = String(req.headers["user-agent"] ?? "");
6613
6653
  dto = {
6614
6654
  ...dto,
@@ -6701,7 +6741,7 @@ exports.AuthService = class _AuthService {
6701
6741
  */
6702
6742
  async login(dto, req) {
6703
6743
  const tenantId = await this.resolveTenantId(dto.tenantId, req);
6704
- const ip = req.ip ?? "";
6744
+ const ip = resolveClientAddress(req);
6705
6745
  const userAgent = String(req.headers["user-agent"] ?? "");
6706
6746
  dto = {
6707
6747
  ...dto,
@@ -7780,7 +7820,7 @@ var AuthController = class {
7780
7820
  */
7781
7821
  async refresh(req, res) {
7782
7822
  const rawRefreshToken = this.tokenDelivery.extractRefreshToken(req) ?? "";
7783
- const ip = req.ip ?? "";
7823
+ const ip = resolveClientAddress(req);
7784
7824
  const userAgent = String(req.headers["user-agent"] ?? "");
7785
7825
  const rotated = await this.authService.refresh(rawRefreshToken, ip, userAgent);
7786
7826
  const authResult = {
@@ -9272,7 +9312,7 @@ var InvitationController = class {
9272
9312
  * @returns Auth response with tokens delivered per the configured `tokenDelivery` mode.
9273
9313
  */
9274
9314
  async accept(dto, req, res) {
9275
- const ip = req.ip ?? "";
9315
+ const ip = resolveClientAddress(req);
9276
9316
  const userAgent = String(req.headers["user-agent"] ?? "");
9277
9317
  const headers = req.headers;
9278
9318
  const result = await this.invitationService.acceptInvitation(dto, ip, userAgent, headers);
@@ -11015,7 +11055,7 @@ var MfaController = class {
11015
11055
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
11016
11056
  */
11017
11057
  async verifyEnable(user, dto, req) {
11018
- const ip = req.ip ?? "";
11058
+ const ip = resolveClientAddress(req);
11019
11059
  const userAgent = String(req.headers["user-agent"] ?? "");
11020
11060
  await this.mfaService.verifyAndEnable(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11021
11061
  }
@@ -11048,7 +11088,7 @@ var MfaController = class {
11048
11088
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
11049
11089
  */
11050
11090
  async challenge(dto, req, res) {
11051
- const ip = req.ip ?? "";
11091
+ const ip = resolveClientAddress(req);
11052
11092
  const userAgent = String(req.headers["user-agent"] ?? "");
11053
11093
  const cookieToken = readMfaTempCookie(req);
11054
11094
  const mfaTempToken = dto.mfaTempToken ?? cookieToken;
@@ -11087,7 +11127,7 @@ var MfaController = class {
11087
11127
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
11088
11128
  */
11089
11129
  async disable(user, dto, req) {
11090
- const ip = req.ip ?? "";
11130
+ const ip = resolveClientAddress(req);
11091
11131
  const userAgent = String(req.headers["user-agent"] ?? "");
11092
11132
  await this.mfaService.disable(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11093
11133
  }
@@ -11111,7 +11151,7 @@ var MfaController = class {
11111
11151
  * @returns The fresh plain-text recovery codes, one-time display.
11112
11152
  */
11113
11153
  async regenerateRecoveryCodes(user, dto, req) {
11114
- const ip = req.ip ?? "";
11154
+ const ip = resolveClientAddress(req);
11115
11155
  const userAgent = String(req.headers["user-agent"] ?? "");
11116
11156
  return this.mfaService.regenerateRecoveryCodes(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11117
11157
  }
@@ -12949,7 +12989,7 @@ var PlatformAuthController = class {
12949
12989
  * @param req - Incoming request (provides IP and User-Agent for session tracking).
12950
12990
  */
12951
12991
  async login(dto, req) {
12952
- const ip = req.ip ?? "";
12992
+ const ip = resolveClientAddress(req);
12953
12993
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
12954
12994
  const result = await this.platformAuthService.login(dto, ip, userAgent);
12955
12995
  if (isMfaChallenge2(result)) {
@@ -12978,7 +13018,7 @@ var PlatformAuthController = class {
12978
13018
  * @throws `PLATFORM_AUTH_REQUIRED` when the submitted MFA token has `context='dashboard'`.
12979
13019
  */
12980
13020
  async mfaChallenge(dto, req) {
12981
- const ip = req.ip ?? "";
13021
+ const ip = resolveClientAddress(req);
12982
13022
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
12983
13023
  if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
12984
13024
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
@@ -13042,7 +13082,7 @@ var PlatformAuthController = class {
13042
13082
  */
13043
13083
  async refresh(req) {
13044
13084
  const rawRefreshToken = this.tokenDelivery.extractPlatformRefreshToken(req) ?? "";
13045
- const ip = req.ip ?? "";
13085
+ const ip = resolveClientAddress(req);
13046
13086
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
13047
13087
  const rotated = await this.platformAuthService.refresh(rawRefreshToken, ip, userAgent);
13048
13088
  const admin = await this.platformAuthService.getMe(rotated.session.userId);
@@ -13229,7 +13269,7 @@ var PlatformMfaController = class {
13229
13269
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
13230
13270
  */
13231
13271
  async verifyEnable(user, dto, req) {
13232
- const ip = req.ip ?? "";
13272
+ const ip = resolveClientAddress(req);
13233
13273
  const userAgent = String(req.headers["user-agent"] ?? "");
13234
13274
  await this.mfaService.verifyAndEnable(user.sub, dto.code, ip, userAgent, "platform");
13235
13275
  }
@@ -13247,7 +13287,7 @@ var PlatformMfaController = class {
13247
13287
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
13248
13288
  */
13249
13289
  async disable(user, dto, req) {
13250
- const ip = req.ip ?? "";
13290
+ const ip = resolveClientAddress(req);
13251
13291
  const userAgent = String(req.headers["user-agent"] ?? "");
13252
13292
  await this.mfaService.disable(user.sub, dto.code, ip, userAgent, "platform");
13253
13293
  }
@@ -13267,7 +13307,7 @@ var PlatformMfaController = class {
13267
13307
  * @returns The fresh plain-text recovery codes, one-time display.
13268
13308
  */
13269
13309
  async regenerateRecoveryCodes(user, dto, req) {
13270
- const ip = req.ip ?? "";
13310
+ const ip = resolveClientAddress(req);
13271
13311
  const userAgent = String(req.headers["user-agent"] ?? "");
13272
13312
  return this.mfaService.regenerateRecoveryCodes(user.sub, dto.code, ip, userAgent, "platform");
13273
13313
  }
@@ -13906,7 +13946,7 @@ exports.ApiKeyGuard = class _ApiKeyGuard {
13906
13946
  ...partial,
13907
13947
  keyId: key?.id ?? null,
13908
13948
  label: key?.label ?? null,
13909
- ip: request.ip ?? ""
13949
+ ip: resolveClientAddress(request)
13910
13950
  };
13911
13951
  const context = this.hookContext(request);
13912
13952
  const run = /* @__PURE__ */ __name(() => hook.call(this.hooks, event, context), "run");
@@ -13931,7 +13971,7 @@ exports.ApiKeyGuard = class _ApiKeyGuard {
13931
13971
  hookContext(request) {
13932
13972
  const headers = Object.fromEntries(Object.entries(request.headers).filter(([name]) => name !== this.options.apiKeys.header));
13933
13973
  return {
13934
- ip: request.ip ?? "",
13974
+ ip: resolveClientAddress(request),
13935
13975
  userAgent: request.headers["user-agent"] ?? "",
13936
13976
  sanitizedHeaders: sanitizeHeaders(headers)
13937
13977
  };
@@ -14941,7 +14981,7 @@ var OAuthController = class _OAuthController {
14941
14981
  * payload, or `undefined` when a redirect was issued.
14942
14982
  */
14943
14983
  async callback(provider, query, req, res) {
14944
- const ip = (req.ip ?? "").slice(0, 64);
14984
+ const ip = resolveClientAddress(req).slice(0, 64);
14945
14985
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
14946
14986
  const stateCookie = readOAuthStateCookie(req);
14947
14987
  if (stateCookie !== void 0) {
@@ -455,7 +455,18 @@ interface IUserRepository {
455
455
  * - `'peer'` — the socket peer address, read directly from the connection. Never consults
456
456
  * `X-Forwarded-For`, so a spoofed header cannot buy an attacker a fresh budget.
457
457
  * - `'trusted-proxy'` — Express's `req.ip`, which honours the app's `trust proxy` setting and
458
- * therefore the forwarding headers it admits.
458
+ * therefore the forwarding headers it admits. When that entry is not an address the nearest
459
+ * trusted hop is used instead, and a non-address string is never the key.
460
+ *
461
+ * `'trusted-proxy'` is only as honest as the hops in front of the app. Behind such a proxy each
462
+ * hop appends the address it saw, so the client is the rightmost entry that is not itself a
463
+ * trusted proxy. A hop that forwards the client's own `X-Forwarded-For` unchanged lets the client
464
+ * choose its address, and a client that varies a valid address gets a fresh budget every time;
465
+ * behind such a hop use `'peer'`, or make the hop append or overwrite the header.
466
+ *
467
+ * Whichever source keys the limit, the address recorded on a session, passed in a hook's context
468
+ * and carried by an API-key audit event is the same validated one: an address, or an empty
469
+ * string when none can be read.
459
470
  */
460
471
  type ClientIpSource = 'peer' | 'trusted-proxy';
461
472
  /**
@@ -820,8 +831,13 @@ interface BymaxAuthModuleOptions {
820
831
  */
821
832
  resolveDomains?: (requestDomain: string) => string[];
822
833
  /**
823
- * `SameSite` attribute applied to every cookie issued by the module
824
- * (access token, refresh token, session signal). Default: `'lax'`.
834
+ * `SameSite` attribute applied to the access-token and session-signal cookies issued by
835
+ * the module. Default: `'lax'`.
836
+ *
837
+ * The refresh-token cookie does not follow this value except for `'none'`: it is issued
838
+ * `Strict` under `'lax'` and `'strict'`, because only the refresh route reads it and no
839
+ * cross-site request needs it. Under `'none'` it is `None` too, since a cross-site
840
+ * frontend's refresh call would otherwise carry no credential.
825
841
  *
826
842
  * Trade-offs:
827
843
  * - `'lax'` (default): cookies travel on top-level cross-site GET navigations.
@@ -5188,7 +5204,8 @@ interface PlatformBearerAuthResponse {
5188
5204
  * set. Use this for mobile/native clients or SPA with cross-origin APIs.
5189
5205
  * - `'both'`: Tokens are set as cookies AND returned in the response body.
5190
5206
  *
5191
- * Cookie security: HttpOnly, Secure (production), SameSite=Strict.
5207
+ * Cookie security: HttpOnly, Secure (production). The access and session-signal cookies follow
5208
+ * `cookies.sameSite`; the refresh cookie is SameSite=Strict unless `none` is configured.
5192
5209
  * Refresh cookies use the configured `cookies.refreshCookiePath`.
5193
5210
  *
5194
5211
  * @layer Service
@@ -5314,6 +5331,16 @@ declare class TokenDeliveryService {
5314
5331
  */
5315
5332
  extractDomain(req: Request): string | undefined;
5316
5333
  private setAuthCookies;
5334
+ /**
5335
+ * `SameSite` of the refresh cookie: Strict unless the deployment is cross-site (`none`).
5336
+ *
5337
+ * Only the refresh route reads this cookie, and a browser sends it there on the app's own
5338
+ * requests; withholding it from every cross-site request costs nothing, whereas the access and
5339
+ * session-signal cookies follow `cookies.sameSite` because the OAuth return trip needs them on
5340
+ * a cross-site top-level navigation. A `none` deployment must keep `none`, or its refresh call
5341
+ * would carry no credential.
5342
+ */
5343
+ private refreshSameSite;
5317
5344
  /** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
5318
5345
  private baseCookieOptions;
5319
5346
  /** Reads the value of the cookie identified by `name` from the request. */
@@ -5607,8 +5634,9 @@ declare class AuthRateLimitGuard implements CanActivate {
5607
5634
  * The address this request is counted against.
5608
5635
  *
5609
5636
  * `'peer'` — the default — reads the socket directly, so `X-Forwarded-For` cannot influence
5610
- * it. `'trusted-proxy'` uses `req.ip`, which honours the app's `trust proxy` setting and the
5611
- * forwarding headers it admits.
5637
+ * it. `'trusted-proxy'` uses the resolved client address, which starts from `req.ip` (honouring
5638
+ * the app's `trust proxy` setting and the forwarding headers it admits) and never returns a
5639
+ * string that is not an address, so a caller cannot mint a bucket by writing one.
5612
5640
  *
5613
5641
  * The default is the strict one because the two failure modes are not symmetric: keying on
5614
5642
  * the peer address behind a proxy over-counts, which is visible and recoverable, while
@@ -455,7 +455,18 @@ interface IUserRepository {
455
455
  * - `'peer'` — the socket peer address, read directly from the connection. Never consults
456
456
  * `X-Forwarded-For`, so a spoofed header cannot buy an attacker a fresh budget.
457
457
  * - `'trusted-proxy'` — Express's `req.ip`, which honours the app's `trust proxy` setting and
458
- * therefore the forwarding headers it admits.
458
+ * therefore the forwarding headers it admits. When that entry is not an address the nearest
459
+ * trusted hop is used instead, and a non-address string is never the key.
460
+ *
461
+ * `'trusted-proxy'` is only as honest as the hops in front of the app. Behind such a proxy each
462
+ * hop appends the address it saw, so the client is the rightmost entry that is not itself a
463
+ * trusted proxy. A hop that forwards the client's own `X-Forwarded-For` unchanged lets the client
464
+ * choose its address, and a client that varies a valid address gets a fresh budget every time;
465
+ * behind such a hop use `'peer'`, or make the hop append or overwrite the header.
466
+ *
467
+ * Whichever source keys the limit, the address recorded on a session, passed in a hook's context
468
+ * and carried by an API-key audit event is the same validated one: an address, or an empty
469
+ * string when none can be read.
459
470
  */
460
471
  type ClientIpSource = 'peer' | 'trusted-proxy';
461
472
  /**
@@ -820,8 +831,13 @@ interface BymaxAuthModuleOptions {
820
831
  */
821
832
  resolveDomains?: (requestDomain: string) => string[];
822
833
  /**
823
- * `SameSite` attribute applied to every cookie issued by the module
824
- * (access token, refresh token, session signal). Default: `'lax'`.
834
+ * `SameSite` attribute applied to the access-token and session-signal cookies issued by
835
+ * the module. Default: `'lax'`.
836
+ *
837
+ * The refresh-token cookie does not follow this value except for `'none'`: it is issued
838
+ * `Strict` under `'lax'` and `'strict'`, because only the refresh route reads it and no
839
+ * cross-site request needs it. Under `'none'` it is `None` too, since a cross-site
840
+ * frontend's refresh call would otherwise carry no credential.
825
841
  *
826
842
  * Trade-offs:
827
843
  * - `'lax'` (default): cookies travel on top-level cross-site GET navigations.
@@ -5188,7 +5204,8 @@ interface PlatformBearerAuthResponse {
5188
5204
  * set. Use this for mobile/native clients or SPA with cross-origin APIs.
5189
5205
  * - `'both'`: Tokens are set as cookies AND returned in the response body.
5190
5206
  *
5191
- * Cookie security: HttpOnly, Secure (production), SameSite=Strict.
5207
+ * Cookie security: HttpOnly, Secure (production). The access and session-signal cookies follow
5208
+ * `cookies.sameSite`; the refresh cookie is SameSite=Strict unless `none` is configured.
5192
5209
  * Refresh cookies use the configured `cookies.refreshCookiePath`.
5193
5210
  *
5194
5211
  * @layer Service
@@ -5314,6 +5331,16 @@ declare class TokenDeliveryService {
5314
5331
  */
5315
5332
  extractDomain(req: Request): string | undefined;
5316
5333
  private setAuthCookies;
5334
+ /**
5335
+ * `SameSite` of the refresh cookie: Strict unless the deployment is cross-site (`none`).
5336
+ *
5337
+ * Only the refresh route reads this cookie, and a browser sends it there on the app's own
5338
+ * requests; withholding it from every cross-site request costs nothing, whereas the access and
5339
+ * session-signal cookies follow `cookies.sameSite` because the OAuth return trip needs them on
5340
+ * a cross-site top-level navigation. A `none` deployment must keep `none`, or its refresh call
5341
+ * would carry no credential.
5342
+ */
5343
+ private refreshSameSite;
5317
5344
  /** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
5318
5345
  private baseCookieOptions;
5319
5346
  /** Reads the value of the cookie identified by `name` from the request. */
@@ -5607,8 +5634,9 @@ declare class AuthRateLimitGuard implements CanActivate {
5607
5634
  * The address this request is counted against.
5608
5635
  *
5609
5636
  * `'peer'` — the default — reads the socket directly, so `X-Forwarded-For` cannot influence
5610
- * it. `'trusted-proxy'` uses `req.ip`, which honours the app's `trust proxy` setting and the
5611
- * forwarding headers it admits.
5637
+ * it. `'trusted-proxy'` uses the resolved client address, which starts from `req.ip` (honouring
5638
+ * the app's `trust proxy` setting and the forwarding headers it admits) and never returns a
5639
+ * string that is not an address, so a caller cannot mint a bucket by writing one.
5612
5640
  *
5613
5641
  * The default is the strict one because the two failure modes are not symmetric: keying on
5614
5642
  * the peer address behind a proxy over-counts, which is visible and recoverable, while
@@ -5,7 +5,7 @@ import { randomInt, scrypt as scrypt$1, randomBytes, timingSafeEqual, randomUUID
5
5
  import { Throttle } from '@nestjs/throttler';
6
6
  import { Transform, plainToInstance } from 'class-transformer';
7
7
  import { IsEmail, MaxLength, IsString, MinLength, IsOptional, IsNotEmpty, Matches, Length, ValidateIf } from 'class-validator';
8
- import { isIPv6 } from 'net';
8
+ import { isIPv6, isIP } from 'net';
9
9
  import { promisify } from 'util';
10
10
 
11
11
  var __defProp = Object.defineProperty;
@@ -2887,6 +2887,31 @@ function isWsTicketSnapshot(value) {
2887
2887
  return typeof record["sub"] === "string" && typeof record["role"] === "string" && typeof record["status"] === "string" && typeof record["mfaEnabled"] === "boolean" && typeof record["mfaVerified"] === "boolean" && typeof record["jti"] === "string" && record["jti"] !== "" && typeof record["epoch"] === "number" && Number.isSafeInteger(record["epoch"]) && record["epoch"] >= 0 && (record["tenantId"] === void 0 || typeof record["tenantId"] === "string");
2888
2888
  }
2889
2889
  __name(isWsTicketSnapshot, "isWsTicketSnapshot");
2890
+ var IPV6 = 6;
2891
+ function isHeaderAddress(candidate) {
2892
+ return typeof candidate === "string" && !candidate.includes("%") && isIP(candidate) !== 0;
2893
+ }
2894
+ __name(isHeaderAddress, "isHeaderAddress");
2895
+ function peerAddress(remoteAddress) {
2896
+ if (typeof remoteAddress !== "string") return "";
2897
+ const zoneIndex = remoteAddress.indexOf("%");
2898
+ const bare = zoneIndex === -1 ? remoteAddress : remoteAddress.slice(0, zoneIndex);
2899
+ const family = isIP(bare);
2900
+ if (zoneIndex !== -1) return family === IPV6 ? bare : "";
2901
+ return family === 0 ? "" : bare;
2902
+ }
2903
+ __name(peerAddress, "peerAddress");
2904
+ function resolveClientAddress(request) {
2905
+ const hops = request.ips ?? [];
2906
+ for (const candidate of [
2907
+ request.ip,
2908
+ ...hops
2909
+ ]) {
2910
+ if (isHeaderAddress(candidate)) return candidate;
2911
+ }
2912
+ return peerAddress(request.socket?.remoteAddress);
2913
+ }
2914
+ __name(resolveClientAddress, "resolveClientAddress");
2890
2915
  var IPV6_GROUPS = 8;
2891
2916
  var IPV6_PREFIX_GROUPS = 4;
2892
2917
  function rateLimitBucket(address) {
@@ -3007,8 +3032,9 @@ var AuthRateLimitGuard = class {
3007
3032
  * The address this request is counted against.
3008
3033
  *
3009
3034
  * `'peer'` — the default — reads the socket directly, so `X-Forwarded-For` cannot influence
3010
- * it. `'trusted-proxy'` uses `req.ip`, which honours the app's `trust proxy` setting and the
3011
- * forwarding headers it admits.
3035
+ * it. `'trusted-proxy'` uses the resolved client address, which starts from `req.ip` (honouring
3036
+ * the app's `trust proxy` setting and the forwarding headers it admits) and never returns a
3037
+ * string that is not an address, so a caller cannot mint a bucket by writing one.
3012
3038
  *
3013
3039
  * The default is the strict one because the two failure modes are not symmetric: keying on
3014
3040
  * the peer address behind a proxy over-counts, which is visible and recoverable, while
@@ -3021,7 +3047,7 @@ var AuthRateLimitGuard = class {
3021
3047
  */
3022
3048
  clientIp(request) {
3023
3049
  if (this.options.rateLimit.clientIpSource === "trusted-proxy") {
3024
- return typeof request.ip === "string" && request.ip !== "" ? request.ip : UNKNOWN_CLIENT;
3050
+ return resolveClientAddress(request) || UNKNOWN_CLIENT;
3025
3051
  }
3026
3052
  const peer = request.socket?.remoteAddress;
3027
3053
  return typeof peer === "string" && peer !== "" ? peer : UNKNOWN_CLIENT;
@@ -3509,6 +3535,7 @@ var TokenDeliveryService = class {
3509
3535
  res.clearCookie(this.options.cookies.accessTokenName, cookieOpts);
3510
3536
  res.clearCookie(this.options.cookies.refreshTokenName, {
3511
3537
  ...cookieOpts,
3538
+ sameSite: this.refreshSameSite(),
3512
3539
  path: this.options.cookies.refreshCookiePath
3513
3540
  });
3514
3541
  res.clearCookie(this.options.cookies.sessionSignalName, {
@@ -3575,6 +3602,7 @@ var TokenDeliveryService = class {
3575
3602
  });
3576
3603
  res.cookie(this.options.cookies.refreshTokenName, rawRefreshToken, {
3577
3604
  ...base,
3605
+ sameSite: this.refreshSameSite(),
3578
3606
  httpOnly: true,
3579
3607
  secure: isProd,
3580
3608
  path: this.options.cookies.refreshCookiePath,
@@ -3587,6 +3615,18 @@ var TokenDeliveryService = class {
3587
3615
  maxAge: refreshMaxAge
3588
3616
  });
3589
3617
  }
3618
+ /**
3619
+ * `SameSite` of the refresh cookie: Strict unless the deployment is cross-site (`none`).
3620
+ *
3621
+ * Only the refresh route reads this cookie, and a browser sends it there on the app's own
3622
+ * requests; withholding it from every cross-site request costs nothing, whereas the access and
3623
+ * session-signal cookies follow `cookies.sameSite` because the OAuth return trip needs them on
3624
+ * a cross-site top-level navigation. A `none` deployment must keep `none`, or its refresh call
3625
+ * would carry no credential.
3626
+ */
3627
+ refreshSameSite() {
3628
+ return this.options.cookies.sameSite === "none" ? "none" : "strict";
3629
+ }
3590
3630
  /** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
3591
3631
  baseCookieOptions(domain) {
3592
3632
  return {
@@ -6606,7 +6646,7 @@ var AuthService = class _AuthService {
6606
6646
  */
6607
6647
  async register(dto, req) {
6608
6648
  const tenantId = await this.resolveTenantId(dto.tenantId, req);
6609
- const ip = req.ip ?? "";
6649
+ const ip = resolveClientAddress(req);
6610
6650
  const userAgent = String(req.headers["user-agent"] ?? "");
6611
6651
  dto = {
6612
6652
  ...dto,
@@ -6699,7 +6739,7 @@ var AuthService = class _AuthService {
6699
6739
  */
6700
6740
  async login(dto, req) {
6701
6741
  const tenantId = await this.resolveTenantId(dto.tenantId, req);
6702
- const ip = req.ip ?? "";
6742
+ const ip = resolveClientAddress(req);
6703
6743
  const userAgent = String(req.headers["user-agent"] ?? "");
6704
6744
  dto = {
6705
6745
  ...dto,
@@ -7778,7 +7818,7 @@ var AuthController = class {
7778
7818
  */
7779
7819
  async refresh(req, res) {
7780
7820
  const rawRefreshToken = this.tokenDelivery.extractRefreshToken(req) ?? "";
7781
- const ip = req.ip ?? "";
7821
+ const ip = resolveClientAddress(req);
7782
7822
  const userAgent = String(req.headers["user-agent"] ?? "");
7783
7823
  const rotated = await this.authService.refresh(rawRefreshToken, ip, userAgent);
7784
7824
  const authResult = {
@@ -9270,7 +9310,7 @@ var InvitationController = class {
9270
9310
  * @returns Auth response with tokens delivered per the configured `tokenDelivery` mode.
9271
9311
  */
9272
9312
  async accept(dto, req, res) {
9273
- const ip = req.ip ?? "";
9313
+ const ip = resolveClientAddress(req);
9274
9314
  const userAgent = String(req.headers["user-agent"] ?? "");
9275
9315
  const headers = req.headers;
9276
9316
  const result = await this.invitationService.acceptInvitation(dto, ip, userAgent, headers);
@@ -11013,7 +11053,7 @@ var MfaController = class {
11013
11053
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
11014
11054
  */
11015
11055
  async verifyEnable(user, dto, req) {
11016
- const ip = req.ip ?? "";
11056
+ const ip = resolveClientAddress(req);
11017
11057
  const userAgent = String(req.headers["user-agent"] ?? "");
11018
11058
  await this.mfaService.verifyAndEnable(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11019
11059
  }
@@ -11046,7 +11086,7 @@ var MfaController = class {
11046
11086
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
11047
11087
  */
11048
11088
  async challenge(dto, req, res) {
11049
- const ip = req.ip ?? "";
11089
+ const ip = resolveClientAddress(req);
11050
11090
  const userAgent = String(req.headers["user-agent"] ?? "");
11051
11091
  const cookieToken = readMfaTempCookie(req);
11052
11092
  const mfaTempToken = dto.mfaTempToken ?? cookieToken;
@@ -11085,7 +11125,7 @@ var MfaController = class {
11085
11125
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
11086
11126
  */
11087
11127
  async disable(user, dto, req) {
11088
- const ip = req.ip ?? "";
11128
+ const ip = resolveClientAddress(req);
11089
11129
  const userAgent = String(req.headers["user-agent"] ?? "");
11090
11130
  await this.mfaService.disable(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11091
11131
  }
@@ -11109,7 +11149,7 @@ var MfaController = class {
11109
11149
  * @returns The fresh plain-text recovery codes, one-time display.
11110
11150
  */
11111
11151
  async regenerateRecoveryCodes(user, dto, req) {
11112
- const ip = req.ip ?? "";
11152
+ const ip = resolveClientAddress(req);
11113
11153
  const userAgent = String(req.headers["user-agent"] ?? "");
11114
11154
  return this.mfaService.regenerateRecoveryCodes(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11115
11155
  }
@@ -12947,7 +12987,7 @@ var PlatformAuthController = class {
12947
12987
  * @param req - Incoming request (provides IP and User-Agent for session tracking).
12948
12988
  */
12949
12989
  async login(dto, req) {
12950
- const ip = req.ip ?? "";
12990
+ const ip = resolveClientAddress(req);
12951
12991
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
12952
12992
  const result = await this.platformAuthService.login(dto, ip, userAgent);
12953
12993
  if (isMfaChallenge2(result)) {
@@ -12976,7 +13016,7 @@ var PlatformAuthController = class {
12976
13016
  * @throws `PLATFORM_AUTH_REQUIRED` when the submitted MFA token has `context='dashboard'`.
12977
13017
  */
12978
13018
  async mfaChallenge(dto, req) {
12979
- const ip = req.ip ?? "";
13019
+ const ip = resolveClientAddress(req);
12980
13020
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
12981
13021
  if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
12982
13022
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
@@ -13040,7 +13080,7 @@ var PlatformAuthController = class {
13040
13080
  */
13041
13081
  async refresh(req) {
13042
13082
  const rawRefreshToken = this.tokenDelivery.extractPlatformRefreshToken(req) ?? "";
13043
- const ip = req.ip ?? "";
13083
+ const ip = resolveClientAddress(req);
13044
13084
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
13045
13085
  const rotated = await this.platformAuthService.refresh(rawRefreshToken, ip, userAgent);
13046
13086
  const admin = await this.platformAuthService.getMe(rotated.session.userId);
@@ -13227,7 +13267,7 @@ var PlatformMfaController = class {
13227
13267
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
13228
13268
  */
13229
13269
  async verifyEnable(user, dto, req) {
13230
- const ip = req.ip ?? "";
13270
+ const ip = resolveClientAddress(req);
13231
13271
  const userAgent = String(req.headers["user-agent"] ?? "");
13232
13272
  await this.mfaService.verifyAndEnable(user.sub, dto.code, ip, userAgent, "platform");
13233
13273
  }
@@ -13245,7 +13285,7 @@ var PlatformMfaController = class {
13245
13285
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
13246
13286
  */
13247
13287
  async disable(user, dto, req) {
13248
- const ip = req.ip ?? "";
13288
+ const ip = resolveClientAddress(req);
13249
13289
  const userAgent = String(req.headers["user-agent"] ?? "");
13250
13290
  await this.mfaService.disable(user.sub, dto.code, ip, userAgent, "platform");
13251
13291
  }
@@ -13265,7 +13305,7 @@ var PlatformMfaController = class {
13265
13305
  * @returns The fresh plain-text recovery codes, one-time display.
13266
13306
  */
13267
13307
  async regenerateRecoveryCodes(user, dto, req) {
13268
- const ip = req.ip ?? "";
13308
+ const ip = resolveClientAddress(req);
13269
13309
  const userAgent = String(req.headers["user-agent"] ?? "");
13270
13310
  return this.mfaService.regenerateRecoveryCodes(user.sub, dto.code, ip, userAgent, "platform");
13271
13311
  }
@@ -13904,7 +13944,7 @@ var ApiKeyGuard = class _ApiKeyGuard {
13904
13944
  ...partial,
13905
13945
  keyId: key?.id ?? null,
13906
13946
  label: key?.label ?? null,
13907
- ip: request.ip ?? ""
13947
+ ip: resolveClientAddress(request)
13908
13948
  };
13909
13949
  const context = this.hookContext(request);
13910
13950
  const run = /* @__PURE__ */ __name(() => hook.call(this.hooks, event, context), "run");
@@ -13929,7 +13969,7 @@ var ApiKeyGuard = class _ApiKeyGuard {
13929
13969
  hookContext(request) {
13930
13970
  const headers = Object.fromEntries(Object.entries(request.headers).filter(([name]) => name !== this.options.apiKeys.header));
13931
13971
  return {
13932
- ip: request.ip ?? "",
13972
+ ip: resolveClientAddress(request),
13933
13973
  userAgent: request.headers["user-agent"] ?? "",
13934
13974
  sanitizedHeaders: sanitizeHeaders(headers)
13935
13975
  };
@@ -14939,7 +14979,7 @@ var OAuthController = class _OAuthController {
14939
14979
  * payload, or `undefined` when a redirect was issued.
14940
14980
  */
14941
14981
  async callback(provider, query, req, res) {
14942
- const ip = (req.ip ?? "").slice(0, 64);
14982
+ const ip = resolveClientAddress(req).slice(0, 64);
14943
14983
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
14944
14984
  const stateCookie = readOAuthStateCookie(req);
14945
14985
  if (stateCookie !== void 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.4.11",
3
+ "version": "1.4.13",
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",