@bymax-one/nest-auth 1.4.13 → 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,44 @@ 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
+
21
59
  ## [1.4.13] - 2026-11-01
22
60
 
23
61
  ### Apply to a derived backend
@@ -4221,7 +4259,8 @@ ever installable.
4221
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
4222
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
4223
4261
 
4224
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.13...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
4225
4264
  [1.4.13]: https://github.com/bymaxone/nest-auth/compare/v1.4.12...v1.4.13
4226
4265
  [1.4.12]: https://github.com/bymaxone/nest-auth/compare/v1.4.11...v1.4.12
4227
4266
  [1.4.11]: https://github.com/bymaxone/nest-auth/compare/v1.4.10...v1.4.11
@@ -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}:
@@ -6482,6 +6482,32 @@ function safeLogLine(line, secrets) {
6482
6482
  }
6483
6483
  __name(safeLogLine, "safeLogLine");
6484
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
+
6485
6511
  // src/server/utils/tenant-scoped.ts
6486
6512
  function tenantScoped(user, tenantId) {
6487
6513
  if (user === null) return null;
@@ -6886,17 +6912,22 @@ exports.AuthService = class _AuthService {
6886
6912
  const sessionHash = sha256(rawRefreshToken);
6887
6913
  const { userId, tenantId } = await this.redis.readSessionOwner(`rt:${sessionHash}`);
6888
6914
  this.logger.log(`logout: userId=${logSafe(userId || "(no live session)")}`);
6915
+ let blacklist = [];
6889
6916
  try {
6890
6917
  const payload = this.tokenManager.verifyIgnoringExpiry(accessToken);
6891
- const now = Math.floor(Date.now() / 1e3);
6892
- const remainingTtl = payload.exp - now;
6918
+ const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
6893
6919
  if (remainingTtl > 0) {
6894
- await this.redis.set(`rv:${payload.jti}`, "1", remainingTtl);
6920
+ blacklist = [
6921
+ () => this.redis.set(`rv:${payload.jti}`, "1", remainingTtl)
6922
+ ];
6895
6923
  }
6896
6924
  } catch {
6897
6925
  }
6898
- await this.redis.del(`rt:${sessionHash}`);
6899
- 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
+ ]);
6900
6931
  if (this.options.sessions.enabled && userId && tenantId !== void 0) {
6901
6932
  await this.sessionService.revokeSession({
6902
6933
  userId,
@@ -6909,6 +6940,7 @@ exports.AuthService = class _AuthService {
6909
6940
  }
6910
6941
  });
6911
6942
  }
6943
+ raiseFirst(failures);
6912
6944
  this.emitLogout(userId, tenantId);
6913
6945
  return userId;
6914
6946
  }
@@ -7796,8 +7828,9 @@ var AuthController = class {
7796
7828
  * token is the credential that authorizes this, and the service reads the session's owner
7797
7829
  * from the stored record rather than from the access token's claims.
7798
7830
  *
7799
- * Always 204: a caller presenting a token for an already-gone session gets their cookies
7800
- * 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.
7801
7834
  *
7802
7835
  * @param req - Incoming request (used to extract tokens).
7803
7836
  * @param res - Response object (passthrough — used to clear cookies).
@@ -10429,6 +10462,37 @@ exports.MfaService = class _MfaService {
10429
10462
  }
10430
10463
  return result;
10431
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
+ }
10432
10496
  // ---------------------------------------------------------------------------
10433
10497
  // disable — TOTP-verified MFA deactivation with session invalidation
10434
10498
  // ---------------------------------------------------------------------------
