@bymax-one/nest-auth 1.4.21 → 1.5.0

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,8 +1,7 @@
1
- import { AUTH_ERROR_CODES, AUTH_PROXY_ROUTES, buildAuthRefreshSkipSuffixes, AUTH_ROUTES, AuthClientError } from '@bymax-one/nest-auth/shared';
1
+ import { AUTH_ERROR_CODES, AUTH_ROUTES, AUTH_PROXY_ROUTES, buildAuthRefreshSkipSuffixes, AuthClientError, trimSlashes, fillRoute } from '@bymax-one/nest-auth/shared';
2
2
  export { AuthClientError } from '@bymax-one/nest-auth/shared';
3
3
 
4
- var __defProp = Object.defineProperty;
5
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
+ // src/client/createAuthFetch.ts
6
5
  var DEFAULT_HEADERS = Object.freeze({
7
6
  "Content-Type": "application/json"
8
7
  });
@@ -20,13 +19,11 @@ function shouldSkipRefreshOnUrl(url, suffixes) {
20
19
  }
21
20
  return false;
22
21
  }
23
- __name(shouldSkipRefreshOnUrl, "shouldSkipRefreshOnUrl");
24
22
  var ERROR_BODY_READ_TIMEOUT_MS = 2e3;
25
23
  async function isExpiredSessionResponse(response) {
26
24
  const code = await readErrorCode(response);
27
25
  return code === void 0 || code === AUTH_ERROR_CODES.TOKEN_INVALID;
28
26
  }
