@bymax-one/nest-auth 1.4.3 → 1.4.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.
@@ -24,6 +24,11 @@ function shouldSkipRefreshOnUrl(url, suffixes) {
24
24
  __name(shouldSkipRefreshOnUrl, "shouldSkipRefreshOnUrl");
25
25
  var ERROR_BODY_READ_TIMEOUT_MS = 2e3;
26
26
  async function isExpiredSessionResponse(response) {
27
+ const code = await readErrorCode(response);
28
+ return code === void 0 || code === shared.AUTH_ERROR_CODES.TOKEN_INVALID;
29
+ }
30
+ __name(isExpiredSessionResponse, "isExpiredSessionResponse");
31
+ async function readErrorCode(response) {
27
32
  const clone = response.clone();
28
33
  let timer;
29
34
  const body = await Promise.race([
@@ -33,12 +38,12 @@ async function isExpiredSessionResponse(response) {
33
38
  })
34
39
  ]);
35
40
  clearTimeout(timer);
36
- if (typeof body !== "object" || body === null) return true;
41
+ if (typeof body !== "object" || body === null) return void 0;
37
42
  const envelope = body;
38
43
  const code = envelope.error?.code ?? envelope.code;
39
- return typeof code !== "string" || code === shared.AUTH_ERROR_CODES.TOKEN_INVALID;
44
+ return typeof code === "string" ? code : void 0;
40
45
  }
