@bymax-one/nest-auth 1.5.3 → 1.5.5

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,72 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.5.5] - 2026-11-14
22
+
23
+ A patch release.
24
+
25
+ ### Fixed
26
+
27
+ - `issueTokensForUserId` no longer marks the session it issues as recently authenticated, matching rust-auth.
28
+
29
+ ### Apply to a derived backend
30
+
31
+ - **`TokenManagerService.issueTokens` takes an optional `credentialProved` override.** A host that calls it directly
32
+ and wants the session to count as a recent authentication passes `{ credentialProved: true }`; without it no
33
+ recent-authentication mark is written. `AuthService.issueTokensForUserId` no longer writes one.
34
+
35
+ ## [1.5.4] - 2026-11-14
36
+
37
+ A patch release for outages and browsers: a Redis outage answers `503 auth.service_unavailable` instead of
38
+ `500`, a background revalidation no longer signs a signed-in user out on a failure that says nothing about the
39
+ session, an option-fed timer cannot be given a delay it cannot honor, and the wire contract is at version 7.
40
+
41
+ ### Fixed
42
+
43
+ - **A Redis outage answers `503 auth.service_unavailable`, not `500 auth.internal`.** With Redis paused or
44
+ stopped, login, refresh, logout, `GET /me`, every guarded route, MFA, registration and the rate-limited
45
+ routes answered `500` with a raw ioredis error in the log. Every Redis call of the library now goes through
46
+ one wrapper: a command that times out, a closed or refused connection, a client that gave up its retries, and
47
+ a server that replies it cannot serve (`READONLY`, `LOADING`, `MASTERDOWN`, `CLUSTERDOWN`, `TRYAGAIN`) raise
48
+ an `AuthException` with the new code, the ioredis error as its `cause` and nothing of it in the body. Any
49
+ other Redis reply error (`NOSCRIPT`, `WRONGTYPE`) stays a `500`. No `Retry-After` is sent.
50
+ - **A background revalidation no longer signs a signed-in user out on a failure that says nothing about the
51
+ session.** `AuthProvider` kept `SET_ERROR` for every non-401 failure, so a `503`, a `500`, a `429` or a
52
+ network error dropped the user to `unauthenticated`. Now only a final answer (a 4xx other than 429) does;
53
+ the user and the state stay through the rest and the next tick tries again. The first check of a page load
54
+ is unchanged.
55
+ - **An option-fed timer can no longer be given a delay a timer cannot honor.** `createAuthFetch({ timeout })`
56
+ throws a `TypeError` at creation for a value that is not a number from `0` to `2147483647`
57
+ (`NaN` and `Infinity` armed every request's abort timer at 1 ms), and `AuthProvider` reads a
58
+ `revalidateInterval` outside that range as the 5-minute default (it was a revalidation request every
59
+ millisecond).
60
+
61
+ ### Changed
62
+
63
+ - **Wire contract version 7.** It adds `auth.service_unavailable` (503), pins that a password-reset request
64
+ whose cooldown store cannot answer answers `503` after the timing floor, the same for every address, and
65
+ pins that a `beforeWorkspaceCreate` hook that fails without refusing creates nothing and answers `500
66
+ auth.internal`. A new `serviceUnavailable` section lists where the 503 is answered, the rule for what the library
67
+ absorbs, and which store failures count as an outage; the classifier's spec reads the outage part.
68
+ - `AuthException` takes an optional third argument `{ cause }`, kept on the exception and never serialized.
69
+ - `supertest` devDependency floor is `^7.3.1`, and the e2e suite binds its port-only listeners to
70
+ `127.0.0.1`.
71
+ - The release workflow builds, verifies and packs once without a publish credential, and the publish job
72
+ checks the tarball's digest and publishes exactly that file with provenance.
73
+
74
+ ### Apply to a derived backend
75
+
76
+ - **A client that switched on `500` to detect an outage must read `503` and `error.code`
77
+ `auth.service_unavailable`.** The status table in the README gains the `503` row. A host filter that renders
78
+ `HttpException`s answers it with its own envelope; one that logs 5xx now logs the real reason through `cause`.
79
+ `AuthExceptionFilter` writes no log line for it, so keep a Redis health check next to your readiness probe.
80
+ - **A password-reset request or resend whose cooldown store cannot answer answers `503` instead of `500`.** A failure
81
+ after the account is known (storing the code) still answers `200`.
82
+ - **The OAuth callback redirects with `error=auth.service_unavailable`** when `oauth.errorRedirectUrl` is set and
83
+ Redis is down, as it does for any other `AuthException`.
84
+ - **`createAuthFetch` throws at creation for an out-of-range `timeout`.** Pass a number of milliseconds from `0`
85
+ (no timeout) to `2147483647`, or omit it.
86
+
21
87
  ## [1.5.3] - 2026-11-14
22
88
 
23
89
  A patch release for workspaces, MFA and the proxy: the paging cursor is a codec the library now exports and
@@ -5083,7 +5149,9 @@ ever installable.
5083
5149
  - 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
5084
5150
  - 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
5085
5151
 
5086
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.3...HEAD
5152
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.5...HEAD
5153
+ [1.5.5]: https://github.com/bymaxone/nest-auth/compare/v1.5.4...v1.5.5
5154
+ [1.5.4]: https://github.com/bymaxone/nest-auth/compare/v1.5.3...v1.5.4
5087
5155
  [1.5.3]: https://github.com/bymaxone/nest-auth/compare/v1.5.2...v1.5.3
5088
5156
  [1.5.2]: https://github.com/bymaxone/nest-auth/compare/v1.5.1...v1.5.2
5089
5157
  [1.5.1]: https://github.com/bymaxone/nest-auth/compare/v1.5.0...v1.5.1
package/README.md CHANGED
@@ -956,8 +956,8 @@ cookie cross-site, and it is the only one where the origin check has anything to
956
956
 
957
957
  > [!IMPORTANT]
958
958
  > **Bound your Redis client.** Every authentication and authorization decision here reads Redis and
959
- > **fails closed**: when Redis is unreachable the request is answered with a `5xx` or a refusal,
960
- > never admitted. What the library cannot do is bound how long the client waits before it gives
959
+ > **fails closed**: when Redis is unreachable the request is refused with `503
960
+ auth.service_unavailable`, never admitted. What the library cannot do is bound how long the client waits before it gives
961
961
  > up, because the client is yours (`BYMAX_AUTH_REDIS_CLIENT`). With ioredis defaults the offline
962
962
  > queue is on and a command retries up to 20 times, so a Redis outage reads as requests that hang
963
963
  > before they fail, and `maxRetriesPerRequest: null` waits forever. Build the client with a
@@ -965,7 +965,7 @@ cookie cross-site, and it is the only one where the origin check has anything to
965
965
  >
966
966
  > ```typescript
967
967
  > new Redis(url, {
968
- > commandTimeout: 500, // ms; every command rejects after this, which the guards answer as a 5xx
968
+ > commandTimeout: 500, // ms; every command rejects after this, which the library answers as a 503
969
969
  > maxRetriesPerRequest: 1, // do not queue a command through repeated reconnects
970
970
  > enableOfflineQueue: false, // refuse a command while disconnected instead of holding it
971
971
  > retryStrategy: (attempt) => Math.min(attempt * 200, 2000) // bounded, never `null` in a server
@@ -979,9 +979,25 @@ cookie cross-site, and it is the only one where the origin check has anything to
979
979
  > at bootstrap every quarter second for up to 5 seconds, so a Redis that is still starting does not
980
980
  > fail the boot on its first refusal, while a mis-pointed address or a wrong password stops the
981
981
  > process from starting, with a message that names only the host and port, instead of surfacing as the first
982
- > request's `5xx`. Expect `5xx` on login, refresh, rate-limited routes and every guarded route for
983
- > as long as Redis is down: that is the fail-closed behaviour, and a health check on Redis belongs
984
- > next to your readiness probe.
982
+ > request's error. While Redis is down, login, refresh, logout, rate-limited routes and every
983
+ > guarded route answer `503` with `error.code` `auth.service_unavailable` and the envelope
984
+ > `{ error: { code, message, details: null } }`; nothing of the store reaches the body, and no
985
+ > `Retry-After` is sent, because nothing here knows when Redis returns. It is the fail-closed
986
+ > behaviour, and a client may retry. A Redis outage is a timeout, a closed or refused connection,
987
+ > or a server that answers it cannot serve (`READONLY` after a failover, `LOADING`, `MASTERDOWN`,
988
+ > `CLUSTERDOWN`); one function classifies them, and any other Redis reply error (a script that is
989
+ > not loaded, a key of the wrong type) is a defect and stays `500 auth.internal`.
990
+ >
991
+ > The 503 is an `AuthException` whose `cause` is the ioredis error, so a host filter that logs 5xx
992
+ > answers (nest-core's, for one) records the real reason. The library's own `AuthExceptionFilter`
993
+ > writes no log line for it: your readiness probe, not the request log, is the signal that Redis is
994
+ > down, so put a Redis health check next to it. Two answers keep their meaning: a password-reset
995
+ > request refused because the cooldown store cannot answer is the same `503` for every address, and the
996
+ > OAuth callback redirects to your `errorRedirectUrl` with `error=auth.service_unavailable` when you
997
+ > configured one. A failure to cache an answer the library can recompute (the workspace membership
998
+ > cache, the denied-access counter, the session limit) is still absorbed, not refused.
999
+ > The paths, the outcome of each and the test that pins it are in
1000
+ > [`docs/redis-outage.md`](./docs/redis-outage.md).
985
1001
 
986
1002
  The breach check is opt-in for a different reason: it is the only part of the credential path
987
1003
  that reaches the network, and a library should not start talking to a third party because it was
@@ -1722,6 +1738,7 @@ chosen at the throw site — `AuthException` takes no status argument. A client
1722
1738
  | `409` | `auth.email_already_exists` · `auth.mfa_already_enabled` · `auth.mfa_state_conflict` · `auth.oauth_email_mismatch` |
1723
1739
  | `429` | `auth.account_locked` · `auth.too_many_requests` |
1724
1740
  | `500` | `auth.internal` |
1741
+ | `503` | `auth.service_unavailable` |
1725
1742
 
1726
1743
  `AUTH_ERROR_STATUS` ships from `@bymax-one/nest-auth/shared`, beside `AUTH_ERROR_CODES`, if you
1727
1744
  need the mapping at runtime — for a typed client, an API document, or a test that asserts against
@@ -1754,10 +1771,12 @@ import { AUTH_ERROR_CODES, AUTH_ERROR_STATUS } from '@bymax-one/nest-auth/shared
1754
1771
  > (`auth.otp_invalid`) at one status (`401`) — a `429` on the ceiling would say the address was
1755
1772
  > registered, since only a record that exists can reach one.
1756
1773
 
1757
- > **When a password-reset request fails.** A failure that is the same for every address, the
1758
- > resend-cooldown store or your repository's `findByEmail` throwing, answers `500`
1759
- > (`auth.internal`) after the same timing floor as every other exit, and the cooldown that request
1760
- > took is released so the retry is not refused. A failure after the account is known (storing the
1774
+ > **When a password-reset request fails.** A failure that is the same for every address answers
1775
+ > after the same timing floor as every other exit: `503` (`auth.service_unavailable`) when the
1776
+ > resend-cooldown store cannot answer, `500` (`auth.internal`) for any other failure of it and for
1777
+ > your repository's `findByEmail` throwing. The answer is the same for every address because the
1778
+ > cooldown is the first thing every request consults, and a later failure releases the cooldown so
1779
+ > the retry is not refused. A failure after the account is known (storing the
1761
1780
  > code, or the mail provider failing after the response has left) is logged and the `200` stands,
1762
1781
  > because it happens only for a registered address. Two limits are left as they are. A `findByEmail`
1763
1782
  > that takes longer than the cooldown (60 seconds) and then fails releases the cooldown by key, and
@@ -2,6 +2,14 @@
2
2
 
3
3
  var shared = require('@bymax-one/nest-auth/shared');
4
4
 
5
+ // src/client/createAuthFetch.ts
6
+
7
+ // src/shared/utils/timer-delay.ts
8
+ var MAX_TIMER_DELAY_MS = 2147483647;
9
+ function isTimerDelay(value) {
10
+ return typeof value === "number" && value >= 0 && value <= MAX_TIMER_DELAY_MS;
11
+ }
12
+
5
13
  // src/client/createAuthFetch.ts
6
14
  var DEFAULT_HEADERS = Object.freeze({
7
15
  "Content-Type": "application/json"
@@ -135,6 +143,15 @@ async function performRefresh(endpoint, credentials) {
135
143
  return { ok: false, reason: "unreachable", status: null };
136
144
  }
137
145
  }
146
+ function requestTimeoutOf(timeout) {
147
+ const timeoutMs = timeout ?? 3e4;
148
+ if (!isTimerDelay(timeoutMs)) {
149
+ throw new TypeError(
150
+ `createAuthFetch: timeout must be a number of milliseconds from 0 to ${MAX_TIMER_DELAY_MS}.`
151
+ );
152
+ }
153
+ return timeoutMs;
154
+ }
138
155
  function createAuthFetch(config = {}) {
139
156
  const baseUrl = config.baseUrl;
140
157
  const refreshEndpoint = config.refreshEndpoint ?? shared.AUTH_PROXY_ROUTES.clientRefresh;
@@ -142,7 +159,7 @@ function createAuthFetch(config = {}) {
142
159
  const defaultHeaders = buildDefaultHeaders(config.defaultHeaders);
143
160
  const onSessionExpired = config.onSessionExpired;
144
161
  const onRefreshFailed = config.onRefreshFailed;
145
- const timeoutMs = config.timeout ?? 3e4;
162
+ const timeoutMs = requestTimeoutOf(config.timeout);
146
163
  const skipRefreshSuffixes = shared.buildAuthRefreshSkipSuffixes(config.routePrefix);
147
164
  const reportCallbackError = (err) => {
148
165
  console.warn("[nest-auth] onRefreshFailed callback threw:", err);
@@ -87,7 +87,8 @@ interface AuthFetchConfig {
87
87
  /**
88
88
  * Per-request timeout in milliseconds.
89
89
  *
90
- * Default: `30_000` (30s). Pass `0` to disable the timeout.
90
+ * Default: `30_000` (30s). Pass `0` to disable the timeout. Anything but a number from `0` to
91
+ * `2147483647` (the largest delay a timer honors) is refused when the wrapper is created.
91
92
  * Disabling is appropriate for long-poll endpoints; for normal
92
93
  * requests keep the default to avoid hanging UIs on slow networks.
93
94
  */
@@ -87,7 +87,8 @@ interface AuthFetchConfig {
87
87
  /**
88
88
  * Per-request timeout in milliseconds.
89
89
  *
90
- * Default: `30_000` (30s). Pass `0` to disable the timeout.
90
+ * Default: `30_000` (30s). Pass `0` to disable the timeout. Anything but a number from `0` to
91
+ * `2147483647` (the largest delay a timer honors) is refused when the wrapper is created.
91
92
  * Disabling is appropriate for long-poll endpoints; for normal
92
93
  * requests keep the default to avoid hanging UIs on slow networks.
93
94
  */
@@ -1,6 +1,14 @@
1
1
  import { AUTH_ERROR_CODES, AUTH_PROXY_ROUTES, buildAuthRefreshSkipSuffixes, AUTH_PASSWORD_ROUTES, AUTH_MFA_ROUTES, AuthClientError, AUTH_DASHBOARD_ROUTES, AUTH_WORKSPACE_ROUTES, trimSlashes, fillRoute } from '@bymax-one/nest-auth/shared';
2
2
  export { AuthClientError } from '@bymax-one/nest-auth/shared';
3
3
 
4
+ // src/client/createAuthFetch.ts
5
+
6
+ // src/shared/utils/timer-delay.ts
7
+ var MAX_TIMER_DELAY_MS = 2147483647;
8
+ function isTimerDelay(value) {
9
+ return typeof value === "number" && value >= 0 && value <= MAX_TIMER_DELAY_MS;
10
+ }
11
+
4
12
  // src/client/createAuthFetch.ts
5
13
  var DEFAULT_HEADERS = Object.freeze({
6
14
  "Content-Type": "application/json"
@@ -134,6 +142,15 @@ async function performRefresh(endpoint, credentials) {
134
142
  return { ok: false, reason: "unreachable", status: null };
135
143
  }
136
144
  }
145
+ function requestTimeoutOf(timeout) {
146
+ const timeoutMs = timeout ?? 3e4;
147
+ if (!isTimerDelay(timeoutMs)) {
148
+ throw new TypeError(
149
+ `createAuthFetch: timeout must be a number of milliseconds from 0 to ${MAX_TIMER_DELAY_MS}.`
150
+ );
151
+ }
152
+ return timeoutMs;
153
+ }
137
154
  function createAuthFetch(config = {}) {
138
155
  const baseUrl = config.baseUrl;
139
156
  const refreshEndpoint = config.refreshEndpoint ?? AUTH_PROXY_ROUTES.clientRefresh;
@@ -141,7 +158,7 @@ function createAuthFetch(config = {}) {
141
158
  const defaultHeaders = buildDefaultHeaders(config.defaultHeaders);
142
159
  const onSessionExpired = config.onSessionExpired;
143
160
  const onRefreshFailed = config.onRefreshFailed;
144
- const timeoutMs = config.timeout ?? 3e4;
161
+ const timeoutMs = requestTimeoutOf(config.timeout);
145
162
  const skipRefreshSuffixes = buildAuthRefreshSkipSuffixes(config.routePrefix);
146
163
  const reportCallbackError = (err) => {
147
164
  console.warn("[nest-auth] onRefreshFailed callback threw:", err);
@@ -42,6 +42,20 @@ function authReducer(state, action) {
42
42
  function isSessionExpiredError(error) {
43
43
  return clientErrorStatus(error) === 401;
44
44
  }
45
+ function useRevalidationLoop(revalidate, interval) {
46
+ const period = interval >= 0 && interval <= 2147483647 ? interval : DEFAULT_REVALIDATE_INTERVAL_MS;
47
+ react.useEffect(() => {
48
+ if (period <= 0) {
49
+ return void 0;
50
+ }
51
+ const handle = setInterval(() => {
52
+ void revalidate(false);
53
+ }, period);
54
+ return () => {
55
+ clearInterval(handle);
56
+ };
57
+ }, [revalidate, period]);
58
+ }
45
59
  function AuthProvider({
46
60
  children,
47
61
  client,
@@ -96,7 +110,7 @@ function AuthProvider({
96
110
  syncedDispatch({ type: "CLEAR_SESSION" });
97
111
  return;
98
112
  }
99
- syncedDispatch({ type: "SET_ERROR" });
113
+ if (!wasAuthenticated || isFinalAnswer(error)) syncedDispatch({ type: "SET_ERROR" });
100
114
  }
101
115
  },
102
116
  [syncedDispatch]
@@ -107,17 +121,7 @@ function AuthProvider({
107
121
  sessionGenerationRef.current = {};
108
122
  };
109
123
  }, [revalidate]);
110
- react.useEffect(() => {
111
- if (revalidateInterval <= 0) {
112
- return void 0;
113
- }
114
- const handle = setInterval(() => {
115
- void revalidate(false);
116
- }, revalidateInterval);
117
- return () => {
118
- clearInterval(handle);
119
- };
120
- }, [revalidate, revalidateInterval]);
124
+ useRevalidationLoop(revalidate, revalidateInterval);
121
125
  const login = react.useCallback(
122
126
  async (email, password, options) => {
123
127
  syncedDispatch({ type: "SET_LOADING" });
@@ -44,6 +44,9 @@ interface AuthProviderProps {
44
44
  * Interval (in milliseconds) between automatic revalidations.
45
45
  * Default: {@link DEFAULT_REVALIDATE_INTERVAL_MS} (5 minutes).
46
46
  *
47
+ * A value that is not a number from `0` to `2147483647` (the largest delay a timer honors, so
48
+ * `NaN` and `Infinity` too) is read as the default, never as a 1 ms loop.
49
+ *
47
50
  * Set to `0` to disable the loop entirely — useful for short-lived
48
51
  * flows (sign-up wizards, kiosk screens) where the overhead of a
49
52
  * background poll is not worth the freshness guarantee.
@@ -44,6 +44,9 @@ interface AuthProviderProps {
44
44
  * Interval (in milliseconds) between automatic revalidations.
45
45
  * Default: {@link DEFAULT_REVALIDATE_INTERVAL_MS} (5 minutes).
46
46
  *
47
+ * A value that is not a number from `0` to `2147483647` (the largest delay a timer honors, so
48
+ * `NaN` and `Infinity` too) is read as the default, never as a 1 ms loop.
49
+ *
47
50
  * Set to `0` to disable the loop entirely — useful for short-lived
48
51
  * flows (sign-up wizards, kiosk screens) where the overhead of a
49
52
  * background poll is not worth the freshness guarantee.
@@ -40,6 +40,20 @@ function authReducer(state, action) {
40
40
  function isSessionExpiredError(error) {
41
41
  return clientErrorStatus(error) === 401;
42
42
  }
43
+ function useRevalidationLoop(revalidate, interval) {
44
+ const period = interval >= 0 && interval <= 2147483647 ? interval : DEFAULT_REVALIDATE_INTERVAL_MS;
45
+ useEffect(() => {
46
+ if (period <= 0) {
47
+ return void 0;
48
+ }
49
+ const handle = setInterval(() => {
50
+ void revalidate(false);
51
+ }, period);
52
+ return () => {
53
+ clearInterval(handle);
54
+ };
55
+ }, [revalidate, period]);
56
+ }
43
57
  function AuthProvider({
44
58
  children,
45
59
  client,
@@ -94,7 +108,7 @@ function AuthProvider({
94
108
  syncedDispatch({ type: "CLEAR_SESSION" });
95
109
  return;
96
110
  }
97
- syncedDispatch({ type: "SET_ERROR" });
111
+ if (!wasAuthenticated || isFinalAnswer(error)) syncedDispatch({ type: "SET_ERROR" });
98
112
  }
99
113
  },
100
114
  [syncedDispatch]
@@ -105,17 +119,7 @@ function AuthProvider({
105
119
  sessionGenerationRef.current = {};
106
120
  };
107
121
  }, [revalidate]);
108
- useEffect(() => {
109
- if (revalidateInterval <= 0) {
110
- return void 0;
111
- }
112
- const handle = setInterval(() => {
113
- void revalidate(false);
114
- }, revalidateInterval);
115
- return () => {
116
- clearInterval(handle);
117
- };
118
- }, [revalidate, revalidateInterval]);
122
+ useRevalidationLoop(revalidate, revalidateInterval);
119
123
  const login = useCallback(
120
124
  async (email, password, options) => {
121
125
  syncedDispatch({ type: "SET_LOADING" });