@bymax-one/nest-auth 1.4.17 → 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,145 @@ 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
+
95
+ ## [1.4.18] - 2026-11-07
96
+
97
+ ### Apply to a derived backend
98
+
99
+ - **A request body declared compressed is now refused with `415 auth.validation`, whatever the
100
+ host's body parser does.** Express's default parser decompresses `gzip`, `deflate` and `br`
101
+ before a handler runs, so these requests used to be accepted; rust-auth refuses them. The
102
+ library now answers `415` "Unsupported media type" in the library envelope for any
103
+ `Content-Encoding` other than `identity` on its JSON-body routes, before the handler. Refresh,
104
+ logout, revoke-all and the WebSocket ticket request are unchecked; the MFA setup routes, which
105
+ accept an empty body, refuse it only when a body is present; `GET`, `HEAD`, `OPTIONS` and
106
+ `DELETE` requests are never checked. The route-by-route scope is the new `requestEncoding`
107
+ section of `conformance/wire-contract.json`, and a test fails when a controller route is added
108
+ without a decision. A client that compresses its request bodies must send them uncompressed;
109
+ browsers and `fetch` do not compress them. A host that also sets `inflate: false` on its JSON
110
+ parser refuses earlier, with the same `415` through `AuthExceptionFilter`.
111
+ - **A body that claims to be compressed and is not now answers `400 auth.validation`
112
+ `Malformed request`, not `500`.** The body parser raises that failure as a plain 400 with no
113
+ `type`, so `AuthExceptionFilter` now answers a 400 error of that shape that arrived before any
114
+ route matched with the fixed message. The `transportErrors` section lists the row.
115
+ - **New public API:** `RequestEncodingGuard`, applied at class level to every library controller
116
+ and available for a host's own controllers; the `@RequestEncoding('unchecked' | 'when-body')`
117
+ decorator and its `RequestEncodingPolicy` type, which set a route's policy (a route with none is
118
+ strict). `content-encoding`, `content-length` and `transfer-encoding` join the headers the library reads,
119
+ so `apiKeys.header` can no longer name them.
120
+ - **A logout that needed a retry now fires `afterLogout` (and `afterPlatformLogout`) once, on the
121
+ retry that completes it.** A logout attempts every revocation write and answers `5xx` when one
122
+ failed, and the attempt had already deleted the refresh session, so the retry found no record to
123
+ say whose logout it was and the hook never fired for it. An attempt that fails a write while it
124
+ still has the session's owner now leaves a short-lived marker, `lp:{sha256(refreshToken)}` on the
125
+ dashboard plane and `plp:{...}` on the platform plane, holding the owner and tenant from the
126
+ session record; it lives for the access-token lifetime and never less than 300 seconds. A retry
127
+ that finds no session reads the owner from the marker, and when it completes with no failure it
128
+ removes the marker and fires the hook only if that removal removed it, so sequential retries
129
+ announce once and a repeat announces nothing; attempts of one logout that run concurrently are
130
+ at-least-once. The owner is never taken from an access
131
+ token's claims. A marker that cannot be written leaves the retry silent, as before, and a marker
132
+ that cannot be removed never fails a completed logout. HTTP statuses, bodies and cookies are
133
+ unchanged. The shared contract gains the two key prefixes and a `logoutPending` record row. A
134
+ consumer whose hook assumed a logout is announced only by the call that found the session now
135
+ also receives it from the completing retry. Private `blacklistWrites` (both services) and
136
+ `revokeSessionMetadata` (`AuthService`) appear in the declarations.
137
+ - **A late MFA re-encryption can no longer overwrite a `disable` or a re-enrolment.** This applies
138
+ only to a deployment that has configured `mfa.previousEncryptionKeys` and still holds secrets
139
+ stored under a retired key: the first successful challenge on such an account re-encrypts the
140
+ secret under the current key, and that write replaces the whole MFA record. If the user disabled
141
+ MFA, or re-enrolled with a new secret and recovery codes, while that write was in flight, it could
142
+ restore the removed factor or the replaced secret and recovery digests. The re-encryption is now
143
+ one of the serialized MFA transitions and writes only when the stored secret still decrypts to
144
+ the secret the challenge opened, and the recovery-code challenge makes the same check before it
145
+ writes back the list without the used code. A sibling challenge that only re-encrypted the same secret does not count as a
146
+ change. Accounts already past the migration, and deployments with no retired key, are not
147
+ affected; draining the retired keys closes the exposure. When another transition holds the lock
148
+ the migration is skipped and retried by the next challenge. No contract change. Private
149
+ `holdsSecret` appears in the `MfaService` declarations, and the private `reencryptSecret` loses
150
+ its recovery-codes parameter.
151
+
152
+ ### Fixed
153
+
154
+ - **Compressed request bodies are refused the way rust-auth refuses them, and a corrupt one no
155
+ longer answers `500`.** See the note above.
156
+ - **A logout completed by a retry no longer goes unannounced.** See the note above.
157
+ - **The MFA re-encryption under the current key no longer overwrites a concurrent `disable` or
158
+ re-enrolment.** See the note above.
159
+
21
160
  ## [1.4.17] - 2026-11-07
22
161
 
23
162
  ### Apply to a derived backend
@@ -4418,7 +4557,9 @@ ever installable.
4418
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
4419
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
4420
4559
 
4421
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.17...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
4562
+ [1.4.18]: https://github.com/bymaxone/nest-auth/compare/v1.4.17...v1.4.18
4422
4563
  [1.4.17]: https://github.com/bymaxone/nest-auth/compare/v1.4.16...v1.4.17
4423
4564
  [1.4.16]: https://github.com/bymaxone/nest-auth/compare/v1.4.15...v1.4.16
4424
4565
  [1.4.15]: https://github.com/bymaxone/nest-auth/compare/v1.4.14...v1.4.15
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);