41
- __name(isExpiredSessionResponse, "isExpiredSessionResponse");
46
+ __name(readErrorCode, "readErrorCode");
42
47
  function resolveRequestUrl(input, baseUrl) {
43
48
  if (typeof input === "string") {
44
49
  return baseUrl !== void 0 && !/^https?:\/\//i.test(input) ? `${baseUrl}${input}` : input;
@@ -49,31 +54,38 @@ function resolveRequestUrl(input, baseUrl) {
49
54
  return input.url;
50
55
  }
51
56
  __name(resolveRequestUrl, "resolveRequestUrl");
52
- function mergeHeaders(defaults, perRequest) {
53
- const merged = {
54
- ...defaults
55
- };
56
- if (perRequest === void 0) {
57
- return merged;
57
+ function isUnsafeHeaderName(name) {
58
+ return name === "__proto__" || name === "constructor" || name === "prototype";
59
+ }
60
+ __name(isUnsafeHeaderName, "isUnsafeHeaderName");
61
+ function applyHeaders(target, source) {
62
+ if (source instanceof Headers) {
63
+ source.forEach((value, name) => {
64
+ if (isUnsafeHeaderName(name)) return;
65
+ target.set(name, value);
66
+ });
67
+ return;
58
68
  }
59
- const isUnsafeName = /* @__PURE__ */ __name((name) => name === "__proto__" || name === "constructor" || name === "prototype", "isUnsafeName");
60
- if (Array.isArray(perRequest)) {
61
- for (const [name, value] of perRequest) {
62
- if (isUnsafeName(name)) continue;
63
- merged[name] = value;
64
- }
65
- return merged;
69
+ const entries = Array.isArray(source) ? source : Object.entries(source);
70
+ for (const [name, value] of entries) {
71
+ if (isUnsafeHeaderName(name.toLowerCase())) continue;
72
+ target.set(name, value);
66
73
  }
67
- if (typeof Headers !== "undefined" && perRequest instanceof Headers) {
68
- perRequest.forEach((value, name) => {
69
- if (isUnsafeName(name)) return;
70
- merged[name] = value;
71
- });
72
- return merged;
74
+ }
75
+ __name(applyHeaders, "applyHeaders");
76
+ function buildDefaultHeaders(configured) {
77
+ const defaults = new Headers();
78
+ applyHeaders(defaults, DEFAULT_HEADERS);
79
+ if (configured !== void 0) {
80
+ applyHeaders(defaults, configured);
73
81
  }
74
- for (const [name, value] of Object.entries(perRequest)) {
75
- if (isUnsafeName(name) || typeof value !== "string") continue;
76
- merged[name] = value;
82
+ return defaults;
83
+ }
84
+ __name(buildDefaultHeaders, "buildDefaultHeaders");
85
+ function mergeHeaders(defaults, perRequest) {
86
+ const merged = new Headers(defaults);
87
+ if (perRequest !== void 0) {
88
+ applyHeaders(merged, perRequest);
77
89
  }
78
90
  return merged;
79
91
  }
@@ -109,6 +121,12 @@ function attachTimeout(init, timeoutMs) {
109
121
  };
110
122
  }
111
123
  __name(attachTimeout, "attachTimeout");
124
+ var TERMINAL_REFRESH_CODES = /* @__PURE__ */ new Set([
125
+ shared.AUTH_ERROR_CODES.ACCOUNT_INACTIVE,
126
+ shared.AUTH_ERROR_CODES.ACCOUNT_SUSPENDED,
127
+ shared.AUTH_ERROR_CODES.ACCOUNT_BANNED,
128
+ shared.AUTH_ERROR_CODES.PENDING_APPROVAL
129
+ ]);
112
130
  async function performRefresh(endpoint, credentials) {
113
131
  try {
114
132
  const response = await fetch(endpoint, {
@@ -118,14 +136,38 @@ async function performRefresh(endpoint, credentials) {
118
136
  "Content-Type": "application/json"
119
137
  }
120
138
  });
121
- const ok = response.ok;
139
+ const { ok, status } = response;
140
+ const code = status === 403 ? await readErrorCode(response) : void 0;
122
141
  void response.body?.cancel().catch(
123
142
  /* istanbul ignore next */
124
143
  () => void 0
125
144
  );
126
- return ok;
145
+ if (ok) return {
146
+ ok: true
147
+ };
148
+ if (status === 401) return {
149
+ ok: false,
150
+ reason: "rejected",
151
+ status
152
+ };
153
+ if (code !== void 0 && TERMINAL_REFRESH_CODES.has(code)) {
154
+ return {
155
+ ok: false,
156
+ reason: "rejected",
157
+ status
158
+ };
159
+ }
160
+ return {
161
+ ok: false,
162
+ reason: "unavailable",
163
+ status
164
+ };
127
165
  } catch {
128
- return false;
166
+ return {
167
+ ok: false,
168
+ reason: "unreachable",
169
+ status: null
170
+ };
129
171
  }
130
172
  }
131
173
  __name(performRefresh, "performRefresh");
@@ -133,13 +175,14 @@ function createAuthFetch(config = {}) {
133
175
  const baseUrl = config.baseUrl;
134
176
  const refreshEndpoint = config.refreshEndpoint ?? shared.AUTH_PROXY_ROUTES.clientRefresh;
135
177
  const credentials = config.credentials ?? "include";
136
- const defaultHeaders = config.defaultHeaders ? {
137
- ...DEFAULT_HEADERS,
138
- ...config.defaultHeaders
139
- } : DEFAULT_HEADERS;
178
+ const defaultHeaders = buildDefaultHeaders(config.defaultHeaders);
140
179
  const onSessionExpired = config.onSessionExpired;
180
+ const onRefreshFailed = config.onRefreshFailed;
141
181
  const timeoutMs = config.timeout ?? 3e4;
142
182
  const skipRefreshSuffixes = shared.buildAuthRefreshSkipSuffixes(config.routePrefix);
183
+ const reportCallbackError = /* @__PURE__ */ __name((err) => {
184
+ console.warn("[nest-auth] onRefreshFailed callback threw:", err);
185
+ }, "reportCallbackError");
143
186
  let inFlightRefresh = null;
144
187
  function getOrStartRefresh() {
145
188
  if (inFlightRefresh !== null) {
@@ -176,8 +219,15 @@ function createAuthFetch(config = {}) {
176
219
  if (!await isExpiredSessionResponse(response)) {
177
220
  return response;
178
221
  }
179
- const refreshed = await getOrStartRefresh();
180
- if (!refreshed) {
222
+ const outcome = await getOrStartRefresh();
223
+ if (!outcome.ok) {
224
+ try {
225
+ void Promise.resolve(onRefreshFailed?.(outcome)).catch(reportCallbackError);
226
+ } catch (err) {
227
+ reportCallbackError(err);
228
+ }
229
+ }
230
+ if (!outcome.ok && outcome.reason === "rejected") {
181
231
  try {
182
232
  onSessionExpired?.();
183
233
  } catch (err) {
@@ -185,6 +235,7 @@ function createAuthFetch(config = {}) {
185
235
  }
186
236
  return response;
187
237
  }
238
+ if (!outcome.ok) return response;
188
239
  const retryAttempt = attachTimeout(initBase, timeoutMs);
189
240
  try {
190
241
  return await fetch(targetForFetch, retryAttempt.init);
@@ -65,6 +65,25 @@ interface AuthFetchConfig {
65
65
  * rejects, so consumers can rely on side effects having happened.
66
66
  */
67
67
  onSessionExpired?: () => void;
68
+ /**
69
+ * Callback invoked when a refresh attempt did not produce a session, whatever the reason.
70
+ *
71
+ * Fires for every failure, including the one that also triggers {@link onSessionExpired} — and
72
+ * before it, so a consumer sees the reason first. This is what makes the answer to *why* usable
73
+ * rather than merely internal: a rate limit deserves "retrying in a moment", a dropped
74
+ * connection deserves "you appear to be offline", and only a refused credential deserves the
75
+ * sign-in screen.
76
+ *
77
+ * Errors are swallowed and reported through `console.warn`, on the same reasoning as
78
+ * {@link onSessionExpired}: a broken consumer callback must not mask the underlying response.
79
+ * That covers an `async` callback too — the signature is `=> void`, which TypeScript lets an
80
+ * async function satisfy, and its rejection is handled rather than left to surface as an
81
+ * unhandled rejection in your app. It is not awaited: this is a notification, and the
82
+ * sign-out decision does not wait behind a consumer's network call.
83
+ *
84
+ * @param failure - Why the attempt failed, and the status behind it when there was one.
85
+ */
86
+ onRefreshFailed?: (failure: RefreshFailure) => void;
68
87
  /**
69
88
  * Per-request timeout in milliseconds.
70
89
  *
@@ -102,6 +121,46 @@ interface AuthFetchConfig {
102
121
  * 401 response.
103
122
  */
104
123
  type AuthFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
124
+ /**
125
+ * Why a refresh attempt did not produce a new session.
126
+ *
127
+ * Three answers, not a boolean, because the caller acts differently on each and a boolean forces
128
+ * it to guess. Measured by a consumer against a real browser round: a rate-limited refresh answers
129
+ * `429`, the boolean made that identical to `401`, and the caller signed the user out of a session
130
+ * whose credential was still valid.
131
+ *
132
+ * - `rejected` — a 401, or a 403 whose error code names a terminal account state. The server
133
+ * looked at the credential and refused it. The session is over, and `status` is `401` or `403`.
134
+ * - `unavailable` — it answered, but not with a session: a 429, a 5xx, a 403 from an origin guard,
135
+ * a 404 from a mistyped `routePrefix`. None of those is a statement about the credential.
136
+ * - `unreachable` — no answer at all: offline, DNS, CORS, an aborted request.
137
+ *
138
+ * 403 is decided by the error CODE rather than the status, because the route answers it for two
139
+ * unrelated reasons. `TrustedOriginGuard` covers `/refresh` and answers `auth.untrusted_origin`
140
+ * with 403 — reading that as expiry would sign out every user of a deployment with a wrong
141
+ * `trustedOrigins`. But `refresh` also revokes every session before rethrowing a blocked-account
142
+ * status, and there a 403 genuinely IS the end of the session. This wrapper reads the code
143
+ * itself: it drains the refresh body, and the caller receives the original resource response, so
144
+ * there is nothing left for it to consult.
145
+ */
146
+ type RefreshFailureReason = 'rejected' | 'unavailable' | 'unreachable';
147
+ /**
148
+ * The result of one refresh attempt.
149
+ *
150
+ * A discriminated union rather than a boolean with a `429` carve-out. The carve-out was offered
151
+ * and declined by the consumer who found the defect, on the grounds that it reproduces the same
152
+ * shape for whichever status turns out to matter next — the refresh has to report WHY it failed,
153
+ * not whether.
154
+ */
155
+ interface RefreshFailure {
156
+ readonly ok: false;
157
+ readonly reason: RefreshFailureReason;
158
+ /** HTTP status the server answered with, or `null` when there was no answer. */
159
+ readonly status: number | null;
160
+ }
161
+ type RefreshOutcome = {
162
+ readonly ok: true;
163
+ } | RefreshFailure;
105
164
  /**
106
165
  * Create a configured fetch wrapper with cookie- and refresh-aware
107
166
  * behavior baked in.
@@ -314,4 +373,4 @@ interface AuthClient {
314
373
  */
315
374
  declare function createAuthClient(config: AuthClientConfig): AuthClient;
316
375
 
317
- export { type AuthClient, type AuthClientConfig, type AuthFetch, type AuthFetchConfig, type LoginInput, type RegisterInput, type ResetPasswordInput, createAuthClient, createAuthFetch };
376
+ export { type AuthClient, type AuthClientConfig, type AuthFetch, type AuthFetchConfig, type LoginInput, type RefreshFailure, type RefreshFailureReason, type RefreshOutcome, type RegisterInput, type ResetPasswordInput, createAuthClient, createAuthFetch };
@@ -65,6 +65,25 @@ interface AuthFetchConfig {
65
65
  * rejects, so consumers can rely on side effects having happened.
66
66
  */
67
67
  onSessionExpired?: () => void;
68
+ /**
69
+ * Callback invoked when a refresh attempt did not produce a session, whatever the reason.
70
+ *
71
+ * Fires for every failure, including the one that also triggers {@link onSessionExpired} — and
72
+ * before it, so a consumer sees the reason first. This is what makes the answer to *why* usable
73
+ * rather than merely internal: a rate limit deserves "retrying in a moment", a dropped
74
+ * connection deserves "you appear to be offline", and only a refused credential deserves the
75
+ * sign-in screen.
76
+ *
77
+ * Errors are swallowed and reported through `console.warn`, on the same reasoning as
78
+ * {@link onSessionExpired}: a broken consumer callback must not mask the underlying response.
79
+ * That covers an `async` callback too — the signature is `=> void`, which TypeScript lets an
80
+ * async function satisfy, and its rejection is handled rather than left to surface as an
81
+ * unhandled rejection in your app. It is not awaited: this is a notification, and the
82
+ * sign-out decision does not wait behind a consumer's network call.
83
+ *
84
+ * @param failure - Why the attempt failed, and the status behind it when there was one.
85
+ */
86
+ onRefreshFailed?: (failure: RefreshFailure) => void;
68
87
  /**
69
88
  * Per-request timeout in milliseconds.
70
89
  *
@@ -102,6 +121,46 @@ interface AuthFetchConfig {
102
121
  * 401 response.
103
122
  */
104
123
  type AuthFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
124
+ /**
125
+ * Why a refresh attempt did not produce a new session.
126
+ *
127
+ * Three answers, not a boolean, because the caller acts differently on each and a boolean forces
128
+ * it to guess. Measured by a consumer against a real browser round: a rate-limited refresh answers
129
+ * `429`, the boolean made that identical to `401`, and the caller signed the user out of a session
130
+ * whose credential was still valid.
131
+ *
132
+ * - `rejected` — a 401, or a 403 whose error code names a terminal account state. The server
133
+ * looked at the credential and refused it. The session is over, and `status` is `401` or `403`.
134
+ * - `unavailable` — it answered, but not with a session: a 429, a 5xx, a 403 from an origin guard,
135
+ * a 404 from a mistyped `routePrefix`. None of those is a statement about the credential.
136
+ * - `unreachable` — no answer at all: offline, DNS, CORS, an aborted request.
137
+ *
138
+ * 403 is decided by the error CODE rather than the status, because the route answers it for two
139
+ * unrelated reasons. `TrustedOriginGuard` covers `/refresh` and answers `auth.untrusted_origin`
140
+ * with 403 — reading that as expiry would sign out every user of a deployment with a wrong
141
+ * `trustedOrigins`. But `refresh` also revokes every session before rethrowing a blocked-account
142
+ * status, and there a 403 genuinely IS the end of the session. This wrapper reads the code
143
+ * itself: it drains the refresh body, and the caller receives the original resource response, so
144
+ * there is nothing left for it to consult.
145
+ */
146
+ type RefreshFailureReason = 'rejected' | 'unavailable' | 'unreachable';
147
+ /**
148
+ * The result of one refresh attempt.
149
+ *
150
+ * A discriminated union rather than a boolean with a `429` carve-out. The carve-out was offered
151
+ * and declined by the consumer who found the defect, on the grounds that it reproduces the same
152
+ * shape for whichever status turns out to matter next — the refresh has to report WHY it failed,
153
+ * not whether.
154
+ */
155
+ interface RefreshFailure {
156
+ readonly ok: false;
157
+ readonly reason: RefreshFailureReason;
158
+ /** HTTP status the server answered with, or `null` when there was no answer. */
159
+ readonly status: number | null;
160
+ }
161
+ type RefreshOutcome = {
162
+ readonly ok: true;
163
+ } | RefreshFailure;
105
164
  /**
106
165
  * Create a configured fetch wrapper with cookie- and refresh-aware
107
166
  * behavior baked in.
@@ -314,4 +373,4 @@ interface AuthClient {
314
373
  */
315
374
  declare function createAuthClient(config: AuthClientConfig): AuthClient;
316
375
 
317
- export { type AuthClient, type AuthClientConfig, type AuthFetch, type AuthFetchConfig, type LoginInput, type RegisterInput, type ResetPasswordInput, createAuthClient, createAuthFetch };
376
+ export { type AuthClient, type AuthClientConfig, type AuthFetch, type AuthFetchConfig, type LoginInput, type RefreshFailure, type RefreshFailureReason, type RefreshOutcome, type RegisterInput, type ResetPasswordInput, createAuthClient, createAuthFetch };
@@ -1,4 +1,4 @@
1
- import { AUTH_PROXY_ROUTES, buildAuthRefreshSkipSuffixes, AUTH_ROUTES, AuthClientError, AUTH_ERROR_CODES } from '@bymax-one/nest-auth/shared';
1
+ import { AUTH_ERROR_CODES, AUTH_PROXY_ROUTES, buildAuthRefreshSkipSuffixes, AUTH_ROUTES, AuthClientError } from '@bymax-one/nest-auth/shared';
2
2
  export { AuthClientError } from '@bymax-one/nest-auth/shared';
3
3
 
4
4
  var __defProp = Object.defineProperty;
@@ -23,6 +23,11 @@ function shouldSkipRefreshOnUrl(url, suffixes) {
23
23
  __name(shouldSkipRefreshOnUrl, "shouldSkipRefreshOnUrl");
24
24
  var ERROR_BODY_READ_TIMEOUT_MS = 2e3;
25
25
  async function isExpiredSessionResponse(response) {
26
+ const code = await readErrorCode(response);
27
+ return code === void 0 || code === AUTH_ERROR_CODES.TOKEN_INVALID;
28
+ }
29
+ __name(isExpiredSessionResponse, "isExpiredSessionResponse");
30
+ async function readErrorCode(response) {
26
31
  const clone = response.clone();
27
32
  let timer;
28
33
  const body = await Promise.race([
@@ -32,12 +37,12 @@ async function isExpiredSessionResponse(response) {
32
37
  })
33
38
  ]);
34
39
  clearTimeout(timer);
35
- if (typeof body !== "object" || body === null) return true;
40
+ if (typeof body !== "object" || body === null) return void 0;
36
41
  const envelope = body;
37
42
  const code = envelope.error?.code ?? envelope.code;
38
- return typeof code !== "string" || code === AUTH_ERROR_CODES.TOKEN_INVALID;
43
+ return typeof code === "string" ? code : void 0;
39
44
  }
40
- __name(isExpiredSessionResponse, "isExpiredSessionResponse");
45
+ __name(readErrorCode, "readErrorCode");
41
46
  function resolveRequestUrl(input, baseUrl) {
42
47
  if (typeof input === "string") {
43
48
  return baseUrl !== void 0 && !/^https?:\/\//i.test(input) ? `${baseUrl}${input}` : input;
@@ -48,31 +53,38 @@ function resolveRequestUrl(input, baseUrl) {
48
53
  return input.url;
49
54
  }
50
55
  __name(resolveRequestUrl, "resolveRequestUrl");
51
- function mergeHeaders(defaults, perRequest) {
52
- const merged = {
53
- ...defaults
54
- };
55
- if (perRequest === void 0) {
56
- return merged;
56
+ function isUnsafeHeaderName(name) {
57
+ return name === "__proto__" || name === "constructor" || name === "prototype";
58
+ }
59
+ __name(isUnsafeHeaderName, "isUnsafeHeaderName");
60
+ function applyHeaders(target, source) {
61
+ if (source instanceof Headers) {
62
+ source.forEach((value, name) => {
63
+ if (isUnsafeHeaderName(name)) return;
64
+ target.set(name, value);
65
+ });
66
+ return;
57
67
  }
58
- const isUnsafeName = /* @__PURE__ */ __name((name) => name === "__proto__" || name === "constructor" || name === "prototype", "isUnsafeName");
59
- if (Array.isArray(perRequest)) {
60
- for (const [name, value] of perRequest) {
61
- if (isUnsafeName(name)) continue;
62
- merged[name] = value;
63
- }
64
- return merged;
68
+ const entries = Array.isArray(source) ? source : Object.entries(source);
69
+ for (const [name, value] of entries) {
70
+ if (isUnsafeHeaderName(name.toLowerCase())) continue;
71
+ target.set(name, value);
65
72
  }
66
- if (typeof Headers !== "undefined" && perRequest instanceof Headers) {
67
- perRequest.forEach((value, name) => {
68
- if (isUnsafeName(name)) return;
69
- merged[name] = value;
70
- });
71
- return merged;
73
+ }
74
+ __name(applyHeaders, "applyHeaders");
75
+ function buildDefaultHeaders(configured) {
76
+ const defaults = new Headers();
77
+ applyHeaders(defaults, DEFAULT_HEADERS);
78
+ if (configured !== void 0) {
79
+ applyHeaders(defaults, configured);
72
80
  }
73
- for (const [name, value] of Object.entries(perRequest)) {
74
- if (isUnsafeName(name) || typeof value !== "string") continue;
75
- merged[name] = value;
81
+ return defaults;
82
+ }
83
+ __name(buildDefaultHeaders, "buildDefaultHeaders");
84
+ function mergeHeaders(defaults, perRequest) {
85
+ const merged = new Headers(defaults);
86
+ if (perRequest !== void 0) {
87
+ applyHeaders(merged, perRequest);
76
88
  }
77
89
  return merged;
78
90
  }
@@ -108,6 +120,12 @@ function attachTimeout(init, timeoutMs) {
108
120
  };
109
121
  }
110
122
  __name(attachTimeout, "attachTimeout");
123
+ var TERMINAL_REFRESH_CODES = /* @__PURE__ */ new Set([
124
+ AUTH_ERROR_CODES.ACCOUNT_INACTIVE,
125
+ AUTH_ERROR_CODES.ACCOUNT_SUSPENDED,
126
+ AUTH_ERROR_CODES.ACCOUNT_BANNED,
127
+ AUTH_ERROR_CODES.PENDING_APPROVAL
128
+ ]);
111
129
  async function performRefresh(endpoint, credentials) {
112
130
  try {
113
131
  const response = await fetch(endpoint, {
@@ -117,14 +135,38 @@ async function performRefresh(endpoint, credentials) {
117
135
  "Content-Type": "application/json"
118
136
  }
119
137
  });
120
- const ok = response.ok;
138
+ const { ok, status } = response;
139
+ const code = status === 403 ? await readErrorCode(response) : void 0;
121
140
  void response.body?.cancel().catch(
122
141
  /* istanbul ignore next */
123
142
  () => void 0
124
143
  );
125
- return ok;
144
+ if (ok) return {
145
+ ok: true
146
+ };
147
+ if (status === 401) return {
148
+ ok: false,
149
+ reason: "rejected",
150
+ status
151
+ };
152
+ if (code !== void 0 && TERMINAL_REFRESH_CODES.has(code)) {
153
+ return {
154
+ ok: false,
155
+ reason: "rejected",
156
+ status
157
+ };
158
+ }
159
+ return {
160
+ ok: false,
161
+ reason: "unavailable",
162
+ status
163
+ };
126
164
  } catch {
127
- return false;
165
+ return {
166
+ ok: false,
167
+ reason: "unreachable",
168
+ status: null
169
+ };
128
170
  }
129
171
  }
130
172
  __name(performRefresh, "performRefresh");
@@ -132,13 +174,14 @@ function createAuthFetch(config = {}) {
132
174
  const baseUrl = config.baseUrl;
133
175
  const refreshEndpoint = config.refreshEndpoint ?? AUTH_PROXY_ROUTES.clientRefresh;
134
176
  const credentials = config.credentials ?? "include";
135
- const defaultHeaders = config.defaultHeaders ? {
136
- ...DEFAULT_HEADERS,
137
- ...config.defaultHeaders
138
- } : DEFAULT_HEADERS;
177
+ const defaultHeaders = buildDefaultHeaders(config.defaultHeaders);
139
178
  const onSessionExpired = config.onSessionExpired;
179
+ const onRefreshFailed = config.onRefreshFailed;
140
180
  const timeoutMs = config.timeout ?? 3e4;
141
181
  const skipRefreshSuffixes = buildAuthRefreshSkipSuffixes(config.routePrefix);
182
+ const reportCallbackError = /* @__PURE__ */ __name((err) => {
183
+ console.warn("[nest-auth] onRefreshFailed callback threw:", err);
184
+ }, "reportCallbackError");
142
185
  let inFlightRefresh = null;
143
186
  function getOrStartRefresh() {
144
187
  if (inFlightRefresh !== null) {
@@ -175,8 +218,15 @@ function createAuthFetch(config = {}) {
175
218
  if (!await isExpiredSessionResponse(response)) {
176
219
  return response;
177
220
  }
178
- const refreshed = await getOrStartRefresh();
179
- if (!refreshed) {
221
+ const outcome = await getOrStartRefresh();
222
+ if (!outcome.ok) {
223
+ try {
224
+ void Promise.resolve(onRefreshFailed?.(outcome)).catch(reportCallbackError);
225
+ } catch (err) {
226
+ reportCallbackError(err);
227
+ }
228
+ }
229
+ if (!outcome.ok && outcome.reason === "rejected") {
180
230
  try {
181
231
  onSessionExpired?.();
182
232
  } catch (err) {
@@ -184,6 +234,7 @@ function createAuthFetch(config = {}) {
184
234
  }
185
235
  return response;
186
236
  }
237
+ if (!outcome.ok) return response;
187
238
  const retryAttempt = attachTimeout(initBase, timeoutMs);
188
239
  try {
189
240
  return await fetch(targetForFetch, retryAttempt.init);