@bymax-one/nest-auth 1.4.18 → 1.4.19

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.19] - 2026-11-07
22
+
23
+ ### Apply to a derived backend
24
+
25
+ - **A logout whose retry marker cannot be removed no longer announces itself twice or never.** When
26
+ the owner comes from the stored session and the store refuses to remove a leftover `lp:` or
27
+ `plp:` marker, the logout reads the marker again. With no marker left it completes and announces;
28
+ with the marker still there it answers `500` `auth.internal` and announces nothing, because the
29
+ session is already gone and the retry claims the marker and announces once; when that read is
30
+ refused too, the owner is recorded again, best effort, and the logout answers `500`. When the
31
+ owner comes from the marker and the store refuses the claim, the logout answers `500` and
32
+ announces nothing: answering success would keep the client from retrying, so nothing would ever
33
+ announce it. A client that retries a `5xx` logout needs no change; a monitor can see these `500`s
34
+ during a Redis fault. The delivery guarantee in the shared contract is unchanged.
35
+ `settlePendingLogout` takes the owner and the marker lifetime as two more parameters; it is not
36
+ exported from the package.
37
+ - **A password-reset request that cannot be served answers `500` instead of a silent `200` when
38
+ the failure is the same for every address.** `POST /password/forgot-password` and
39
+ `POST /password/resend-otp` used to acknowledge `200` whatever failed. A failure before the
40
+ account is known, the resend-cooldown store or the account lookup, now answers `500`
41
+ `auth.internal` after the usual floor, because it tells the caller nothing about the
42
+ address. A failure after the account is known, issuing or storing the code, is logged and still
43
+ answers `200`, because it happens only for a registered address. The resend cooldown a request
44
+ took is released on any failure, so the retry a `500` invites is not refused for the rest of the cooldown window. A
45
+ cooldown hit takes the same floor as every other exit. A client or monitor that treated these
46
+ routes as always `200` sees `500` during a Redis or repository outage. The contract's
47
+ `responseBodies.passwordResetRequest` gains a `failures` note stating the rule. Private `answerResetRequest` appears in the `PasswordResetService` declarations.
48
+ - **The Next.js logout handler keeps the cookies when the upstream logout did not complete.**
49
+ `createLogoutHandler` clears the three auth cookies only once the upstream has given a final
50
+ answer below `500` other than `429` (a `2xx`, or a `4xx` such as an expired or already-revoked
51
+ session). When the upstream answers `5xx`, the handler answers that status and touches no cookie; a `429` from the
52
+ throttled logout route, answered before anything is revoked, is handled the same way and passes
53
+ on the upstream `Retry-After`; when the upstream is unreachable or the request fails, it answers
54
+ `502` and touches no cookie. In `'redirect'` mode none of these redirects. The cookies are the client's only handle for retrying the same logout, and the
55
+ upstream endpoint is idempotent, so the retry completes it. A caller that treated the handler's
56
+ answer as always successful sees a `5xx`, `502` or `429` it did not see before; `AuthClient.logout()`
57
+ rejects on it, as it does for any non-2xx. Cross-site and non-`POST` requests are answered as
58
+ before.
59
+ - **The React `logout()` keeps the authenticated state when the server logout did not
60
+ complete.** `AuthProvider` clears the session state after a successful logout and after a final
61
+ answer, an `AuthClientError` with a status below `500` and not `429`, and rethrows in the second
62
+ case. After a `5xx` (`502` included), a `429` or a failure with no answer at all, such as a
63
+ network failure, the state stays `authenticated` with the same user and the error is rethrown, because the session may be
64
+ alive and the UI must not read signed-out. A consumer that relied on the state being cleared
65
+ whenever `logout()` rejected now finds it still `authenticated` after such a rejection and
66
+ should offer a retry; repeating the call is safe because the server logout is idempotent. A
67
+ session probe already in flight is applied after a failed logout, not discarded. The rule is
68
+ written in the `logout` documentation on `AuthContextValue`, which also says which statuses the
69
+ hook can see behind the proxy route. The error is recognized by its `name` and an integer `status` of at least 100,
70
+ not by `instanceof`, so a second copy of the error class decides the same way; the check that
71
+ fires `onSessionExpired` on a `401` uses the same recognition, so an application that loads the
72
+ client and the provider through different module formats of the package no longer misses it.
73
+ No contract change.
74
+
75
+ ### Fixed
76
+
77
+ - **A password-reset request no longer hides an outage behind `200`.** See the note above.
78
+ - **A logout no longer announces itself twice, or never, when its marker cannot be removed.** See
79
+ the note above.
80
+ - **A failed logout through the Next.js proxy no longer looks successful.** See the note above.
81
+ - **A failed logout no longer shows the UI as signed out while the session is alive.** See the
82
+ note above.
83
+
84
+ ### Documentation
85
+
86
+ - **A password-reset lookup slower than the resend cooldown can remove a later request's
87
+ cooldown.** The flows release the cooldown by key when the lookup throws, so a lookup that
88
+ fails after more than the cooldown (60 seconds) releases a key that may by then belong to a
89
+ later request. Keep `findByEmail` well under the cooldown; the library does not guard against it.
90
+ - **A host `updateMfa` that outlasts the MFA transition lock can reorder MFA writes.** The lock
91
+ expires on its own after `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), a write still running then is
92
+ overtaken and lands after the next change, and the interface has no compare-and-set for the
93
+ library to use. Keep `updateMfa` well under the lock's lifetime; a guard of your own inside it narrows the window only for a stall after its own read, because the library passes the new values and not the ones it read.
94
+
21
95
  ## [1.4.18] - 2026-11-07
22
96
 
23
97
  ### Apply to a derived backend
@@ -4483,7 +4557,8 @@ ever installable.
4483
4557
  - 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
4484
4558
  - 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
4485
4559
 
4486
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.18...HEAD
4560
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.19...HEAD
4561
+ [1.4.19]: https://github.com/bymaxone/nest-auth/compare/v1.4.18...v1.4.19
4487
4562
  [1.4.18]: https://github.com/bymaxone/nest-auth/compare/v1.4.17...v1.4.18
4488
4563
  [1.4.17]: https://github.com/bymaxone/nest-auth/compare/v1.4.16...v1.4.17
4489
4564
  [1.4.16]: https://github.com/bymaxone/nest-auth/compare/v1.4.15...v1.4.16
package/README.md CHANGED
@@ -1058,6 +1058,23 @@ All options are configurable via `registerAsync()`. Here are the key configurati
1058
1058
  > otherwise surface at a user's first challenge rather than at boot. Drop the entry once your
1059
1059
  > enrolled users have had time to authenticate at least once.
1060
1060
 
1061
+ > [!WARNING]
1062
+ > **Keep your `updateMfa` fast.** Every MFA state change
1063
+ > rewrites the account's MFA record through your repository's `updateMfa`, and the library
1064
+ > serializes those writes per account with a lock that expires on its own
1065
+ > (`MFA_TRANSITION_LOCK_TTL_SECONDS`, 10 seconds) so a process that dies mid-write cannot strand
1066
+ > the account. The lock cannot outlast a write that is still running: if your `updateMfa` stalls
1067
+ > past that time, a second change takes the lock, reads the record, and writes it, and the stalled
1068
+ > write then lands _after_ it and overwrites it. The repository interface offers no
1069
+ > compare-and-set for the library to use, so it cannot detect this. Keep `updateMfa` well under the
1070
+ > lock's lifetime (a plain single-row update is, but a call that waits on a contended lock or a slow
1071
+ > replica may not be). A guard of your own inside `updateMfa` can narrow the window only for a stall
1072
+ > that happens after the guard's own read, such as a wait on a row lock inside the `UPDATE`: the
1073
+ > library passes `updateMfa` the new values and not the ones it read, so closing the window
1074
+ > completely would need those values passed in. The lock is held
1075
+ > across the read the transition makes inside it as well as the write, so a slow `findById` counts
1076
+ > against the same lifetime.
1077
+
1061
1078
  > [!IMPORTANT]
1062
1079
  > **The parameters that carry a control's strength are bounded at startup.** `mfa.totpWindow`
1063
1080
  > must be `0..=10`: the window counts 30-second steps on _either_ side of now, so `2n + 1`
@@ -2399,6 +2416,17 @@ went one release stated and unenforced.
2399
2416
  > (`auth.otp_invalid`) at one status (`401`) — a `429` on the ceiling would say the address was
2400
2417
  > registered, since only a record that exists can reach one.
2401
2418
 
2419
+ > **When a password-reset request fails.** A failure that is the same for every address, the
2420
+ > resend-cooldown store or your repository's `findByEmail` throwing, answers `500`
2421
+ > (`auth.internal`) after the same timing floor as every other exit, and the cooldown that request
2422
+ > took is released so the retry is not refused. A failure after the account is known (storing the
2423
+ > code, or the mail provider failing after the response has left) is logged and the `200` stands,
2424
+ > because it happens only for a registered address. Two limits are left as they are. A `findByEmail`
2425
+ > that takes longer than the cooldown (60 seconds) and then fails releases the cooldown by key, and
2426
+ > by then that key may belong to a later request, whose cooldown is removed early: keep
2427
+ > `findByEmail` well under the cooldown. A mail provider that fails late never touches the
2428
+ > cooldown, so the address stays throttled for the rest of its window.
2429
+
2402
2430
  ### Server Decorators
2403
2431
 
2404
2432
  | Decorator | Usage |
@@ -1086,6 +1086,9 @@ function buildUnauthorisedResponse() {
1086
1086
  __name(buildUnauthorisedResponse, "buildUnauthorisedResponse");
1087
1087
  var CLIENT_REFRESH_ROUTE = shared.AUTH_PROXY_ROUTES.clientRefresh;
1088
1088
  var DEFAULT_LOGOUT_PATH = `/auth/${shared.AUTH_DASHBOARD_ROUTES.logout}`;
1089
+ var SERVER_ERROR_STATUS = 500;
1090
+ var TOO_MANY_REQUESTS_STATUS = 429;
1091
+ var BAD_GATEWAY_STATUS = 502;
1089
1092
  var DEFAULT_REFRESH_COOKIE_PATH2 = "/api/auth";
1090
1093
  function createLogoutHandler(config) {
1091
1094
  const refreshCookiePath = validateLogoutConfig(config);
@@ -1114,15 +1117,20 @@ function createLogoutHandler(config) {
1114
1117
  };
1115
1118
  const incomingAuth = request.headers.get("authorization");
1116
1119
  if (incomingAuth) upstreamHeaders.authorization = incomingAuth;
1120
+ let upstream;
1117
1121
  try {
1118
- await fetch(logoutUrl, {
1122
+ upstream = await fetch(logoutUrl, {
1119
1123
  method: "POST",
1120
1124
  headers: upstreamHeaders,
1121
1125
  redirect: "manual"
1122
1126
  });
1123
1127
  } catch {
1128
+ return failedLogoutResponse(BAD_GATEWAY_STATUS);
1129
+ }
1130
+ if (upstream.status >= SERVER_ERROR_STATUS || upstream.status === TOO_MANY_REQUESTS_STATUS) {
1131
+ return failedLogoutResponse(upstream.status, upstream.headers.get("retry-after"));
1124
1132
  }
1125
- return buildLogoutResponse(request, config, refreshCookiePath);
1133
+ return buildLogoutResponse(config, refreshCookiePath);
1126
1134
  }, "logoutHandler");
1127
1135
  }
1128
1136
  __name(createLogoutHandler, "createLogoutHandler");
@@ -1143,7 +1151,18 @@ function validateLogoutConfig(config) {
1143
1151
  return refreshCookiePath;
1144
1152
  }
1145
1153
  __name(validateLogoutConfig, "validateLogoutConfig");
1146
- function buildLogoutResponse(request, config, refreshCookiePath) {
1154
+ function failedLogoutResponse(status, retryAfter = null) {
1155
+ const headers = new Headers({
1156
+ "Cache-Control": "no-store, no-cache"
1157
+ });
1158
+ if (retryAfter !== null) headers.set("Retry-After", retryAfter);
1159
+ return new Response(null, {
1160
+ status,
1161
+ headers
1162
+ });
1163
+ }
1164
+ __name(failedLogoutResponse, "failedLogoutResponse");
1165
+ function buildLogoutResponse(config, refreshCookiePath) {
1147
1166
  if (config.mode === "redirect") {
1148
1167
  const response2 = redirectToPath(config.loginPath);
1149
1168
  attachClearCookies(response2, config, refreshCookiePath);
@@ -1032,14 +1032,29 @@ declare const CLIENT_REFRESH_ROUTE: "/api/auth/client-refresh";
1032
1032
  *
1033
1033
  * The handler forwards the incoming cookies to the upstream NestJS
1034
1034
  * `POST /auth/logout` endpoint (which revokes the refresh token
1035
- * server-side) and, regardless of whether the upstream responds with
1036
- * success or failure, clears the three auth cookies on the browser.
1037
- * A user who pressed "logout" MUST end up logged out of the browser
1038
- * session even if the upstream is unreachable — otherwise a network
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.
1035
+ * server-side) and clears the three auth cookies on the browser once the
1036
+ * upstream has given a final answer.
1037
+ *
1038
+ * Rule, one line per upstream outcome:
1039
+ *
1040
+ * - the upstream answers below 500 other than 429 (2xx, and a 4xx such as
1041
+ * an expired or already-revoked session): the logout is final, so the
1042
+ * three cookies are cleared and the configured response (200, or the
1043
+ * redirect) is sent;
1044
+ * - the upstream answers 5xx: the logout did not complete and the session
1045
+ * is still alive, so NO cookie is touched and the upstream status is
1046
+ * answered as it is, with no redirect in `'redirect'` mode;
1047
+ * - the upstream answers 429: the logout route is throttled before it
1048
+ * revokes anything, so the session is still alive. Same as 5xx: 429 is
1049
+ * answered with the upstream `Retry-After`, no cookie is touched and
1050
+ * there is no redirect;
1051
+ * - the upstream is unreachable or the request fails: NO cookie is touched
1052
+ * and 502 is answered, with no redirect in `'redirect'` mode.
1053
+ *
1054
+ * The cookies are the client's only handle for retrying the same logout, so
1055
+ * clearing them after a failed revocation would leave a live session the
1056
+ * user believes is gone. The idempotent retry of the NestJS endpoint is
1057
+ * what completes it.
1043
1058
  *
1044
1059
  * Two response modes are supported, expressed as a discriminated
1045
1060
  * union on {@link LogoutHandlerConfig}:
@@ -1032,14 +1032,29 @@ declare const CLIENT_REFRESH_ROUTE: "/api/auth/client-refresh";
1032
1032
  *
1033
1033
  * The handler forwards the incoming cookies to the upstream NestJS
1034
1034
  * `POST /auth/logout` endpoint (which revokes the refresh token
1035
- * server-side) and, regardless of whether the upstream responds with
1036
- * success or failure, clears the three auth cookies on the browser.
1037
- * A user who pressed "logout" MUST end up logged out of the browser
1038
- * session even if the upstream is unreachable — otherwise a network
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.
1035
+ * server-side) and clears the three auth cookies on the browser once the
1036
+ * upstream has given a final answer.
1037
+ *
1038
+ * Rule, one line per upstream outcome:
1039
+ *
1040
+ * - the upstream answers below 500 other than 429 (2xx, and a 4xx such as
1041
+ * an expired or already-revoked session): the logout is final, so the
1042
+ * three cookies are cleared and the configured response (200, or the
1043
+ * redirect) is sent;
1044
+ * - the upstream answers 5xx: the logout did not complete and the session
1045
+ * is still alive, so NO cookie is touched and the upstream status is
1046
+ * answered as it is, with no redirect in `'redirect'` mode;
1047
+ * - the upstream answers 429: the logout route is throttled before it
1048
+ * revokes anything, so the session is still alive. Same as 5xx: 429 is
1049
+ * answered with the upstream `Retry-After`, no cookie is touched and
1050
+ * there is no redirect;
1051
+ * - the upstream is unreachable or the request fails: NO cookie is touched
1052
+ * and 502 is answered, with no redirect in `'redirect'` mode.
1053
+ *
1054
+ * The cookies are the client's only handle for retrying the same logout, so
1055
+ * clearing them after a failed revocation would leave a live session the
1056
+ * user believes is gone. The idempotent retry of the NestJS endpoint is
1057
+ * what completes it.
1043
1058
  *
1044
1059
  * Two response modes are supported, expressed as a discriminated
1045
1060
  * union on {@link LogoutHandlerConfig}:
@@ -1084,6 +1084,9 @@ function buildUnauthorisedResponse() {
1084
1084
  __name(buildUnauthorisedResponse, "buildUnauthorisedResponse");
1085
1085
  var CLIENT_REFRESH_ROUTE = AUTH_PROXY_ROUTES.clientRefresh;
1086
1086
  var DEFAULT_LOGOUT_PATH = `/auth/${AUTH_DASHBOARD_ROUTES.logout}`;
1087
+ var SERVER_ERROR_STATUS = 500;
1088
+ var TOO_MANY_REQUESTS_STATUS = 429;
1089
+ var BAD_GATEWAY_STATUS = 502;
1087
1090
  var DEFAULT_REFRESH_COOKIE_PATH2 = "/api/auth";
1088
1091
  function createLogoutHandler(config) {
1089
1092
  const refreshCookiePath = validateLogoutConfig(config);
@@ -1112,15 +1115,20 @@ function createLogoutHandler(config) {
1112
1115
  };
1113
1116
  const incomingAuth = request.headers.get("authorization");
1114
1117
  if (incomingAuth) upstreamHeaders.authorization = incomingAuth;
1118
+ let upstream;
1115
1119
  try {
1116
- await fetch(logoutUrl, {
1120
+ upstream = await fetch(logoutUrl, {
1117
1121
  method: "POST",
1118
1122
  headers: upstreamHeaders,
1119
1123
  redirect: "manual"
1120
1124
  });
1121
1125
  } catch {
1126
+ return failedLogoutResponse(BAD_GATEWAY_STATUS);
1127
+ }
1128
+ if (upstream.status >= SERVER_ERROR_STATUS || upstream.status === TOO_MANY_REQUESTS_STATUS) {
1129
+ return failedLogoutResponse(upstream.status, upstream.headers.get("retry-after"));
1122
1130
  }
1123
- return buildLogoutResponse(request, config, refreshCookiePath);
1131
+ return buildLogoutResponse(config, refreshCookiePath);
1124
1132
  }, "logoutHandler");
1125
1133
  }
1126
1134
  __name(createLogoutHandler, "createLogoutHandler");
@@ -1141,7 +1149,18 @@ function validateLogoutConfig(config) {
1141
1149
  return refreshCookiePath;
1142
1150
  }
1143
1151
  __name(validateLogoutConfig, "validateLogoutConfig");
1144
- function buildLogoutResponse(request, config, refreshCookiePath) {
1152
+ function failedLogoutResponse(status, retryAfter = null) {
1153
+ const headers = new Headers({
1154
+ "Cache-Control": "no-store, no-cache"
1155
+ });
1156
+ if (retryAfter !== null) headers.set("Retry-After", retryAfter);
1157
+ return new Response(null, {
1158
+ status,
1159
+ headers
1160
+ });
1161
+ }
1162
+ __name(failedLogoutResponse, "failedLogoutResponse");
1163
+ function buildLogoutResponse(config, refreshCookiePath) {
1145
1164
  if (config.mode === "redirect") {
1146
1165
  const response2 = redirectToPath(config.loginPath);
1147
1166
  attachClearCookies(response2, config, refreshCookiePath);
@@ -1,7 +1,6 @@
1
1
  'use strict';
2
2
 
3
3
  var React = require('react');
4
- var shared = require('@bymax-one/nest-auth/shared');
5
4
 
6
5
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
6
 
@@ -13,6 +12,20 @@ var AuthContext = React.createContext(null);
13
12
 
14
13
  // src/react/AuthProvider.tsx
15
14
  var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
15
+ var HTTP_STATUS_MIN = 100;
16
+ function clientErrorStatus(error) {
17
+ if (typeof error !== "object" || error === null) return void 0;
18
+ const { name, status } = error;
19
+ if (name !== "AuthClientError" || !Number.isInteger(status)) return void 0;
20
+ const code = status;
21
+ return code >= HTTP_STATUS_MIN ? code : void 0;
22
+ }
23
+ __name(clientErrorStatus, "clientErrorStatus");
24
+ function isFinalAnswer(error) {
25
+ const status = clientErrorStatus(error);
26
+ return status !== void 0 && status < 500 && status !== 429;
27
+ }
28
+ __name(isFinalAnswer, "isFinalAnswer");
16
29
  var INITIAL_STATE = {
17
30
  user: null,
18
31
  status: "loading",
@@ -47,7 +60,7 @@ function authReducer(state, action) {
47
60
  }
48
61
  __name(authReducer, "authReducer");
49
62
  function isSessionExpiredError(error) {
50
- return error instanceof shared.AuthClientError && error.status === 401;
63
+ return clientErrorStatus(error) === 401;
51
64
  }
52
65
  __name(isSessionExpiredError, "isSessionExpiredError");
53
66
  function AuthProvider({ children, client, onSessionExpired, revalidateInterval = DEFAULT_REVALIDATE_INTERVAL_MS }) {
@@ -197,17 +210,25 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
197
210
  }, [
198
211
  syncedDispatch
199
212
  ]);
213
+ const clearSession = React.useCallback(() => {
214
+ sessionGenerationRef.current = {};
215
+ syncedDispatch({
216
+ type: "CLEAR_SESSION"
217
+ });
218
+ }, [
219
+ syncedDispatch
220
+ ]);
200
221
  const logout = React.useCallback(async () => {
201
222
  try {
202
223
  await clientRef.current.logout();
203
- } finally {
204
- sessionGenerationRef.current = {};
205
- syncedDispatch({
206
- type: "CLEAR_SESSION"
207
- });
224
+ } catch (error) {
225
+ if (!isFinalAnswer(error)) throw error;
226
+ clearSession();
227
+ throw error;
208
228
  }
229
+ clearSession();
209
230
  }, [
210
- syncedDispatch
231
+ clearSession
211
232
  ]);
212
233
  const refresh = React.useCallback(async () => {
213
234
  await revalidate(false);
@@ -135,15 +135,35 @@ interface AuthContextValue {
135
135
  register: (data: RegisterInput) => Promise<AuthResult>;
136
136
  /**
137
137
  * Revoke the current session server-side and clear the local
138
- * context state.
138
+ * context state once the server has confirmed or finally answered.
139
139
  *
140
- * @throws The underlying error raised by `AuthClient.logout` when
141
- * the network call fails. Local context state is STILL cleared
142
- * before the error propagates — consumers can treat a rejection
143
- * as "you are signed out locally, but the server revocation
144
- * request did not complete" and decide whether to retry.
145
- * Callers that do not care about the server-side outcome should
146
- * wrap the call in a try/catch and ignore the error.
140
+ * Rule, by what the server logout did:
141
+ *
142
+ * - it succeeds: the session is revoked and the context state clears;
143
+ * - it fails with a final answer, an `AuthClientError` whose status is
144
+ * below 500 and not 429 (the session is gone or was never valid, and
145
+ * the proxy has cleared the cookies): the context state clears and the
146
+ * error is rethrown;
147
+ * - it fails with a 5xx (502 included), with a 429 (the logout route's
148
+ * throttle, answered before anything is revoked) or with no answer at
149
+ * all (a network failure, an abort): the logout is unconfirmed and the
150
+ * session may be alive, so the context state stays authenticated and
151
+ * the error is rethrown.
152
+ *
153
+ * Which statuses the hook can see depends on the topology. Behind the
154
+ * Next.js proxy route, an upstream answer below 500 other than 429 is
155
+ * answered 200 (or a redirect) after the cookies are cleared, so an
156
+ * upstream 4xx is never relayed: the hook sees a 5xx, a 502 or a 429,
157
+ * which keep the cookies. A 4xx the route answers itself (403 for a
158
+ * cross-site request, 405 for another method) or one from something in
159
+ * front of it reaches the hook and clears the context. Talking to the
160
+ * NestJS server directly, the hook sees the server's own 4xx.
161
+ *
162
+ * @throws The underlying error raised by `AuthClient.logout`. A caller
163
+ * that finds the status still `authenticated` after the rejection
164
+ * should offer a retry; repeating the call is safe because the server
165
+ * logout is idempotent. Callers that do not care about the server-side
166
+ * outcome should wrap the call in a try/catch and ignore the error.
147
167
  */
148
168
  logout: () => Promise<void>;
149
169
  /**
@@ -135,15 +135,35 @@ interface AuthContextValue {
135
135
  register: (data: RegisterInput) => Promise<AuthResult>;
136
136
  /**
137
137
  * Revoke the current session server-side and clear the local
138
- * context state.
138
+ * context state once the server has confirmed or finally answered.
139
139
  *
140
- * @throws The underlying error raised by `AuthClient.logout` when
141
- * the network call fails. Local context state is STILL cleared
142
- * before the error propagates — consumers can treat a rejection
143
- * as "you are signed out locally, but the server revocation
144
- * request did not complete" and decide whether to retry.
145
- * Callers that do not care about the server-side outcome should
146
- * wrap the call in a try/catch and ignore the error.
140
+ * Rule, by what the server logout did:
141
+ *
142
+ * - it succeeds: the session is revoked and the context state clears;
143
+ * - it fails with a final answer, an `AuthClientError` whose status is
144
+ * below 500 and not 429 (the session is gone or was never valid, and
145
+ * the proxy has cleared the cookies): the context state clears and the
146
+ * error is rethrown;
147
+ * - it fails with a 5xx (502 included), with a 429 (the logout route's
148
+ * throttle, answered before anything is revoked) or with no answer at
149
+ * all (a network failure, an abort): the logout is unconfirmed and the
150
+ * session may be alive, so the context state stays authenticated and
151
+ * the error is rethrown.
152
+ *
153
+ * Which statuses the hook can see depends on the topology. Behind the
154
+ * Next.js proxy route, an upstream answer below 500 other than 429 is
155
+ * answered 200 (or a redirect) after the cookies are cleared, so an
156
+ * upstream 4xx is never relayed: the hook sees a 5xx, a 502 or a 429,
157
+ * which keep the cookies. A 4xx the route answers itself (403 for a
158
+ * cross-site request, 405 for another method) or one from something in
159
+ * front of it reaches the hook and clears the context. Talking to the
160
+ * NestJS server directly, the hook sees the server's own 4xx.
161
+ *
162
+ * @throws The underlying error raised by `AuthClient.logout`. A caller
163
+ * that finds the status still `authenticated` after the rejection
164
+ * should offer a retry; repeating the call is safe because the server
165
+ * logout is idempotent. Callers that do not care about the server-side
166
+ * outcome should wrap the call in a try/catch and ignore the error.
147
167
  */
148
168
  logout: () => Promise<void>;
149
169
  /**
@@ -1,5 +1,4 @@
1
1
  import React, { createContext, useReducer, useRef, useEffect, useCallback, useMemo, useContext } from 'react';
2
- import { AuthClientError } from '@bymax-one/nest-auth/shared';
3
2
 
4
3
  var __defProp = Object.defineProperty;
5
4
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
@@ -7,6 +6,20 @@ var AuthContext = createContext(null);
7
6
 
8
7
  // src/react/AuthProvider.tsx
9
8
  var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
9
+ var HTTP_STATUS_MIN = 100;
10
+ function clientErrorStatus(error) {
11
+ if (typeof error !== "object" || error === null) return void 0;
12
+ const { name, status } = error;
13
+ if (name !== "AuthClientError" || !Number.isInteger(status)) return void 0;
14
+ const code = status;
15
+ return code >= HTTP_STATUS_MIN ? code : void 0;
16
+ }
17
+ __name(clientErrorStatus, "clientErrorStatus");
18
+ function isFinalAnswer(error) {
19
+ const status = clientErrorStatus(error);
20
+ return status !== void 0 && status < 500 && status !== 429;
21
+ }
22
+ __name(isFinalAnswer, "isFinalAnswer");
10
23
  var INITIAL_STATE = {
11
24
  user: null,
12
25
  status: "loading",
@@ -41,7 +54,7 @@ function authReducer(state, action) {
41
54
  }
42
55
  __name(authReducer, "authReducer");
43
56
  function isSessionExpiredError(error) {
44
- return error instanceof AuthClientError && error.status === 401;
57
+ return clientErrorStatus(error) === 401;
45
58
  }
46
59
  __name(isSessionExpiredError, "isSessionExpiredError");
47
60
  function AuthProvider({ children, client, onSessionExpired, revalidateInterval = DEFAULT_REVALIDATE_INTERVAL_MS }) {
@@ -191,17 +204,25 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
191
204
  }, [
192
205
  syncedDispatch
193
206
  ]);
207
+ const clearSession = useCallback(() => {
208
+ sessionGenerationRef.current = {};
209
+ syncedDispatch({
210
+ type: "CLEAR_SESSION"
211
+ });
212
+ }, [
213
+ syncedDispatch
214
+ ]);
194
215
  const logout = useCallback(async () => {
195
216
  try {
196
217
  await clientRef.current.logout();
197
- } finally {
198
- sessionGenerationRef.current = {};
199
- syncedDispatch({
200
- type: "CLEAR_SESSION"
201
- });
218
+ } catch (error) {
219
+ if (!isFinalAnswer(error)) throw error;
220
+ clearSession();
221
+ throw error;
202
222
  }
223
+ clearSession();
203
224
  }, [
204
- syncedDispatch
225
+ clearSession
205
226
  ]);
206
227
  const refresh = useCallback(async () => {
207
228
  await revalidate(false);
@@ -6704,16 +6704,26 @@ async function rememberPendingLogout(redis, key, owner, ttlSeconds, logger) {
6704
6704
  }
6705
6705
  }
6706
6706
  __name(rememberPendingLogout, "rememberPendingLogout");
6707
- async function settlePendingLogout(redis, key, fromSession, logger) {
6707
+ async function settlePendingLogout(redis, key, fromSession, owner, ttlSeconds, logger) {
6708
6708
  try {
6709
6709
  const removed = await redis.del(key);
6710
6710
  return fromSession || removed;
6711
6711
  } catch (err) {
6712
6712
  logger.warn(`logout: the retry marker could not be cleared \u2014 ${describeChannelStatus(err)}`);
6713
- return fromSession;
6713
+ if (!fromSession) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
6714
+ return confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger);
6714
6715
  }
6715
6716
  }
6716
6717
  __name(settlePendingLogout, "settlePendingLogout");
6718
+ async function confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger) {
6719
+ try {
6720
+ if (await redis.get(key) === null) return true;
6721
+ } catch {
6722
+ await rememberPendingLogout(redis, key, owner, ttlSeconds, logger);
6723
+ }
6724
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
6725
+ }
6726
+ __name(confirmNoStaleMarker, "confirmNoStaleMarker");
6717
6727
 
6718
6728
  // src/server/utils/resolve-tenant-id.ts
6719
6729
  async function resolveTenantId(dtoTenantId, req, resolver) {
@@ -7166,14 +7176,18 @@ exports.AuthService = class _AuthService {
7166
7176
  () => this.redis.del(`rp:${sessionHash}`)
7167
7177
  ]);
7168
7178
  await this.revokeSessionMetadata(userId, tenantId, sessionHash);
7179
+ const markerTtl = logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn);
7169
7180
  if (failures.length > 0 && fromSession) {
7170
7181
  await rememberPendingLogout(this.redis, markerKey, {
7171
7182
  userId,
7172
7183
  tenantId
7173
- }, logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn), this.logger);
7184
+ }, markerTtl, this.logger);
7174
7185
  }
7175
7186
  raiseFirst(failures);
7176
- if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, this.logger)) {
7187
+ if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, {
7188
+ userId,
7189
+ tenantId
7190
+ }, markerTtl, this.logger)) {
7177
7191
  this.emitLogout(userId, tenantId);
7178
7192
  }
7179
7193
  return userId;
@@ -11991,6 +12005,51 @@ _ts_decorate43([
11991
12005
  }),
11992
12006
  _ts_metadata42("design:type", String)
11993
12007
  ], VerifyOtpDto.prototype, "tenantId", void 0);
12008
+
12009
+ // src/server/utils/answer-reset-request.ts
12010
+ async function answerResetRequest(deps, request) {
12011
+ const { redis, logger } = deps;
12012
+ const { label, cooldownKey, start } = request;
12013
+ const holdFloor = /* @__PURE__ */ __name(() => sleep(Math.max(0, request.floorMs - (Date.now() - start))), "holdFloor");
12014
+ const releaseCooldown = /* @__PURE__ */ __name(async () => {
12015
+ try {
12016
+ await redis.del(cooldownKey);
12017
+ } catch (err) {
12018
+ logger.error(`${label}: cooldown release failed: ${describeChannelStatus(err)}`);
12019
+ }
12020
+ }, "releaseCooldown");
12021
+ let claimed;
12022
+ try {
12023
+ claimed = await redis.setnx(cooldownKey, request.cooldownSeconds);
12024
+ } catch (err) {
12025
+ logger.error(`${label}: cooldown store failed: ${describeChannelStatus(err)}`);
12026
+ await holdFloor();
12027
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
12028
+ }
12029
+ if (!claimed) {
12030
+ await holdFloor();
12031
+ return;
12032
+ }
12033
+ let account;
12034
+ try {
12035
+ account = await request.findAccount();
12036
+ } catch (err) {
12037
+ logger.error(`${label}: account lookup failed: ${describeChannelStatus(err)}`);
12038
+ await releaseCooldown();
12039
+ await holdFloor();
12040
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
12041
+ }
12042
+ try {
12043
+ if (account && !request.isBlocked(account.status)) await request.issue(account.id);
12044
+ } catch (err) {
12045
+ logger.error(`${label}: unexpected error: ${describeChannelStatus(err)}`);
12046
+ await releaseCooldown();
12047
+ }
12048
+ await holdFloor();
12049
+ }
12050
+ __name(answerResetRequest, "answerResetRequest");
12051
+
12052
+ // src/server/services/password-reset.service.ts
11994
12053
  function _ts_decorate44(decorators, target, key, desc) {
11995
12054
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
11996
12055
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -12056,12 +12115,14 @@ exports.PasswordResetService = class _PasswordResetService {
12056
12115
  * inactive, or suspended), issues a reset token or OTP (depending on
12057
12116
  * `options.passwordReset.method`) and sends it via the email provider.
12058
12117
  *
12059
- * **Always returns without throwing**, even when:
12118
+ * **Resolves the same way** whether or not the account exists:
12060
12119
  * - The email does not exist in the tenant.
12061
12120
  * - The account is blocked.
12062
- * - The email provider fails.
12121
+ * - Issuing or storing the code, or the email provider, fails for an account that exists.
12063
12122
  *
12064
- * This anti-enumeration design ensures the response cannot be used to probe
12123
+ * A failure that is the same for every address, the resend-cooldown store or the account
12124
+ * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
12125
+ * released. This anti-enumeration design ensures the response cannot be used to probe
12065
12126
  * whether an email address is registered.
12066
12127
  *
12067
12128
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
@@ -12077,30 +12138,8 @@ exports.PasswordResetService = class _PasswordResetService {
12077
12138
  email: normalizeEmail(dto.email)
12078
12139
  };
12079
12140
  const start = Date.now();
12080
- const cooldownKey = `resend:${PASSWORD_RESET_PURPOSE}:${this.otpIdentifier(tenantId, dto.email)}`;
12081
- const wasSet = await this.redis.setnx(cooldownKey, RESEND_COOLDOWN_SECONDS);
12082
- if (!wasSet) {
12083
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12084
- return;
12085
- }
12086
- try {
12087
- const user = tenantScoped(await this.userRepo.findByEmail({
12088
- email: dto.email,
12089
- tenantId
12090
- }), tenantId);
12091
- if (user && !this.isBlocked(user.status)) {
12092
- const { method } = this.options.passwordReset;
12093
- if (method === "otp") {
12094
- await this.sendOtp(dto.email, tenantId, user.id);
12095
- } else {
12096
- await this.sendToken(dto.email, tenantId, user.id);
12097
- }
12098
- }
12099
- } catch (err) {
12100
- this.logger.error(`initiateReset: unexpected error: ${describeChannelStatus(err)}`);
12101
- } finally {
12102
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12103
- }
12141
+ const { method } = this.options.passwordReset;
12142
+ await this.answerResetRequest("initiateReset", dto.email, tenantId, start, (userId) => method === "otp" ? this.sendOtp(dto.email, tenantId, userId) : this.sendToken(dto.email, tenantId, userId));
12104
12143
  }
12105
12144
  /**
12106
12145
  * Resets the user's password using a verified proof (token, OTP, or verifiedToken).
@@ -12206,8 +12245,9 @@ exports.PasswordResetService = class _PasswordResetService {
12206
12245
  * Requests a new password-reset OTP for the given email address.
12207
12246
  *
12208
12247
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
12209
- * prevent OTP flooding. Always returns success regardless of whether the
12210
- * user exists — anti-enumeration principle.
12248
+ * prevent OTP flooding. Resolves the same way whether or not the user exists —
12249
+ * anti-enumeration principle; a failure of the cooldown store or the account lookup
12250
+ * throws `INTERNAL` (500) after the floor and releases the cooldown.
12211
12251
  *
12212
12252
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
12213
12253
  *
@@ -12221,26 +12261,29 @@ exports.PasswordResetService = class _PasswordResetService {
12221
12261
  email: normalizeEmail(dto.email)
12222
12262
  };
12223
12263
  const start = Date.now();
12224
- const identifier = this.otpIdentifier(tenantId, dto.email);
12225
- const cooldownKey = `resend:${PASSWORD_RESET_PURPOSE}:${identifier}`;
12226
- const wasSet = await this.redis.setnx(cooldownKey, RESEND_COOLDOWN_SECONDS);
12227
- if (!wasSet) {
12228
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12229
- return;
12230
- }
12231
- try {
12232
- const user = tenantScoped(await this.userRepo.findByEmail({
12233
- email: dto.email,
12264
+ await this.answerResetRequest("resendOtp", dto.email, tenantId, start, (userId) => this.sendOtp(dto.email, tenantId, userId));
12265
+ }
12266
+ // ---------------------------------------------------------------------------
12267
+ // Private helpers — reset requests
12268
+ // ---------------------------------------------------------------------------
12269
+ /** Runs one `forgot-password` or `resend-otp` request through the shared failure rule. */
12270
+ answerResetRequest(label, email, tenantId, start, issue) {
12271
+ return answerResetRequest({
12272
+ redis: this.redis,
12273
+ logger: this.logger
12274
+ }, {
12275
+ label,
12276
+ cooldownKey: `resend:${PASSWORD_RESET_PURPOSE}:${this.otpIdentifier(tenantId, email)}`,
12277
+ cooldownSeconds: RESEND_COOLDOWN_SECONDS,
12278
+ floorMs: ANTI_ENUM_MIN_MS2,
12279
+ start,
12280
+ findAccount: /* @__PURE__ */ __name(async () => tenantScoped(await this.userRepo.findByEmail({
12281
+ email,
12234
12282
  tenantId
12235
- }), tenantId);
12236
- if (user && !this.isBlocked(user.status)) {
12237
- await this.sendOtp(dto.email, tenantId, user.id);
12238
- }
12239
- } catch (err) {
12240
- this.logger.error(`resendOtp: unexpected error: ${describeChannelStatus(err)}`);
12241
- } finally {
12242
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12243
- }
12283
+ }), tenantId), "findAccount"),
12284
+ isBlocked: /* @__PURE__ */ __name((status) => this.isBlocked(status), "isBlocked"),
12285
+ issue
12286
+ });
12244
12287
  }
12245
12288
  // ---------------------------------------------------------------------------
12246
12289
  // Private helpers — reset paths
@@ -12702,8 +12745,9 @@ var PasswordResetController = class {
12702
12745
  * Initiates a password reset for the given email address.
12703
12746
  *
12704
12747
  * Sends a reset token or OTP to the user's email if the account exists and
12705
- * is eligible. Always returns `200 OK` with an empty JSON object regardless of outcome
12706
- * (anti-enumeration; the body is pinned by the wire contract).
12748
+ * is eligible. Answers `200 OK` with an empty JSON object whether or not the account exists
12749
+ * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
12750
+ * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
12707
12751
  *
12708
12752
  * @param dto - Validated DTO with `email` and `tenantId`.
12709
12753
  * @returns An empty object.
@@ -12790,8 +12834,9 @@ var PasswordResetController = class {
12790
12834
  * Re-sends the password-reset OTP for the given email address.
12791
12835
  *
12792
12836
  * Subject to a 60-second atomic cooldown per `(tenantId, email)` pair.
12793
- * Always returns `200 OK` with an empty JSON object regardless of outcome (anti-enumeration;
12794
- * the body is pinned by the wire contract).
12837
+ * Answers `200 OK` with an empty JSON object whether or not the account exists
12838
+ * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
12839
+ * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
12795
12840
  *
12796
12841
  * @param dto - Validated DTO with `email` and `tenantId`.
12797
12842
  * @returns An empty object.
@@ -13181,14 +13226,18 @@ exports.PlatformAuthService = class _PlatformAuthService {
13181
13226
  ]),
13182
13227
  settleAfter(() => this.redis.del("prp:" + tokenHash), prune("prp:" + tokenHash))
13183
13228
  ]);
13229
+ const markerTtl = logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn);
13184
13230
  if (failures.length > 0 && fromSession) {
13185
13231
  await rememberPendingLogout(this.redis, markerKey, {
13186
13232
  userId,
13187
13233
  tenantId: void 0
13188
- }, logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn), this.logger);
13234
+ }, markerTtl, this.logger);
13189
13235
  }
13190
13236
  raiseFirst(failures);
13191
- if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, this.logger)) {
13237
+ if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, {
13238
+ userId,
13239
+ tenantId: void 0
13240
+ }, markerTtl, this.logger)) {
13192
13241
  this.emitPlatformLogout(userId);
13193
13242
  }
13194
13243
  return userId;
@@ -276,6 +276,11 @@ interface IUserRepository {
276
276
  /**
277
277
  * Finds a user by email address within a specific tenant.
278
278
  *
279
+ * **Keep this call well under the password-reset resend cooldown (60 seconds).** The reset flows
280
+ * claim the cooldown before they call this, and release it by key when this call throws. A call
281
+ * that takes longer than the cooldown and then fails releases a key that may by then belong to a
282
+ * later request, whose cooldown is removed early. The library does not guard against it.
283
+ *
279
284
  * @returns The matching user record, or null if not found.
280
285
  */
281
286
  findByEmail(params: FindUserByEmailParams): Promise<AuthUser | null>;
@@ -312,6 +317,15 @@ interface IUserRepository {
312
317
  * spent recovery code in the account's list. An implementation MUST scope the update by both the
313
318
  * id and the tenant, exactly as its read does.
314
319
  *
320
+ * **Keep this call well under the MFA transition lock's lifetime.** The library serializes MFA
321
+ * state changes per account with a lock that expires on its own after
322
+ * `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), so a process that dies mid-write cannot strand
323
+ * the account. A write still running when the lock expires is overtaken: a second change takes
324
+ * the lock, reads the record and writes it, and this write then lands after it and overwrites it.
325
+ * The interface has no compare-and-set for the library to use, so it cannot detect that. The
326
+ * parameters carry only the new values, so a guard inside this method can narrow the window only
327
+ * for a stall after its own read; closing it would need the values the library read passed in.
328
+ *
315
329
  * @param params - See {@link UpdateMfaParams}.
