@bymax-one/nest-auth 1.5.3 → 1.5.4

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,58 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.5.4] - 2026-11-14
22
+
23
+ A patch release for outages and browsers: a Redis outage answers `503 auth.service_unavailable` instead of
24
+ `500`, a background revalidation no longer signs a signed-in user out on a failure that says nothing about the
25
+ session, an option-fed timer cannot be given a delay it cannot honor, and the wire contract is at version 7.
26
+
27
+ ### Fixed
28
+
29
+ - **A Redis outage answers `503 auth.service_unavailable`, not `500 auth.internal`.** With Redis paused or
30
+ stopped, login, refresh, logout, `GET /me`, every guarded route, MFA, registration and the rate-limited
31
+ routes answered `500` with a raw ioredis error in the log. Every Redis call of the library now goes through
32
+ one wrapper: a command that times out, a closed or refused connection, a client that gave up its retries, and
33
+ a server that replies it cannot serve (`READONLY`, `LOADING`, `MASTERDOWN`, `CLUSTERDOWN`, `TRYAGAIN`) raise
34
+ an `AuthException` with the new code, the ioredis error as its `cause` and nothing of it in the body. Any
35
+ other Redis reply error (`NOSCRIPT`, `WRONGTYPE`) stays a `500`. No `Retry-After` is sent.
36
+ - **A background revalidation no longer signs a signed-in user out on a failure that says nothing about the
37
+ session.** `AuthProvider` kept `SET_ERROR` for every non-401 failure, so a `503`, a `500`, a `429` or a
38
+ network error dropped the user to `unauthenticated`. Now only a final answer (a 4xx other than 429) does;
39
+ the user and the state stay through the rest and the next tick tries again. The first check of a page load
40
+ is unchanged.
41
+ - **An option-fed timer can no longer be given a delay a timer cannot honor.** `createAuthFetch({ timeout })`
42
+ throws a `TypeError` at creation for a value that is not a number from `0` to `2147483647`
43
+ (`NaN` and `Infinity` armed every request's abort timer at 1 ms), and `AuthProvider` reads a
44
+ `revalidateInterval` outside that range as the 5-minute default (it was a revalidation request every
45
+ millisecond).
46
+
47
+ ### Changed
48
+
49
+ - **Wire contract version 7.** It adds `auth.service_unavailable` (503), pins that a password-reset request
50
+ whose cooldown store cannot answer answers `503` after the timing floor, the same for every address, and
51
+ pins that a `beforeWorkspaceCreate` hook that fails without refusing creates nothing and answers `500
52
+ auth.internal`. A new `serviceUnavailable` section lists where the 503 is answered, the rule for what the library
53
+ absorbs, and which store failures count as an outage; the classifier's spec reads the outage part.
54
+ - `AuthException` takes an optional third argument `{ cause }`, kept on the exception and never serialized.
55
+ - `supertest` devDependency floor is `^7.3.1`, and the e2e suite binds its port-only listeners to
56
+ `127.0.0.1`.
57
+ - The release workflow builds, verifies and packs once without a publish credential, and the publish job
58
+ checks the tarball's digest and publishes exactly that file with provenance.
59
+
60
+ ### Apply to a derived backend
61
+
62
+ - **A client that switched on `500` to detect an outage must read `503` and `error.code`
63
+ `auth.service_unavailable`.** The status table in the README gains the `503` row. A host filter that renders
64
+ `HttpException`s answers it with its own envelope; one that logs 5xx now logs the real reason through `cause`.
65
+ `AuthExceptionFilter` writes no log line for it, so keep a Redis health check next to your readiness probe.
66
+ - **A password-reset request or resend whose cooldown store cannot answer answers `503` instead of `500`.** A failure
67
+ after the account is known (storing the code) still answers `200`.
68
+ - **The OAuth callback redirects with `error=auth.service_unavailable`** when `oauth.errorRedirectUrl` is set and
69
+ Redis is down, as it does for any other `AuthException`.
70
+ - **`createAuthFetch` throws at creation for an out-of-range `timeout`.** Pass a number of milliseconds from `0`
71
+ (no timeout) to `2147483647`, or omit it.
72
+
21
73
  ## [1.5.3] - 2026-11-14
22
74
 
23
75
  A patch release for workspaces, MFA and the proxy: the paging cursor is a codec the library now exports and
@@ -5083,7 +5135,8 @@ ever installable.
5083
5135
  - 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
5136
  - 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
5137
 
5086
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.3...HEAD
5138
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.4...HEAD
5139
+ [1.5.4]: https://github.com/bymaxone/nest-auth/compare/v1.5.3...v1.5.4
5087
5140
  [1.5.3]: https://github.com/bymaxone/nest-auth/compare/v1.5.2...v1.5.3
5088
5141
  [1.5.2]: https://github.com/bymaxone/nest-auth/compare/v1.5.1...v1.5.2
5089
5142
  [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" });
@@ -2276,7 +2276,17 @@ var AUTH_ERROR_CODES = {
2276
2276
  * answers with. Without the filter the framework's own 500 shape stands, which is the
2277
2277
  * behaviour this library had before it existed.
2278
2278
  */
2279
- INTERNAL: "auth.internal"
2279
+ INTERNAL: "auth.internal",
2280
+ /**
2281
+ * A store this request depends on, Redis, did not answer in time or could not be reached, so
2282
+ * the request was refused and nothing was admitted. Retrying later may succeed; nothing here
2283
+ * knows when, so the answer carries no `Retry-After`.
2284
+ *
2285
+ * Raised by the library's Redis wrapper, not only by {@link AuthExceptionFilter}: it is a typed
2286
+ * exception, so any host filter that renders an `HttpException` answers it as a 503. The ioredis
2287
+ * error rides on the exception as `cause` and is never serialized.
2288
+ */
2289
+ SERVICE_UNAVAILABLE: "auth.service_unavailable"
2280
2290
  };
2281
2291
  var AUTH_ERROR_STATUS = {
2282
2292
  "auth.invalid_credentials": 401,
@@ -2328,7 +2338,8 @@ var AUTH_ERROR_STATUS = {
2328
2338
  "auth.registration_closed": 403,
2329
2339
  "auth.workspace_limit_reached": 403,
2330
2340
  "auth.workspace_pending_deletion": 409,
2331
- "auth.internal": 500
2341
+ "auth.internal": 500,
2342
+ "auth.service_unavailable": 503
2332
2343
  };
2333
2344
  var AUTH_ERROR_MESSAGES = {
2334
2345
  "auth.invalid_credentials": "Invalid email or password",
@@ -2380,7 +2391,8 @@ var AUTH_ERROR_MESSAGES = {
2380
2391
  "auth.registration_closed": "Registration is closed",
2381
2392
  "auth.workspace_limit_reached": "Workspace limit reached. Workspaces pending deletion count toward the limit.",
2382
2393
  "auth.workspace_pending_deletion": "Workspace is scheduled for deletion",
2383
- "auth.internal": "Internal server error"
2394
+ "auth.internal": "Internal server error",
2395
+ "auth.service_unavailable": "Service temporarily unavailable"
2384
2396
  };
2385
2397
  var MESSAGE_BY_CODE = new Map(Object.entries(AUTH_ERROR_MESSAGES));
2386
2398
  var STATUS_BY_CODE = new Map(Object.entries(AUTH_ERROR_STATUS));
@@ -2394,8 +2406,10 @@ var AuthException = class extends common.HttpException {
2394
2406
  * @param details - Optional structured payload attached to the error body under
2395
2407
  * `error.details`. An array where the failure is a list — `auth.validation` renders its
2396
2408
  * per-field failures that way, matching what rust-auth serializes for the same code.
2409
+ * @param options - `cause`: the error this one reports, kept on the exception for a host's
2410
+ * logger and never serialized into the body.
2397
2411
  */
2398
- constructor(code, details) {
2412
+ constructor(code, details, options) {
2399
2413
  super(
2400
2414
  {
2401
2415
  error: {
@@ -2408,11 +2422,88 @@ var AuthException = class extends common.HttpException {
2408
2422
  // A code with no entry is a programming error on the throwing side, not something the
2409
2423
  // caller did — 500 says so, and says it with a number rather than the `undefined` an
2410
2424
  // unguarded lookup used to hand to Express.
2411
- STATUS_BY_CODE.get(code) ?? common.HttpStatus.INTERNAL_SERVER_ERROR
2425
+ STATUS_BY_CODE.get(code) ?? common.HttpStatus.INTERNAL_SERVER_ERROR,
2426
+ options?.cause === void 0 ? void 0 : {
2427
+ cause: options.cause
2428
+ }
2412
2429
  );
2413
2430
  }
2414
2431
  };
2415
2432
 
2433
+ // src/server/redis/redis-outage.ts
2434
+ var MESSAGE_KINDS = /* @__PURE__ */ new Map([
2435
+ [
2436
+ "Command timed out",
2437
+ "timeout"
2438
+ ],
2439
+ [
2440
+ "Connection is closed.",
2441
+ "closed"
2442
+ ],
2443
+ [
2444
+ "Stream isn't writeable and enableOfflineQueue options is false",
2445
+ "closed"
2446
+ ]
2447
+ ]);
2448
+ var NETWORK_CODES = /* @__PURE__ */ new Set([
2449
+ "ECONNREFUSED",
2450
+ "ECONNRESET",
2451
+ "ETIMEDOUT",
2452
+ "EPIPE",
2453
+ "ENOTFOUND",
2454
+ "EAI_AGAIN",
2455
+ "EHOSTUNREACH",
2456
+ "ENETUNREACH"
2457
+ ]);
2458
+ var UNAVAILABLE_REPLIES = /* @__PURE__ */ new Set([
2459
+ "READONLY",
2460
+ "LOADING",
2461
+ "MASTERDOWN",
2462
+ "CLUSTERDOWN",
2463
+ "TRYAGAIN"
2464
+ ]);
2465
+ function redisOutageKindOf(error) {
2466
+ if (!(error instanceof Error)) return void 0;
2467
+ if (error.name === "MaxRetriesPerRequestError") return "unreachable";
2468
+ if (error.name === "ReplyError") {
2469
+ return UNAVAILABLE_REPLIES.has(error.message.split(" ", 1)[0]) ? "unavailable" : void 0;
2470
+ }
2471
+ const { code } = error;
2472
+ if (typeof code === "string" && NETWORK_CODES.has(code)) return "unreachable";
2473
+ return MESSAGE_KINDS.get(error.message);
2474
+ }
2475
+ __name(redisOutageKindOf, "redisOutageKindOf");
2476
+ function rethrowAsOutage(error) {
2477
+ if (redisOutageKindOf(error) === void 0) throw error;
2478
+ throw new AuthException(AUTH_ERROR_CODES.SERVICE_UNAVAILABLE, void 0, {
2479
+ cause: error
2480
+ });
2481
+ }
2482
+ __name(rethrowAsOutage, "rethrowAsOutage");
2483
+ function isServiceUnavailable(error) {
2484
+ if (!(error instanceof AuthException)) return false;
2485
+ const body = error.getResponse();
2486
+ return body.error?.code === AUTH_ERROR_CODES.SERVICE_UNAVAILABLE;
2487
+ }
2488
+ __name(isServiceUnavailable, "isServiceUnavailable");
2489
+ function isThenable(value) {
2490
+ return typeof value === "object" && value !== null && typeof value.then === "function";
2491
+ }
2492
+ __name(isThenable, "isThenable");
2493
+ function mappingOutages(redis) {
2494
+ return new Proxy(redis, {
2495
+ get(target, property) {
2496
+ const value = Reflect.get(target, property, target);
2497
+ if (typeof value !== "function") return value;
2498
+ return (...args) => {
2499
+ const result = Reflect.apply(value, target, args);
2500
+ return isThenable(result) ? result.then(void 0, rethrowAsOutage) : result;
2501
+ };
2502
+ }
2503
+ });
2504
+ }
2505
+ __name(mappingOutages, "mappingOutages");
2506
+
2416
2507
  // src/server/constants/user-subject.ts
2417
2508
  function userSubject(plane, userId, tenantId) {
2418
2509
  if (plane === "platform") return `platform:${userId}`;
@@ -2460,7 +2551,6 @@ function _ts_param(paramIndex, decorator) {
2460
2551
  };
2461
2552
  }
2462
2553
  __name(_ts_param, "_ts_param");
2463
- var EPOCH_TTL_SECONDS = TOKEN_EPOCH_RETENTION_SECONDS;
2464
2554
  var WS_TICKET_ENTROPY_BYTES = 32;
2465
2555
  var GRACE_TAG = "GRACE:";
2466
2556
  var REUSED_TAG = "REUSED:";
@@ -2628,7 +2718,7 @@ var AuthRedisService = class {
2628
2718
  */
2629
2719
  #hmacKey;
2630
2720
  constructor(redis, options) {
2631
- this.#redis = redis;
2721
+ this.#redis = mappingOutages(redis);
2632
2722
  this.namespace = options.redisNamespace;
2633
2723
  this.#hmacKey = options.hmacKey;
2634
2724
  }
@@ -3334,7 +3424,7 @@ var AuthRedisService = class {
3334
3424
  return v`, [
3335
3425
  key
3336
3426
  ], [
3337
- String(EPOCH_TTL_SECONDS)
3427
+ String(TOKEN_EPOCH_RETENTION_SECONDS)
3338
3428
  ]);
3339
3429
  return typeof result === "number" ? result : 0;
3340
3430
  }
@@ -7306,7 +7396,7 @@ async function settlePendingLogout(redis, key, fromSession, owner, ttlSeconds, l
7306
7396
  return fromSession || removed;
7307
7397
  } catch (err) {
7308
7398
  logger.warn(`logout: the retry marker could not be cleared \u2014 ${describeChannelStatus(err)}`);
7309
- if (!fromSession) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
7399
+ if (!fromSession) throw isServiceUnavailable(err) ? err : new AuthException(AUTH_ERROR_CODES.INTERNAL);
7310
7400
  return confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger);
7311
7401
  }
7312
7402
  }
@@ -7314,8 +7404,9 @@ __name(settlePendingLogout, "settlePendingLogout");
7314
7404
  async function confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger) {
7315
7405
  try {
7316
7406
  if (await redis.get(key) === null) return true;
7317
- } catch {
7407
+ } catch (err) {
7318
7408
  await rememberPendingLogout(redis, key, owner, ttlSeconds, logger);
7409
+ if (isServiceUnavailable(err)) throw err;
7319
7410
  }
7320
7411
  throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
7321
7412
  }
@@ -12996,7 +13087,7 @@ async function answerResetRequest(deps, request) {
12996
13087
  } catch (err) {
12997
13088
  logger.error(`${label}: cooldown store failed: ${describeChannelStatus(err)}`);
12998
13089
  await holdFloor();
12999
- throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13090
+ throw isServiceUnavailable(err) ? err : new AuthException(AUTH_ERROR_CODES.INTERNAL);
13000
13091
  }
13001
13092
  if (!claimed) {
13002
13093
  await holdFloor();
@@ -13123,10 +13214,9 @@ exports.PasswordResetService = class _PasswordResetService {
13123
13214
  * - The account is blocked.
13124
13215
  * - Issuing or storing the code, or the email provider, fails for an account that exists.
13125
13216
  *
13126
- * A failure that is the same for every address, the resend-cooldown store or the account
13127
- * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
13128
- * released. This anti-enumeration design ensures the response cannot be used to probe
13129
- * whether an email address is registered.
13217
+ * What a failure answers, and when the cooldown this call took is released, is decided in one
13218
+ * place, {@link answerResetRequest}. The response cannot be used to probe whether an email
13219
+ * address is registered.
13130
13220
  *
13131
13221
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
13132
13222
  * milliseconds to respond, regardless of whether the user was found.
@@ -13234,8 +13324,8 @@ exports.PasswordResetService = class _PasswordResetService {
13234
13324
  *
13235
13325
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
13236
13326
  * prevent OTP flooding. Resolves the same way whether or not the user exists —
13237
- * anti-enumeration principle; a failure of the cooldown store or the account lookup
13238
- * throws `INTERNAL` (500) after the floor and releases the cooldown.
13327
+ * anti-enumeration principle; what a failure answers is decided in one place,
13328
+ * {@link answerResetRequest}.
13239
13329
  *
13240
13330
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
13241
13331
  *
@@ -13733,8 +13823,8 @@ var PasswordResetController = class {
13733
13823
  *
13734
13824
  * Sends a reset token or OTP to the user's email if the account exists and
13735
13825
  * is eligible. Answers `200 OK` with an empty JSON object whether or not the account exists
13736
- * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
13737
- * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
13826
+ * (anti-enumeration; the body is pinned by the wire contract). What a failure answers is
13827
+ * decided in one place, `answerResetRequest` (utils/answer-reset-request.ts).
13738
13828
  *
13739
13829
  * @param dto - Validated DTO with `email` and `tenantId`.
13740
13830
  * @returns An empty object.
@@ -13822,8 +13912,8 @@ var PasswordResetController = class {
13822
13912
  *
13823
13913
  * Subject to a 60-second atomic cooldown per `(tenantId, email)` pair.
13824
13914
  * Answers `200 OK` with an empty JSON object whether or not the account exists
13825
- * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
13826
- * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
13915
+ * (anti-enumeration; the body is pinned by the wire contract). What a failure answers is
13916
+ * decided in one place, `answerResetRequest` (utils/answer-reset-request.ts).
13827
13917
  *
13828
13918
  * @param dto - Validated DTO with `email` and `tenantId`.
13829
13919
  * @returns An empty object.
@@ -2749,6 +2749,16 @@ declare const AUTH_ERROR_CODES: {
2749
2749
  * behaviour this library had before it existed.
2750
2750
  */
2751
2751
  readonly INTERNAL: "auth.internal";
2752
+ /**
2753
+ * A store this request depends on, Redis, did not answer in time or could not be reached, so
2754
+ * the request was refused and nothing was admitted. Retrying later may succeed; nothing here
2755
+ * knows when, so the answer carries no `Retry-After`.
2756
+ *
2757
+ * Raised by the library's Redis wrapper, not only by {@link AuthExceptionFilter}: it is a typed
2758
+ * exception, so any host filter that renders an `HttpException` answers it as a 503. The ioredis
2759
+ * error rides on the exception as `cause` and is never serialized.
2760
+ */
2761
+ readonly SERVICE_UNAVAILABLE: "auth.service_unavailable";
2752
2762
  };
2753
2763
  /**
2754
2764
  * String literal union of all valid `AuthException` error codes.
@@ -2837,8 +2847,12 @@ declare class AuthException extends HttpException {
2837
2847
  * @param details - Optional structured payload attached to the error body under
2838
2848
  * `error.details`. An array where the failure is a list — `auth.validation` renders its
2839
2849
  * per-field failures that way, matching what rust-auth serializes for the same code.
2850
+ * @param options - `cause`: the error this one reports, kept on the exception for a host's
2851
+ * logger and never serialized into the body.
2840
2852
  */
2841
- constructor(code: AuthErrorCode, details?: Record<string, unknown> | readonly unknown[]);
2853
+ constructor(code: AuthErrorCode, details?: Record<string, unknown> | readonly unknown[], options?: {
2854
+ readonly cause?: unknown;
2855
+ });
2842
2856
  }
2843
2857
 
2844
2858
  /**
@@ -11888,10 +11902,9 @@ declare class PasswordResetService {
11888
11902
  * - The account is blocked.
11889
11903
  * - Issuing or storing the code, or the email provider, fails for an account that exists.
11890
11904
  *
11891
- * A failure that is the same for every address, the resend-cooldown store or the account
11892
- * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
11893
- * released. This anti-enumeration design ensures the response cannot be used to probe
11894
- * whether an email address is registered.
11905
+ * What a failure answers, and when the cooldown this call took is released, is decided in one
11906
+ * place, {@link answerResetRequest}. The response cannot be used to probe whether an email
11907
+ * address is registered.
11895
11908
  *
11896
11909
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
11897
11910
  * milliseconds to respond, regardless of whether the user was found.
@@ -11948,8 +11961,8 @@ declare class PasswordResetService {
11948
11961
  *
11949
11962
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
11950
11963
  * prevent OTP flooding. Resolves the same way whether or not the user exists —
11951
- * anti-enumeration principle; a failure of the cooldown store or the account lookup
11952
- * throws `INTERNAL` (500) after the floor and releases the cooldown.
11964
+ * anti-enumeration principle; what a failure answers is decided in one place,
11965
+ * {@link answerResetRequest}.
11953
11966
  *
11954
11967
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
11955
11968
  *
@@ -2749,6 +2749,16 @@ declare const AUTH_ERROR_CODES: {
2749
2749
  * behaviour this library had before it existed.
2750
2750
  */
2751
2751
  readonly INTERNAL: "auth.internal";
2752
+ /**
2753
+ * A store this request depends on, Redis, did not answer in time or could not be reached, so
2754
+ * the request was refused and nothing was admitted. Retrying later may succeed; nothing here
2755
+ * knows when, so the answer carries no `Retry-After`.
2756
+ *
2757
+ * Raised by the library's Redis wrapper, not only by {@link AuthExceptionFilter}: it is a typed
2758
+ * exception, so any host filter that renders an `HttpException` answers it as a 503. The ioredis
2759
+ * error rides on the exception as `cause` and is never serialized.
2760
+ */
2761
+ readonly SERVICE_UNAVAILABLE: "auth.service_unavailable";
2752
2762
  };
2753
2763
  /**
2754
2764
  * String literal union of all valid `AuthException` error codes.
@@ -2837,8 +2847,12 @@ declare class AuthException extends HttpException {
2837
2847
  * @param details - Optional structured payload attached to the error body under
2838
2848
  * `error.details`. An array where the failure is a list — `auth.validation` renders its
2839
2849
  * per-field failures that way, matching what rust-auth serializes for the same code.
2850
+ * @param options - `cause`: the error this one reports, kept on the exception for a host's
2851
+ * logger and never serialized into the body.
2840
2852
  */
2841
- constructor(code: AuthErrorCode, details?: Record<string, unknown> | readonly unknown[]);
2853
+ constructor(code: AuthErrorCode, details?: Record<string, unknown> | readonly unknown[], options?: {
2854
+ readonly cause?: unknown;
2855
+ });
2842
2856
  }
2843
2857
 
2844
2858
  /**
@@ -11888,10 +11902,9 @@ declare class PasswordResetService {
11888
11902
  * - The account is blocked.
11889
11903
  * - Issuing or storing the code, or the email provider, fails for an account that exists.
11890
11904
  *
11891
- * A failure that is the same for every address, the resend-cooldown store or the account
11892
- * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
11893
- * released. This anti-enumeration design ensures the response cannot be used to probe
11894
- * whether an email address is registered.
11905
+ * What a failure answers, and when the cooldown this call took is released, is decided in one
11906
+ * place, {@link answerResetRequest}. The response cannot be used to probe whether an email
11907
+ * address is registered.
11895
11908
  *
11896
11909
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
11897
11910
  * milliseconds to respond, regardless of whether the user was found.
@@ -11948,8 +11961,8 @@ declare class PasswordResetService {
11948
11961
  *
11949
11962
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
11950
11963
  * prevent OTP flooding. Resolves the same way whether or not the user exists —
11951
- * anti-enumeration principle; a failure of the cooldown store or the account lookup
11952
- * throws `INTERNAL` (500) after the floor and releases the cooldown.
11964
+ * anti-enumeration principle; what a failure answers is decided in one place,
11965
+ * {@link answerResetRequest}.
11953
11966
  *
11954
11967
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
11955
11968
  *
@@ -2274,7 +2274,17 @@ var AUTH_ERROR_CODES = {
2274
2274
  * answers with. Without the filter the framework's own 500 shape stands, which is the
2275
2275
  * behaviour this library had before it existed.
2276
2276
  */
2277
- INTERNAL: "auth.internal"
2277
+ INTERNAL: "auth.internal",
2278
+ /**
2279
+ * A store this request depends on, Redis, did not answer in time or could not be reached, so
2280
+ * the request was refused and nothing was admitted. Retrying later may succeed; nothing here
2281
+ * knows when, so the answer carries no `Retry-After`.
2282
+ *
2283
+ * Raised by the library's Redis wrapper, not only by {@link AuthExceptionFilter}: it is a typed
2284
+ * exception, so any host filter that renders an `HttpException` answers it as a 503. The ioredis
2285
+ * error rides on the exception as `cause` and is never serialized.
2286
+ */
2287
+ SERVICE_UNAVAILABLE: "auth.service_unavailable"
2278
2288
  };
2279
2289
  var AUTH_ERROR_STATUS = {
2280
2290
  "auth.invalid_credentials": 401,
@@ -2326,7 +2336,8 @@ var AUTH_ERROR_STATUS = {
2326
2336
  "auth.registration_closed": 403,
2327
2337
  "auth.workspace_limit_reached": 403,
2328
2338
  "auth.workspace_pending_deletion": 409,
2329
- "auth.internal": 500
2339
+ "auth.internal": 500,
2340
+ "auth.service_unavailable": 503
2330
2341
  };
2331
2342
  var AUTH_ERROR_MESSAGES = {
2332
2343
  "auth.invalid_credentials": "Invalid email or password",
@@ -2378,7 +2389,8 @@ var AUTH_ERROR_MESSAGES = {
2378
2389
  "auth.registration_closed": "Registration is closed",
2379
2390
  "auth.workspace_limit_reached": "Workspace limit reached. Workspaces pending deletion count toward the limit.",
2380
2391
  "auth.workspace_pending_deletion": "Workspace is scheduled for deletion",
2381
- "auth.internal": "Internal server error"
2392
+ "auth.internal": "Internal server error",
2393
+ "auth.service_unavailable": "Service temporarily unavailable"
2382
2394
  };
2383
2395
  var MESSAGE_BY_CODE = new Map(Object.entries(AUTH_ERROR_MESSAGES));
2384
2396
  var STATUS_BY_CODE = new Map(Object.entries(AUTH_ERROR_STATUS));
@@ -2392,8 +2404,10 @@ var AuthException = class extends HttpException {
2392
2404
  * @param details - Optional structured payload attached to the error body under
2393
2405
  * `error.details`. An array where the failure is a list — `auth.validation` renders its
2394
2406
  * per-field failures that way, matching what rust-auth serializes for the same code.
2407
+ * @param options - `cause`: the error this one reports, kept on the exception for a host's
2408
+ * logger and never serialized into the body.
2395
2409
  */
2396
- constructor(code, details) {
2410
+ constructor(code, details, options) {
2397
2411
  super(
2398
2412
  {
2399
2413
  error: {
@@ -2406,11 +2420,88 @@ var AuthException = class extends HttpException {
2406
2420
  // A code with no entry is a programming error on the throwing side, not something the
2407
2421
  // caller did — 500 says so, and says it with a number rather than the `undefined` an
2408
2422
  // unguarded lookup used to hand to Express.
2409
- STATUS_BY_CODE.get(code) ?? HttpStatus.INTERNAL_SERVER_ERROR
2423
+ STATUS_BY_CODE.get(code) ?? HttpStatus.INTERNAL_SERVER_ERROR,
2424
+ options?.cause === void 0 ? void 0 : {
2425
+ cause: options.cause
2426
+ }
2410
2427
  );
2411
2428
  }
2412
2429
  };
2413
2430
 
2431
+ // src/server/redis/redis-outage.ts
2432
+ var MESSAGE_KINDS = /* @__PURE__ */ new Map([
2433
+ [
2434
+ "Command timed out",
2435
+ "timeout"
2436
+ ],
2437
+ [
2438
+ "Connection is closed.",
2439
+ "closed"
2440
+ ],
2441
+ [
2442
+ "Stream isn't writeable and enableOfflineQueue options is false",
2443
+ "closed"
2444
+ ]
2445
+ ]);
2446
+ var NETWORK_CODES = /* @__PURE__ */ new Set([
2447
+ "ECONNREFUSED",
2448
+ "ECONNRESET",
2449
+ "ETIMEDOUT",
2450
+ "EPIPE",
2451
+ "ENOTFOUND",
2452
+ "EAI_AGAIN",
2453
+ "EHOSTUNREACH",
2454
+ "ENETUNREACH"
2455
+ ]);
2456
+ var UNAVAILABLE_REPLIES = /* @__PURE__ */ new Set([
2457
+ "READONLY",
2458
+ "LOADING",
2459
+ "MASTERDOWN",
2460
+ "CLUSTERDOWN",
2461
+ "TRYAGAIN"
2462
+ ]);
2463
+ function redisOutageKindOf(error) {
2464
+ if (!(error instanceof Error)) return void 0;
2465
+ if (error.name === "MaxRetriesPerRequestError") return "unreachable";
2466
+ if (error.name === "ReplyError") {
2467
+ return UNAVAILABLE_REPLIES.has(error.message.split(" ", 1)[0]) ? "unavailable" : void 0;
2468
+ }
2469
+ const { code } = error;
2470
+ if (typeof code === "string" && NETWORK_CODES.has(code)) return "unreachable";
2471
+ return MESSAGE_KINDS.get(error.message);
2472
+ }
2473
+ __name(redisOutageKindOf, "redisOutageKindOf");
2474
+ function rethrowAsOutage(error) {
2475
+ if (redisOutageKindOf(error) === void 0) throw error;
2476
+ throw new AuthException(AUTH_ERROR_CODES.SERVICE_UNAVAILABLE, void 0, {
2477
+ cause: error
2478
+ });
2479
+ }
2480
+ __name(rethrowAsOutage, "rethrowAsOutage");
2481
+ function isServiceUnavailable(error) {
2482
+ if (!(error instanceof AuthException)) return false;
2483
+ const body = error.getResponse();
2484
+ return body.error?.code === AUTH_ERROR_CODES.SERVICE_UNAVAILABLE;
2485
+ }
2486
+ __name(isServiceUnavailable, "isServiceUnavailable");
2487
+ function isThenable(value) {
2488
+ return typeof value === "object" && value !== null && typeof value.then === "function";
2489
+ }
2490
+ __name(isThenable, "isThenable");
2491
+ function mappingOutages(redis) {
2492
+ return new Proxy(redis, {
2493
+ get(target, property) {
2494
+ const value = Reflect.get(target, property, target);
2495
+ if (typeof value !== "function") return value;
2496
+ return (...args) => {
2497
+ const result = Reflect.apply(value, target, args);
2498
+ return isThenable(result) ? result.then(void 0, rethrowAsOutage) : result;
2499
+ };
2500
+ }
2501
+ });
2502
+ }
2503
+ __name(mappingOutages, "mappingOutages");
2504
+
2414
2505
  // src/server/constants/user-subject.ts
2415
2506
  function userSubject(plane, userId, tenantId) {
2416
2507
  if (plane === "platform") return `platform:${userId}`;
@@ -2458,7 +2549,6 @@ function _ts_param(paramIndex, decorator) {
2458
2549
  };
2459
2550
  }
2460
2551
  __name(_ts_param, "_ts_param");
2461
- var EPOCH_TTL_SECONDS = TOKEN_EPOCH_RETENTION_SECONDS;
2462
2552
  var WS_TICKET_ENTROPY_BYTES = 32;
2463
2553
  var GRACE_TAG = "GRACE:";
2464
2554
  var REUSED_TAG = "REUSED:";
@@ -2626,7 +2716,7 @@ var AuthRedisService = class {
2626
2716
  */
2627
2717
  #hmacKey;
2628
2718
  constructor(redis, options) {
2629
- this.#redis = redis;
2719
+ this.#redis = mappingOutages(redis);
2630
2720
  this.namespace = options.redisNamespace;
2631
2721
  this.#hmacKey = options.hmacKey;
2632
2722
  }
@@ -3332,7 +3422,7 @@ var AuthRedisService = class {
3332
3422
  return v`, [
3333
3423
  key
3334
3424
  ], [
3335
- String(EPOCH_TTL_SECONDS)
3425
+ String(TOKEN_EPOCH_RETENTION_SECONDS)
3336
3426
  ]);
3337
3427
  return typeof result === "number" ? result : 0;
3338
3428
  }
@@ -7304,7 +7394,7 @@ async function settlePendingLogout(redis, key, fromSession, owner, ttlSeconds, l
7304
7394
  return fromSession || removed;
7305
7395
  } catch (err) {
7306
7396
  logger.warn(`logout: the retry marker could not be cleared \u2014 ${describeChannelStatus(err)}`);
7307
- if (!fromSession) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
7397
+ if (!fromSession) throw isServiceUnavailable(err) ? err : new AuthException(AUTH_ERROR_CODES.INTERNAL);
7308
7398
  return confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger);
7309
7399
  }
7310
7400
  }
@@ -7312,8 +7402,9 @@ __name(settlePendingLogout, "settlePendingLogout");
7312
7402
  async function confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger) {
7313
7403
  try {
7314
7404
  if (await redis.get(key) === null) return true;
7315
- } catch {
7405
+ } catch (err) {
7316
7406
  await rememberPendingLogout(redis, key, owner, ttlSeconds, logger);
7407
+ if (isServiceUnavailable(err)) throw err;
7317
7408
  }
7318
7409
  throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
7319
7410
  }
@@ -12994,7 +13085,7 @@ async function answerResetRequest(deps, request) {
12994
13085
  } catch (err) {
12995
13086
  logger.error(`${label}: cooldown store failed: ${describeChannelStatus(err)}`);
12996
13087
  await holdFloor();
12997
- throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13088
+ throw isServiceUnavailable(err) ? err : new AuthException(AUTH_ERROR_CODES.INTERNAL);
12998
13089
  }
12999
13090
  if (!claimed) {
13000
13091
  await holdFloor();
@@ -13121,10 +13212,9 @@ var PasswordResetService = class _PasswordResetService {
13121
13212
  * - The account is blocked.
13122
13213
  * - Issuing or storing the code, or the email provider, fails for an account that exists.
13123
13214
  *
13124
- * A failure that is the same for every address, the resend-cooldown store or the account
13125
- * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
13126
- * released. This anti-enumeration design ensures the response cannot be used to probe
13127
- * whether an email address is registered.
13215
+ * What a failure answers, and when the cooldown this call took is released, is decided in one
13216
+ * place, {@link answerResetRequest}. The response cannot be used to probe whether an email
13217
+ * address is registered.
13128
13218
  *
13129
13219
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
13130
13220
  * milliseconds to respond, regardless of whether the user was found.
@@ -13232,8 +13322,8 @@ var PasswordResetService = class _PasswordResetService {
13232
13322
  *
13233
13323
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
13234
13324
  * prevent OTP flooding. Resolves the same way whether or not the user exists —
13235
- * anti-enumeration principle; a failure of the cooldown store or the account lookup
13236
- * throws `INTERNAL` (500) after the floor and releases the cooldown.
13325
+ * anti-enumeration principle; what a failure answers is decided in one place,
13326
+ * {@link answerResetRequest}.
13237
13327
  *
13238
13328
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
13239
13329
  *
@@ -13731,8 +13821,8 @@ var PasswordResetController = class {
13731
13821
  *
13732
13822
  * Sends a reset token or OTP to the user's email if the account exists and
13733
13823
  * is eligible. Answers `200 OK` with an empty JSON object whether or not the account exists
13734
- * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
13735
- * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
13824
+ * (anti-enumeration; the body is pinned by the wire contract). What a failure answers is
13825
+ * decided in one place, `answerResetRequest` (utils/answer-reset-request.ts).
13736
13826
  *
13737
13827
  * @param dto - Validated DTO with `email` and `tenantId`.
13738
13828
  * @returns An empty object.
@@ -13820,8 +13910,8 @@ var PasswordResetController = class {
13820
13910
  *
13821
13911
  * Subject to a 60-second atomic cooldown per `(tenantId, email)` pair.
13822
13912
  * Answers `200 OK` with an empty JSON object whether or not the account exists
13823
- * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
13824
- * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
13913
+ * (anti-enumeration; the body is pinned by the wire contract). What a failure answers is
13914
+ * decided in one place, `answerResetRequest` (utils/answer-reset-request.ts).
13825
13915
  *
13826
13916
  * @param dto - Validated DTO with `email` and `tenantId`.
13827
13917
  * @returns An empty object.
@@ -100,7 +100,12 @@ var AUTH_ERROR_CODES = {
100
100
  * An unexpected internal failure. Raised only by the server's optional `AuthExceptionFilter`,
101
101
  * which gives unhandled failures the same envelope everything else answers with.
102
102
  */
103
- INTERNAL: "auth.internal"
103
+ INTERNAL: "auth.internal",
104
+ /**
105
+ * A store the request depends on, Redis, did not answer in time or could not be reached, so
106
+ * the request was refused and nothing was admitted. A client may retry later.
107
+ */
108
+ SERVICE_UNAVAILABLE: "auth.service_unavailable"
104
109
  };
105
110
  var AUTH_ERROR_STATUS = {
106
111
  "auth.invalid_credentials": 401,
@@ -152,7 +157,8 @@ var AUTH_ERROR_STATUS = {
152
157
  "auth.registration_closed": 403,
153
158
  "auth.workspace_limit_reached": 403,
154
159
  "auth.workspace_pending_deletion": 409,
155
- "auth.internal": 500
160
+ "auth.internal": 500,
161
+ "auth.service_unavailable": 503
156
162
  };
157
163
 
158
164
  // src/shared/utils/fill-route.ts
@@ -150,6 +150,11 @@ declare const AUTH_ERROR_CODES: {
150
150
  * which gives unhandled failures the same envelope everything else answers with.
151
151
  */
152
152
  readonly INTERNAL: "auth.internal";
153
+ /**
154
+ * A store the request depends on, Redis, did not answer in time or could not be reached, so
155
+ * the request was refused and nothing was admitted. A client may retry later.
156
+ */
157
+ readonly SERVICE_UNAVAILABLE: "auth.service_unavailable";
153
158
  };
154
159
  /**
155
160
  * String literal union of every `AUTH_ERROR_CODES` value.
@@ -150,6 +150,11 @@ declare const AUTH_ERROR_CODES: {
150
150
  * which gives unhandled failures the same envelope everything else answers with.
151
151
  */
152
152
  readonly INTERNAL: "auth.internal";
153
+ /**
154
+ * A store the request depends on, Redis, did not answer in time or could not be reached, so
155
+ * the request was refused and nothing was admitted. A client may retry later.
156
+ */
157
+ readonly SERVICE_UNAVAILABLE: "auth.service_unavailable";
153
158
  };
154
159
  /**
155
160
  * String literal union of every `AUTH_ERROR_CODES` value.
@@ -98,7 +98,12 @@ var AUTH_ERROR_CODES = {
98
98
  * An unexpected internal failure. Raised only by the server's optional `AuthExceptionFilter`,
99
99
  * which gives unhandled failures the same envelope everything else answers with.
100
100
  */
101
- INTERNAL: "auth.internal"
101
+ INTERNAL: "auth.internal",
102
+ /**
103
+ * A store the request depends on, Redis, did not answer in time or could not be reached, so
104
+ * the request was refused and nothing was admitted. A client may retry later.
105
+ */
106
+ SERVICE_UNAVAILABLE: "auth.service_unavailable"
102
107
  };
103
108
  var AUTH_ERROR_STATUS = {
104
109
  "auth.invalid_credentials": 401,
@@ -150,7 +155,8 @@ var AUTH_ERROR_STATUS = {
150
155
  "auth.registration_closed": 403,
151
156
  "auth.workspace_limit_reached": 403,
152
157
  "auth.workspace_pending_deletion": 409,
153
- "auth.internal": 500
158
+ "auth.internal": 500,
159
+ "auth.service_unavailable": 503
154
160
  };
155
161
 
156
162
  // src/shared/utils/fill-route.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.5.3",
3
+ "version": "1.5.4",
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",
@@ -228,7 +228,7 @@
228
228
  "reflect-metadata": "^0.2.2",
229
229
  "socket.io": "^4.8.3",
230
230
  "socket.io-client": "^4.8.3",
231
- "supertest": "^7.2.2",
231
+ "supertest": "^7.3.1",
232
232
  "testcontainers": "^12.2.1",
233
233
  "ts-jest": "^29.4.9",
234
234
  "ts-node": "^10.9.2",