@bymax-one/nest-auth 1.4.2 → 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.
@@ -1,4 +1,4 @@
1
- import { AUTH_PROXY_ROUTES, buildAuthRefreshSkipSuffixes, AUTH_ROUTES, AuthClientError } 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;
@@ -21,6 +21,28 @@ function shouldSkipRefreshOnUrl(url, suffixes) {
21
21
  return false;
22
22
  }
23
23
  __name(shouldSkipRefreshOnUrl, "shouldSkipRefreshOnUrl");
24
+ var ERROR_BODY_READ_TIMEOUT_MS = 2e3;
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) {
31
+ const clone = response.clone();
32
+ let timer;
33
+ const body = await Promise.race([
34
+ clone.json().catch(() => void 0),
35
+ new Promise((resolve) => {
36
+ timer = setTimeout(() => resolve(void 0), ERROR_BODY_READ_TIMEOUT_MS);
37
+ })
38
+ ]);
39
+ clearTimeout(timer);
40
+ if (typeof body !== "object" || body === null) return void 0;
41
+ const envelope = body;
42
+ const code = envelope.error?.code ?? envelope.code;
43
+ return typeof code === "string" ? code : void 0;
44
+ }
45
+ __name(readErrorCode, "readErrorCode");
24
46
  function resolveRequestUrl(input, baseUrl) {
25
47
  if (typeof input === "string") {
26
48
  return baseUrl !== void 0 && !/^https?:\/\//i.test(input) ? `${baseUrl}${input}` : input;
@@ -31,31 +53,38 @@ function resolveRequestUrl(input, baseUrl) {
31
53
  return input.url;
32
54
  }
33
55
  __name(resolveRequestUrl, "resolveRequestUrl");
34
- function mergeHeaders(defaults, perRequest) {
35
- const merged = {
36
- ...defaults
37
- };
38
- if (perRequest === void 0) {
39
- 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;
40
67
  }
41
- const isUnsafeName = /* @__PURE__ */ __name((name) => name === "__proto__" || name === "constructor" || name === "prototype", "isUnsafeName");
42
- if (Array.isArray(perRequest)) {
43
- for (const [name, value] of perRequest) {
44
- if (isUnsafeName(name)) continue;
45
- merged[name] = value;
46
- }
47
- 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);
48
72
  }
49
- if (typeof Headers !== "undefined" && perRequest instanceof Headers) {
50
- perRequest.forEach((value, name) => {
51
- if (isUnsafeName(name)) return;
52
- merged[name] = value;
53
- });
54
- 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);
55
80
  }
56
- for (const [name, value] of Object.entries(perRequest)) {
57
- if (isUnsafeName(name) || typeof value !== "string") continue;
58
- 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);
59
88
  }
60
89
  return merged;
61
90
  }
@@ -91,6 +120,12 @@ function attachTimeout(init, timeoutMs) {
91
120
  };
92
121
  }
93
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
+ ]);
94
129
  async function performRefresh(endpoint, credentials) {
95
130
  try {
96
131
  const response = await fetch(endpoint, {
@@ -100,14 +135,38 @@ async function performRefresh(endpoint, credentials) {
100
135
  "Content-Type": "application/json"
101
136
  }
102
137
  });
103
- const ok = response.ok;
104
- await response.body?.cancel().catch(
138
+ const { ok, status } = response;
139
+ const code = status === 403 ? await readErrorCode(response) : void 0;
140
+ void response.body?.cancel().catch(
105
141
  /* istanbul ignore next */
106
142
  () => void 0
107
143
  );
108
- 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
+ };
109
164
  } catch {
110
- return false;
165
+ return {
166
+ ok: false,
167
+ reason: "unreachable",
168
+ status: null
169
+ };
111
170
  }
112
171
  }
113
172
  __name(performRefresh, "performRefresh");
@@ -115,13 +174,14 @@ function createAuthFetch(config = {}) {
115
174
  const baseUrl = config.baseUrl;
116
175
  const refreshEndpoint = config.refreshEndpoint ?? AUTH_PROXY_ROUTES.clientRefresh;
117
176
  const credentials = config.credentials ?? "include";
118
- const defaultHeaders = config.defaultHeaders ? {
119
- ...DEFAULT_HEADERS,
120
- ...config.defaultHeaders
121
- } : DEFAULT_HEADERS;
177
+ const defaultHeaders = buildDefaultHeaders(config.defaultHeaders);
122
178
  const onSessionExpired = config.onSessionExpired;
179
+ const onRefreshFailed = config.onRefreshFailed;
123
180
  const timeoutMs = config.timeout ?? 3e4;
124
181
  const skipRefreshSuffixes = buildAuthRefreshSkipSuffixes(config.routePrefix);
182
+ const reportCallbackError = /* @__PURE__ */ __name((err) => {
183
+ console.warn("[nest-auth] onRefreshFailed callback threw:", err);
184
+ }, "reportCallbackError");
125
185
  let inFlightRefresh = null;
126
186
  function getOrStartRefresh() {
127
187
  if (inFlightRefresh !== null) {
@@ -155,8 +215,18 @@ function createAuthFetch(config = {}) {
155
215
  if (response.status !== 401 || shouldSkipRefreshOnUrl(url, skipRefreshSuffixes)) {
156
216
  return response;
157
217
  }
158
- const refreshed = await getOrStartRefresh();
159
- if (!refreshed) {
218
+ if (!await isExpiredSessionResponse(response)) {
219
+ return response;
220
+ }
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") {
160
230
  try {
161
231
  onSessionExpired?.();
162
232
  } catch (err) {
@@ -164,6 +234,7 @@ function createAuthFetch(config = {}) {
164
234
  }
165
235
  return response;
166
236
  }
237
+ if (!outcome.ok) return response;
167
238
  const retryAttempt = attachTimeout(initBase, timeoutMs);
168
239
  try {
169
240
  return await fetch(targetForFetch, retryAttempt.init);
@@ -233,7 +304,7 @@ async function expectNoContent(response) {
233
304
  const text = await response.text();
234
305
  throwAuthError(response, text);
235
306
  }
236
- await response.body?.cancel().catch(
307
+ void response.body?.cancel().catch(
237
308
  /* istanbul ignore next */
238
309
  () => void 0
239
310
  );
@@ -364,15 +435,17 @@ function createAuthClient(config) {
364
435
  async forgotPassword(email, tenantId) {
365
436
  return postNoContent(AUTH_ROUTES.password.forgotPassword, {
366
437
  email,
367
- tenantId
438
+ ...tenantId !== void 0 ? {
439
+ tenantId
440
+ } : {}
368
441
  });
369
442
  },
370
443
  async resetPassword(input) {
371
444
  const payload = {
372
445
  email: input.email,
373
- tenantId: input.tenantId,
374
446
  newPassword: input.newPassword
375
447
  };
448
+ if (input.tenantId !== void 0) payload["tenantId"] = input.tenantId;
376
449
  if (input.token !== void 0) payload["token"] = input.token;
377
450
  if (input.otp !== void 0) payload["otp"] = input.otp;
378
451
  if (input.verifiedToken !== void 0) payload["verifiedToken"] = input.verifiedToken;