316
330
  */
317
331
  updateMfa(params: UpdateMfaParams): Promise<void>;
@@ -3796,6 +3810,15 @@ interface IPlatformUserRepository {
3796
3810
  * `mfaSecret` with AES-256-GCM and hash `mfaRecoveryCodes` with SHA-256
3797
3811
  * before passing them here.
3798
3812
  *
3813
+ * **Keep this call well under the MFA transition lock's lifetime.** The library serializes MFA
3814
+ * state changes per account with a lock that expires on its own after
3815
+ * `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), so a process that dies mid-write cannot strand
3816
+ * the account. A write still running when the lock expires is overtaken: a second change takes
3817
+ * the lock, reads the record and writes it, and this write then lands after it and overwrites it.
3818
+ * The interface has no compare-and-set for the library to use, so it cannot detect that. The
3819
+ * parameters carry only the new values, so a guard inside this method can narrow the window only
3820
+ * for a stall after its own read; closing it would need the values the library read passed in.
3821
+ *
3799
3822
  * @param id - The platform administrator's unique identifier.
3800
3823
  * @param data - New MFA state. See {@link UpdatePlatformMfaData}.
3801
3824
  */
@@ -9793,12 +9816,14 @@ declare class PasswordResetService {
9793
9816
  * inactive, or suspended), issues a reset token or OTP (depending on
9794
9817
  * `options.passwordReset.method`) and sends it via the email provider.
9795
9818
  *
9796
- * **Always returns without throwing**, even when:
9819
+ * **Resolves the same way** whether or not the account exists:
9797
9820
  * - The email does not exist in the tenant.
9798
9821
  * - The account is blocked.
9799
- * - The email provider fails.
9822
+ * - Issuing or storing the code, or the email provider, fails for an account that exists.
9800
9823
  *
9801
- * This anti-enumeration design ensures the response cannot be used to probe
9824
+ * A failure that is the same for every address, the resend-cooldown store or the account
9825
+ * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
9826
+ * released. This anti-enumeration design ensures the response cannot be used to probe
9802
9827
  * whether an email address is registered.
9803
9828
  *
9804
9829
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
@@ -9850,14 +9875,17 @@ declare class PasswordResetService {
9850
9875
  * Requests a new password-reset OTP for the given email address.
9851
9876
  *
9852
9877
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
9853
- * prevent OTP flooding. Always returns success regardless of whether the
9854
- * user exists — anti-enumeration principle.
9878
+ * prevent OTP flooding. Resolves the same way whether or not the user exists —
9879
+ * anti-enumeration principle; a failure of the cooldown store or the account lookup
9880
+ * throws `INTERNAL` (500) after the floor and releases the cooldown.
9855
9881
  *
9856
9882
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
9857
9883
  *
9858
9884
  * @param dto - Validated DTO with `email` and `tenantId`.
9859
9885
  */
9860
9886
  resendOtp(dto: ResendOtpDto, req: Request): Promise<void>;
9887
+ /** Runs one `forgot-password` or `resend-otp` request through the shared failure rule. */
9888
+ private answerResetRequest;
9861
9889
  /**
9862
9890
  * Token-based reset path: atomically consumes the token from Redis and updates
9863
9891
  * the password.
@@ -276,6 +276,11 @@ interface IUserRepository {
276
276
  /**
277
277
  * Finds a user by email address within a specific tenant.
278
278
  *
279
+ * **Keep this call well under the password-reset resend cooldown (60 seconds).** The reset flows
280
+ * claim the cooldown before they call this, and release it by key when this call throws. A call
281
+ * that takes longer than the cooldown and then fails releases a key that may by then belong to a
282
+ * later request, whose cooldown is removed early. The library does not guard against it.
283
+ *
279
284
  * @returns The matching user record, or null if not found.
280
285
  */
281
286
  findByEmail(params: FindUserByEmailParams): Promise<AuthUser | null>;
@@ -312,6 +317,15 @@ interface IUserRepository {
312
317
  * spent recovery code in the account's list. An implementation MUST scope the update by both the
313
318
  * id and the tenant, exactly as its read does.
314
319
  *
320
+ * **Keep this call well under the MFA transition lock's lifetime.** The library serializes MFA
321
+ * state changes per account with a lock that expires on its own after
322
+ * `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), so a process that dies mid-write cannot strand
323
+ * the account. A write still running when the lock expires is overtaken: a second change takes
324
+ * the lock, reads the record and writes it, and this write then lands after it and overwrites it.
325
+ * The interface has no compare-and-set for the library to use, so it cannot detect that. The
326
+ * parameters carry only the new values, so a guard inside this method can narrow the window only
327
+ * for a stall after its own read; closing it would need the values the library read passed in.
328
+ *
315
329
  * @param params - See {@link UpdateMfaParams}.