@@ -12750,22 +12814,30 @@ exports.PlatformAuthService = class _PlatformAuthService {
12750
12814
  const tokenHash = sha256(rawRefreshToken);
12751
12815
  const { userId } = await this.redis.readSessionOwner(`prt:${tokenHash}`);
12752
12816
  this.logger.log(`logout: adminId=${logSafe(userId || "(no live session)")}`);
12817
+ let blacklist = [];
12753
12818
  try {
12754
12819
  const payload = this.tokenManager.verifyPlatformIgnoringExpiry(accessToken);
12755
12820
  const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
12756
12821
  if (remainingTtl > 0) {
12757
- await this.redis.set(`rv:${payload.jti}`, "1", remainingTtl);
12822
+ blacklist = [
12823
+ () => this.redis.set(`rv:${payload.jti}`, "1", remainingTtl)
12824
+ ];
12758
12825
  }
12759
12826
  } catch {
12760
12827
  }
12761
- await this.redis.del("prt:" + tokenHash);
12762
- await this.redis.del("prp:" + tokenHash);
12763
- if (userId) {
12764
- const index = sessionIndexKey("platform", userId, this.options.hmacKey, void 0);
12765
- await this.redis.srem(index, "prt:" + tokenHash);
12766
- await this.redis.srem(index, "prp:" + tokenHash);
12767
- }
12768
- 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);
12769
12841
  this.emitPlatformLogout(userId);
12770
12842
  return userId;
12771
12843
  }
@@ -12955,10 +13027,6 @@ function _ts_param27(paramIndex, decorator) {
12955
13027
  };
12956
13028
  }
12957
13029
  __name(_ts_param27, "_ts_param");
12958
- function isPlatformResult2(result) {
12959
- return "admin" in result;
12960
- }
12961
- __name(isPlatformResult2, "isPlatformResult");
12962
13030
  function isMfaChallenge2(result) {
12963
13031
  return "mfaRequired" in result && result.mfaRequired === true;
12964
13032
  }
@@ -13004,14 +13072,8 @@ var PlatformAuthController = class {
13004
13072
  * Completes a platform administrator MFA challenge.
13005
13073
  *
13006
13074
  * Exchanges a short-lived `mfaTempToken` (issued at login) and a TOTP code for
13007
- * full platform auth tokens. The `context: 'platform'` in the temp token directs
13008
- * {@link MfaService.challenge} to issue a {@link PlatformAuthResult}.
13009
- *
13010
- * Explicitly guards against cross-context token abuse: if a dashboard-context MFA
13011
- * temp token is submitted here, the response will contain an `AuthResult` (not a
13012
- * `PlatformAuthResult`). The `isPlatformResult` check detects this and throws
13013
- * `PLATFORM_AUTH_REQUIRED` rather than silently returning a dashboard-scoped token
13014
- * 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.
13015
13077
  *
13016
13078
  * @param dto - Contains the MFA temp token and the TOTP (or recovery) code.
13017
13079
  * @param req - Incoming request (provides IP and User-Agent for brute-force tracking).
@@ -13023,11 +13085,7 @@ var PlatformAuthController = class {
13023
13085
  if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
13024
13086
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
13025
13087
  }
13026
- const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
13027
- if (!isPlatformResult2(result)) {
13028
- throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
13029
- }
13030
- return this.tokenDelivery.deliverPlatformAuthResponse(result);
13088
+ return this.tokenDelivery.deliverPlatformAuthResponse(await this.mfaService.challengePlatformOnly(dto.mfaTempToken, dto.code, ip, userAgent));
13031
13089
  }
13032
13090
  // ---------------------------------------------------------------------------
13033
13091
  // GET /platform/me
