@bymax-one/nest-auth 1.4.22 → 1.5.1
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 +249 -1
- package/README.md +241 -2
- package/dist/client/index.cjs +125 -121
- package/dist/client/index.d.cts +97 -3
- package/dist/client/index.d.ts +97 -3
- package/dist/client/index.mjs +124 -121
- package/dist/nextjs/index.cjs +303 -330
- package/dist/nextjs/index.d.cts +76 -3
- package/dist/nextjs/index.d.ts +76 -3
- package/dist/nextjs/index.mjs +303 -331
- package/dist/react/index.cjs +388 -191
- package/dist/react/index.d.cts +121 -4
- package/dist/react/index.d.ts +121 -4
- package/dist/react/index.mjs +370 -171
- package/dist/server/index.cjs +6402 -757
- package/dist/server/index.d.cts +3352 -431
- package/dist/server/index.d.ts +3352 -431
- package/dist/server/index.mjs +6389 -759
- package/dist/shared/index.cjs +139 -66
- package/dist/shared/index.d.cts +257 -8
- package/dist/shared/index.d.ts +257 -8
- package/dist/shared/index.mjs +136 -67
- package/package.json +6 -2
package/dist/client/index.cjs
CHANGED
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
var shared = require('@bymax-one/nest-auth/shared');
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
5
|
+
// src/client/createAuthFetch.ts
|
|
7
6
|
var DEFAULT_HEADERS = Object.freeze({
|
|
8
7
|
"Content-Type": "application/json"
|
|
9
8
|
});
|
|
@@ -21,13 +20,11 @@ function shouldSkipRefreshOnUrl(url, suffixes) {
|
|
|
21
20
|
}
|
|
22
21
|
return false;
|
|
23
22
|
}
|
|
24
|
-
__name(shouldSkipRefreshOnUrl, "shouldSkipRefreshOnUrl");
|
|
25
23
|
var ERROR_BODY_READ_TIMEOUT_MS = 2e3;
|
|
26
24
|
async function isExpiredSessionResponse(response) {
|
|
27
25
|
const code = await readErrorCode(response);
|
|
28
26
|
return code === void 0 || code === shared.AUTH_ERROR_CODES.TOKEN_INVALID;
|
|
29
27
|
}
|
|
30
|
-
__name(isExpiredSessionResponse, "isExpiredSessionResponse");
|
|
31
28
|
async function readErrorCode(response) {
|
|
32
29
|
const clone = response.clone();
|
|
33
30
|
let timer;
|
|
@@ -43,7 +40,6 @@ async function readErrorCode(response) {
|
|
|
43
40
|
const code = envelope.error?.code ?? envelope.code;
|
|
44
41
|
return typeof code === "string" ? code : void 0;
|
|
45
42
|
}
|
|
46
|
-
__name(readErrorCode, "readErrorCode");
|
|
47
43
|
function resolveRequestUrl(input, baseUrl) {
|
|
48
44
|
if (typeof input === "string") {
|
|
49
45
|
return baseUrl !== void 0 && !/^https?:\/\//i.test(input) ? `${baseUrl}${input}` : input;
|
|
@@ -53,11 +49,9 @@ function resolveRequestUrl(input, baseUrl) {
|
|
|
53
49
|
}
|
|
54
50
|
return input.url;
|
|
55
51
|
}
|
|
56
|
-
__name(resolveRequestUrl, "resolveRequestUrl");
|
|
57
52
|
function isUnsafeHeaderName(name) {
|
|
58
53
|
return name === "__proto__" || name === "constructor" || name === "prototype";
|
|
59
54
|
}
|
|
60
|
-
__name(isUnsafeHeaderName, "isUnsafeHeaderName");
|
|
61
55
|
function applyHeaders(target, source) {
|
|
62
56
|
if (source instanceof Headers) {
|
|
63
57
|
source.forEach((value, name) => {
|
|
@@ -72,7 +66,6 @@ function applyHeaders(target, source) {
|
|
|
72
66
|
target.set(name, value);
|
|
73
67
|
}
|
|
74
68
|
}
|
|
75
|
-
__name(applyHeaders, "applyHeaders");
|
|
76
69
|
function buildDefaultHeaders(configured) {
|
|
77
70
|
const defaults = new Headers();
|
|
78
71
|
applyHeaders(defaults, DEFAULT_HEADERS);
|
|
@@ -81,7 +74,6 @@ function buildDefaultHeaders(configured) {
|
|
|
81
74
|
}
|
|
82
75
|
return defaults;
|
|
83
76
|
}
|
|
84
|
-
__name(buildDefaultHeaders, "buildDefaultHeaders");
|
|
85
77
|
function mergeHeaders(defaults, perRequest) {
|
|
86
78
|
const merged = new Headers(defaults);
|
|
87
79
|
if (perRequest !== void 0) {
|
|
@@ -89,13 +81,12 @@ function mergeHeaders(defaults, perRequest) {
|
|
|
89
81
|
}
|
|
90
82
|
return merged;
|
|
91
83
|
}
|
|
92
|
-
__name(mergeHeaders, "mergeHeaders");
|
|
93
84
|
function attachTimeout(init, timeoutMs) {
|
|
94
85
|
if (timeoutMs <= 0) {
|
|
95
86
|
return {
|
|
96
87
|
init,
|
|
97
|
-
cleanup:
|
|
98
|
-
}
|
|
88
|
+
cleanup: () => {
|
|
89
|
+
}
|
|
99
90
|
};
|
|
100
91
|
}
|
|
101
92
|
const controller = new AbortController();
|
|
@@ -107,20 +98,14 @@ function attachTimeout(init, timeoutMs) {
|
|
|
107
98
|
if (userSignal.aborted) {
|
|
108
99
|
controller.abort();
|
|
109
100
|
} else {
|
|
110
|
-
userSignal.addEventListener("abort", () => controller.abort(), {
|
|
111
|
-
once: true
|
|
112
|
-
});
|
|
101
|
+
userSignal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
113
102
|
}
|
|
114
103
|
}
|
|
115
104
|
return {
|
|
116
|
-
init: {
|
|
117
|
-
|
|
118
|
-
signal: controller.signal
|
|
119
|
-
},
|
|
120
|
-
cleanup: /* @__PURE__ */ __name(() => clearTimeout(timer), "cleanup")
|
|
105
|
+
init: { ...init, signal: controller.signal },
|
|
106
|
+
cleanup: () => clearTimeout(timer)
|
|
121
107
|
};
|
|
122
108
|
}
|
|
123
|
-
__name(attachTimeout, "attachTimeout");
|
|
124
109
|
var TERMINAL_REFRESH_CODES = /* @__PURE__ */ new Set([
|
|
125
110
|
shared.AUTH_ERROR_CODES.ACCOUNT_INACTIVE,
|
|
126
111
|
shared.AUTH_ERROR_CODES.ACCOUNT_SUSPENDED,
|
|
@@ -132,9 +117,7 @@ async function performRefresh(endpoint, credentials) {
|
|
|
132
117
|
const response = await fetch(endpoint, {
|
|
133
118
|
method: "POST",
|
|
134
119
|
credentials,
|
|
135
|
-
headers: {
|
|
136
|
-
"Content-Type": "application/json"
|
|
137
|
-
}
|
|
120
|
+
headers: { "Content-Type": "application/json" }
|
|
138
121
|
});
|
|
139
122
|
const { ok, status } = response;
|
|
140
123
|
const code = status === 403 ? await readErrorCode(response) : void 0;
|
|
@@ -142,35 +125,16 @@ async function performRefresh(endpoint, credentials) {
|
|
|
142
125
|
/* istanbul ignore next */
|
|
143
126
|
() => void 0
|
|
144
127
|
);
|
|
145
|
-
if (ok) return {
|
|
146
|
-
|
|
147
|
-
};
|
|
148
|
-
if (status === 401) return {
|
|
149
|
-
ok: false,
|
|
150
|
-
reason: "rejected",
|
|
151
|
-
status
|
|
152
|
-
};
|
|
128
|
+
if (ok) return { ok: true };
|
|
129
|
+
if (status === 401) return { ok: false, reason: "rejected", status };
|
|
153
130
|
if (code !== void 0 && TERMINAL_REFRESH_CODES.has(code)) {
|
|
154
|
-
return {
|
|
155
|
-
ok: false,
|
|
156
|
-
reason: "rejected",
|
|
157
|
-
status
|
|
158
|
-
};
|
|
131
|
+
return { ok: false, reason: "rejected", status };
|
|
159
132
|
}
|
|
160
|
-
return {
|
|
161
|
-
ok: false,
|
|
162
|
-
reason: "unavailable",
|
|
163
|
-
status
|
|
164
|
-
};
|
|
133
|
+
return { ok: false, reason: "unavailable", status };
|
|
165
134
|
} catch {
|
|
166
|
-
return {
|
|
167
|
-
ok: false,
|
|
168
|
-
reason: "unreachable",
|
|
169
|
-
status: null
|
|
170
|
-
};
|
|
135
|
+
return { ok: false, reason: "unreachable", status: null };
|
|
171
136
|
}
|
|
172
137
|
}
|
|
173
|
-
__name(performRefresh, "performRefresh");
|
|
174
138
|
function createAuthFetch(config = {}) {
|
|
175
139
|
const baseUrl = config.baseUrl;
|
|
176
140
|
const refreshEndpoint = config.refreshEndpoint ?? shared.AUTH_PROXY_ROUTES.clientRefresh;
|
|
@@ -180,9 +144,9 @@ function createAuthFetch(config = {}) {
|
|
|
180
144
|
const onRefreshFailed = config.onRefreshFailed;
|
|
181
145
|
const timeoutMs = config.timeout ?? 3e4;
|
|
182
146
|
const skipRefreshSuffixes = shared.buildAuthRefreshSkipSuffixes(config.routePrefix);
|
|
183
|
-
const reportCallbackError =
|
|
147
|
+
const reportCallbackError = (err) => {
|
|
184
148
|
console.warn("[nest-auth] onRefreshFailed callback threw:", err);
|
|
185
|
-
}
|
|
149
|
+
};
|
|
186
150
|
let inFlightRefresh = null;
|
|
187
151
|
function getOrStartRefresh() {
|
|
188
152
|
if (inFlightRefresh !== null) {
|
|
@@ -194,8 +158,7 @@ function createAuthFetch(config = {}) {
|
|
|
194
158
|
inFlightRefresh = attempt;
|
|
195
159
|
return attempt;
|
|
196
160
|
}
|
|
197
|
-
|
|
198
|
-
return /* @__PURE__ */ __name(async function authFetch(input, init) {
|
|
161
|
+
return async function authFetch(input, init) {
|
|
199
162
|
const initBase = {
|
|
200
163
|
...init ?? {},
|
|
201
164
|
credentials,
|
|
@@ -242,31 +205,17 @@ function createAuthFetch(config = {}) {
|
|
|
242
205
|
} finally {
|
|
243
206
|
retryAttempt.cleanup();
|
|
244
207
|
}
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
__name(createAuthFetch, "createAuthFetch");
|
|
248
|
-
function trimSlashes(value, leading) {
|
|
249
|
-
let start = 0;
|
|
250
|
-
let end = value.length;
|
|
251
|
-
if (leading) {
|
|
252
|
-
while (start < end && value[start] === "/") start += 1;
|
|
253
|
-
}
|
|
254
|
-
while (end > start && value[end - 1] === "/") end -= 1;
|
|
255
|
-
return value.slice(start, end);
|
|
208
|
+
};
|
|
256
209
|
}
|
|
257
|
-
__name(trimSlashes, "trimSlashes");
|
|
258
210
|
function normalizeBaseUrl(baseUrl) {
|
|
259
|
-
return trimSlashes(baseUrl, false);
|
|
211
|
+
return shared.trimSlashes(baseUrl, false);
|
|
260
212
|
}
|
|
261
|
-
__name(normalizeBaseUrl, "normalizeBaseUrl");
|
|
262
213
|
function normalizeRoutePrefix(prefix) {
|
|
263
|
-
return trimSlashes(prefix, true);
|
|
214
|
+
return shared.trimSlashes(prefix, true);
|
|
264
215
|
}
|
|
265
|
-
__name(normalizeRoutePrefix, "normalizeRoutePrefix");
|
|
266
216
|
function jsonBody(value) {
|
|
267
217
|
return JSON.stringify(value);
|
|
268
218
|
}
|
|
269
|
-
__name(jsonBody, "jsonBody");
|
|
270
219
|
function extractErrorBody(text, response) {
|
|
271
220
|
if (text.length === 0) return void 0;
|
|
272
221
|
try {
|
|
@@ -278,20 +227,21 @@ function extractErrorBody(text, response) {
|
|
|
278
227
|
return void 0;
|
|
279
228
|
}
|
|
280
229
|
}
|
|
281
|
-
__name(extractErrorBody, "extractErrorBody");
|
|
282
230
|
function throwAuthError(response, text) {
|
|
283
231
|
const body = extractErrorBody(text, response);
|
|
284
232
|
const message = body?.message ?? `Request failed with status ${response.status}`;
|
|
285
233
|
throw new shared.AuthClientError(message, response.status, body);
|
|
286
234
|
}
|
|
287
|
-
__name(throwAuthError, "throwAuthError");
|
|
288
235
|
async function parseJsonOrThrow(response) {
|
|
289
236
|
const text = await response.text();
|
|
290
237
|
if (!response.ok) {
|
|
291
238
|
throwAuthError(response, text);
|
|
292
239
|
}
|
|
293
240
|
if (text.length === 0) {
|
|
294
|
-
throw new shared.AuthClientError(
|
|
241
|
+
throw new shared.AuthClientError(
|
|
242
|
+
`Response from ${response.url} was empty \u2014 expected a JSON body`,
|
|
243
|
+
response.status
|
|
244
|
+
);
|
|
295
245
|
}
|
|
296
246
|
try {
|
|
297
247
|
return JSON.parse(text);
|
|
@@ -299,7 +249,6 @@ async function parseJsonOrThrow(response) {
|
|
|
299
249
|
throw new shared.AuthClientError(`Response from ${response.url} is not valid JSON`, response.status);
|
|
300
250
|
}
|
|
301
251
|
}
|
|
302
|
-
__name(parseJsonOrThrow, "parseJsonOrThrow");
|
|
303
252
|
async function expectNoContent(response) {
|
|
304
253
|
if (!response.ok) {
|
|
305
254
|
const text = await response.text();
|
|
@@ -310,7 +259,6 @@ async function expectNoContent(response) {
|
|
|
310
259
|
() => void 0
|
|
311
260
|
);
|
|
312
261
|
}
|
|
313
|
-
__name(expectNoContent, "expectNoContent");
|
|
314
262
|
var UNKNOWN_STATUS_TEXT = "Error";
|
|
315
263
|
function readErrorEnvelope(value, response) {
|
|
316
264
|
const envelope = value?.error;
|
|
@@ -333,57 +281,46 @@ function readErrorEnvelope(value, response) {
|
|
|
333
281
|
// other branch returns. Block form because the mutant sits two lines below a wrapped
|
|
334
282
|
// comment, where the per-line directive points at the comment's own continuation.
|
|
335
283
|
details: typeof details === "object" && details !== null ? details : null
|
|
284
|
+
// Stryker restore ConditionalExpression
|
|
336
285
|
};
|
|
337
286
|
}
|
|
338
|
-
__name(readErrorEnvelope, "readErrorEnvelope");
|
|
339
287
|
function isAuthErrorBody(value) {
|
|
340
288
|
if (typeof value !== "object" || value === null) return false;
|
|
341
289
|
const candidate = value;
|
|
342
290
|
return typeof candidate["message"] === "string" && typeof candidate["error"] === "string" && typeof candidate["statusCode"] === "number";
|
|
343
291
|
}
|
|
344
|
-
__name(isAuthErrorBody, "isAuthErrorBody");
|
|
345
292
|
function buildUrl(baseUrl, routePrefix, path) {
|
|
346
293
|
if (path.startsWith("/")) {
|
|
347
294
|
return `${baseUrl}${path}`;
|
|
348
295
|
}
|
|
349
296
|
return routePrefix.length > 0 ? `${baseUrl}/${routePrefix}/${path}` : `${baseUrl}/${path}`;
|
|
350
297
|
}
|
|
351
|
-
|
|
352
|
-
function createAuthClient(config) {
|
|
298
|
+
function resolveTransport(config) {
|
|
353
299
|
const baseUrl = normalizeBaseUrl(config.baseUrl);
|
|
354
300
|
const routePrefix = normalizeRoutePrefix(config.routePrefix ?? "auth");
|
|
355
301
|
const authFetch = config.authFetch ?? createAuthFetch({
|
|
356
|
-
// Deliberately NO `baseUrl
|
|
357
|
-
//
|
|
358
|
-
//
|
|
359
|
-
//
|
|
360
|
-
//
|
|
361
|
-
// of them. An absolute base hid it, because the second prepend is skipped for anything
|
|
362
|
-
// matching `^https?://` — which is why every test in this file, all of which use an
|
|
363
|
-
// absolute base AND inject a stub `authFetch`, stayed green.
|
|
302
|
+
// Deliberately NO `baseUrl`: this client composes the full URL itself in `url()`, and
|
|
303
|
+
// `createAuthFetch` prepends its own `baseUrl` to any input that is not absolute, so passing
|
|
304
|
+
// it here applied the base TWICE (`/api/api/auth/*`, a 404 on every call under a same-origin
|
|
305
|
+
// base). An absolute base hid it, because the second prepend is skipped for `^https?://`
|
|
306
|
+
// inputs, which is why tests with an absolute base and a stub `authFetch` stayed green.
|
|
364
307
|
routePrefix,
|
|
365
308
|
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — createAuthFetch coalesces each option with `??`/falsy checks downstream
|
|
366
|
-
...config.refreshEndpoint !== void 0 ? {
|
|
367
|
-
refreshEndpoint: config.refreshEndpoint
|
|
368
|
-
} : {},
|
|
309
|
+
...config.refreshEndpoint !== void 0 ? { refreshEndpoint: config.refreshEndpoint } : {},
|
|
369
310
|
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
|
|
370
|
-
...config.credentials !== void 0 ? {
|
|
371
|
-
credentials: config.credentials
|
|
372
|
-
} : {},
|
|
311
|
+
...config.credentials !== void 0 ? { credentials: config.credentials } : {},
|
|
373
312
|
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
|
|
374
|
-
...config.defaultHeaders !== void 0 ? {
|
|
375
|
-
defaultHeaders: config.defaultHeaders
|
|
376
|
-
} : {},
|
|
313
|
+
...config.defaultHeaders !== void 0 ? { defaultHeaders: config.defaultHeaders } : {},
|
|
377
314
|
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
|
|
378
|
-
...config.onSessionExpired !== void 0 ? {
|
|
379
|
-
onSessionExpired: config.onSessionExpired
|
|
380
|
-
} : {},
|
|
315
|
+
...config.onSessionExpired !== void 0 ? { onSessionExpired: config.onSessionExpired } : {},
|
|
381
316
|
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
|
|
382
|
-
...config.timeout !== void 0 ? {
|
|
383
|
-
timeout: config.timeout
|
|
384
|
-
} : {}
|
|
317
|
+
...config.timeout !== void 0 ? { timeout: config.timeout } : {}
|
|
385
318
|
});
|
|
386
|
-
const url =
|
|
319
|
+
const url = (path) => buildUrl(baseUrl, routePrefix, path);
|
|
320
|
+
return { authFetch, url };
|
|
321
|
+
}
|
|
322
|
+
function createAuthClient(config) {
|
|
323
|
+
const { authFetch, url } = resolveTransport(config);
|
|
387
324
|
async function post(path, body) {
|
|
388
325
|
const response = await authFetch(url(path), {
|
|
389
326
|
method: "POST",
|
|
@@ -391,7 +328,6 @@ function createAuthClient(config) {
|
|
|
391
328
|
});
|
|
392
329
|
return parseJsonOrThrow(response);
|
|
393
330
|
}
|
|
394
|
-
__name(post, "post");
|
|
395
331
|
async function postNoContent(path, body) {
|
|
396
332
|
const response = await authFetch(url(path), {
|
|
397
333
|
method: "POST",
|
|
@@ -399,46 +335,43 @@ function createAuthClient(config) {
|
|
|
399
335
|
});
|
|
400
336
|
await expectNoContent(response);
|
|
401
337
|
}
|
|
402
|
-
__name(postNoContent, "postNoContent");
|
|
403
338
|
async function get(path) {
|
|
404
|
-
const response = await authFetch(url(path), {
|
|
405
|
-
method: "GET"
|
|
406
|
-
});
|
|
339
|
+
const response = await authFetch(url(path), { method: "GET" });
|
|
407
340
|
return parseJsonOrThrow(response);
|
|
408
341
|
}
|
|
409
|
-
__name(get, "get");
|
|
410
342
|
return {
|
|
411
343
|
async login(input) {
|
|
412
|
-
return post(shared.
|
|
344
|
+
return post(shared.AUTH_DASHBOARD_ROUTES.login, input);
|
|
413
345
|
},
|
|
414
346
|
async register(data) {
|
|
415
|
-
return post(shared.
|
|
347
|
+
return post(shared.AUTH_DASHBOARD_ROUTES.register, data);
|
|
416
348
|
},
|
|
417
349
|
async logout() {
|
|
418
|
-
return postNoContent(shared.
|
|
350
|
+
return postNoContent(shared.AUTH_DASHBOARD_ROUTES.logout, {});
|
|
419
351
|
},
|
|
420
352
|
async refresh() {
|
|
421
|
-
return post(shared.
|
|
353
|
+
return post(shared.AUTH_DASHBOARD_ROUTES.refresh, {});
|
|
422
354
|
},
|
|
423
355
|
async getMe() {
|
|
424
|
-
return get(shared.
|
|
356
|
+
return get(shared.AUTH_DASHBOARD_ROUTES.me);
|
|
425
357
|
},
|
|
426
358
|
async mfaChallenge(tempToken, code) {
|
|
427
|
-
const result = await post(shared.
|
|
359
|
+
const result = await post(shared.AUTH_MFA_ROUTES.challenge, {
|
|
428
360
|
mfaTempToken: tempToken,
|
|
429
361
|
code
|
|
430
362
|
});
|
|
431
363
|
if ("mfaRequired" in result) {
|
|
432
|
-
throw new shared.AuthClientError(
|
|
364
|
+
throw new shared.AuthClientError(
|
|
365
|
+
"MFA challenge endpoint returned another challenge \u2014 server contract mismatch",
|
|
366
|
+
502
|
|
367
|
+
);
|
|
433
368
|
}
|
|
434
369
|
return result;
|
|
435
370
|
},
|
|
436
371
|
async forgotPassword(email, tenantId) {
|
|
437
|
-
return postNoContent(shared.
|
|
372
|
+
return postNoContent(shared.AUTH_PASSWORD_ROUTES.forgotPassword, {
|
|
438
373
|
email,
|
|
439
|
-
...tenantId !== void 0 ? {
|
|
440
|
-
tenantId
|
|
441
|
-
} : {}
|
|
374
|
+
...tenantId !== void 0 ? { tenantId } : {}
|
|
442
375
|
});
|
|
443
376
|
},
|
|
444
377
|
async resetPassword(input) {
|
|
@@ -450,11 +383,81 @@ function createAuthClient(config) {
|
|
|
450
383
|
if (input.token !== void 0) payload["token"] = input.token;
|
|
451
384
|
if (input.otp !== void 0) payload["otp"] = input.otp;
|
|
452
385
|
if (input.verifiedToken !== void 0) payload["verifiedToken"] = input.verifiedToken;
|
|
453
|
-
return postNoContent(shared.
|
|
386
|
+
return postNoContent(shared.AUTH_PASSWORD_ROUTES.resetPassword, payload);
|
|
454
387
|
}
|
|
455
388
|
};
|
|
456
389
|
}
|
|
457
|
-
|
|
390
|
+
var ROUTES = shared.AUTH_WORKSPACE_ROUTES;
|
|
391
|
+
function paged(path, page) {
|
|
392
|
+
const query = new URLSearchParams();
|
|
393
|
+
if (page?.cursor !== void 0) query.set("cursor", page.cursor);
|
|
394
|
+
if (page?.limit !== void 0) query.set("limit", String(page.limit));
|
|
395
|
+
const text = query.toString();
|
|
396
|
+
return text === "" ? path : `${path}?${text}`;
|
|
397
|
+
}
|
|
398
|
+
var inWorkspace = (template, workspaceId) => shared.fillRoute(template, { workspaceId });
|
|
399
|
+
var ofMember = (workspaceId, userId) => shared.fillRoute(ROUTES.member, { workspaceId, userId });
|
|
400
|
+
function workspaceCalls({
|
|
401
|
+
json,
|
|
402
|
+
none
|
|
403
|
+
}) {
|
|
404
|
+
return {
|
|
405
|
+
listWorkspaces: async (page, init) => json("GET", paged(ROUTES.list, page), void 0, init?.signal),
|
|
406
|
+
getWorkspaceAccess: async (id) => json("GET", inWorkspace(ROUTES.access, id)),
|
|
407
|
+
switchWorkspace: async (id) => none("POST", inWorkspace(ROUTES.switch, id), {}),
|
|
408
|
+
createWorkspace: async (name) => json("POST", ROUTES.list, { name }),
|
|
409
|
+
renameWorkspace: async (id, name) => json("PATCH", inWorkspace(ROUTES.rename, id), { name }),
|
|
410
|
+
scheduleWorkspaceDeletion: async (id, reauth) => none("POST", inWorkspace(ROUTES.scheduleDeletion, id), { password: reauth?.password }),
|
|
411
|
+
restoreWorkspace: async (id) => none("POST", inWorkspace(ROUTES.restore, id), {})
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
function memberCalls({
|
|
415
|
+
json,
|
|
416
|
+
none
|
|
417
|
+
}) {
|
|
418
|
+
return {
|
|
419
|
+
listWorkspaceMembers: async (id, page) => json("GET", paged(inWorkspace(ROUTES.members, id), page)),
|
|
420
|
+
changeWorkspaceMemberRole: async (id, userId, role) => json("PATCH", ofMember(id, userId), { role }),
|
|
421
|
+
removeWorkspaceMember: async (id, userId) => none("DELETE", ofMember(id, userId)),
|
|
422
|
+
leaveWorkspace: async (id) => none("POST", inWorkspace(ROUTES.leave, id), {}),
|
|
423
|
+
transferWorkspaceOwnership: async (id, input) => none("POST", inWorkspace(ROUTES.transferOwnership, id), {
|
|
424
|
+
userId: input.userId,
|
|
425
|
+
demoteSelfTo: input.demoteSelfTo,
|
|
426
|
+
password: input.password
|
|
427
|
+
})
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
function invitationCalls({
|
|
431
|
+
json,
|
|
432
|
+
none
|
|
433
|
+
}) {
|
|
434
|
+
return {
|
|
435
|
+
inviteToWorkspace: async (id, input) => none("POST", inWorkspace(ROUTES.invitations, id), { email: input.email, role: input.role }),
|
|
436
|
+
listWorkspaceInvitations: async (id, page) => json("GET", paged(inWorkspace(ROUTES.invitations, id), page)),
|
|
437
|
+
resendWorkspaceInvitation: async (id, email) => none("POST", inWorkspace(ROUTES.resendInvitation, id), { email }),
|
|
438
|
+
revokeWorkspaceInvitation: async (id, email) => none("POST", inWorkspace(ROUTES.revokeInvitation, id), { email }),
|
|
439
|
+
previewWorkspaceInvitation: async (token) => json("POST", ROUTES.previewInvitation, { token }),
|
|
440
|
+
acceptWorkspaceInvitation: async (token) => json("POST", ROUTES.acceptInvitation, { token }),
|
|
441
|
+
acceptWorkspaceInvitationSignup: async (input) => json("POST", ROUTES.acceptInvitationSignup, {
|
|
442
|
+
token: input.token,
|
|
443
|
+
name: input.name,
|
|
444
|
+
password: input.password
|
|
445
|
+
})
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
function createWorkspaceClient(config) {
|
|
449
|
+
const { authFetch, url } = resolveTransport(config);
|
|
450
|
+
const send = (method, path, body, signal) => (
|
|
451
|
+
// JSON.stringify answers `undefined` for no body and drops a key whose value is `undefined`, so an
|
|
452
|
+
// absent option is an absent key on the wire.
|
|
453
|
+
authFetch(url(path), { method, body: JSON.stringify(body), signal: signal ?? null })
|
|
454
|
+
);
|
|
455
|
+
const requests = {
|
|
456
|
+
json: async (method, path, body, signal) => parseJsonOrThrow(await send(method, path, body, signal)),
|
|
457
|
+
none: async (method, path, body) => expectNoContent(await send(method, path, body))
|
|
458
|
+
};
|
|
459
|
+
return { ...workspaceCalls(requests), ...memberCalls(requests), ...invitationCalls(requests) };
|
|
460
|
+
}
|
|
458
461
|
|
|
459
462
|
Object.defineProperty(exports, "AuthClientError", {
|
|
460
463
|
enumerable: true,
|
|
@@ -462,3 +465,4 @@ Object.defineProperty(exports, "AuthClientError", {
|
|
|
462
465
|
});
|
|
463
466
|
exports.createAuthClient = createAuthClient;
|
|
464
467
|
exports.createAuthFetch = createAuthFetch;
|
|
468
|
+
exports.createWorkspaceClient = createWorkspaceClient;
|
package/dist/client/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LoginResult, AuthResult, AuthUserClient } from '@bymax-one/nest-auth/shared';
|
|
1
|
+
import { LoginResult, AuthResult, AuthUserClient, WorkspacePageParams, WorkspaceListResult, WorkspaceAccessClient, WorkspaceClient, WorkspaceMemberPage, WorkspaceMemberClient, WorkspaceInvitationPage, WorkspaceInvitationPreview, AcceptedWorkspaceInvitation } from '@bymax-one/nest-auth/shared';
|
|
2
2
|
export { AuthClientError, AuthErrorCode, AuthErrorResponse } from '@bymax-one/nest-auth/shared';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -373,5 +373,99 @@ interface AuthClient {
|
|
|
373
373
|
*/
|
|
374
374
|
declare function createAuthClient(config: AuthClientConfig): AuthClient;
|
|
375
375
|
|
|
376
|
-
|
|
377
|
-
|
|
376
|
+
/**
|
|
377
|
+
* Typed workspace calls for the client: listing, switching, members, lifecycle and invitations.
|
|
378
|
+
*
|
|
379
|
+
* Thin wrappers over {@link AUTH_WORKSPACE_ROUTES}. The workspace a call acts in is always the
|
|
380
|
+
* path segment, percent-encoded, never a body field or a header: that is the rule the server
|
|
381
|
+
* enforces, and a client that offered another way would only produce requests the server refuses.
|
|
382
|
+
* Nothing here decides access; every answer is the server's.
|
|
383
|
+
*/
|
|
384
|
+
|
|
385
|
+
/** What a password-confirmed action sends: only a host that requires re-authentication needs it. */
|
|
386
|
+
interface WorkspaceReauth {
|
|
387
|
+
/** The caller's password, for an account that has one. */
|
|
388
|
+
password?: string;
|
|
389
|
+
}
|
|
390
|
+
/** The input of an ownership transfer. */
|
|
391
|
+
interface TransferOwnershipInput extends WorkspaceReauth {
|
|
392
|
+
/** The member who becomes an owner. */
|
|
393
|
+
userId: string;
|
|
394
|
+
/** The role the caller keeps after handing ownership over; omitted, the server's own default. */
|
|
395
|
+
demoteSelfTo?: string;
|
|
396
|
+
}
|
|
397
|
+
/** The input of an invitation to a workspace. */
|
|
398
|
+
interface InviteToWorkspaceInput {
|
|
399
|
+
email: string;
|
|
400
|
+
role: string;
|
|
401
|
+
}
|
|
402
|
+
/** The input of accepting an invitation by creating the account it was addressed to. */
|
|
403
|
+
interface AcceptInvitationSignupInput {
|
|
404
|
+
token: string;
|
|
405
|
+
name: string;
|
|
406
|
+
password: string;
|
|
407
|
+
}
|
|
408
|
+
/** What a read can be given besides its parameters. */
|
|
409
|
+
interface WorkspaceRequestInit {
|
|
410
|
+
/** Aborts the request when it aborts. */
|
|
411
|
+
signal?: AbortSignal;
|
|
412
|
+
}
|
|
413
|
+
/** The workspace calls of the typed client. */
|
|
414
|
+
interface WorkspaceClientMethods {
|
|
415
|
+
/**
|
|
416
|
+
* Lists the caller's own workspaces, and the one they last switched to. An aborted `signal` cancels
|
|
417
|
+
* the request.
|
|
418
|
+
*/
|
|
419
|
+
listWorkspaces(page?: WorkspacePageParams, init?: WorkspaceRequestInit): Promise<WorkspaceListResult>;
|
|
420
|
+
/** Reads a workspace and the caller's role in it. */
|
|
421
|
+
getWorkspaceAccess(workspaceId: string): Promise<WorkspaceAccessClient>;
|
|
422
|
+
/** Records a workspace as the caller's last active one. No token changes. */
|
|
423
|
+
switchWorkspace(workspaceId: string): Promise<void>;
|
|
424
|
+
/** Creates a workspace owned by the caller. */
|
|
425
|
+
createWorkspace(name: string): Promise<WorkspaceClient>;
|
|
426
|
+
/** Renames a workspace. */
|
|
427
|
+
renameWorkspace(workspaceId: string, name: string): Promise<WorkspaceClient>;
|
|
428
|
+
/** Schedules a workspace for deletion. */
|
|
429
|
+
scheduleWorkspaceDeletion(workspaceId: string, reauth?: WorkspaceReauth): Promise<void>;
|
|
430
|
+
/** Undoes a scheduled deletion inside its grace period. */
|
|
431
|
+
restoreWorkspace(workspaceId: string): Promise<void>;
|
|
432
|
+
/** Lists the members of a workspace. */
|
|
433
|
+
listWorkspaceMembers(workspaceId: string, page?: WorkspacePageParams): Promise<WorkspaceMemberPage>;
|
|
434
|
+
/** Changes a member's role. */
|
|
435
|
+
changeWorkspaceMemberRole(workspaceId: string, userId: string, role: string): Promise<WorkspaceMemberClient>;
|
|
436
|
+
/** Removes a member. */
|
|
437
|
+
removeWorkspaceMember(workspaceId: string, userId: string): Promise<void>;
|
|
438
|
+
/** Leaves a workspace. The last owner must hand ownership over or delete it first. */
|
|
439
|
+
leaveWorkspace(workspaceId: string): Promise<void>;
|
|
440
|
+
/** Hands ownership to another member. */
|
|
441
|
+
transferWorkspaceOwnership(workspaceId: string, input: TransferOwnershipInput): Promise<void>;
|
|
442
|
+
/** Invites an address to a workspace. */
|
|
443
|
+
inviteToWorkspace(workspaceId: string, input: InviteToWorkspaceInput): Promise<void>;
|
|
444
|
+
/** Lists the pending invitations of a workspace. */
|
|
445
|
+
listWorkspaceInvitations(workspaceId: string, page?: WorkspacePageParams): Promise<WorkspaceInvitationPage>;
|
|
446
|
+
/** Sends a pending invitation again under a new token. */
|
|
447
|
+
resendWorkspaceInvitation(workspaceId: string, email: string): Promise<void>;
|
|
448
|
+
/** Withdraws a pending invitation. */
|
|
449
|
+
revokeWorkspaceInvitation(workspaceId: string, email: string): Promise<void>;
|
|
450
|
+
/** Reads what an invitation token is for, without signing in. */
|
|
451
|
+
previewWorkspaceInvitation(token: string): Promise<WorkspaceInvitationPreview>;
|
|
452
|
+
/** Accepts an invitation as the signed-in account it was addressed to. */
|
|
453
|
+
acceptWorkspaceInvitation(token: string): Promise<AcceptedWorkspaceInvitation>;
|
|
454
|
+
/** Accepts an invitation by creating the account it was addressed to. */
|
|
455
|
+
acceptWorkspaceInvitationSignup(input: AcceptInvitationSignupInput): Promise<AuthResult & AcceptedWorkspaceInvitation>;
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Creates the typed workspace client.
|
|
459
|
+
*
|
|
460
|
+
* Separate from {@link createAuthClient} on purpose: a frontend that does not use workspaces never
|
|
461
|
+
* imports this, so its bundler drops all of it. Pass the same configuration as `createAuthClient`,
|
|
462
|
+
* including `authFetch` when the two should share one refresh logic: a refresh in flight is then
|
|
463
|
+
* shared by both rather than raced.
|
|
464
|
+
*
|
|
465
|
+
* @param config - The client configuration, as for `createAuthClient`.
|
|
466
|
+
* @returns The workspace calls.
|
|
467
|
+
*/
|
|
468
|
+
declare function createWorkspaceClient(config: AuthClientConfig): WorkspaceClientMethods;
|
|
469
|
+
|
|
470
|
+
export { createAuthClient, createAuthFetch, createWorkspaceClient };
|
|
471
|
+
export type { AcceptInvitationSignupInput, AuthClient, AuthClientConfig, AuthFetch, AuthFetchConfig, InviteToWorkspaceInput, LoginInput, RefreshFailure, RefreshFailureReason, RefreshOutcome, RegisterInput, ResetPasswordInput, TransferOwnershipInput, WorkspaceClientMethods, WorkspaceReauth, WorkspaceRequestInit };
|