@bymax-one/nest-auth 1.5.7 → 1.5.9

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,118 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.5.9] - 2026-11-17
22
+
23
+ A patch release.
24
+
25
+ ### Fixed
26
+
27
+ - **A numeric option that is `NaN`, a fraction, a negative or a string is refused at startup, where two of them switched
28
+ a security bound off.** A bound written as `x < min || x > max` accepts `NaN`, because a comparison with `NaN` is false
29
+ both ways. `sessions.defaultMaxSessions: NaN` evicted no session (`length <= NaN` is false and `slice(0, NaN)` is empty),
30
+ so the concurrent-session cap did not exist, and `jwt.absoluteSessionLifetimeDays: NaN` skipped the 30-day
31
+ reauthentication cap that only `0` may switch off. The bounds on `passwordReset.otpLength`, `mfa.totpWindow`,
32
+ `mfa.recoveryCodeCount` and `jwt.refreshGraceWindowSeconds` accepted `NaN` and a fraction too, and failed at runtime
33
+ instead of at boot; other numeric options had no check at all. One module, `config/numeric-options.ts`, now tests each
34
+ value as a whole number (for the lifetime in days, a finite one) before it applies a range with a ceiling, because
35
+ `Number.isInteger(1e300)` is true and a value that large overflows the expiry Redis accepts or the lifetime the cap compares to.
36
+ - **An option that has a default and holds `undefined` or `null` is unset, so its default applies, never "no bound".** The defaults were
37
+ spread under the host's group, so an own key holding `undefined` replaced the default: `Number(process.env.X) || undefined`
38
+ switched the session cap (`sessions.defaultMaxSessions`) and the absolute lifetime cap off, which is the `NaN` bug reached
39
+ through a different value. The options are read once, by property access, into a plain object without the unset keys, at the top level and in
40
+ each option group with fixed keys, so a group that is a typed configuration class is read like an object literal and every default and
41
+ every validator sees the same thing. `null` follows the same rule: some options refused it and some took it through
42
+ `??`. The options that hold a host-defined map or a required value are the exception, and refuse `null` by name:
43
+ `oauth.successRedirectUrl`, `oauth.mfaRedirectUrl`, `oauth.errorRedirectUrl`, `oauth.<provider>`, each
44
+ `roles.hierarchy.<role>` and each `workspaces.permissions.<action>`. `oauth.<provider>` and
45
+ `roles.hierarchy.<role>` refuse `undefined` as well. `jwt.secret` and `roles.hierarchy` have no default, so a
46
+ `null` or `undefined` there is refused as required.
47
+ - `jwt.accessCookieMaxAgeMs` has a floor of 1000: the cookie `Max-Age` is sent in whole seconds, so 1 to 999 became
48
+ `Max-Age=0`, which deletes the cookie.
49
+ - A refusal that receives a value that is not a number, `null` or `undefined` names its type (`received a string`) and does not print it, so a secret
50
+ passed to the wrong option does not reach a log; a number is printed, because `NaN` or `1e300` is what an operator needs to see.
51
+ `jwt.accessExpiresIn`'s refusal still quotes its value; it is fixed in 1.5.10. A message that said `Got: 1.1` for `jwt.refreshExpiresInDays` states the rule:
52
+ days × 86400 must be a whole number of seconds when computed in floating point; 1.5 and 0.25 are, 1.1 and 0.7 are not.
53
+ - A message override of `DefaultAuthEmailProvider` that holds `undefined` keeps the default copy; it threw a `TypeError`
54
+ (`is not a function`) when the message was built.
55
+ - `userStatusCacheTtlSeconds` has a ceiling of 3600 seconds. It is the window in which a suspended account still passes
56
+ the dashboard guards, so it is a security bound and not a tuning knob.
57
+
58
+ ### Apply to a derived backend
59
+
60
+ A configuration that booted before is refused at startup when it sets any of these. The message names the option, and
61
+ each line says what was accepted until now:
62
+
63
+ - `sessions.defaultMaxSessions`: anything but a whole number from 1 to 1000. Any number booted, including `NaN` (no
64
+ session was ever evicted), `0` and a negative.
65
+ - `jwt.absoluteSessionLifetimeDays`: anything but `0` (which switches the cap off) or a number of days from one hour
66
+ (`0.0417`) to 3650. Any number booted, including `NaN`, a negative, `Infinity` and `1e306`, whose length in
67
+ milliseconds overflows, so the cap was skipped.
68
+ - `jwt.refreshExpiresInDays`: more than 3650, or a value whose length in seconds is not a whole number. `1.1` days booted
69
+ and then every login failed, because Redis refuses `95040.00000000001` seconds; `1e300` booted too.
70
+ - `passwordReset.tokenTtlSeconds`, `passwordReset.otpTtlSeconds`, `emailVerification.otpTtlSeconds`,
71
+ `emailChange.tokenTtlSeconds`, `invitations.tokenTtlSeconds`: anything but a whole number from 1 to 315360000 (ten
72
+ years). Any number booted, and Redis refused the expiry on every request.
73
+ - `jwt.accessCookieMaxAgeMs`: from 1000 to ten years in milliseconds. Any number booted, and 1 to 999 sent `Max-Age=0`.
74
+ - `bruteForce.windowSeconds`: anything but a whole number from 1 to 604800 (one week). A window of months or years
75
+ booted and locked an account out for that long.
76
+ - `userStatusCacheTtlSeconds`: anything but a whole number from 1 to 3600. Any number booted.
77
+ - `password.parallelization`: more than 16. Any integer from 1 booted, and Node refuses scrypt parameters it cannot run
78
+ on the first derivation, which is the first login after deploy; each unit of `p` is a linear cost an unauthenticated
79
+ request pays.
80
+ - `passwordReset.otpLength` (4 to 8), `mfa.totpWindow`, `mfa.recoveryCodeCount` (1 to 50) and
81
+ `jwt.refreshGraceWindowSeconds` (0 to 300): `NaN`, a fraction, and a numeric string, which the range checks let
82
+ through. `Infinity` was already refused by the range.
83
+
84
+ `null` and `undefined` mean "unset" for every option that has a default: a host that passed `null` to an option that used to refuse it
85
+ boots with the default, and one that relied on an own key holding `undefined` to remove a cap gets the default cap. In
86
+ `jwt.absoluteSessionLifetimeDays` a numeric string such as `'30'` is newly refused; a string was already refused for
87
+ `jwt.refreshExpiresInDays`, which now also refuses more than 3650 days and a length that is not whole seconds.
88
+
89
+ Also refused or changed:
90
+
91
+ - `jwt.accessCookieMaxAgeMs` must be a whole number: `1500.5` booted before.
92
+ - `password.parallelization` has a ceiling of 16, and `sessions.defaultMaxSessions` one of 1000.
93
+ - A group or the options given as a class instance now take effect through their getters and prototype; those values
94
+ were ignored before, so a configuration that relied on the defaults for them now applies the values it declares.
95
+ - Refusal messages read `(received …)` where they read `(current: …)` or `(got: …)`, and a string is no longer quoted
96
+ (the OAuth `callbackUrl`, `rateLimit.clientIpSource` and the redirect URLs); a test or a log filter that matches
97
+ the old text must change.
98
+
99
+ A value read from an environment variable must be converted with `Number(...)` before it is passed, and checked for `NaN`.
100
+
101
+ ## [1.5.8] - 2026-11-17
102
+
103
+ A patch release.
104
+
105
+ ### Fixed
106
+
107
+ - **`refresh()` no longer resolves over a revalidation the server did not answer.** `AuthProvider` caught every failure of
108
+ its `GET /me` check, so an explicit `await refresh()` resolved on a 5xx, a 429, a network failure or an abort while the
109
+ state kept the user it had not re-checked. A caller that refreshes after an action that may have changed the account (a
110
+ role change) then read a stale user as fresh. `refresh()` now rejects with the error `getMe` raised in those cases and
111
+ leaves the state as it was. A 401 or another final answer is a state change and still resolves, and so does a refresh
112
+ that fails while no session was established. The background interval and the first probe are unchanged: they never
113
+ reject.
114
+ - Two comments say what the code does without a count that can drift (the keys `CREATE_SESSION_LUA` writes for every
115
+ session, and the status-cache fill spec's note on the best-effort write).
116
+
117
+ ### Apply to a derived backend
118
+
119
+ - **A frontend that awaits `refresh()` without a `catch` now has an unhandled rejection on an outage.** Wrap it where the
120
+ result matters, and where it does not, say so:
121
+
122
+ ```ts
123
+ try {
124
+ await refresh()
125
+ } catch {
126
+ // The server could not confirm the session: `user` is what it was, not a fresh read. Offer a retry.
127
+ }
128
+ ```
129
+
130
+ A handler that fires it as `void refresh()` needs `.catch(() => undefined)`. The library's own cross-tab workspace reload
131
+ already does.
132
+
21
133
  ## [1.5.7] - 2026-11-17
22
134
 
23
135
  A patch release.
@@ -5223,7 +5335,9 @@ ever installable.
5223
5335
  - 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
5224
5336
  - 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
5225
5337
 
5226
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.7...HEAD
5338
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.9...HEAD
5339
+ [1.5.9]: https://github.com/bymaxone/nest-auth/compare/v1.5.8...v1.5.9
5340
+ [1.5.8]: https://github.com/bymaxone/nest-auth/compare/v1.5.7...v1.5.8
5227
5341
  [1.5.7]: https://github.com/bymaxone/nest-auth/compare/v1.5.6...v1.5.7
5228
5342
  [1.5.6]: https://github.com/bymaxone/nest-auth/compare/v1.5.5...v1.5.6
5229
5343
  [1.5.5]: https://github.com/bymaxone/nest-auth/compare/v1.5.4...v1.5.5
package/README.md CHANGED
@@ -805,6 +805,9 @@ All options are configurable via `registerAsync()`. Here are the key configurati
805
805
  | **password** (screen) | `blocklist` — extra words the default screen refuses, on top of the ones it ships | `[]` |
806
806
  | **controllers** | Toggle individual controllers on/off — passed to `registerAsync()` itself, never returned from `useFactory` (which refuses it at startup) | `auth`, `passwordReset` on; rest opt-in |
807
807
 
808
+ An option that is omitted, or that holds `undefined` or `null`, is unset and takes its default; it never means "no limit". To switch
809
+ a cap off, use the documented value (`0` for `jwt.absoluteSessionLifetimeDays`), not an absent one. A host-defined map or a required value (`oauth.<provider>`, the `oauth` redirect URLs, `roles.hierarchy.<role>`, `workspaces.permissions.<action>`) refuses `null` by name.
810
+
808
811
  > [!NOTE]
809
812
  > When a feature is not enabled (e.g., `mfa`, `sessions`, `platform`), its controllers and services are **not registered** in the NestJS container — zero overhead. A feature is enabled by `controllers.<name>: true` on the `registerAsync()` call together with its configuration group (`mfa.encryptionKey` and `mfa.issuer`, `sessions.enabled`, `platform.enabled`); either half alone leaves it unregistered or fails at startup.
810
813
 
@@ -902,7 +905,7 @@ All options are configurable via `registerAsync()`. Here are the key configurati
902
905
  > be `0..=2`: the window counts 30-second steps on _either_ side of now, so `2n + 1` codes are
903
906
  > valid at once (three at the default of 1). `mfa.recoveryCodeCount` must be `1..=50`,
904
907
  > because zero enrols an account with no way back if the authenticator is lost.
905
- > `password.blockSize` must be at least 8 and `password.parallelization` at least 1: scrypt's memory
908
+ > `password.blockSize` must be at least 8 and `password.parallelization` between 1 and 16: scrypt's memory
906
909
  > cost is `128 * N * r`, so a smaller block size divides the hardness `password.costFactor`'s floor
907
910
  > exists to guarantee.
908
911
 
@@ -940,6 +943,10 @@ All options are configurable via `registerAsync()`. Here are the key configurati
940
943
  > [Invalidating the account cache](./docs/server-services.md#invalidating-the-account-cache--accountstatusserviceinvalidate)).
941
944
  > `bumpUserTokenEpoch` is the heavier lever: it ends every session the user has. Lower
942
945
  > `userStatusCacheTtlSeconds` if a faster answer matters more than the repository reads it costs.
946
+ >
947
+ > `userStatusCacheTtlSeconds` is a whole number of seconds from **1 to 3600**. It is the window in which a
948
+ > suspended account keeps passing the guard, so the module refuses a longer one (and a fraction, `NaN`
949
+ > or a string) at boot.
943
950
 
944
951
  `jwt.absoluteSessionLifetimeDays` caps how long one login can be extended by rotation, and is
945
952
  **on by default at 30 days** — NIST SP 800-63B-4 §3 makes a definite reauthentication timeout a
@@ -947,6 +954,7 @@ SHALL and puts it at no more than 30 days for AAL1. Without a cap, a client refr
947
954
  fifteen minutes keeps a session alive forever, and a refresh token stolen once becomes permanent
948
955
  access. Raise it to a value the product can justify, or set `0` to accept unbounded sessions
949
956
  deliberately.
957
+ Any other value is from one hour (`0.0417` days) to `3650` days.
950
958
 
951
959
  Lowering the value ends sessions that are already older than the new one, at their next rotation;
952
960
  raising it or setting `0` ends nothing. Sessions established before the cap existed carry no
@@ -19,6 +19,13 @@ function isFinalAnswer(error) {
19
19
  const status = clientErrorStatus(error);
20
20
  return status !== void 0 && status < 500 && status !== 429;
21
21
  }
22
+ function signalSessionExpired(callback) {
23
+ try {
24
+ callback?.();
25
+ } catch (callbackError) {
26
+ console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
27
+ }
28
+ }
22
29
  var INITIAL_STATE = {
23
30
  user: null,
24
31
  status: "loading",
@@ -92,7 +99,7 @@ function AuthProvider({
92
99
  }
93
100
  }, []);
94
101
  const revalidate = react.useCallback(
95
- async (isInitial) => {
102
+ async (isInitial, rethrow = false) => {
96
103
  const generation = sessionGenerationRef.current;
97
104
  try {
98
105
  const user = await clientRef.current.getMe();
@@ -102,17 +109,12 @@ function AuthProvider({
102
109
  if (sessionGenerationRef.current !== generation) return;
103
110
  const wasAuthenticated = statusRef.current === "authenticated";
104
111
  if (isSessionExpiredError(error)) {
105
- if (!isInitial && wasAuthenticated) {
106
- try {
107
- onSessionExpiredRef.current?.();
108
- } catch (callbackError) {
109
- console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
110
- }
111
- }
112
+ if (!isInitial && wasAuthenticated) signalSessionExpired(onSessionExpiredRef.current);
112
113
  syncedDispatch({ type: "CLEAR_SESSION" });
113
114
  return;
114
115
  }
115
116
  if (!wasAuthenticated || isFinalAnswer(error)) syncedDispatch({ type: "SET_ERROR" });
117
+ else if (rethrow) throw error;
116
118
  }
117
119
  },
118
120
  [syncedDispatch]
@@ -178,7 +180,7 @@ function AuthProvider({
178
180
  clearSession();
179
181
  }, [clearSession]);
180
182
  const refresh = react.useCallback(async () => {
181
- await revalidate(false);
183
+ await revalidate(false, true);
182
184
  }, [revalidate]);
183
185
  const forgotPassword = react.useCallback(
184
186
  async (email, tenantId) => {
@@ -386,7 +388,7 @@ function useBroadcastReload(sessionRefresh, statusRef, identityRef, reload) {
386
388
  return react.useCallback(() => {
387
389
  if (statusRef.current !== "authenticated") return;
388
390
  const heardAs = identityRef.current;
389
- void sessionRefresh().then(() => setRequest({ heardAs }));
391
+ void sessionRefresh().catch(() => void 0).then(() => setRequest({ heardAs }));
390
392
  }, [sessionRefresh, statusRef, identityRef]);
391
393
  }
392
394
  function useWorkspaceChannel(onMessage) {
@@ -178,6 +178,11 @@ interface AuthContextValue {
178
178
  * may have changed the user's role server-side). Not required for
179
179
  * routine session maintenance — the provider handles that
180
180
  * automatically via the configured interval.
181
+ *
182
+ * @throws The error `client.getMe` raised when the server could not confirm the session: a 5xx,
183
+ * a 429, a network failure or an abort, over a session that was authenticated. The state is
184
+ * left as it was, so the user it holds was not re-checked; catch the rejection and offer a
185
+ * retry. A final answer (a 401 included) is a state change and resolves.
181
186
  */
182
187
  refresh: () => Promise<void>;
183
188
  /**
@@ -178,6 +178,11 @@ interface AuthContextValue {
178
178
  * may have changed the user's role server-side). Not required for
179
179
  * routine session maintenance — the provider handles that
180
180
  * automatically via the configured interval.
181
+ *
182
+ * @throws The error `client.getMe` raised when the server could not confirm the session: a 5xx,
183
+ * a 429, a network failure or an abort, over a session that was authenticated. The state is
184
+ * left as it was, so the user it holds was not re-checked; catch the rejection and offer a
185
+ * retry. A final answer (a 401 included) is a state change and resolves.
181
186
  */
182
187
  refresh: () => Promise<void>;
183
188
  /**
@@ -17,6 +17,13 @@ function isFinalAnswer(error) {
17
17
  const status = clientErrorStatus(error);
18
18
  return status !== void 0 && status < 500 && status !== 429;
19
19
  }
20
+ function signalSessionExpired(callback) {
21
+ try {
22
+ callback?.();
23
+ } catch (callbackError) {
24
+ console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
25
+ }
26
+ }
20
27
  var INITIAL_STATE = {
21
28
  user: null,
22
29
  status: "loading",
@@ -90,7 +97,7 @@ function AuthProvider({
90
97
  }
91
98
  }, []);
92
99
  const revalidate = useCallback(
93
- async (isInitial) => {
100
+ async (isInitial, rethrow = false) => {
94
101
  const generation = sessionGenerationRef.current;
95
102
  try {
96
103
  const user = await clientRef.current.getMe();
@@ -100,17 +107,12 @@ function AuthProvider({
100
107
  if (sessionGenerationRef.current !== generation) return;
101
108
  const wasAuthenticated = statusRef.current === "authenticated";
102
109
  if (isSessionExpiredError(error)) {
103
- if (!isInitial && wasAuthenticated) {
104
- try {
105
- onSessionExpiredRef.current?.();
106
- } catch (callbackError) {
107
- console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
108
- }
109
- }
110
+ if (!isInitial && wasAuthenticated) signalSessionExpired(onSessionExpiredRef.current);
110
111
  syncedDispatch({ type: "CLEAR_SESSION" });
111
112
  return;
112
113
  }
113
114
  if (!wasAuthenticated || isFinalAnswer(error)) syncedDispatch({ type: "SET_ERROR" });
115
+ else if (rethrow) throw error;
114
116
  }
115
117
  },
116
118
  [syncedDispatch]
@@ -176,7 +178,7 @@ function AuthProvider({
176
178
  clearSession();
177
179
  }, [clearSession]);
178
180
  const refresh = useCallback(async () => {
179
- await revalidate(false);
181
+ await revalidate(false, true);
180
182
  }, [revalidate]);
181
183
  const forgotPassword = useCallback(
182
184
  async (email, tenantId) => {
@@ -384,7 +386,7 @@ function useBroadcastReload(sessionRefresh, statusRef, identityRef, reload) {
384
386
  return useCallback(() => {
385
387
  if (statusRef.current !== "authenticated") return;
386
388
  const heardAs = identityRef.current;
387
- void sessionRefresh().then(() => setRequest({ heardAs }));
389
+ void sessionRefresh().catch(() => void 0).then(() => setRequest({ heardAs }));
388
390
  }, [sessionRefresh, statusRef, identityRef]);
389
391
  }
390
392
  function useWorkspaceChannel(onMessage) {