@@ -3112,6 +3112,11 @@ interface IAuthHooks {
3112
3112
  * Use this hook to clean up session-related state, emit audit events, or
3113
3113
  * notify downstream services.
3114
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
+ *
3115
3120
  * @param userId - The internal ID of the user who logged out.
3116
3121
  * @param context - Request metadata (IP, user agent, sanitized headers).
3117
3122
  */
@@ -3129,6 +3134,10 @@ interface IAuthHooks {
3129
3134
  * the access token stays presentable until it expires, and the session's removal is unobserved.
3130
3135
  * That matters most for a live platform stream, which has no other signal to close on.
3131
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
+ *
3132
3141
  * @param userId - The internal ID of the administrator who logged out.
3133
3142
  * @param context - Request metadata; `plane` is `'platform'` and there is no tenant.
3134
3143
  */
@@ -8996,6 +9005,27 @@ declare class MfaService {
8996
9005
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
8997
9006
  */
8998
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>;
8999
9029
  /**
9000
9030
  * Disables MFA on a user's account after verifying a current TOTP code.
9001
9031
  *
@@ -3112,6 +3112,11 @@ interface IAuthHooks {
3112
3112
  * Use this hook to clean up session-related state, emit audit events, or
3113
3113
  * notify downstream services.
3114
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
+ *
3115
3120
  * @param userId - The internal ID of the user who logged out.
3116
3121
  * @param context - Request metadata (IP, user agent, sanitized headers).
3117
3122
  */
@@ -3129,6 +3134,10 @@ interface IAuthHooks {
3129
3134
  * the access token stays presentable until it expires, and the session's removal is unobserved.
3130
3135
  * That matters most for a live platform stream, which has no other signal to close on.
3131
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
+ *
3132
3141
  * @param userId - The internal ID of the administrator who logged out.
3133
3142
  * @param context - Request metadata; `plane` is `'platform'` and there is no tenant.
3134
3143
  */
@@ -8996,6 +9005,27 @@ declare class MfaService {
8996
9005
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
8997
9006
  */
8998
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>;
8999
9029
  /**
9000
9030
  * Disables MFA on a user's account after verifying a current TOTP code.
9001
9031
  *
@@ -6480,6 +6480,32 @@ function safeLogLine(line, secrets) {
6480
6480
  }
6481
6481
  __name(safeLogLine, "safeLogLine");
6482
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
+
6483
6509
  // src/server/utils/tenant-scoped.ts
6484
6510
  function tenantScoped(user, tenantId) {
6485
6511
  if (user === null) return null;
@@ -6884,17 +6910,22 @@ var AuthService = class _AuthService {
6884
6910
  const sessionHash = sha256(rawRefreshToken);
6885
6911
  const { userId, tenantId } = await this.redis.readSessionOwner(`rt:${sessionHash}`);
6886
6912
  this.logger.log(`logout: userId=${logSafe(userId || "(no live session)")}`);
6913
+ let blacklist = [];
6887
6914
  try {
6888
6915
  const payload = this.tokenManager.verifyIgnoringExpiry(accessToken);
6889
- const now = Math.floor(Date.now() / 1e3);
6890
- const remainingTtl = payload.exp - now;
6916
+ const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
6891
6917
  if (remainingTtl > 0) {
6892
- await this.redis.set(`rv:${payload.jti}`, "1", remainingTtl);
6918
+ blacklist = [
6919
+ () => this.redis.set(`rv:${payload.jti}`, "1", remainingTtl)
6920
+ ];
6893
6921
  }
6894
6922
  } catch {
6895
6923
  }
6896
- await this.redis.del(`rt:${sessionHash}`);
6897
- 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
+ ]);
6898
6929
  if (this.options.sessions.enabled && userId && tenantId !== void 0) {
6899
6930
  await this.sessionService.revokeSession({
6900
6931
  userId,
@@ -6907,6 +6938,7 @@ var AuthService = class _AuthService {
6907
6938
  }
6908
6939
  });
6909
6940
  }
6941
+ raiseFirst(failures);
6910
6942
  this.emitLogout(userId, tenantId);
6911
6943
  return userId;
6912
6944
  }
@@ -7794,8 +7826,9 @@ var AuthController = class {
7794
7826
  * token is the credential that authorizes this, and the service reads the session's owner
7795
7827
  * from the stored record rather than from the access token's claims.
7796
7828
  *
7797
- * Always 204: a caller presenting a token for an already-gone session gets their cookies
7798
- * 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.
7799
7832
  *
7800
7833
  * @param req - Incoming request (used to extract tokens).
7801
7834
  * @param res - Response object (passthrough — used to clear cookies).
@@ -10427,6 +10460,37 @@ var MfaService = class _MfaService {
10427
10460
  }
10428
10461
  return result;
10429
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
+ }
10430
10494
  // ---------------------------------------------------------------------------
10431
10495
  // disable — TOTP-verified MFA deactivation with session invalidation
10432
10496
  // ---------------------------------------------------------------------------
@@ -12748,22 +12812,30 @@ var PlatformAuthService = class _PlatformAuthService {
12748
12812
  const tokenHash = sha256(rawRefreshToken);
12749
12813
  const { userId } = await this.redis.readSessionOwner(`prt:${tokenHash}`);
12750
12814
  this.logger.log(`logout: adminId=${logSafe(userId || "(no live session)")}`);
12815
+ let blacklist = [];
12751
12816
  try {
12752
12817
  const payload = this.tokenManager.verifyPlatformIgnoringExpiry(accessToken);
12753
12818
  const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
12754
12819
  if (remainingTtl > 0) {
12755
- await this.redis.set(`rv:${payload.jti}`, "1", remainingTtl);
12820
+ blacklist = [
12821
+ () => this.redis.set(`rv:${payload.jti}`, "1", remainingTtl)
12822
+ ];
12756
12823
  }
12757
12824
  } catch {
12758
12825
  }
12759
- await this.redis.del("prt:" + tokenHash);
12760
- await this.redis.del("prp:" + tokenHash);
12761
- if (userId) {
12762
- const index = sessionIndexKey("platform", userId, this.options.hmacKey, void 0);
12763
- await this.redis.srem(index, "prt:" + tokenHash);
12764
- await this.redis.srem(index, "prp:" + tokenHash);
12765
- }
12766
- 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);
12767
12839
  this.emitPlatformLogout(userId);
12768
12840
  return userId;
12769
12841
  }
@@ -12953,10 +13025,6 @@ function _ts_param27(paramIndex, decorator) {
12953
13025
  };
12954
13026
  }
12955
13027
  __name(_ts_param27, "_ts_param");
12956
- function isPlatformResult2(result) {
12957
- return "admin" in result;
12958
- }
12959
- __name(isPlatformResult2, "isPlatformResult");
12960
13028
  function isMfaChallenge2(result) {
12961
13029
  return "mfaRequired" in result && result.mfaRequired === true;
12962
13030
  }
@@ -13002,14 +13070,8 @@ var PlatformAuthController = class {
13002
13070
  * Completes a platform administrator MFA challenge.
13003
13071
  *
13004
13072
  * Exchanges a short-lived `mfaTempToken` (issued at login) and a TOTP code for
13005
- * full platform auth tokens. The `context: 'platform'` in the temp token directs
13006
- * {@link MfaService.challenge} to issue a {@link PlatformAuthResult}.
13007
- *
13008
- * Explicitly guards against cross-context token abuse: if a dashboard-context MFA
13009
- * temp token is submitted here, the response will contain an `AuthResult` (not a
13010
- * `PlatformAuthResult`). The `isPlatformResult` check detects this and throws
13011
- * `PLATFORM_AUTH_REQUIRED` rather than silently returning a dashboard-scoped token
13012
- * 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.
13013
13075
  *
13014
13076
  * @param dto - Contains the MFA temp token and the TOTP (or recovery) code.
13015
13077
  * @param req - Incoming request (provides IP and User-Agent for brute-force tracking).
@@ -13021,11 +13083,7 @@ var PlatformAuthController = class {
13021
13083
  if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
13022
13084
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
13023
13085
  }
13024
- const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
13025
- if (!isPlatformResult2(result)) {
13026
- throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
13027
- }
13028
- return this.tokenDelivery.deliverPlatformAuthResponse(result);
13086
+ return this.tokenDelivery.deliverPlatformAuthResponse(await this.mfaService.challengePlatformOnly(dto.mfaTempToken, dto.code, ip, userAgent));
13029
13087
  }
13030
13088
  // ---------------------------------------------------------------------------
13031
13089
  // GET /platform/me
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.4.13",
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",