316
330
  */
317
331
  updateMfa(params: UpdateMfaParams): Promise<void>;
@@ -3796,6 +3810,15 @@ interface IPlatformUserRepository {
3796
3810
  * `mfaSecret` with AES-256-GCM and hash `mfaRecoveryCodes` with SHA-256
3797
3811
  * before passing them here.
3798
3812
  *
3813
+ * **Keep this call well under the MFA transition lock's lifetime.** The library serializes MFA
3814
+ * state changes per account with a lock that expires on its own after
3815
+ * `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), so a process that dies mid-write cannot strand
3816
+ * the account. A write still running when the lock expires is overtaken: a second change takes
3817
+ * the lock, reads the record and writes it, and this write then lands after it and overwrites it.
3818
+ * The interface has no compare-and-set for the library to use, so it cannot detect that. The
3819
+ * parameters carry only the new values, so a guard inside this method can narrow the window only
3820
+ * for a stall after its own read; closing it would need the values the library read passed in.
3821
+ *
3799
3822
  * @param id - The platform administrator's unique identifier.
3800
3823
  * @param data - New MFA state. See {@link UpdatePlatformMfaData}.
3801
3824
  */
@@ -9793,12 +9816,14 @@ declare class PasswordResetService {
9793
9816
  * inactive, or suspended), issues a reset token or OTP (depending on
9794
9817
  * `options.passwordReset.method`) and sends it via the email provider.
9795
9818
  *
9796
- * **Always returns without throwing**, even when:
9819
+ * **Resolves the same way** whether or not the account exists:
9797
9820
  * - The email does not exist in the tenant.
9798
9821
  * - The account is blocked.
9799
- * - The email provider fails.
9822
+ * - Issuing or storing the code, or the email provider, fails for an account that exists.
9800
9823
  *
9801
- * This anti-enumeration design ensures the response cannot be used to probe
9824
+ * A failure that is the same for every address, the resend-cooldown store or the account
9825
+ * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
9826
+ * released. This anti-enumeration design ensures the response cannot be used to probe
9802
9827
  * whether an email address is registered.
9803
9828
  *
9804
9829
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
@@ -9850,14 +9875,17 @@ declare class PasswordResetService {
9850
9875
  * Requests a new password-reset OTP for the given email address.
9851
9876
  *
9852
9877
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
9853
- * prevent OTP flooding. Always returns success regardless of whether the
9854
- * user exists — anti-enumeration principle.
9878
+ * prevent OTP flooding. Resolves the same way whether or not the user exists —
9879
+ * anti-enumeration principle; a failure of the cooldown store or the account lookup
9880
+ * throws `INTERNAL` (500) after the floor and releases the cooldown.
9855
9881
  *
9856
9882
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
9857
9883
  *
9858
9884
  * @param dto - Validated DTO with `email` and `tenantId`.
9859
9885
  */
9860
9886
  resendOtp(dto: ResendOtpDto, req: Request): Promise<void>;
9887
+ /** Runs one `forgot-password` or `resend-otp` request through the shared failure rule. */
9888
+ private answerResetRequest;
9861
9889
  /**
9862
9890
  * Token-based reset path: atomically consumes the token from Redis and updates
9863
9891
  * the password.
@@ -6702,16 +6702,26 @@ async function rememberPendingLogout(redis, key, owner, ttlSeconds, logger) {
6702
6702
  }
6703
6703
  }
6704
6704
  __name(rememberPendingLogout, "rememberPendingLogout");
6705
- async function settlePendingLogout(redis, key, fromSession, logger) {
6705
+ async function settlePendingLogout(redis, key, fromSession, owner, ttlSeconds, logger) {
6706
6706
  try {
6707
6707
  const removed = await redis.del(key);
6708
6708
  return fromSession || removed;
6709
6709
  } catch (err) {
6710
6710
  logger.warn(`logout: the retry marker could not be cleared \u2014 ${describeChannelStatus(err)}`);
6711
- return fromSession;
6711
+ if (!fromSession) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
6712
+ return confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger);
6712
6713
  }
6713
6714
  }
6714
6715
  __name(settlePendingLogout, "settlePendingLogout");
6716
+ async function confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger) {
6717
+ try {
6718
+ if (await redis.get(key) === null) return true;
6719
+ } catch {
6720
+ await rememberPendingLogout(redis, key, owner, ttlSeconds, logger);
6721
+ }
6722
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
6723
+ }
6724
+ __name(confirmNoStaleMarker, "confirmNoStaleMarker");
6715
6725
 
6716
6726
  // src/server/utils/resolve-tenant-id.ts
6717
6727
  async function resolveTenantId(dtoTenantId, req, resolver) {
@@ -7164,14 +7174,18 @@ var AuthService = class _AuthService {
7164
7174
  () => this.redis.del(`rp:${sessionHash}`)
7165
7175
  ]);
7166
7176
  await this.revokeSessionMetadata(userId, tenantId, sessionHash);
7177
+ const markerTtl = logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn);
7167
7178
  if (failures.length > 0 && fromSession) {
7168
7179
  await rememberPendingLogout(this.redis, markerKey, {
7169
7180
  userId,
7170
7181
  tenantId
7171
- }, logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn), this.logger);
7182
+ }, markerTtl, this.logger);
7172
7183
  }
7173
7184
  raiseFirst(failures);
7174
- if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, this.logger)) {
7185
+ if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, {
7186
+ userId,
7187
+ tenantId
7188
+ }, markerTtl, this.logger)) {
7175
7189
  this.emitLogout(userId, tenantId);
7176
7190
  }
7177
7191
  return userId;
@@ -11989,6 +12003,51 @@ _ts_decorate43([
11989
12003
  }),
11990
12004
  _ts_metadata42("design:type", String)
11991
12005
  ], VerifyOtpDto.prototype, "tenantId", void 0);
12006
+
12007
+ // src/server/utils/answer-reset-request.ts
12008
+ async function answerResetRequest(deps, request) {
12009
+ const { redis, logger } = deps;
12010
+ const { label, cooldownKey, start } = request;
12011
+ const holdFloor = /* @__PURE__ */ __name(() => sleep(Math.max(0, request.floorMs - (Date.now() - start))), "holdFloor");
12012
+ const releaseCooldown = /* @__PURE__ */ __name(async () => {
12013
+ try {
12014
+ await redis.del(cooldownKey);
12015
+ } catch (err) {
12016
+ logger.error(`${label}: cooldown release failed: ${describeChannelStatus(err)}`);
12017
+ }
12018
+ }, "releaseCooldown");
12019
+ let claimed;
12020
+ try {
12021
+ claimed = await redis.setnx(cooldownKey, request.cooldownSeconds);
12022
+ } catch (err) {
12023
+ logger.error(`${label}: cooldown store failed: ${describeChannelStatus(err)}`);
12024
+ await holdFloor();
12025
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
12026
+ }
12027
+ if (!claimed) {
12028
+ await holdFloor();
12029
+ return;
12030
+ }
12031
+ let account;
12032
+ try {
12033
+ account = await request.findAccount();
12034
+ } catch (err) {
12035
+ logger.error(`${label}: account lookup failed: ${describeChannelStatus(err)}`);
12036
+ await releaseCooldown();
12037
+ await holdFloor();
12038
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
12039
+ }
12040
+ try {
12041
+ if (account && !request.isBlocked(account.status)) await request.issue(account.id);
12042
+ } catch (err) {
12043
+ logger.error(`${label}: unexpected error: ${describeChannelStatus(err)}`);
12044
+ await releaseCooldown();
12045
+ }
12046
+ await holdFloor();
12047
+ }
12048
+ __name(answerResetRequest, "answerResetRequest");
12049
+
12050
+ // src/server/services/password-reset.service.ts
11992
12051
  function _ts_decorate44(decorators, target, key, desc) {
11993
12052
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
11994
12053
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -12054,12 +12113,14 @@ var PasswordResetService = class _PasswordResetService {
12054
12113
  * inactive, or suspended), issues a reset token or OTP (depending on
12055
12114
  * `options.passwordReset.method`) and sends it via the email provider.
12056
12115
  *
12057
- * **Always returns without throwing**, even when:
12116
+ * **Resolves the same way** whether or not the account exists:
12058
12117
  * - The email does not exist in the tenant.
12059
12118
  * - The account is blocked.
12060
- * - The email provider fails.
12119
+ * - Issuing or storing the code, or the email provider, fails for an account that exists.
12061
12120
  *
12062
- * This anti-enumeration design ensures the response cannot be used to probe
12121
+ * A failure that is the same for every address, the resend-cooldown store or the account
12122
+ * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
12123
+ * released. This anti-enumeration design ensures the response cannot be used to probe
12063
12124
  * whether an email address is registered.
12064
12125
  *
12065
12126
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
@@ -12075,30 +12136,8 @@ var PasswordResetService = class _PasswordResetService {
12075
12136
  email: normalizeEmail(dto.email)
12076
12137
  };
12077
12138
  const start = Date.now();
12078
- const cooldownKey = `resend:${PASSWORD_RESET_PURPOSE}:${this.otpIdentifier(tenantId, dto.email)}`;
12079
- const wasSet = await this.redis.setnx(cooldownKey, RESEND_COOLDOWN_SECONDS);
12080
- if (!wasSet) {
12081
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12082
- return;
12083
- }
12084
- try {
12085
- const user = tenantScoped(await this.userRepo.findByEmail({
12086
- email: dto.email,
12087
- tenantId
12088
- }), tenantId);
12089
- if (user && !this.isBlocked(user.status)) {
12090
- const { method } = this.options.passwordReset;
12091
- if (method === "otp") {
12092
- await this.sendOtp(dto.email, tenantId, user.id);
12093
- } else {
12094
- await this.sendToken(dto.email, tenantId, user.id);
12095
- }
12096
- }
12097
- } catch (err) {
12098
- this.logger.error(`initiateReset: unexpected error: ${describeChannelStatus(err)}`);
12099
- } finally {
12100
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12101
- }
12139
+ const { method } = this.options.passwordReset;
12140
+ await this.answerResetRequest("initiateReset", dto.email, tenantId, start, (userId) => method === "otp" ? this.sendOtp(dto.email, tenantId, userId) : this.sendToken(dto.email, tenantId, userId));
12102
12141
  }
12103
12142
  /**
12104
12143
  * Resets the user's password using a verified proof (token, OTP, or verifiedToken).
@@ -12204,8 +12243,9 @@ var PasswordResetService = class _PasswordResetService {
12204
12243
  * Requests a new password-reset OTP for the given email address.
12205
12244
  *
12206
12245
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
12207
- * prevent OTP flooding. Always returns success regardless of whether the
12208
- * user exists — anti-enumeration principle.
12246
+ * prevent OTP flooding. Resolves the same way whether or not the user exists —
12247
+ * anti-enumeration principle; a failure of the cooldown store or the account lookup
12248
+ * throws `INTERNAL` (500) after the floor and releases the cooldown.
12209
12249
  *
12210
12250
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
12211
12251
  *
@@ -12219,26 +12259,29 @@ var PasswordResetService = class _PasswordResetService {
12219
12259
  email: normalizeEmail(dto.email)
12220
12260
  };
12221
12261
  const start = Date.now();
12222
- const identifier = this.otpIdentifier(tenantId, dto.email);
12223
- const cooldownKey = `resend:${PASSWORD_RESET_PURPOSE}:${identifier}`;
12224
- const wasSet = await this.redis.setnx(cooldownKey, RESEND_COOLDOWN_SECONDS);
12225
- if (!wasSet) {
12226
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12227
- return;
12228
- }
12229
- try {
12230
- const user = tenantScoped(await this.userRepo.findByEmail({
12231
- email: dto.email,
12262
+ await this.answerResetRequest("resendOtp", dto.email, tenantId, start, (userId) => this.sendOtp(dto.email, tenantId, userId));
12263
+ }
12264
+ // ---------------------------------------------------------------------------
12265
+ // Private helpers — reset requests
12266
+ // ---------------------------------------------------------------------------
12267
+ /** Runs one `forgot-password` or `resend-otp` request through the shared failure rule. */
12268
+ answerResetRequest(label, email, tenantId, start, issue) {
12269
+ return answerResetRequest({
12270
+ redis: this.redis,
12271
+ logger: this.logger
12272
+ }, {
12273
+ label,
12274
+ cooldownKey: `resend:${PASSWORD_RESET_PURPOSE}:${this.otpIdentifier(tenantId, email)}`,
12275
+ cooldownSeconds: RESEND_COOLDOWN_SECONDS,
12276
+ floorMs: ANTI_ENUM_MIN_MS2,
12277
+ start,
12278
+ findAccount: /* @__PURE__ */ __name(async () => tenantScoped(await this.userRepo.findByEmail({
12279
+ email,
12232
12280
  tenantId
12233
- }), tenantId);
12234
- if (user && !this.isBlocked(user.status)) {
12235
- await this.sendOtp(dto.email, tenantId, user.id);
12236
- }
12237
- } catch (err) {
12238
- this.logger.error(`resendOtp: unexpected error: ${describeChannelStatus(err)}`);
12239
- } finally {
12240
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12241
- }
12281
+ }), tenantId), "findAccount"),
12282
+ isBlocked: /* @__PURE__ */ __name((status) => this.isBlocked(status), "isBlocked"),
12283
+ issue
12284
+ });
12242
12285
  }
12243
12286
  // ---------------------------------------------------------------------------
12244
12287
  // Private helpers — reset paths
@@ -12700,8 +12743,9 @@ var PasswordResetController = class {
12700
12743
  * Initiates a password reset for the given email address.
12701
12744
  *
12702
12745
  * Sends a reset token or OTP to the user's email if the account exists and
12703
- * is eligible. Always returns `200 OK` with an empty JSON object regardless of outcome
12704
- * (anti-enumeration; the body is pinned by the wire contract).
12746
+ * is eligible. Answers `200 OK` with an empty JSON object whether or not the account exists
12747
+ * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
12748
+ * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
12705
12749
  *
12706
12750
  * @param dto - Validated DTO with `email` and `tenantId`.
12707
12751
  * @returns An empty object.
@@ -12788,8 +12832,9 @@ var PasswordResetController = class {
12788
12832
  * Re-sends the password-reset OTP for the given email address.
12789
12833
  *
12790
12834
  * Subject to a 60-second atomic cooldown per `(tenantId, email)` pair.
12791
- * Always returns `200 OK` with an empty JSON object regardless of outcome (anti-enumeration;
12792
- * the body is pinned by the wire contract).
12835
+ * Answers `200 OK` with an empty JSON object whether or not the account exists
12836
+ * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
12837
+ * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
12793
12838
  *
12794
12839
  * @param dto - Validated DTO with `email` and `tenantId`.
12795
12840
  * @returns An empty object.
@@ -13179,14 +13224,18 @@ var PlatformAuthService = class _PlatformAuthService {
13179
13224
  ]),
13180
13225
  settleAfter(() => this.redis.del("prp:" + tokenHash), prune("prp:" + tokenHash))
13181
13226
  ]);
13227
+ const markerTtl = logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn);
13182
13228
  if (failures.length > 0 && fromSession) {
13183
13229
  await rememberPendingLogout(this.redis, markerKey, {
13184
13230
  userId,
13185
13231
  tenantId: void 0
13186
- }, logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn), this.logger);
13232
+ }, markerTtl, this.logger);
13187
13233
  }
13188
13234
  raiseFirst(failures);
13189
- if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, this.logger)) {
13235
+ if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, {
13236
+ userId,
13237
+ tenantId: void 0
13238
+ }, markerTtl, this.logger)) {
13190
13239
  this.emitPlatformLogout(userId);
13191
13240
  }
13192
13241
  return userId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.4.18",
3
+ "version": "1.4.19",
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",