@bymax-one/nest-auth 1.0.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.
- package/CHANGELOG.md +369 -0
- package/LICENSE +21 -0
- package/README.md +886 -0
- package/dist/client/index.cjs +347 -0
- package/dist/client/index.d.cts +301 -0
- package/dist/client/index.d.ts +301 -0
- package/dist/client/index.mjs +341 -0
- package/dist/nextjs/index.cjs +1103 -0
- package/dist/nextjs/index.d.cts +1025 -0
- package/dist/nextjs/index.d.ts +1025 -0
- package/dist/nextjs/index.mjs +1083 -0
- package/dist/react/index.cjs +304 -0
- package/dist/react/index.d.cts +342 -0
- package/dist/react/index.d.ts +342 -0
- package/dist/react/index.mjs +295 -0
- package/dist/server/index.cjs +8039 -0
- package/dist/server/index.d.cts +5092 -0
- package/dist/server/index.d.ts +5092 -0
- package/dist/server/index.mjs +7996 -0
- package/dist/shared/index.cjs +240 -0
- package/dist/shared/index.d.cts +736 -0
- package/dist/shared/index.d.ts +736 -0
- package/dist/shared/index.mjs +223 -0
- package/package.json +195 -0
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { LoginResult, AuthResult, AuthUserClient } from '@bymax-one/nest-auth/shared';
|
|
2
|
+
export { AuthClientError, AuthErrorCode, AuthErrorResponse } from '@bymax-one/nest-auth/shared';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Fetch wrapper for the @bymax-one/nest-auth client subpath.
|
|
6
|
+
*
|
|
7
|
+
* Wraps the platform's native `fetch` so that consumer code can issue
|
|
8
|
+
* authenticated requests without manually:
|
|
9
|
+
*
|
|
10
|
+
* - attaching `credentials: 'include'` on every call,
|
|
11
|
+
* - intercepting 401 responses to attempt a transparent refresh,
|
|
12
|
+
* - retrying the original request after a successful refresh,
|
|
13
|
+
* - de-duplicating concurrent refresh attempts (single-flight),
|
|
14
|
+
* - or notifying the application when the session is irrecoverable.
|
|
15
|
+
*
|
|
16
|
+
* Zero runtime dependencies: relies only on the global `fetch` and the
|
|
17
|
+
* stable constants exported from `@bymax-one/nest-auth/shared`.
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Configuration options for {@link createAuthFetch}.
|
|
21
|
+
*
|
|
22
|
+
* Every field is optional so that the default factory output works
|
|
23
|
+
* out-of-the-box against a same-domain Next.js proxy. Override only
|
|
24
|
+
* what your deployment actually needs to change.
|
|
25
|
+
*/
|
|
26
|
+
interface AuthFetchConfig {
|
|
27
|
+
/**
|
|
28
|
+
* Optional base URL prepended to relative request URLs.
|
|
29
|
+
*
|
|
30
|
+
* When omitted, relative URLs (`/api/users`) are passed to `fetch`
|
|
31
|
+
* verbatim — appropriate for browser environments where the request
|
|
32
|
+
* is naturally same-origin. Provide this in non-browser contexts
|
|
33
|
+
* (Node-side server components, tests, mobile apps) so that the
|
|
34
|
+
* URL parsing in the skip-list logic can operate on a full URL.
|
|
35
|
+
*/
|
|
36
|
+
baseUrl?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Pathname or full URL of the refresh endpoint.
|
|
39
|
+
*
|
|
40
|
+
* Default: {@link AUTH_PROXY_ROUTES.clientRefresh}
|
|
41
|
+
* (`/api/auth/client-refresh`). Replace this when your application
|
|
42
|
+
* exposes the refresh endpoint at a non-default path.
|
|
43
|
+
*/
|
|
44
|
+
refreshEndpoint?: string;
|
|
45
|
+
/**
|
|
46
|
+
* Credentials policy for every issued request.
|
|
47
|
+
*
|
|
48
|
+
* Default: `'include'`. Set to `'same-origin'` for same-origin
|
|
49
|
+
* deployments that want to avoid CORS preflights, or to `'omit'`
|
|
50
|
+
* when working with bearer-only deployments that do not use cookies.
|
|
51
|
+
*/
|
|
52
|
+
credentials?: RequestCredentials;
|
|
53
|
+
/**
|
|
54
|
+
* Headers merged into every request.
|
|
55
|
+
*
|
|
56
|
+
* Default: `{ 'Content-Type': 'application/json' }`. Headers passed
|
|
57
|
+
* per-request in `fetch(..., { headers })` override these.
|
|
58
|
+
*/
|
|
59
|
+
defaultHeaders?: Record<string, string>;
|
|
60
|
+
/**
|
|
61
|
+
* Callback invoked when a refresh attempt fails irrecoverably.
|
|
62
|
+
*
|
|
63
|
+
* Wire this to a UI redirect, a state-store reset, or a logout
|
|
64
|
+
* helper. The callback runs before the auth-fetched promise
|
|
65
|
+
* rejects, so consumers can rely on side effects having happened.
|
|
66
|
+
*/
|
|
67
|
+
onSessionExpired?: () => void;
|
|
68
|
+
/**
|
|
69
|
+
* Per-request timeout in milliseconds.
|
|
70
|
+
*
|
|
71
|
+
* Default: `30_000` (30s). Pass `0` to disable the timeout.
|
|
72
|
+
* Disabling is appropriate for long-poll endpoints; for normal
|
|
73
|
+
* requests keep the default to avoid hanging UIs on slow networks.
|
|
74
|
+
*/
|
|
75
|
+
timeout?: number;
|
|
76
|
+
/**
|
|
77
|
+
* NestJS `routePrefix` the upstream auth server is mounted under.
|
|
78
|
+
*
|
|
79
|
+
* Used to compose the pathname-suffix skip list so that 401s from
|
|
80
|
+
* credential-issuing endpoints (login, refresh, mfa/challenge, …)
|
|
81
|
+
* are NOT retried after a refresh attempt. Default: `'auth'`.
|
|
82
|
+
* Set this explicitly when the server uses a non-default prefix
|
|
83
|
+
* (e.g. `'authentication'`, `'api/v1/auth'`) or 401 retries will
|
|
84
|
+
* misfire on those endpoints.
|
|
85
|
+
*/
|
|
86
|
+
routePrefix?: string;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The fetch-compatible function returned by {@link createAuthFetch}.
|
|
90
|
+
*
|
|
91
|
+
* Has the same signature as the native `fetch` but applies the
|
|
92
|
+
* configured credentials, headers, refresh interception, and retry.
|
|
93
|
+
*
|
|
94
|
+
* @remarks
|
|
95
|
+
* Passing a {@link Request} object whose body is a stream is not
|
|
96
|
+
* supported when the request may be retried after a refresh —
|
|
97
|
+
* `Request` body streams can only be read once, and the retry will
|
|
98
|
+
* fail with `TypeError: body already used`. Prefer passing a URL
|
|
99
|
+
* string plus an `init` with a string/`FormData`/`URLSearchParams`
|
|
100
|
+
* body, which can be re-sent safely. This restriction does not
|
|
101
|
+
* apply to GET/HEAD requests or to requests that do not receive a
|
|
102
|
+
* 401 response.
|
|
103
|
+
*/
|
|
104
|
+
type AuthFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
105
|
+
/**
|
|
106
|
+
* Create a configured fetch wrapper with cookie- and refresh-aware
|
|
107
|
+
* behavior baked in.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* const authFetch = createAuthFetch({
|
|
112
|
+
* baseUrl: 'https://api.example.com',
|
|
113
|
+
* onSessionExpired: () => router.push('/sign-in')
|
|
114
|
+
* })
|
|
115
|
+
*
|
|
116
|
+
* const response = await authFetch('/api/users')
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
declare function createAuthFetch(config?: AuthFetchConfig): AuthFetch;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Typed authentication client for the @bymax-one/nest-auth library.
|
|
123
|
+
*
|
|
124
|
+
* Wraps {@link createAuthFetch} with method-shaped helpers for every
|
|
125
|
+
* standard auth flow (login, register, logout, refresh, getMe, MFA
|
|
126
|
+
* challenge, password reset). Designed for the cookie-mode default —
|
|
127
|
+
* HttpOnly cookies do the actual authentication, the methods just
|
|
128
|
+
* compose the right URL, body, and method verb.
|
|
129
|
+
*
|
|
130
|
+
* Zero runtime dependencies beyond `fetch` and the shared subpath.
|
|
131
|
+
*/
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Configuration accepted by {@link createAuthClient}.
|
|
135
|
+
*
|
|
136
|
+
* Same surface as {@link AuthFetchConfig} plus a required `baseUrl` —
|
|
137
|
+
* the typed client always issues requests to a known server origin so
|
|
138
|
+
* the per-method URL composition is unambiguous.
|
|
139
|
+
*/
|
|
140
|
+
interface AuthClientConfig extends Omit<AuthFetchConfig, 'baseUrl'> {
|
|
141
|
+
/**
|
|
142
|
+
* Absolute base URL of the @bymax-one/nest-auth server
|
|
143
|
+
* (e.g. `'https://api.example.com'`). The trailing slash is
|
|
144
|
+
* optional; both forms are normalized internally.
|
|
145
|
+
*/
|
|
146
|
+
baseUrl: string;
|
|
147
|
+
/**
|
|
148
|
+
* Optional route prefix mounted by the consumer's NestJS app. When
|
|
149
|
+
* the server uses a non-default `routePrefix`, mirror it here so
|
|
150
|
+
* that the client targets the right URLs. Default: `'auth'`.
|
|
151
|
+
*/
|
|
152
|
+
routePrefix?: string;
|
|
153
|
+
/**
|
|
154
|
+
* Optional pre-built fetch wrapper. When provided, the client uses
|
|
155
|
+
* this wrapper instead of building one from `baseUrl`/`credentials`/
|
|
156
|
+
* `defaultHeaders`. Useful for tests or for sharing a single
|
|
157
|
+
* wrapper across multiple clients (dashboard + platform).
|
|
158
|
+
*/
|
|
159
|
+
authFetch?: AuthFetch;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Payload accepted by {@link AuthClient.register}.
|
|
163
|
+
*
|
|
164
|
+
* Mirrors the `RegisterDto` exposed by the server controller. Field
|
|
165
|
+
* names match exactly so consumers can spread an existing form state
|
|
166
|
+
* into the call without renaming.
|
|
167
|
+
*/
|
|
168
|
+
interface RegisterInput {
|
|
169
|
+
/** User's primary email address. */
|
|
170
|
+
email: string;
|
|
171
|
+
/** Plaintext password — server hashes immediately on receipt. */
|
|
172
|
+
password: string;
|
|
173
|
+
/** Display name. */
|
|
174
|
+
name: string;
|
|
175
|
+
/** Tenant identifier scoping the new account. */
|
|
176
|
+
tenantId: string;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Payload accepted by {@link AuthClient.login}.
|
|
180
|
+
*
|
|
181
|
+
* `tenantId` is required because the server-side `LoginDto` enforces it
|
|
182
|
+
* with `@IsNotEmpty()`. Multi-tenant deployments use it to scope the
|
|
183
|
+
* credential lookup; single-tenant deployments must still supply a
|
|
184
|
+
* stable identifier (commonly `'default'`).
|
|
185
|
+
*/
|
|
186
|
+
interface LoginInput {
|
|
187
|
+
/** User's primary email address. */
|
|
188
|
+
email: string;
|
|
189
|
+
/** Plaintext password — server hashes immediately on receipt. */
|
|
190
|
+
password: string;
|
|
191
|
+
/** Tenant identifier the login attempt is scoped to. */
|
|
192
|
+
tenantId: string;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Fields shared by every reset-password flow.
|
|
196
|
+
*
|
|
197
|
+
* The wire-shape variants below extend this and add exactly one of
|
|
198
|
+
* `token`, `otp`, or `verifiedToken` — TypeScript then rejects calls
|
|
199
|
+
* that try to combine them.
|
|
200
|
+
*/
|
|
201
|
+
interface ResetPasswordBase {
|
|
202
|
+
/** Email address of the account being reset. */
|
|
203
|
+
email: string;
|
|
204
|
+
/** Tenant the account belongs to. */
|
|
205
|
+
tenantId: string;
|
|
206
|
+
/** New plaintext password — server hashes immediately. Min 8 chars, max 128. */
|
|
207
|
+
newPassword: string;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Payload accepted by {@link AuthClient.resetPassword}.
|
|
211
|
+
*
|
|
212
|
+
* Discriminated union: callers must supply exactly one of `token`,
|
|
213
|
+
* `otp`, or `verifiedToken`. The server's `ResetPasswordDto`
|
|
214
|
+
* cross-validates the choice; the union shape lifts that constraint
|
|
215
|
+
* into the type system so misuse is caught at compile time rather
|
|
216
|
+
* than as a runtime 400.
|
|
217
|
+
*/
|
|
218
|
+
type ResetPasswordInput = (ResetPasswordBase & {
|
|
219
|
+
token: string;
|
|
220
|
+
otp?: never;
|
|
221
|
+
verifiedToken?: never;
|
|
222
|
+
}) | (ResetPasswordBase & {
|
|
223
|
+
otp: string;
|
|
224
|
+
token?: never;
|
|
225
|
+
verifiedToken?: never;
|
|
226
|
+
}) | (ResetPasswordBase & {
|
|
227
|
+
verifiedToken: string;
|
|
228
|
+
token?: never;
|
|
229
|
+
otp?: never;
|
|
230
|
+
});
|
|
231
|
+
/**
|
|
232
|
+
* Public method surface of the typed auth client.
|
|
233
|
+
*/
|
|
234
|
+
interface AuthClient {
|
|
235
|
+
/**
|
|
236
|
+
* Submit credentials and receive either a full {@link AuthResult}
|
|
237
|
+
* or an {@link MfaChallengeResult} when the account requires MFA.
|
|
238
|
+
*
|
|
239
|
+
* @returns A discriminated {@link LoginResult} — branch on
|
|
240
|
+
* `'mfaRequired' in result` to handle the MFA case.
|
|
241
|
+
*/
|
|
242
|
+
login(input: LoginInput): Promise<LoginResult>;
|
|
243
|
+
/**
|
|
244
|
+
* Register a new local account. The server may auto-login on
|
|
245
|
+
* success or require email verification before login is permitted,
|
|
246
|
+
* depending on `emailVerification.required`.
|
|
247
|
+
*/
|
|
248
|
+
register(data: RegisterInput): Promise<AuthResult>;
|
|
249
|
+
/** Revoke the current session and clear the auth cookies server-side. */
|
|
250
|
+
logout(): Promise<void>;
|
|
251
|
+
/**
|
|
252
|
+
* Manually rotate the refresh token. The auto-refresh in
|
|
253
|
+
* {@link createAuthFetch} handles this automatically on 401, so
|
|
254
|
+
* call this only for explicit refresh flows.
|
|
255
|
+
*/
|
|
256
|
+
refresh(): Promise<AuthResult>;
|
|
257
|
+
/** Fetch the currently authenticated user. */
|
|
258
|
+
getMe(): Promise<AuthUserClient>;
|
|
259
|
+
/**
|
|
260
|
+
* Complete an MFA challenge by submitting the temp token returned
|
|
261
|
+
* from `login` together with either a 6-digit TOTP code or a
|
|
262
|
+
* recovery code in `xxxx-xxxx-xxxx` format.
|
|
263
|
+
*/
|
|
264
|
+
mfaChallenge(tempToken: string, code: string): Promise<AuthResult>;
|
|
265
|
+
/**
|
|
266
|
+
* Initiate a password reset. The server returns 200 regardless of
|
|
267
|
+
* whether the email is registered — the response carries no signal
|
|
268
|
+
* either way (anti-enumeration design). Both `email` and `tenantId`
|
|
269
|
+
* are required by the server DTO.
|
|
270
|
+
*/
|
|
271
|
+
forgotPassword(email: string, tenantId: string): Promise<void>;
|
|
272
|
+
/**
|
|
273
|
+
* Submit a new password using one of the three reset flows:
|
|
274
|
+
* token, OTP, or verified-token. See {@link ResetPasswordInput}
|
|
275
|
+
* for the mutual-exclusivity rule.
|
|
276
|
+
*/
|
|
277
|
+
resetPassword(input: ResetPasswordInput): Promise<void>;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Build a typed {@link AuthClient} bound to a specific server.
|
|
281
|
+
*
|
|
282
|
+
* @example
|
|
283
|
+
* ```ts
|
|
284
|
+
* const auth = createAuthClient({
|
|
285
|
+
* baseUrl: 'https://api.example.com',
|
|
286
|
+
* onSessionExpired: () => router.push('/sign-in')
|
|
287
|
+
* })
|
|
288
|
+
*
|
|
289
|
+
* const result = await auth.login({
|
|
290
|
+
* email: 'user@example.com',
|
|
291
|
+
* password: 'pw',
|
|
292
|
+
* tenantId: 'default'
|
|
293
|
+
* })
|
|
294
|
+
* if ('mfaRequired' in result) {
|
|
295
|
+
* const final = await auth.mfaChallenge(result.mfaTempToken, '123456')
|
|
296
|
+
* }
|
|
297
|
+
* ```
|
|
298
|
+
*/
|
|
299
|
+
declare function createAuthClient(config: AuthClientConfig): AuthClient;
|
|
300
|
+
|
|
301
|
+
export { type AuthClient, type AuthClientConfig, type AuthFetch, type AuthFetchConfig, type LoginInput, type RegisterInput, type ResetPasswordInput, createAuthClient, createAuthFetch };
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { AUTH_PROXY_ROUTES, buildAuthRefreshSkipSuffixes, AUTH_ROUTES, AuthClientError } from '@bymax-one/nest-auth/shared';
|
|
2
|
+
export { AuthClientError } from '@bymax-one/nest-auth/shared';
|
|
3
|
+
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
6
|
+
var DEFAULT_HEADERS = Object.freeze({
|
|
7
|
+
"Content-Type": "application/json"
|
|
8
|
+
});
|
|
9
|
+
function shouldSkipRefreshOnUrl(url, suffixes) {
|
|
10
|
+
let pathname;
|
|
11
|
+
try {
|
|
12
|
+
pathname = new URL(url, "http://_placeholder").pathname;
|
|
13
|
+
} catch {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
for (const suffix of suffixes) {
|
|
17
|
+
if (pathname.endsWith(suffix)) {
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
__name(shouldSkipRefreshOnUrl, "shouldSkipRefreshOnUrl");
|
|
24
|
+
function resolveRequestUrl(input, baseUrl) {
|
|
25
|
+
if (typeof input === "string") {
|
|
26
|
+
return baseUrl !== void 0 && !/^https?:\/\//i.test(input) ? `${baseUrl}${input}` : input;
|
|
27
|
+
}
|
|
28
|
+
if (input instanceof URL) {
|
|
29
|
+
return input.toString();
|
|
30
|
+
}
|
|
31
|
+
return input.url;
|
|
32
|
+
}
|
|
33
|
+
__name(resolveRequestUrl, "resolveRequestUrl");
|
|
34
|
+
function mergeHeaders(defaults, perRequest) {
|
|
35
|
+
const merged = {
|
|
36
|
+
...defaults
|
|
37
|
+
};
|
|
38
|
+
if (perRequest === void 0) {
|
|
39
|
+
return merged;
|
|
40
|
+
}
|
|
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;
|
|
48
|
+
}
|
|
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;
|
|
55
|
+
}
|
|
56
|
+
for (const [name, value] of Object.entries(perRequest)) {
|
|
57
|
+
if (isUnsafeName(name) || typeof value !== "string") continue;
|
|
58
|
+
merged[name] = value;
|
|
59
|
+
}
|
|
60
|
+
return merged;
|
|
61
|
+
}
|
|
62
|
+
__name(mergeHeaders, "mergeHeaders");
|
|
63
|
+
function attachTimeout(init, timeoutMs) {
|
|
64
|
+
if (timeoutMs <= 0) {
|
|
65
|
+
return {
|
|
66
|
+
init,
|
|
67
|
+
cleanup: /* @__PURE__ */ __name(() => {
|
|
68
|
+
}, "cleanup")
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const controller = new AbortController();
|
|
72
|
+
const timer = setTimeout(() => {
|
|
73
|
+
controller.abort();
|
|
74
|
+
}, timeoutMs);
|
|
75
|
+
const userSignal = init.signal;
|
|
76
|
+
if (userSignal != null) {
|
|
77
|
+
if (userSignal.aborted) {
|
|
78
|
+
controller.abort();
|
|
79
|
+
} else {
|
|
80
|
+
userSignal.addEventListener("abort", () => controller.abort(), {
|
|
81
|
+
once: true
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
init: {
|
|
87
|
+
...init,
|
|
88
|
+
signal: controller.signal
|
|
89
|
+
},
|
|
90
|
+
cleanup: /* @__PURE__ */ __name(() => clearTimeout(timer), "cleanup")
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
__name(attachTimeout, "attachTimeout");
|
|
94
|
+
async function performRefresh(endpoint, credentials) {
|
|
95
|
+
try {
|
|
96
|
+
const response = await fetch(endpoint, {
|
|
97
|
+
method: "POST",
|
|
98
|
+
credentials,
|
|
99
|
+
headers: {
|
|
100
|
+
"Content-Type": "application/json"
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
const ok = response.ok;
|
|
104
|
+
await response.body?.cancel().catch(
|
|
105
|
+
/* istanbul ignore next */
|
|
106
|
+
() => void 0
|
|
107
|
+
);
|
|
108
|
+
return ok;
|
|
109
|
+
} catch {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
__name(performRefresh, "performRefresh");
|
|
114
|
+
function createAuthFetch(config = {}) {
|
|
115
|
+
const baseUrl = config.baseUrl;
|
|
116
|
+
const refreshEndpoint = config.refreshEndpoint ?? AUTH_PROXY_ROUTES.clientRefresh;
|
|
117
|
+
const credentials = config.credentials ?? "include";
|
|
118
|
+
const defaultHeaders = config.defaultHeaders ? {
|
|
119
|
+
...DEFAULT_HEADERS,
|
|
120
|
+
...config.defaultHeaders
|
|
121
|
+
} : DEFAULT_HEADERS;
|
|
122
|
+
const onSessionExpired = config.onSessionExpired;
|
|
123
|
+
const timeoutMs = config.timeout ?? 3e4;
|
|
124
|
+
const skipRefreshSuffixes = buildAuthRefreshSkipSuffixes(config.routePrefix);
|
|
125
|
+
let inFlightRefresh = null;
|
|
126
|
+
function getOrStartRefresh() {
|
|
127
|
+
if (inFlightRefresh !== null) {
|
|
128
|
+
return inFlightRefresh;
|
|
129
|
+
}
|
|
130
|
+
const attempt = performRefresh(refreshEndpoint, credentials).finally(() => {
|
|
131
|
+
inFlightRefresh = null;
|
|
132
|
+
});
|
|
133
|
+
inFlightRefresh = attempt;
|
|
134
|
+
return attempt;
|
|
135
|
+
}
|
|
136
|
+
__name(getOrStartRefresh, "getOrStartRefresh");
|
|
137
|
+
return /* @__PURE__ */ __name(async function authFetch(input, init) {
|
|
138
|
+
const initBase = {
|
|
139
|
+
...init ?? {},
|
|
140
|
+
credentials,
|
|
141
|
+
headers: mergeHeaders(defaultHeaders, init?.headers)
|
|
142
|
+
};
|
|
143
|
+
const url = resolveRequestUrl(input, baseUrl);
|
|
144
|
+
const targetForFetch = (
|
|
145
|
+
// Stryker disable next-line ConditionalExpression: when baseUrl is undefined the ternary returns `input` regardless, so the guard's boolean is unobservable
|
|
146
|
+
baseUrl !== void 0 && typeof input === "string" ? url : input
|
|
147
|
+
);
|
|
148
|
+
const firstAttempt = attachTimeout(initBase, timeoutMs);
|
|
149
|
+
let response;
|
|
150
|
+
try {
|
|
151
|
+
response = await fetch(targetForFetch, firstAttempt.init);
|
|
152
|
+
} finally {
|
|
153
|
+
firstAttempt.cleanup();
|
|
154
|
+
}
|
|
155
|
+
if (response.status !== 401 || shouldSkipRefreshOnUrl(url, skipRefreshSuffixes)) {
|
|
156
|
+
return response;
|
|
157
|
+
}
|
|
158
|
+
const refreshed = await getOrStartRefresh();
|
|
159
|
+
if (!refreshed) {
|
|
160
|
+
try {
|
|
161
|
+
onSessionExpired?.();
|
|
162
|
+
} catch (err) {
|
|
163
|
+
console.warn("[nest-auth] onSessionExpired callback threw:", err);
|
|
164
|
+
}
|
|
165
|
+
return response;
|
|
166
|
+
}
|
|
167
|
+
const retryAttempt = attachTimeout(initBase, timeoutMs);
|
|
168
|
+
try {
|
|
169
|
+
return await fetch(targetForFetch, retryAttempt.init);
|
|
170
|
+
} finally {
|
|
171
|
+
retryAttempt.cleanup();
|
|
172
|
+
}
|
|
173
|
+
}, "authFetch");
|
|
174
|
+
}
|
|
175
|
+
__name(createAuthFetch, "createAuthFetch");
|
|
176
|
+
function normalizeBaseUrl(baseUrl) {
|
|
177
|
+
return baseUrl.replace(/\/+$/, "");
|
|
178
|
+
}
|
|
179
|
+
__name(normalizeBaseUrl, "normalizeBaseUrl");
|
|
180
|
+
function normalizeRoutePrefix(prefix) {
|
|
181
|
+
return prefix.replace(/^\/+|\/+$/g, "");
|
|
182
|
+
}
|
|
183
|
+
__name(normalizeRoutePrefix, "normalizeRoutePrefix");
|
|
184
|
+
function jsonBody(value) {
|
|
185
|
+
return JSON.stringify(value);
|
|
186
|
+
}
|
|
187
|
+
__name(jsonBody, "jsonBody");
|
|
188
|
+
function extractErrorBody(text) {
|
|
189
|
+
if (text.length === 0) return void 0;
|
|
190
|
+
try {
|
|
191
|
+
const parsed = JSON.parse(text);
|
|
192
|
+
return isAuthErrorBody(parsed) ? parsed : void 0;
|
|
193
|
+
} catch {
|
|
194
|
+
return void 0;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
__name(extractErrorBody, "extractErrorBody");
|
|
198
|
+
function throwAuthError(response, text) {
|
|
199
|
+
const body = extractErrorBody(text);
|
|
200
|
+
const message = body?.message ?? `Request failed with status ${response.status}`;
|
|
201
|
+
throw new AuthClientError(message, response.status, body);
|
|
202
|
+
}
|
|
203
|
+
__name(throwAuthError, "throwAuthError");
|
|
204
|
+
async function parseJsonOrThrow(response) {
|
|
205
|
+
const text = await response.text();
|
|
206
|
+
if (!response.ok) {
|
|
207
|
+
throwAuthError(response, text);
|
|
208
|
+
}
|
|
209
|
+
if (text.length === 0) {
|
|
210
|
+
throw new AuthClientError(`Response from ${response.url} was empty \u2014 expected a JSON body`, response.status);
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
return JSON.parse(text);
|
|
214
|
+
} catch {
|
|
215
|
+
throw new AuthClientError(`Response from ${response.url} is not valid JSON`, response.status);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
__name(parseJsonOrThrow, "parseJsonOrThrow");
|
|
219
|
+
async function expectNoContent(response) {
|
|
220
|
+
if (!response.ok) {
|
|
221
|
+
const text = await response.text();
|
|
222
|
+
throwAuthError(response, text);
|
|
223
|
+
}
|
|
224
|
+
await response.body?.cancel().catch(
|
|
225
|
+
/* istanbul ignore next */
|
|
226
|
+
() => void 0
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
__name(expectNoContent, "expectNoContent");
|
|
230
|
+
function isAuthErrorBody(value) {
|
|
231
|
+
if (typeof value !== "object" || value === null) return false;
|
|
232
|
+
const candidate = value;
|
|
233
|
+
return typeof candidate["message"] === "string" && typeof candidate["error"] === "string" && typeof candidate["statusCode"] === "number";
|
|
234
|
+
}
|
|
235
|
+
__name(isAuthErrorBody, "isAuthErrorBody");
|
|
236
|
+
function buildUrl(baseUrl, routePrefix, path) {
|
|
237
|
+
if (path.startsWith("/")) {
|
|
238
|
+
return `${baseUrl}${path}`;
|
|
239
|
+
}
|
|
240
|
+
return routePrefix.length > 0 ? `${baseUrl}/${routePrefix}/${path}` : `${baseUrl}/${path}`;
|
|
241
|
+
}
|
|
242
|
+
__name(buildUrl, "buildUrl");
|
|
243
|
+
function createAuthClient(config) {
|
|
244
|
+
const baseUrl = normalizeBaseUrl(config.baseUrl);
|
|
245
|
+
const routePrefix = normalizeRoutePrefix(config.routePrefix ?? "auth");
|
|
246
|
+
const authFetch = config.authFetch ?? createAuthFetch({
|
|
247
|
+
baseUrl,
|
|
248
|
+
routePrefix,
|
|
249
|
+
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — createAuthFetch coalesces each option with `??`/falsy checks downstream
|
|
250
|
+
...config.refreshEndpoint !== void 0 ? {
|
|
251
|
+
refreshEndpoint: config.refreshEndpoint
|
|
252
|
+
} : {},
|
|
253
|
+
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
|
|
254
|
+
...config.credentials !== void 0 ? {
|
|
255
|
+
credentials: config.credentials
|
|
256
|
+
} : {},
|
|
257
|
+
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
|
|
258
|
+
...config.defaultHeaders !== void 0 ? {
|
|
259
|
+
defaultHeaders: config.defaultHeaders
|
|
260
|
+
} : {},
|
|
261
|
+
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
|
|
262
|
+
...config.onSessionExpired !== void 0 ? {
|
|
263
|
+
onSessionExpired: config.onSessionExpired
|
|
264
|
+
} : {},
|
|
265
|
+
// Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
|
|
266
|
+
...config.timeout !== void 0 ? {
|
|
267
|
+
timeout: config.timeout
|
|
268
|
+
} : {}
|
|
269
|
+
});
|
|
270
|
+
const url = /* @__PURE__ */ __name((path) => buildUrl(baseUrl, routePrefix, path), "url");
|
|
271
|
+
async function post(path, body) {
|
|
272
|
+
const response = await authFetch(url(path), {
|
|
273
|
+
method: "POST",
|
|
274
|
+
body: jsonBody(body)
|
|
275
|
+
});
|
|
276
|
+
return parseJsonOrThrow(response);
|
|
277
|
+
}
|
|
278
|
+
__name(post, "post");
|
|
279
|
+
async function postNoContent(path, body) {
|
|
280
|
+
const response = await authFetch(url(path), {
|
|
281
|
+
method: "POST",
|
|
282
|
+
body: jsonBody(body)
|
|
283
|
+
});
|
|
284
|
+
await expectNoContent(response);
|
|
285
|
+
}
|
|
286
|
+
__name(postNoContent, "postNoContent");
|
|
287
|
+
async function get(path) {
|
|
288
|
+
const response = await authFetch(url(path), {
|
|
289
|
+
method: "GET"
|
|
290
|
+
});
|
|
291
|
+
return parseJsonOrThrow(response);
|
|
292
|
+
}
|
|
293
|
+
__name(get, "get");
|
|
294
|
+
return {
|
|
295
|
+
async login(input) {
|
|
296
|
+
return post(AUTH_ROUTES.dashboard.login, input);
|
|
297
|
+
},
|
|
298
|
+
async register(data) {
|
|
299
|
+
return post(AUTH_ROUTES.dashboard.register, data);
|
|
300
|
+
},
|
|
301
|
+
async logout() {
|
|
302
|
+
return postNoContent(AUTH_ROUTES.dashboard.logout, {});
|
|
303
|
+
},
|
|
304
|
+
async refresh() {
|
|
305
|
+
return post(AUTH_ROUTES.dashboard.refresh, {});
|
|
306
|
+
},
|
|
307
|
+
async getMe() {
|
|
308
|
+
return get(AUTH_ROUTES.dashboard.me);
|
|
309
|
+
},
|
|
310
|
+
async mfaChallenge(tempToken, code) {
|
|
311
|
+
const result = await post(AUTH_ROUTES.mfa.challenge, {
|
|
312
|
+
mfaTempToken: tempToken,
|
|
313
|
+
code
|
|
314
|
+
});
|
|
315
|
+
if ("mfaRequired" in result) {
|
|
316
|
+
throw new AuthClientError("MFA challenge endpoint returned another challenge \u2014 server contract mismatch", 502);
|
|
317
|
+
}
|
|
318
|
+
return result;
|
|
319
|
+
},
|
|
320
|
+
async forgotPassword(email, tenantId) {
|
|
321
|
+
return postNoContent(AUTH_ROUTES.password.forgotPassword, {
|
|
322
|
+
email,
|
|
323
|
+
tenantId
|
|
324
|
+
});
|
|
325
|
+
},
|
|
326
|
+
async resetPassword(input) {
|
|
327
|
+
const payload = {
|
|
328
|
+
email: input.email,
|
|
329
|
+
tenantId: input.tenantId,
|
|
330
|
+
newPassword: input.newPassword
|
|
331
|
+
};
|
|
332
|
+
if (input.token !== void 0) payload["token"] = input.token;
|
|
333
|
+
if (input.otp !== void 0) payload["otp"] = input.otp;
|
|
334
|
+
if (input.verifiedToken !== void 0) payload["verifiedToken"] = input.verifiedToken;
|
|
335
|
+
return postNoContent(AUTH_ROUTES.password.resetPassword, payload);
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
__name(createAuthClient, "createAuthClient");
|
|
340
|
+
|
|
341
|
+
export { createAuthClient, createAuthFetch };
|