@bymax-one/nest-auth 1.4.12 → 1.4.14

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,80 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.14] - 2026-11-01
22
+
23
+ ### Apply to a derived backend
24
+
25
+ - **A dashboard MFA temp token presented at `POST /platform/mfa/challenge` is refused before
26
+ anything is spent.** The route answered `401 auth.platform_auth_required` as documented, but only
27
+ after the challenge had run: it consumed the token, burned the TOTP code, stored a dashboard
28
+ session whose refresh token nobody received, stamped the last login and fired the login hooks.
29
+ That orphan session counted against the per-user session limit and could evict a real one, the
30
+ hooks reported a login that never answered, and the user had to start over because the token was
31
+ spent. The plane is now read from the token first, so the refusal spends nothing, and the same
32
+ token and code still complete at the dashboard challenge route. A refused attempt does not count toward the
33
+ brute-force counter either. The error code is unchanged, and the dashboard route keeps serving
34
+ both planes. A handler that relied on `afterLogin` or `onNewSession` firing for such a request
35
+ no longer sees it.
36
+ - **`MfaService` has a new public member, `challengePlatformOnly(mfaTempToken, code, ip,
37
+ userAgent)`.** It is the challenge for an entry point that serves the platform plane only: it
38
+ refuses a non-platform plane with `PLATFORM_AUTH_REQUIRED` before any side effect, then runs the
39
+ challenge and returns a `PlatformAuthResult`. A host that mounts its own platform challenge route
40
+ can call it to get the same refusal. `challenge()` is unchanged.
41
+ - **Logout fails when it cannot revoke.** `POST /auth/logout` and `POST /platform/logout` used to
42
+ answer success even when the store refused one of the writes that revoke the caller's
43
+ credentials. Every credential write is now attempted, whatever the earlier ones did, and the first
44
+ failure is raised once the rest have run. The route answers a 5xx instead of `204` and does not
45
+ clear the caller's cookies, so the client can retry. On the platform route, a session's index entry
46
+ is removed only after the credential it names is deleted, so a later sign-out-everywhere can still
47
+ find a session that logout could not end. A token that cannot be verified (absent, expired, forged) still logs out as
48
+ before, and a store that cannot answer the initial read still fails closed. A host that treated a
49
+ `204` from logout as proof of revocation now sees a 5xx during a store outage. The logout hook
50
+ (`afterLogout`, `afterPlatformLogout`) is fired by the call that finds the session record: when an
51
+ earlier attempt deleted the record and failed another write, it answered a 5xx without the hook,
52
+ and the retry that completes the logout finds no record and does not fire it.
53
+
54
+ ### Fixed
55
+
56
+ - **A refused cross-plane MFA challenge left an orphan session behind.** See the Apply note above.
57
+ - **Logout reported success when a revocation write was refused.** See the Apply note above.
58
+
59
+ ## [1.4.13] - 2026-11-01
60
+
61
+ ### Apply to a derived backend
62
+
63
+ - **A client address that is not an address is no longer a rate-limit key, and no longer reaches a
64
+ hook, a session or an audit event.** With `rateLimit.clientIpSource: 'trusted-proxy'` the limiter
65
+ keyed on `req.ip`, and behind a hop that forwards the client's own `X-Forwarded-For` unchanged
66
+ Express returns the first entry its `trust proxy` setting does not trust, which is an arbitrary
67
+ string when that entry is not an address. A client that varied it on every request got a fresh
68
+ budget each time. One function now resolves
69
+ the address for the limiter and for every place that records it: `req.ip`, then the rest of
70
+ `req.ips` (the trusted hops, nearest the client first), then the socket peer, taking the first
71
+ that is an address. A header entry that carries an IPv6 zone index is not one, while the socket peer's zone,
72
+ which a link-local peer reports, is cut. An unparsable client entry is therefore
73
+ charged to the nearest trusted hop, so every caller that sends one shares that hop's bucket; a
74
+ chain with no address in it at all falls back to the shared unknown bucket, as before.
75
+ **What consumers see differently:** `HookContext.ip`, which every hook receives, and the `ip` of
76
+ 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`
77
+ stored on a session and shown by the sessions list and the new-session email follows the same
78
+ value. In `clientIpSource: 'peer'` the limiter still keys on the socket; the recorded address
79
+ still comes from `req.ip` when the application sets `trust proxy`, and is validated the same
80
+ way.
81
+ **Not changed:**
82
+ `'trusted-proxy'` is only as honest as the hops in front of the app. Behind such a proxy each hop
83
+ appends the address it saw, so the client is the rightmost entry that is not itself a trusted
84
+ proxy. A hop that forwards the client's own `X-Forwarded-For` unchanged lets the client choose
85
+ its address even when every entry is a valid one, and a client that varies a valid address still
86
+ gets a fresh budget each time. Behind
87
+ such a hop use `'peer'`, or make the hop append or overwrite the header.
88
+
89
+ ### Fixed
90
+
91
+ - **The per-address rate limit could be bypassed behind a proxy that forwards `X-Forwarded-For`
92
+ unchanged.** See the Apply note above.
93
+ - **A client-written non-address string could reach hook payloads and API-key audit events.** See the Apply note above.
94
+
21
95
  ## [1.4.12] - 2026-11-01
22
96
 
23
97
  ### Apply to a derived backend
@@ -4185,7 +4259,9 @@ ever installable.
4185
4259
  - 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
4186
4260
  - 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
4187
4261
 
4188
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.12...HEAD
4262
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.14...HEAD
4263
+ [1.4.14]: https://github.com/bymaxone/nest-auth/compare/v1.4.13...v1.4.14
4264
+ [1.4.13]: https://github.com/bymaxone/nest-auth/compare/v1.4.12...v1.4.13
4189
4265
  [1.4.12]: https://github.com/bymaxone/nest-auth/compare/v1.4.11...v1.4.12
4190
4266
  [1.4.11]: https://github.com/bymaxone/nest-auth/compare/v1.4.10...v1.4.11
4191
4267
  [1.4.10]: https://github.com/bymaxone/nest-auth/compare/v1.4.9...v1.4.10
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
@@ -1037,6 +1037,9 @@ declare const CLIENT_REFRESH_ROUTE: "/api/auth/client-refresh";
1037
1037
  * A user who pressed "logout" MUST end up logged out of the browser
1038
1038
  * session even if the upstream is unreachable — otherwise a network
1039
1039
  * glitch leaves them with cookies they thought they had invalidated.
1040
+ * The upstream's answer is not surfaced to the caller, so a logout the
1041
+ * server could not complete (it answers a 5xx when the store refuses a
1042
+ * revocation write) looks the same as one that did.
1040
1043
  *
1041
1044
  * Two response modes are supported, expressed as a discriminated
1042
1045
  * union on {@link LogoutHandlerConfig}:
@@ -1037,6 +1037,9 @@ declare const CLIENT_REFRESH_ROUTE: "/api/auth/client-refresh";
1037
1037
  * A user who pressed "logout" MUST end up logged out of the browser
1038
1038
  * session even if the upstream is unreachable — otherwise a network
1039
1039
  * glitch leaves them with cookies they thought they had invalidated.
1040
+ * The upstream's answer is not surfaced to the caller, so a logout the
1041
+ * server could not complete (it answers a 5xx when the store refuses a
1042
+ * revocation write) looks the same as one that did.
1040
1043
  *
1041
1044
  * Two response modes are supported, expressed as a discriminated
1042
1045
  * union on {@link LogoutHandlerConfig}:
@@ -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;
@@ -6456,6 +6482,32 @@ function safeLogLine(line, secrets) {
6456
6482
  }
6457
6483
  __name(safeLogLine, "safeLogLine");
6458
6484
 
6485
+ // src/server/utils/settle-writes.ts
6486
+ async function settleWrites(writes) {
6487
+ const failures = [];
6488
+ for (const write of writes) {
6489
+ try {
6490
+ await write();
6491
+ } catch (err) {
6492
+ failures.push(err);
6493
+ }
6494
+ }
6495
+ return failures;
6496
+ }
6497
+ __name(settleWrites, "settleWrites");
6498
+ function raiseFirst(failures) {
6499
+ const [first] = failures;
6500
+ if (failures.length > 0) throw first;
6501
+ }
6502
+ __name(raiseFirst, "raiseFirst");
6503
+ function settleAfter(first, followUps) {
6504
+ return async () => {
6505
+ await first();
6506
+ raiseFirst(await settleWrites(followUps));
6507
+ };
6508
+ }
6509
+ __name(settleAfter, "settleAfter");
6510
+
6459
6511
  // src/server/utils/tenant-scoped.ts
6460
6512
  function tenantScoped(user, tenantId) {
6461
6513
  if (user === null) return null;
@@ -6622,7 +6674,7 @@ exports.AuthService = class _AuthService {
6622
6674
  */
6623
6675
  async register(dto, req) {
6624
6676
  const tenantId = await this.resolveTenantId(dto.tenantId, req);
6625
- const ip = req.ip ?? "";
6677
+ const ip = resolveClientAddress(req);
6626
6678
  const userAgent = String(req.headers["user-agent"] ?? "");
6627
6679
  dto = {
6628
6680
  ...dto,
@@ -6715,7 +6767,7 @@ exports.AuthService = class _AuthService {
6715
6767
  */
6716
6768
  async login(dto, req) {
6717
6769
  const tenantId = await this.resolveTenantId(dto.tenantId, req);
6718
- const ip = req.ip ?? "";
6770
+ const ip = resolveClientAddress(req);
6719
6771
  const userAgent = String(req.headers["user-agent"] ?? "");
6720
6772
  dto = {
6721
6773
  ...dto,
@@ -6860,17 +6912,22 @@ exports.AuthService = class _AuthService {
6860
6912
  const sessionHash = sha256(rawRefreshToken);
6861
6913
  const { userId, tenantId } = await this.redis.readSessionOwner(`rt:${sessionHash}`);
6862
6914
  this.logger.log(`logout: userId=${logSafe(userId || "(no live session)")}`);
6915
+ let blacklist = [];
6863
6916
  try {
6864
6917
  const payload = this.tokenManager.verifyIgnoringExpiry(accessToken);
6865
- const now = Math.floor(Date.now() / 1e3);
6866
- const remainingTtl = payload.exp - now;
6918
+ const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
6867
6919
  if (remainingTtl > 0) {
6868
- await this.redis.set(`rv:${payload.jti}`, "1", remainingTtl);
6920
+ blacklist = [
6921
+ () => this.redis.set(`rv:${payload.jti}`, "1", remainingTtl)
6922
+ ];
6869
6923
  }
6870
6924
  } catch {
6871
6925
  }
6872
- await this.redis.del(`rt:${sessionHash}`);
6873
- await this.redis.del(`rp:${sessionHash}`);
6926
+ const failures = await settleWrites([
6927
+ ...blacklist,
6928
+ () => this.redis.del(`rt:${sessionHash}`),
6929
+ () => this.redis.del(`rp:${sessionHash}`)
6930
+ ]);
6874
6931
  if (this.options.sessions.enabled && userId && tenantId !== void 0) {
6875
6932
  await this.sessionService.revokeSession({
6876
6933
  userId,
@@ -6883,6 +6940,7 @@ exports.AuthService = class _AuthService {
6883
6940
  }
6884
6941
  });
6885
6942
  }
6943
+ raiseFirst(failures);
6886
6944
  this.emitLogout(userId, tenantId);
6887
6945
  return userId;
6888
6946
  }
@@ -7770,8 +7828,9 @@ var AuthController = class {
7770
7828
  * token is the credential that authorizes this, and the service reads the session's owner
7771
7829
  * from the stored record rather than from the access token's claims.
7772
7830
  *
7773
- * Always 204: a caller presenting a token for an already-gone session gets their cookies
7774
- * cleared and learns nothing about whether a session existed.
7831
+ * A caller presenting a token for an already-gone session gets a 204 with their cookies
7832
+ * cleared and learns nothing about whether a session existed. When the store refuses a
7833
+ * revocation write the route answers a 5xx and leaves the cookies in place, so the client can retry.
7775
7834
  *
7776
7835
  * @param req - Incoming request (used to extract tokens).
7777
7836
  * @param res - Response object (passthrough — used to clear cookies).
@@ -7794,7 +7853,7 @@ var AuthController = class {
7794
7853
  */
7795
7854
  async refresh(req, res) {
7796
7855
  const rawRefreshToken = this.tokenDelivery.extractRefreshToken(req) ?? "";
7797
- const ip = req.ip ?? "";
7856
+ const ip = resolveClientAddress(req);
7798
7857
  const userAgent = String(req.headers["user-agent"] ?? "");
7799
7858
  const rotated = await this.authService.refresh(rawRefreshToken, ip, userAgent);
7800
7859
  const authResult = {
@@ -9286,7 +9345,7 @@ var InvitationController = class {
9286
9345
  * @returns Auth response with tokens delivered per the configured `tokenDelivery` mode.
9287
9346
  */
9288
9347
  async accept(dto, req, res) {
9289
- const ip = req.ip ?? "";
9348
+ const ip = resolveClientAddress(req);
9290
9349
  const userAgent = String(req.headers["user-agent"] ?? "");
9291
9350
  const headers = req.headers;
9292
9351
  const result = await this.invitationService.acceptInvitation(dto, ip, userAgent, headers);
@@ -10403,6 +10462,37 @@ exports.MfaService = class _MfaService {
10403
10462
  }
10404
10463
  return result;
10405
10464
  }
10465
+ /**
10466
+ * The challenge for an entry point that serves the platform plane only.
10467
+ *
10468
+ * Reads the plane from the temp token first and refuses a dashboard token with
10469
+ * `PLATFORM_AUTH_REQUIRED` before anything is spent. {@link MfaService.challenge} consumes the
10470
+ * token, burns the TOTP code, stores a session, stamps the last login and fires the hooks, so
10471
+ * refusing after it leaves an orphan session nobody holds a token for. The first verification only
10472
+ * reads: it touches neither the brute-force counter nor the TOTP anti-replay key. The challenge
10473
+ * verifies the token again, and the plane is a signed claim, so both reads see the same one.
10474
+ *
10475
+ * @param mfaTempToken - Short-lived MFA challenge JWT issued at platform login.
10476
+ * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
10477
+ * @param ip - Client IP address for session audit.
10478
+ * @param userAgent - User-Agent header for session description.
10479
+ * @returns The platform auth result.
10480
+ * @throws `PLATFORM_AUTH_REQUIRED` if the token is for the dashboard plane.
10481
+ * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
10482
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
10483
+ * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
10484
+ */
10485
+ async challengePlatformOnly(mfaTempToken, code, ip, userAgent) {
10486
+ const { context } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
10487
+ if (context !== "platform") {
10488
+ throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
10489
+ }
10490
+ const result = await this.challenge(mfaTempToken, code, ip, userAgent);
10491
+ if (!("admin" in result)) {
10492
+ throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
10493
+ }
10494
+ return result;
10495
+ }
10406
10496
  // ---------------------------------------------------------------------------
10407
10497
  // disable — TOTP-verified MFA deactivation with session invalidation
10408
10498
  // ---------------------------------------------------------------------------
@@ -11029,7 +11119,7 @@ var MfaController = class {
11029
11119
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
11030
11120
  */
11031
11121
  async verifyEnable(user, dto, req) {
11032
- const ip = req.ip ?? "";
11122
+ const ip = resolveClientAddress(req);
11033
11123
  const userAgent = String(req.headers["user-agent"] ?? "");
11034
11124
  await this.mfaService.verifyAndEnable(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11035
11125
  }
@@ -11062,7 +11152,7 @@ var MfaController = class {
11062
11152
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
11063
11153
  */
11064
11154
  async challenge(dto, req, res) {
11065
- const ip = req.ip ?? "";
11155
+ const ip = resolveClientAddress(req);
11066
11156
  const userAgent = String(req.headers["user-agent"] ?? "");
11067
11157
  const cookieToken = readMfaTempCookie(req);
11068
11158
  const mfaTempToken = dto.mfaTempToken ?? cookieToken;
@@ -11101,7 +11191,7 @@ var MfaController = class {
11101
11191
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
11102
11192
  */
11103
11193
  async disable(user, dto, req) {
11104
- const ip = req.ip ?? "";
11194
+ const ip = resolveClientAddress(req);
11105
11195
  const userAgent = String(req.headers["user-agent"] ?? "");
11106
11196
  await this.mfaService.disable(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11107
11197
  }
@@ -11125,7 +11215,7 @@ var MfaController = class {
11125
11215
  * @returns The fresh plain-text recovery codes, one-time display.
11126
11216
  */
11127
11217
  async regenerateRecoveryCodes(user, dto, req) {
11128
- const ip = req.ip ?? "";
11218
+ const ip = resolveClientAddress(req);
11129
11219
  const userAgent = String(req.headers["user-agent"] ?? "");
11130
11220
  return this.mfaService.regenerateRecoveryCodes(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11131
11221
  }
@@ -12724,22 +12814,30 @@ exports.PlatformAuthService = class _PlatformAuthService {
12724
12814
  const tokenHash = sha256(rawRefreshToken);
12725
12815
  const { userId } = await this.redis.readSessionOwner(`prt:${tokenHash}`);
12726
12816
  this.logger.log(`logout: adminId=${logSafe(userId || "(no live session)")}`);
12817
+ let blacklist = [];
12727
12818
  try {
12728
12819
  const payload = this.tokenManager.verifyPlatformIgnoringExpiry(accessToken);
12729
12820
  const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
12730
12821
  if (remainingTtl > 0) {
12731
- await this.redis.set(`rv:${payload.jti}`, "1", remainingTtl);
12822
+ blacklist = [
12823
+ () => this.redis.set(`rv:${payload.jti}`, "1", remainingTtl)
12824
+ ];
12732
12825
  }
12733
12826
  } catch {
12734
12827
  }
12735
- await this.redis.del("prt:" + tokenHash);
12736
- await this.redis.del("prp:" + tokenHash);
12737
- if (userId) {
12738
- const index = sessionIndexKey("platform", userId, this.options.hmacKey, void 0);
12739
- await this.redis.srem(index, "prt:" + tokenHash);
12740
- await this.redis.srem(index, "prp:" + tokenHash);
12741
- }
12742
- await this.redis.del("psd:" + tokenHash);
12828
+ const index = userId ? sessionIndexKey("platform", userId, this.options.hmacKey, void 0) : "";
12829
+ const prune = /* @__PURE__ */ __name((member) => index === "" ? [] : [
12830
+ () => this.redis.srem(index, member)
12831
+ ], "prune");
12832
+ const failures = await settleWrites([
12833
+ ...blacklist,
12834
+ settleAfter(() => this.redis.del("prt:" + tokenHash), [
12835
+ ...prune("prt:" + tokenHash),
12836
+ () => this.redis.del("psd:" + tokenHash)
12837
+ ]),
12838
+ settleAfter(() => this.redis.del("prp:" + tokenHash), prune("prp:" + tokenHash))
12839
+ ]);
12840
+ raiseFirst(failures);
12743
12841
  this.emitPlatformLogout(userId);
12744
12842
  return userId;
12745
12843
  }
@@ -12929,10 +13027,6 @@ function _ts_param27(paramIndex, decorator) {
12929
13027
  };
12930
13028
  }
12931
13029
  __name(_ts_param27, "_ts_param");
12932
- function isPlatformResult2(result) {
12933
- return "admin" in result;
12934
- }
12935
- __name(isPlatformResult2, "isPlatformResult");
12936
13030
  function isMfaChallenge2(result) {
12937
13031
  return "mfaRequired" in result && result.mfaRequired === true;
12938
13032
  }
@@ -12963,7 +13057,7 @@ var PlatformAuthController = class {
12963
13057
  * @param req - Incoming request (provides IP and User-Agent for session tracking).
12964
13058
  */
12965
13059
  async login(dto, req) {
12966
- const ip = req.ip ?? "";
13060
+ const ip = resolveClientAddress(req);
12967
13061
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
12968
13062
  const result = await this.platformAuthService.login(dto, ip, userAgent);
12969
13063
  if (isMfaChallenge2(result)) {
@@ -12978,30 +13072,20 @@ var PlatformAuthController = class {
12978
13072
  * Completes a platform administrator MFA challenge.
12979
13073
  *
12980
13074
  * Exchanges a short-lived `mfaTempToken` (issued at login) and a TOTP code for
12981
- * full platform auth tokens. The `context: 'platform'` in the temp token directs
12982
- * {@link MfaService.challenge} to issue a {@link PlatformAuthResult}.
12983
- *
12984
- * Explicitly guards against cross-context token abuse: if a dashboard-context MFA
12985
- * temp token is submitted here, the response will contain an `AuthResult` (not a
12986
- * `PlatformAuthResult`). The `isPlatformResult` check detects this and throws
12987
- * `PLATFORM_AUTH_REQUIRED` rather than silently returning a dashboard-scoped token
12988
- * as if it were a platform auth response.
13075
+ * full platform auth tokens through {@link MfaService.challengePlatformOnly}, which refuses a
13076
+ * dashboard-context token before anything is spent.
12989
13077
  *
12990
13078
  * @param dto - Contains the MFA temp token and the TOTP (or recovery) code.
12991
13079
  * @param req - Incoming request (provides IP and User-Agent for brute-force tracking).
12992
13080
  * @throws `PLATFORM_AUTH_REQUIRED` when the submitted MFA token has `context='dashboard'`.
12993
13081
  */
12994
13082
  async mfaChallenge(dto, req) {
12995
- const ip = req.ip ?? "";
13083
+ const ip = resolveClientAddress(req);
12996
13084
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
12997
13085
  if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
12998
13086
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
12999
13087
  }
13000
- const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
13001
- if (!isPlatformResult2(result)) {
13002
- throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
13003
- }
13004
- return this.tokenDelivery.deliverPlatformAuthResponse(result);
13088
+ return this.tokenDelivery.deliverPlatformAuthResponse(await this.mfaService.challengePlatformOnly(dto.mfaTempToken, dto.code, ip, userAgent));
13005
13089
  }
13006
13090
  // ---------------------------------------------------------------------------
13007
13091
  // GET /platform/me
@@ -13056,7 +13140,7 @@ var PlatformAuthController = class {
13056
13140
  */
13057
13141
  async refresh(req) {
13058
13142
  const rawRefreshToken = this.tokenDelivery.extractPlatformRefreshToken(req) ?? "";
13059
- const ip = req.ip ?? "";
13143
+ const ip = resolveClientAddress(req);
13060
13144
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
13061
13145
  const rotated = await this.platformAuthService.refresh(rawRefreshToken, ip, userAgent);
13062
13146
  const admin = await this.platformAuthService.getMe(rotated.session.userId);
@@ -13243,7 +13327,7 @@ var PlatformMfaController = class {
13243
13327
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
13244
13328
  */
13245
13329
  async verifyEnable(user, dto, req) {
13246
- const ip = req.ip ?? "";
13330
+ const ip = resolveClientAddress(req);
13247
13331
  const userAgent = String(req.headers["user-agent"] ?? "");
13248
13332
  await this.mfaService.verifyAndEnable(user.sub, dto.code, ip, userAgent, "platform");
13249
13333
  }
@@ -13261,7 +13345,7 @@ var PlatformMfaController = class {
13261
13345
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
13262
13346
  */
13263
13347
  async disable(user, dto, req) {
13264
- const ip = req.ip ?? "";
13348
+ const ip = resolveClientAddress(req);
13265
13349
  const userAgent = String(req.headers["user-agent"] ?? "");
13266
13350
  await this.mfaService.disable(user.sub, dto.code, ip, userAgent, "platform");
13267
13351
  }
@@ -13281,7 +13365,7 @@ var PlatformMfaController = class {
13281
13365
  * @returns The fresh plain-text recovery codes, one-time display.
13282
13366
  */
13283
13367
  async regenerateRecoveryCodes(user, dto, req) {
13284
- const ip = req.ip ?? "";
13368
+ const ip = resolveClientAddress(req);
13285
13369
  const userAgent = String(req.headers["user-agent"] ?? "");
13286
13370
  return this.mfaService.regenerateRecoveryCodes(user.sub, dto.code, ip, userAgent, "platform");
13287
13371
  }
@@ -13920,7 +14004,7 @@ exports.ApiKeyGuard = class _ApiKeyGuard {
13920
14004
  ...partial,
13921
14005
  keyId: key?.id ?? null,
13922
14006
  label: key?.label ?? null,
13923
- ip: request.ip ?? ""
14007
+ ip: resolveClientAddress(request)
13924
14008
  };
13925
14009
  const context = this.hookContext(request);
13926
14010
  const run = /* @__PURE__ */ __name(() => hook.call(this.hooks, event, context), "run");
@@ -13945,7 +14029,7 @@ exports.ApiKeyGuard = class _ApiKeyGuard {
13945
14029
  hookContext(request) {
13946
14030
  const headers = Object.fromEntries(Object.entries(request.headers).filter(([name]) => name !== this.options.apiKeys.header));
13947
14031
  return {
13948
- ip: request.ip ?? "",
14032
+ ip: resolveClientAddress(request),
13949
14033
  userAgent: request.headers["user-agent"] ?? "",
13950
14034
  sanitizedHeaders: sanitizeHeaders(headers)
13951
14035
  };
@@ -14955,7 +15039,7 @@ var OAuthController = class _OAuthController {
14955
15039
  * payload, or `undefined` when a redirect was issued.
14956
15040
  */
14957
15041
  async callback(provider, query, req, res) {
14958
- const ip = (req.ip ?? "").slice(0, 64);
15042
+ const ip = resolveClientAddress(req).slice(0, 64);
14959
15043
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
14960
15044
  const stateCookie = readOAuthStateCookie(req);
14961
15045
  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
  /**
@@ -3101,6 +3112,11 @@ interface IAuthHooks {
3101
3112
  * Use this hook to clean up session-related state, emit audit events, or
3102
3113
  * notify downstream services.
3103
3114
  *
3115
+ * Fired by the call that finds the session record and names its owner. If an earlier attempt
3116
+ * deleted the record but failed another revocation write, it answered a 5xx without this hook,
3117
+ * and the retry that completes the logout finds no record, so it names nobody and does not fire
3118
+ * it: that logout is never reported here.
3119
+ *
3104
3120
  * @param userId - The internal ID of the user who logged out.
3105
3121
  * @param context - Request metadata (IP, user agent, sanitized headers).
3106
3122
  */
@@ -3118,6 +3134,10 @@ interface IAuthHooks {
3118
3134
  * the access token stays presentable until it expires, and the session's removal is unobserved.
3119
3135
  * That matters most for a live platform stream, which has no other signal to close on.
3120
3136
  *
3137
+ * It is fired by the call that finds the session record and names its owner. If an earlier
3138
+ * attempt deleted the record but failed another revocation write, it answered a 5xx without this
3139
+ * hook, and the retry that completes the logout finds no record and does not fire it.
3140
+ *
3121
3141
  * @param userId - The internal ID of the administrator who logged out.
3122
3142
  * @param context - Request metadata; `plane` is `'platform'` and there is no tenant.
3123
3143
  */
@@ -5623,8 +5643,9 @@ declare class AuthRateLimitGuard implements CanActivate {
5623
5643
  * The address this request is counted against.
5624
5644
  *
5625
5645
  * `'peer'` — the default — reads the socket directly, so `X-Forwarded-For` cannot influence
5626
- * it. `'trusted-proxy'` uses `req.ip`, which honours the app's `trust proxy` setting and the
5627
- * forwarding headers it admits.
5646
+ * it. `'trusted-proxy'` uses the resolved client address, which starts from `req.ip` (honouring
5647
+ * the app's `trust proxy` setting and the forwarding headers it admits) and never returns a
5648
+ * string that is not an address, so a caller cannot mint a bucket by writing one.
5628
5649
  *
5629
5650
  * The default is the strict one because the two failure modes are not symmetric: keying on
5630
5651
  * the peer address behind a proxy over-counts, which is visible and recoverable, while
@@ -8984,6 +9005,27 @@ declare class MfaService {
8984
9005
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
8985
9006
  */
8986
9007
  challenge(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<AuthResult | PlatformAuthResult>;
9008
+ /**
9009
+ * The challenge for an entry point that serves the platform plane only.
9010
+ *
9011
+ * Reads the plane from the temp token first and refuses a dashboard token with
9012
+ * `PLATFORM_AUTH_REQUIRED` before anything is spent. {@link MfaService.challenge} consumes the
9013
+ * token, burns the TOTP code, stores a session, stamps the last login and fires the hooks, so
9014
+ * refusing after it leaves an orphan session nobody holds a token for. The first verification only
9015
+ * reads: it touches neither the brute-force counter nor the TOTP anti-replay key. The challenge
9016
+ * verifies the token again, and the plane is a signed claim, so both reads see the same one.
9017
+ *
9018
+ * @param mfaTempToken - Short-lived MFA challenge JWT issued at platform login.
9019
+ * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
9020
+ * @param ip - Client IP address for session audit.
9021
+ * @param userAgent - User-Agent header for session description.
9022
+ * @returns The platform auth result.
9023
+ * @throws `PLATFORM_AUTH_REQUIRED` if the token is for the dashboard plane.
9024
+ * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
9025
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
9026
+ * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
9027
+ */
9028
+ challengePlatformOnly(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<PlatformAuthResult>;
8987
9029
  /**
8988
9030
  * Disables MFA on a user's account after verifying a current TOTP code.
8989
9031
  *
@@ -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
  /**
@@ -3101,6 +3112,11 @@ interface IAuthHooks {
3101
3112
  * Use this hook to clean up session-related state, emit audit events, or
3102
3113
  * notify downstream services.
3103
3114
  *
3115
+ * Fired by the call that finds the session record and names its owner. If an earlier attempt
3116
+ * deleted the record but failed another revocation write, it answered a 5xx without this hook,
3117
+ * and the retry that completes the logout finds no record, so it names nobody and does not fire
3118
+ * it: that logout is never reported here.
3119
+ *
3104
3120
  * @param userId - The internal ID of the user who logged out.
3105
3121
  * @param context - Request metadata (IP, user agent, sanitized headers).
3106
3122
  */
@@ -3118,6 +3134,10 @@ interface IAuthHooks {
3118
3134
  * the access token stays presentable until it expires, and the session's removal is unobserved.
3119
3135
  * That matters most for a live platform stream, which has no other signal to close on.
3120
3136
  *
3137
+ * It is fired by the call that finds the session record and names its owner. If an earlier
3138
+ * attempt deleted the record but failed another revocation write, it answered a 5xx without this
3139
+ * hook, and the retry that completes the logout finds no record and does not fire it.
3140
+ *
3121
3141
  * @param userId - The internal ID of the administrator who logged out.
3122
3142
  * @param context - Request metadata; `plane` is `'platform'` and there is no tenant.
3123
3143
  */
@@ -5623,8 +5643,9 @@ declare class AuthRateLimitGuard implements CanActivate {
5623
5643
  * The address this request is counted against.
5624
5644
  *
5625
5645
  * `'peer'` — the default — reads the socket directly, so `X-Forwarded-For` cannot influence
5626
- * it. `'trusted-proxy'` uses `req.ip`, which honours the app's `trust proxy` setting and the
5627
- * forwarding headers it admits.
5646
+ * it. `'trusted-proxy'` uses the resolved client address, which starts from `req.ip` (honouring
5647
+ * the app's `trust proxy` setting and the forwarding headers it admits) and never returns a
5648
+ * string that is not an address, so a caller cannot mint a bucket by writing one.
5628
5649
  *
5629
5650
  * The default is the strict one because the two failure modes are not symmetric: keying on
5630
5651
  * the peer address behind a proxy over-counts, which is visible and recoverable, while
@@ -8984,6 +9005,27 @@ declare class MfaService {
8984
9005
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
8985
9006
  */
8986
9007
  challenge(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<AuthResult | PlatformAuthResult>;
9008
+ /**
9009
+ * The challenge for an entry point that serves the platform plane only.
9010
+ *
9011
+ * Reads the plane from the temp token first and refuses a dashboard token with
9012
+ * `PLATFORM_AUTH_REQUIRED` before anything is spent. {@link MfaService.challenge} consumes the
9013
+ * token, burns the TOTP code, stores a session, stamps the last login and fires the hooks, so
9014
+ * refusing after it leaves an orphan session nobody holds a token for. The first verification only
9015
+ * reads: it touches neither the brute-force counter nor the TOTP anti-replay key. The challenge
9016
+ * verifies the token again, and the plane is a signed claim, so both reads see the same one.
9017
+ *
9018
+ * @param mfaTempToken - Short-lived MFA challenge JWT issued at platform login.
9019
+ * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
9020
+ * @param ip - Client IP address for session audit.
9021
+ * @param userAgent - User-Agent header for session description.
9022
+ * @returns The platform auth result.
9023
+ * @throws `PLATFORM_AUTH_REQUIRED` if the token is for the dashboard plane.
9024
+ * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
9025
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
9026
+ * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
9027
+ */
9028
+ challengePlatformOnly(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<PlatformAuthResult>;
8987
9029
  /**
8988
9030
  * Disables MFA on a user's account after verifying a current TOTP code.
8989
9031
  *
@@ -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;
@@ -6454,6 +6480,32 @@ function safeLogLine(line, secrets) {
6454
6480
  }
6455
6481
  __name(safeLogLine, "safeLogLine");
6456
6482
 
6483
+ // src/server/utils/settle-writes.ts
6484
+ async function settleWrites(writes) {
6485
+ const failures = [];
6486
+ for (const write of writes) {
6487
+ try {
6488
+ await write();
6489
+ } catch (err) {
6490
+ failures.push(err);
6491
+ }
6492
+ }
6493
+ return failures;
6494
+ }
6495
+ __name(settleWrites, "settleWrites");
6496
+ function raiseFirst(failures) {
6497
+ const [first] = failures;
6498
+ if (failures.length > 0) throw first;
6499
+ }
6500
+ __name(raiseFirst, "raiseFirst");
6501
+ function settleAfter(first, followUps) {
6502
+ return async () => {
6503
+ await first();
6504
+ raiseFirst(await settleWrites(followUps));
6505
+ };
6506
+ }
6507
+ __name(settleAfter, "settleAfter");
6508
+
6457
6509
  // src/server/utils/tenant-scoped.ts
6458
6510
  function tenantScoped(user, tenantId) {
6459
6511
  if (user === null) return null;
@@ -6620,7 +6672,7 @@ var AuthService = class _AuthService {
6620
6672
  */
6621
6673
  async register(dto, req) {
6622
6674
  const tenantId = await this.resolveTenantId(dto.tenantId, req);
6623
- const ip = req.ip ?? "";
6675
+ const ip = resolveClientAddress(req);
6624
6676
  const userAgent = String(req.headers["user-agent"] ?? "");
6625
6677
  dto = {
6626
6678
  ...dto,
@@ -6713,7 +6765,7 @@ var AuthService = class _AuthService {
6713
6765
  */
6714
6766
  async login(dto, req) {
6715
6767
  const tenantId = await this.resolveTenantId(dto.tenantId, req);
6716
- const ip = req.ip ?? "";
6768
+ const ip = resolveClientAddress(req);
6717
6769
  const userAgent = String(req.headers["user-agent"] ?? "");
6718
6770
  dto = {
6719
6771
  ...dto,
@@ -6858,17 +6910,22 @@ var AuthService = class _AuthService {
6858
6910
  const sessionHash = sha256(rawRefreshToken);
6859
6911
  const { userId, tenantId } = await this.redis.readSessionOwner(`rt:${sessionHash}`);
6860
6912
  this.logger.log(`logout: userId=${logSafe(userId || "(no live session)")}`);
6913
+ let blacklist = [];
6861
6914
  try {
6862
6915
  const payload = this.tokenManager.verifyIgnoringExpiry(accessToken);
6863
- const now = Math.floor(Date.now() / 1e3);
6864
- const remainingTtl = payload.exp - now;
6916
+ const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
6865
6917
  if (remainingTtl > 0) {
6866
- await this.redis.set(`rv:${payload.jti}`, "1", remainingTtl);
6918
+ blacklist = [
6919
+ () => this.redis.set(`rv:${payload.jti}`, "1", remainingTtl)
6920
+ ];
6867
6921
  }
6868
6922
  } catch {
6869
6923
  }
6870
- await this.redis.del(`rt:${sessionHash}`);
6871
- await this.redis.del(`rp:${sessionHash}`);
6924
+ const failures = await settleWrites([
6925
+ ...blacklist,
6926
+ () => this.redis.del(`rt:${sessionHash}`),
6927
+ () => this.redis.del(`rp:${sessionHash}`)
6928
+ ]);
6872
6929
  if (this.options.sessions.enabled && userId && tenantId !== void 0) {
6873
6930
  await this.sessionService.revokeSession({
6874
6931
  userId,
@@ -6881,6 +6938,7 @@ var AuthService = class _AuthService {
6881
6938
  }
6882
6939
  });
6883
6940
  }
6941
+ raiseFirst(failures);
6884
6942
  this.emitLogout(userId, tenantId);
6885
6943
  return userId;
6886
6944
  }
@@ -7768,8 +7826,9 @@ var AuthController = class {
7768
7826
  * token is the credential that authorizes this, and the service reads the session's owner
7769
7827
  * from the stored record rather than from the access token's claims.
7770
7828
  *
7771
- * Always 204: a caller presenting a token for an already-gone session gets their cookies
7772
- * cleared and learns nothing about whether a session existed.
7829
+ * A caller presenting a token for an already-gone session gets a 204 with their cookies
7830
+ * cleared and learns nothing about whether a session existed. When the store refuses a
7831
+ * revocation write the route answers a 5xx and leaves the cookies in place, so the client can retry.
7773
7832
  *
7774
7833
  * @param req - Incoming request (used to extract tokens).
7775
7834
  * @param res - Response object (passthrough — used to clear cookies).
@@ -7792,7 +7851,7 @@ var AuthController = class {
7792
7851
  */
7793
7852
  async refresh(req, res) {
7794
7853
  const rawRefreshToken = this.tokenDelivery.extractRefreshToken(req) ?? "";
7795
- const ip = req.ip ?? "";
7854
+ const ip = resolveClientAddress(req);
7796
7855
  const userAgent = String(req.headers["user-agent"] ?? "");
7797
7856
  const rotated = await this.authService.refresh(rawRefreshToken, ip, userAgent);
7798
7857
  const authResult = {
@@ -9284,7 +9343,7 @@ var InvitationController = class {
9284
9343
  * @returns Auth response with tokens delivered per the configured `tokenDelivery` mode.
9285
9344
  */
9286
9345
  async accept(dto, req, res) {
9287
- const ip = req.ip ?? "";
9346
+ const ip = resolveClientAddress(req);
9288
9347
  const userAgent = String(req.headers["user-agent"] ?? "");
9289
9348
  const headers = req.headers;
9290
9349
  const result = await this.invitationService.acceptInvitation(dto, ip, userAgent, headers);
@@ -10401,6 +10460,37 @@ var MfaService = class _MfaService {
10401
10460
  }
10402
10461
  return result;
10403
10462
  }
10463
+ /**
10464
+ * The challenge for an entry point that serves the platform plane only.
10465
+ *
10466
+ * Reads the plane from the temp token first and refuses a dashboard token with
10467
+ * `PLATFORM_AUTH_REQUIRED` before anything is spent. {@link MfaService.challenge} consumes the
10468
+ * token, burns the TOTP code, stores a session, stamps the last login and fires the hooks, so
10469
+ * refusing after it leaves an orphan session nobody holds a token for. The first verification only
10470
+ * reads: it touches neither the brute-force counter nor the TOTP anti-replay key. The challenge
10471
+ * verifies the token again, and the plane is a signed claim, so both reads see the same one.
10472
+ *
10473
+ * @param mfaTempToken - Short-lived MFA challenge JWT issued at platform login.
10474
+ * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
10475
+ * @param ip - Client IP address for session audit.
10476
+ * @param userAgent - User-Agent header for session description.
10477
+ * @returns The platform auth result.
10478
+ * @throws `PLATFORM_AUTH_REQUIRED` if the token is for the dashboard plane.
10479
+ * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
10480
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
10481
+ * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
10482
+ */
10483
+ async challengePlatformOnly(mfaTempToken, code, ip, userAgent) {
10484
+ const { context } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
10485
+ if (context !== "platform") {
10486
+ throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
10487
+ }
10488
+ const result = await this.challenge(mfaTempToken, code, ip, userAgent);
10489
+ if (!("admin" in result)) {
10490
+ throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
10491
+ }
10492
+ return result;
10493
+ }
10404
10494
  // ---------------------------------------------------------------------------
10405
10495
  // disable — TOTP-verified MFA deactivation with session invalidation
10406
10496
  // ---------------------------------------------------------------------------
@@ -11027,7 +11117,7 @@ var MfaController = class {
11027
11117
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
11028
11118
  */
11029
11119
  async verifyEnable(user, dto, req) {
11030
- const ip = req.ip ?? "";
11120
+ const ip = resolveClientAddress(req);
11031
11121
  const userAgent = String(req.headers["user-agent"] ?? "");
11032
11122
  await this.mfaService.verifyAndEnable(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11033
11123
  }
@@ -11060,7 +11150,7 @@ var MfaController = class {
11060
11150
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
11061
11151
  */
11062
11152
  async challenge(dto, req, res) {
11063
- const ip = req.ip ?? "";
11153
+ const ip = resolveClientAddress(req);
11064
11154
  const userAgent = String(req.headers["user-agent"] ?? "");
11065
11155
  const cookieToken = readMfaTempCookie(req);
11066
11156
  const mfaTempToken = dto.mfaTempToken ?? cookieToken;
@@ -11099,7 +11189,7 @@ var MfaController = class {
11099
11189
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
11100
11190
  */
11101
11191
  async disable(user, dto, req) {
11102
- const ip = req.ip ?? "";
11192
+ const ip = resolveClientAddress(req);
11103
11193
  const userAgent = String(req.headers["user-agent"] ?? "");
11104
11194
  await this.mfaService.disable(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11105
11195
  }
@@ -11123,7 +11213,7 @@ var MfaController = class {
11123
11213
  * @returns The fresh plain-text recovery codes, one-time display.
11124
11214
  */
11125
11215
  async regenerateRecoveryCodes(user, dto, req) {
11126
- const ip = req.ip ?? "";
11216
+ const ip = resolveClientAddress(req);
11127
11217
  const userAgent = String(req.headers["user-agent"] ?? "");
11128
11218
  return this.mfaService.regenerateRecoveryCodes(user.sub, dto.code, ip, userAgent, "dashboard", user.tenantId);
11129
11219
  }
@@ -12722,22 +12812,30 @@ var PlatformAuthService = class _PlatformAuthService {
12722
12812
  const tokenHash = sha256(rawRefreshToken);
12723
12813
  const { userId } = await this.redis.readSessionOwner(`prt:${tokenHash}`);
12724
12814
  this.logger.log(`logout: adminId=${logSafe(userId || "(no live session)")}`);
12815
+ let blacklist = [];
12725
12816
  try {
12726
12817
  const payload = this.tokenManager.verifyPlatformIgnoringExpiry(accessToken);
12727
12818
  const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
12728
12819
  if (remainingTtl > 0) {
12729
- await this.redis.set(`rv:${payload.jti}`, "1", remainingTtl);
12820
+ blacklist = [
12821
+ () => this.redis.set(`rv:${payload.jti}`, "1", remainingTtl)
12822
+ ];
12730
12823
  }
12731
12824
  } catch {
12732
12825
  }
12733
- await this.redis.del("prt:" + tokenHash);
12734
- await this.redis.del("prp:" + tokenHash);
12735
- if (userId) {
12736
- const index = sessionIndexKey("platform", userId, this.options.hmacKey, void 0);
12737
- await this.redis.srem(index, "prt:" + tokenHash);
12738
- await this.redis.srem(index, "prp:" + tokenHash);
12739
- }
12740
- await this.redis.del("psd:" + tokenHash);
12826
+ const index = userId ? sessionIndexKey("platform", userId, this.options.hmacKey, void 0) : "";
12827
+ const prune = /* @__PURE__ */ __name((member) => index === "" ? [] : [
12828
+ () => this.redis.srem(index, member)
12829
+ ], "prune");
12830
+ const failures = await settleWrites([
12831
+ ...blacklist,
12832
+ settleAfter(() => this.redis.del("prt:" + tokenHash), [
12833
+ ...prune("prt:" + tokenHash),
12834
+ () => this.redis.del("psd:" + tokenHash)
12835
+ ]),
12836
+ settleAfter(() => this.redis.del("prp:" + tokenHash), prune("prp:" + tokenHash))
12837
+ ]);
12838
+ raiseFirst(failures);
12741
12839
  this.emitPlatformLogout(userId);
12742
12840
  return userId;
12743
12841
  }
@@ -12927,10 +13025,6 @@ function _ts_param27(paramIndex, decorator) {
12927
13025
  };
12928
13026
  }
12929
13027
  __name(_ts_param27, "_ts_param");
12930
- function isPlatformResult2(result) {
12931
- return "admin" in result;
12932
- }
12933
- __name(isPlatformResult2, "isPlatformResult");
12934
13028
  function isMfaChallenge2(result) {
12935
13029
  return "mfaRequired" in result && result.mfaRequired === true;
12936
13030
  }
@@ -12961,7 +13055,7 @@ var PlatformAuthController = class {
12961
13055
  * @param req - Incoming request (provides IP and User-Agent for session tracking).
12962
13056
  */
12963
13057
  async login(dto, req) {
12964
- const ip = req.ip ?? "";
13058
+ const ip = resolveClientAddress(req);
12965
13059
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
12966
13060
  const result = await this.platformAuthService.login(dto, ip, userAgent);
12967
13061
  if (isMfaChallenge2(result)) {
@@ -12976,30 +13070,20 @@ var PlatformAuthController = class {
12976
13070
  * Completes a platform administrator MFA challenge.
12977
13071
  *
12978
13072
  * Exchanges a short-lived `mfaTempToken` (issued at login) and a TOTP code for
12979
- * full platform auth tokens. The `context: 'platform'` in the temp token directs
12980
- * {@link MfaService.challenge} to issue a {@link PlatformAuthResult}.
12981
- *
12982
- * Explicitly guards against cross-context token abuse: if a dashboard-context MFA
12983
- * temp token is submitted here, the response will contain an `AuthResult` (not a
12984
- * `PlatformAuthResult`). The `isPlatformResult` check detects this and throws
12985
- * `PLATFORM_AUTH_REQUIRED` rather than silently returning a dashboard-scoped token
12986
- * as if it were a platform auth response.
13073
+ * full platform auth tokens through {@link MfaService.challengePlatformOnly}, which refuses a
13074
+ * dashboard-context token before anything is spent.
12987
13075
  *
12988
13076
  * @param dto - Contains the MFA temp token and the TOTP (or recovery) code.
12989
13077
  * @param req - Incoming request (provides IP and User-Agent for brute-force tracking).
12990
13078
  * @throws `PLATFORM_AUTH_REQUIRED` when the submitted MFA token has `context='dashboard'`.
12991
13079
  */
12992
13080
  async mfaChallenge(dto, req) {
12993
- const ip = req.ip ?? "";
13081
+ const ip = resolveClientAddress(req);
12994
13082
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
12995
13083
  if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
12996
13084
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
12997
13085
  }
12998
- const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
12999
- if (!isPlatformResult2(result)) {
13000
- throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
13001
- }
13002
- return this.tokenDelivery.deliverPlatformAuthResponse(result);
13086
+ return this.tokenDelivery.deliverPlatformAuthResponse(await this.mfaService.challengePlatformOnly(dto.mfaTempToken, dto.code, ip, userAgent));
13003
13087
  }
13004
13088
  // ---------------------------------------------------------------------------
13005
13089
  // GET /platform/me
@@ -13054,7 +13138,7 @@ var PlatformAuthController = class {
13054
13138
  */
13055
13139
  async refresh(req) {
13056
13140
  const rawRefreshToken = this.tokenDelivery.extractPlatformRefreshToken(req) ?? "";
13057
- const ip = req.ip ?? "";
13141
+ const ip = resolveClientAddress(req);
13058
13142
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
13059
13143
  const rotated = await this.platformAuthService.refresh(rawRefreshToken, ip, userAgent);
13060
13144
  const admin = await this.platformAuthService.getMe(rotated.session.userId);
@@ -13241,7 +13325,7 @@ var PlatformMfaController = class {
13241
13325
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
13242
13326
  */
13243
13327
  async verifyEnable(user, dto, req) {
13244
- const ip = req.ip ?? "";
13328
+ const ip = resolveClientAddress(req);
13245
13329
  const userAgent = String(req.headers["user-agent"] ?? "");
13246
13330
  await this.mfaService.verifyAndEnable(user.sub, dto.code, ip, userAgent, "platform");
13247
13331
  }
@@ -13259,7 +13343,7 @@ var PlatformMfaController = class {
13259
13343
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
13260
13344
  */
13261
13345
  async disable(user, dto, req) {
13262
- const ip = req.ip ?? "";
13346
+ const ip = resolveClientAddress(req);
13263
13347
  const userAgent = String(req.headers["user-agent"] ?? "");
13264
13348
  await this.mfaService.disable(user.sub, dto.code, ip, userAgent, "platform");
13265
13349
  }
@@ -13279,7 +13363,7 @@ var PlatformMfaController = class {
13279
13363
  * @returns The fresh plain-text recovery codes, one-time display.
13280
13364
  */
13281
13365
  async regenerateRecoveryCodes(user, dto, req) {
13282
- const ip = req.ip ?? "";
13366
+ const ip = resolveClientAddress(req);
13283
13367
  const userAgent = String(req.headers["user-agent"] ?? "");
13284
13368
  return this.mfaService.regenerateRecoveryCodes(user.sub, dto.code, ip, userAgent, "platform");
13285
13369
  }
@@ -13918,7 +14002,7 @@ var ApiKeyGuard = class _ApiKeyGuard {
13918
14002
  ...partial,
13919
14003
  keyId: key?.id ?? null,
13920
14004
  label: key?.label ?? null,
13921
- ip: request.ip ?? ""
14005
+ ip: resolveClientAddress(request)
13922
14006
  };
13923
14007
  const context = this.hookContext(request);
13924
14008
  const run = /* @__PURE__ */ __name(() => hook.call(this.hooks, event, context), "run");
@@ -13943,7 +14027,7 @@ var ApiKeyGuard = class _ApiKeyGuard {
13943
14027
  hookContext(request) {
13944
14028
  const headers = Object.fromEntries(Object.entries(request.headers).filter(([name]) => name !== this.options.apiKeys.header));
13945
14029
  return {
13946
- ip: request.ip ?? "",
14030
+ ip: resolveClientAddress(request),
13947
14031
  userAgent: request.headers["user-agent"] ?? "",
13948
14032
  sanitizedHeaders: sanitizeHeaders(headers)
13949
14033
  };
@@ -14953,7 +15037,7 @@ var OAuthController = class _OAuthController {
14953
15037
  * payload, or `undefined` when a redirect was issued.
14954
15038
  */
14955
15039
  async callback(provider, query, req, res) {
14956
- const ip = (req.ip ?? "").slice(0, 64);
15040
+ const ip = resolveClientAddress(req).slice(0, 64);
14957
15041
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
14958
15042
  const stateCookie = readOAuthStateCookie(req);
14959
15043
  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.12",
3
+ "version": "1.4.14",
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",