29
- __name(isExpiredSessionResponse, "isExpiredSessionResponse");
30
27
  async function readErrorCode(response) {
31
28
  const clone = response.clone();
32
29
  let timer;
@@ -42,7 +39,6 @@ async function readErrorCode(response) {
42
39
  const code = envelope.error?.code ?? envelope.code;
43
40
  return typeof code === "string" ? code : void 0;
44
41
  }
45
- __name(readErrorCode, "readErrorCode");
46
42
  function resolveRequestUrl(input, baseUrl) {
47
43
  if (typeof input === "string") {
48
44
  return baseUrl !== void 0 && !/^https?:\/\//i.test(input) ? `${baseUrl}${input}` : input;
@@ -52,11 +48,9 @@ function resolveRequestUrl(input, baseUrl) {
52
48
  }
53
49
  return input.url;
54
50
  }
55
- __name(resolveRequestUrl, "resolveRequestUrl");
56
51
  function isUnsafeHeaderName(name) {
57
52
  return name === "__proto__" || name === "constructor" || name === "prototype";
58
53
  }
59
- __name(isUnsafeHeaderName, "isUnsafeHeaderName");
60
54
  function applyHeaders(target, source) {
61
55
  if (source instanceof Headers) {
62
56
  source.forEach((value, name) => {
@@ -71,7 +65,6 @@ function applyHeaders(target, source) {
71
65
  target.set(name, value);
72
66
  }
73
67
  }
74
- __name(applyHeaders, "applyHeaders");
75
68
  function buildDefaultHeaders(configured) {
76
69
  const defaults = new Headers();
77
70
  applyHeaders(defaults, DEFAULT_HEADERS);
@@ -80,7 +73,6 @@ function buildDefaultHeaders(configured) {
80
73
  }
81
74
  return defaults;
82
75
  }
83
- __name(buildDefaultHeaders, "buildDefaultHeaders");
84
76
  function mergeHeaders(defaults, perRequest) {
85
77
  const merged = new Headers(defaults);
86
78
  if (perRequest !== void 0) {
@@ -88,13 +80,12 @@ function mergeHeaders(defaults, perRequest) {
88
80
  }
89
81
  return merged;
90
82
  }
91
- __name(mergeHeaders, "mergeHeaders");
92
83
  function attachTimeout(init, timeoutMs) {
93
84
  if (timeoutMs <= 0) {
94
85
  return {
95
86
  init,
96
- cleanup: /* @__PURE__ */ __name(() => {
97
- }, "cleanup")
87
+ cleanup: () => {
88
+ }
98
89
  };
99
90
  }
100
91
  const controller = new AbortController();
@@ -106,20 +97,14 @@ function attachTimeout(init, timeoutMs) {
106
97
  if (userSignal.aborted) {
107
98
  controller.abort();
108
99
  } else {
109
- userSignal.addEventListener("abort", () => controller.abort(), {
110
- once: true
111
- });
100
+ userSignal.addEventListener("abort", () => controller.abort(), { once: true });
112
101
  }
113
102
  }
114
103
  return {
115
- init: {
116
- ...init,
117
- signal: controller.signal
118
- },
119
- cleanup: /* @__PURE__ */ __name(() => clearTimeout(timer), "cleanup")
104
+ init: { ...init, signal: controller.signal },
105
+ cleanup: () => clearTimeout(timer)
120
106
  };
121
107
  }
122
- __name(attachTimeout, "attachTimeout");
123
108
  var TERMINAL_REFRESH_CODES = /* @__PURE__ */ new Set([
124
109
  AUTH_ERROR_CODES.ACCOUNT_INACTIVE,
125
110
  AUTH_ERROR_CODES.ACCOUNT_SUSPENDED,
@@ -131,9 +116,7 @@ async function performRefresh(endpoint, credentials) {
131
116
  const response = await fetch(endpoint, {
132
117
  method: "POST",
133
118
  credentials,
134
- headers: {
135
- "Content-Type": "application/json"
136
- }
119
+ headers: { "Content-Type": "application/json" }
137
120
  });
138
121
  const { ok, status } = response;
139
122
  const code = status === 403 ? await readErrorCode(response) : void 0;
@@ -141,35 +124,16 @@ async function performRefresh(endpoint, credentials) {
141
124
  /* istanbul ignore next */
142
125
  () => void 0
143
126
  );
144
- if (ok) return {
145
- ok: true
146
- };
147
- if (status === 401) return {
148
- ok: false,
149
- reason: "rejected",
150
- status
151
- };
127
+ if (ok) return { ok: true };
128
+ if (status === 401) return { ok: false, reason: "rejected", status };
152
129
  if (code !== void 0 && TERMINAL_REFRESH_CODES.has(code)) {
153
- return {
154
- ok: false,
155
- reason: "rejected",
156
- status
157
- };
130
+ return { ok: false, reason: "rejected", status };
158
131
  }
159
- return {
160
- ok: false,
161
- reason: "unavailable",
162
- status
163
- };
132
+ return { ok: false, reason: "unavailable", status };
164
133
  } catch {
165
- return {
166
- ok: false,
167
- reason: "unreachable",
168
- status: null
169
- };
134
+ return { ok: false, reason: "unreachable", status: null };
170
135
  }
171
136
  }
172
- __name(performRefresh, "performRefresh");
173
137
  function createAuthFetch(config = {}) {
174
138
  const baseUrl = config.baseUrl;
175
139
  const refreshEndpoint = config.refreshEndpoint ?? AUTH_PROXY_ROUTES.clientRefresh;
@@ -179,9 +143,9 @@ function createAuthFetch(config = {}) {
179
143
  const onRefreshFailed = config.onRefreshFailed;
180
144
  const timeoutMs = config.timeout ?? 3e4;
181
145
  const skipRefreshSuffixes = buildAuthRefreshSkipSuffixes(config.routePrefix);
182
- const reportCallbackError = /* @__PURE__ */ __name((err) => {
146
+ const reportCallbackError = (err) => {
183
147
  console.warn("[nest-auth] onRefreshFailed callback threw:", err);
184
- }, "reportCallbackError");
148
+ };
185
149
  let inFlightRefresh = null;
186
150
  function getOrStartRefresh() {
187
151
  if (inFlightRefresh !== null) {
@@ -193,8 +157,7 @@ function createAuthFetch(config = {}) {
193
157
  inFlightRefresh = attempt;
194
158
  return attempt;
195
159
  }
196
- __name(getOrStartRefresh, "getOrStartRefresh");
197
- return /* @__PURE__ */ __name(async function authFetch(input, init) {
160
+ return async function authFetch(input, init) {
198
161
  const initBase = {
199
162
  ...init ?? {},
200
163
  credentials,
@@ -241,31 +204,17 @@ function createAuthFetch(config = {}) {
241
204
  } finally {
242
205
  retryAttempt.cleanup();
243
206
  }
244
- }, "authFetch");
245
- }
246
- __name(createAuthFetch, "createAuthFetch");
247
- function trimSlashes(value, leading) {
248
- let start = 0;
249
- let end = value.length;
250
- if (leading) {
251
- while (start < end && value[start] === "/") start += 1;
252
- }
253
- while (end > start && value[end - 1] === "/") end -= 1;
254
- return value.slice(start, end);
207
+ };
255
208
  }
256
- __name(trimSlashes, "trimSlashes");
257
209
  function normalizeBaseUrl(baseUrl) {
258
210
  return trimSlashes(baseUrl, false);
259
211
  }
260
- __name(normalizeBaseUrl, "normalizeBaseUrl");
261
212
  function normalizeRoutePrefix(prefix) {
262
213
  return trimSlashes(prefix, true);
263
214
  }
264
- __name(normalizeRoutePrefix, "normalizeRoutePrefix");
265
215
  function jsonBody(value) {
266
216
  return JSON.stringify(value);
267
217
  }
268
- __name(jsonBody, "jsonBody");
269
218
  function extractErrorBody(text, response) {
270
219
  if (text.length === 0) return void 0;
271
220
  try {
@@ -277,20 +226,21 @@ function extractErrorBody(text, response) {
277
226
  return void 0;
278
227
  }
279
228
  }
280
- __name(extractErrorBody, "extractErrorBody");
281
229
  function throwAuthError(response, text) {
282
230
  const body = extractErrorBody(text, response);
283
231
  const message = body?.message ?? `Request failed with status ${response.status}`;
284
232
  throw new AuthClientError(message, response.status, body);
285
233
  }
286
- __name(throwAuthError, "throwAuthError");
287
234
  async function parseJsonOrThrow(response) {
288
235
  const text = await response.text();
289
236
  if (!response.ok) {
290
237
  throwAuthError(response, text);
291
238
  }
292
239
  if (text.length === 0) {
293
- throw new AuthClientError(`Response from ${response.url} was empty \u2014 expected a JSON body`, response.status);
240
+ throw new AuthClientError(
241
+ `Response from ${response.url} was empty \u2014 expected a JSON body`,
242
+ response.status
243
+ );
294
244
  }
295
245
  try {
296
246
  return JSON.parse(text);
@@ -298,7 +248,6 @@ async function parseJsonOrThrow(response) {
298
248
  throw new AuthClientError(`Response from ${response.url} is not valid JSON`, response.status);
299
249
  }
300
250
  }
301
- __name(parseJsonOrThrow, "parseJsonOrThrow");
302
251
  async function expectNoContent(response) {
303
252
  if (!response.ok) {
304
253
  const text = await response.text();
@@ -309,7 +258,6 @@ async function expectNoContent(response) {
309
258
  () => void 0
310
259
  );
311
260
  }
312
- __name(expectNoContent, "expectNoContent");
313
261
  var UNKNOWN_STATUS_TEXT = "Error";
314
262
  function readErrorEnvelope(value, response) {
315
263
  const envelope = value?.error;
@@ -332,57 +280,46 @@ function readErrorEnvelope(value, response) {
332
280
  // other branch returns. Block form because the mutant sits two lines below a wrapped
333
281
  // comment, where the per-line directive points at the comment's own continuation.
334
282
  details: typeof details === "object" && details !== null ? details : null
283
+ // Stryker restore ConditionalExpression
335
284
  };
336
285
  }
337
- __name(readErrorEnvelope, "readErrorEnvelope");
338
286
  function isAuthErrorBody(value) {
339
287
  if (typeof value !== "object" || value === null) return false;
340
288
  const candidate = value;
341
289
  return typeof candidate["message"] === "string" && typeof candidate["error"] === "string" && typeof candidate["statusCode"] === "number";
342
290
  }
343
- __name(isAuthErrorBody, "isAuthErrorBody");
344
291
  function buildUrl(baseUrl, routePrefix, path) {
345
292
  if (path.startsWith("/")) {
346
293
  return `${baseUrl}${path}`;
347
294
  }
348
295
  return routePrefix.length > 0 ? `${baseUrl}/${routePrefix}/${path}` : `${baseUrl}/${path}`;
349
296
  }
350
- __name(buildUrl, "buildUrl");
351
- function createAuthClient(config) {
297
+ function resolveTransport(config) {
352
298
  const baseUrl = normalizeBaseUrl(config.baseUrl);
353
299
  const routePrefix = normalizeRoutePrefix(config.routePrefix ?? "auth");
354
300
  const authFetch = config.authFetch ?? createAuthFetch({
355
- // Deliberately NO `baseUrl`. This client composes the full URL itself in `url()` below,
356
- // and `createAuthFetch` prepends its own `baseUrl` to any input that is not absolute —
357
- // so passing it here applied the base TWICE. With the documented same-origin setting
358
- // (`baseUrl: '/api'`, used by the README and by AuthProvider's own example) every call
359
- // went to `/api/api/auth/*` and 404'd: login, register, logout, refresh and getMe, all
360
- // of them. An absolute base hid it, because the second prepend is skipped for anything
361
- // matching `^https?://` — which is why every test in this file, all of which use an
362
- // absolute base AND inject a stub `authFetch`, stayed green.
301
+ // Deliberately NO `baseUrl`: this client composes the full URL itself in `url()`, and
302
+ // `createAuthFetch` prepends its own `baseUrl` to any input that is not absolute, so passing
303
+ // it here applied the base TWICE (`/api/api/auth/*`, a 404 on every call under a same-origin
304
+ // base). An absolute base hid it, because the second prepend is skipped for `^https?://`
305
+ // inputs, which is why tests with an absolute base and a stub `authFetch` stayed green.
363
306
  routePrefix,
364
307
  // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — createAuthFetch coalesces each option with `??`/falsy checks downstream
365
- ...config.refreshEndpoint !== void 0 ? {
366
- refreshEndpoint: config.refreshEndpoint
367
- } : {},
308
+ ...config.refreshEndpoint !== void 0 ? { refreshEndpoint: config.refreshEndpoint } : {},
368
309
  // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
369
- ...config.credentials !== void 0 ? {
370
- credentials: config.credentials
371
- } : {},
310
+ ...config.credentials !== void 0 ? { credentials: config.credentials } : {},
372
311
  // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
373
- ...config.defaultHeaders !== void 0 ? {
374
- defaultHeaders: config.defaultHeaders
375
- } : {},
312
+ ...config.defaultHeaders !== void 0 ? { defaultHeaders: config.defaultHeaders } : {},
376
313
  // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
377
- ...config.onSessionExpired !== void 0 ? {
378
- onSessionExpired: config.onSessionExpired
379
- } : {},
314
+ ...config.onSessionExpired !== void 0 ? { onSessionExpired: config.onSessionExpired } : {},
380
315
  // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
381
- ...config.timeout !== void 0 ? {
382
- timeout: config.timeout
383
- } : {}
316
+ ...config.timeout !== void 0 ? { timeout: config.timeout } : {}
384
317
  });
385
- const url = /* @__PURE__ */ __name((path) => buildUrl(baseUrl, routePrefix, path), "url");
318
+ const url = (path) => buildUrl(baseUrl, routePrefix, path);
319
+ return { authFetch, url };
320
+ }
321
+ function createAuthClient(config) {
322
+ const { authFetch, url } = resolveTransport(config);
386
323
  async function post(path, body) {
387
324
  const response = await authFetch(url(path), {
388
325
  method: "POST",
@@ -390,7 +327,6 @@ function createAuthClient(config) {
390
327
  });
391
328
  return parseJsonOrThrow(response);
392
329
  }
393
- __name(post, "post");
394
330
  async function postNoContent(path, body) {
395
331
  const response = await authFetch(url(path), {
396
332
  method: "POST",
@@ -398,14 +334,10 @@ function createAuthClient(config) {
398
334
  });
399
335
  await expectNoContent(response);
400
336
  }
401
- __name(postNoContent, "postNoContent");
402
337
  async function get(path) {
403
- const response = await authFetch(url(path), {
404
- method: "GET"
405
- });
338
+ const response = await authFetch(url(path), { method: "GET" });
406
339
  return parseJsonOrThrow(response);
407
340
  }
408
- __name(get, "get");
409
341
  return {
410
342
  async login(input) {
411
343
  return post(AUTH_ROUTES.dashboard.login, input);
@@ -428,16 +360,17 @@ function createAuthClient(config) {
428
360
  code
429
361
  });
430
362
  if ("mfaRequired" in result) {
431
- throw new AuthClientError("MFA challenge endpoint returned another challenge \u2014 server contract mismatch", 502);
363
+ throw new AuthClientError(
364
+ "MFA challenge endpoint returned another challenge \u2014 server contract mismatch",
365
+ 502
366
+ );
432
367
  }
433
368
  return result;
434
369
  },
435
370
  async forgotPassword(email, tenantId) {
436
371
  return postNoContent(AUTH_ROUTES.password.forgotPassword, {
437
372
  email,
438
- ...tenantId !== void 0 ? {
439
- tenantId
440
- } : {}
373
+ ...tenantId !== void 0 ? { tenantId } : {}
441
374
  });
442
375
  },
443
376
  async resetPassword(input) {
@@ -453,6 +386,76 @@ function createAuthClient(config) {
453
386
  }
454
387
  };
455
388
  }
456
- __name(createAuthClient, "createAuthClient");
389
+ var ROUTES = AUTH_ROUTES.workspaces;
390
+ function paged(path, page) {
391
+ const query = new URLSearchParams();
392
+ if (page?.cursor !== void 0) query.set("cursor", page.cursor);
393
+ if (page?.limit !== void 0) query.set("limit", String(page.limit));
394
+ const text = query.toString();
395
+ return text === "" ? path : `${path}?${text}`;
396
+ }
397
+ var inWorkspace = (template, workspaceId) => fillRoute(template, { workspaceId });
398
+ var ofMember = (workspaceId, userId) => fillRoute(ROUTES.member, { workspaceId, userId });
399
+ function workspaceCalls({
400
+ json,
401
+ none
402
+ }) {
403
+ return {
404
+ listWorkspaces: async (page, init) => json("GET", paged(ROUTES.list, page), void 0, init?.signal),
405
+ getWorkspaceAccess: async (id) => json("GET", inWorkspace(ROUTES.access, id)),
406
+ switchWorkspace: async (id) => none("POST", inWorkspace(ROUTES.switch, id), {}),
407
+ createWorkspace: async (name) => json("POST", ROUTES.list, { name }),
408
+ renameWorkspace: async (id, name) => json("PATCH", inWorkspace(ROUTES.rename, id), { name }),
409
+ scheduleWorkspaceDeletion: async (id, reauth) => none("POST", inWorkspace(ROUTES.scheduleDeletion, id), { password: reauth?.password }),
410
+ restoreWorkspace: async (id) => none("POST", inWorkspace(ROUTES.restore, id), {})
411
+ };
412
+ }
413
+ function memberCalls({
414
+ json,
415
+ none
416
+ }) {
417
+ return {
418
+ listWorkspaceMembers: async (id, page) => json("GET", paged(inWorkspace(ROUTES.members, id), page)),
419
+ changeWorkspaceMemberRole: async (id, userId, role) => json("PATCH", ofMember(id, userId), { role }),
420
+ removeWorkspaceMember: async (id, userId) => none("DELETE", ofMember(id, userId)),
421
+ leaveWorkspace: async (id) => none("POST", inWorkspace(ROUTES.leave, id), {}),
422
+ transferWorkspaceOwnership: async (id, input) => none("POST", inWorkspace(ROUTES.transferOwnership, id), {
423
+ userId: input.userId,
424
+ demoteSelfTo: input.demoteSelfTo,
425
+ password: input.password
426
+ })
427
+ };
428
+ }
429
+ function invitationCalls({
430
+ json,
431
+ none
432
+ }) {
433
+ return {
434
+ inviteToWorkspace: async (id, input) => none("POST", inWorkspace(ROUTES.invitations, id), { email: input.email, role: input.role }),
435
+ listWorkspaceInvitations: async (id, page) => json("GET", paged(inWorkspace(ROUTES.invitations, id), page)),
436
+ resendWorkspaceInvitation: async (id, email) => none("POST", inWorkspace(ROUTES.resendInvitation, id), { email }),
437
+ revokeWorkspaceInvitation: async (id, email) => none("POST", inWorkspace(ROUTES.revokeInvitation, id), { email }),
438
+ previewWorkspaceInvitation: async (token) => json("POST", ROUTES.previewInvitation, { token }),
439
+ acceptWorkspaceInvitation: async (token) => json("POST", ROUTES.acceptInvitation, { token }),
440
+ acceptWorkspaceInvitationSignup: async (input) => json("POST", ROUTES.acceptInvitationSignup, {
441
+ token: input.token,
442
+ name: input.name,
443
+ password: input.password
444
+ })
445
+ };
446
+ }
447
+ function createWorkspaceClient(config) {
448
+ const { authFetch, url } = resolveTransport(config);
449
+ const send = (method, path, body, signal) => (
450
+ // JSON.stringify answers `undefined` for no body and drops a key whose value is `undefined`, so an
451
+ // absent option is an absent key on the wire.
452
+ authFetch(url(path), { method, body: JSON.stringify(body), signal: signal ?? null })
453
+ );
454
+ const requests = {
455
+ json: async (method, path, body, signal) => parseJsonOrThrow(await send(method, path, body, signal)),
456
+ none: async (method, path, body) => expectNoContent(await send(method, path, body))
457
+ };
458
+ return { ...workspaceCalls(requests), ...memberCalls(requests), ...invitationCalls(requests) };
459
+ }
457
460
 
458
- export { createAuthClient, createAuthFetch };
461
+ export { createAuthClient, createAuthFetch, createWorkspaceClient };