@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,342 @@
|
|
|
1
|
+
import { ReactNode } from 'react';
|
|
2
|
+
import { AuthClient, RegisterInput, ResetPasswordInput } from '@bymax-one/nest-auth/client';
|
|
3
|
+
import { AuthUserClient, LoginResult, AuthResult } from '@bymax-one/nest-auth/shared';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* React provider for @bymax-one/nest-auth.
|
|
7
|
+
*
|
|
8
|
+
* Owns the session state machine (`loading` → `authenticated` /
|
|
9
|
+
* `unauthenticated`), bridges the typed {@link AuthClient} into
|
|
10
|
+
* {@link AuthContext}, and schedules a best-effort revalidation loop
|
|
11
|
+
* so long-lived UIs surface role/status changes without requiring the
|
|
12
|
+
* user to refresh manually.
|
|
13
|
+
*
|
|
14
|
+
* The provider is deliberately thin: it does not parse tokens, touch
|
|
15
|
+
* storage, or decide how the server delivers credentials. Every
|
|
16
|
+
* transport detail lives in the `client` subpath; this file only
|
|
17
|
+
* coordinates state and React plumbing.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Props accepted by {@link AuthProvider}.
|
|
22
|
+
*/
|
|
23
|
+
interface AuthProviderProps {
|
|
24
|
+
/** Rendered inside the provider once state is initialized. */
|
|
25
|
+
children: ReactNode;
|
|
26
|
+
/**
|
|
27
|
+
* Authentication client built via `createAuthClient`. The provider
|
|
28
|
+
* never constructs one itself so test harnesses and SSR shells can
|
|
29
|
+
* inject a mock or a pre-configured instance.
|
|
30
|
+
*/
|
|
31
|
+
client: AuthClient;
|
|
32
|
+
/**
|
|
33
|
+
* Fired when the provider detects that the session has expired —
|
|
34
|
+
* i.e. a prior `authenticated` state transitions to
|
|
35
|
+
* `unauthenticated` because `getMe()` or `refresh()` failed with a
|
|
36
|
+
* 401. Typical wiring: redirect to the sign-in page.
|
|
37
|
+
*
|
|
38
|
+
* Not called on the initial mount when no session exists to begin
|
|
39
|
+
* with (that is "not signed in", not "session expired"), nor on
|
|
40
|
+
* explicit {@link AuthContextValue.logout} calls.
|
|
41
|
+
*/
|
|
42
|
+
onSessionExpired?: () => void;
|
|
43
|
+
/**
|
|
44
|
+
* Interval (in milliseconds) between automatic revalidations.
|
|
45
|
+
* Default: {@link DEFAULT_REVALIDATE_INTERVAL_MS} (5 minutes).
|
|
46
|
+
*
|
|
47
|
+
* Set to `0` to disable the loop entirely — useful for short-lived
|
|
48
|
+
* flows (sign-up wizards, kiosk screens) where the overhead of a
|
|
49
|
+
* background poll is not worth the freshness guarantee.
|
|
50
|
+
*/
|
|
51
|
+
revalidateInterval?: number;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Top-level React provider that wires the auth state machine into the
|
|
55
|
+
* {@link AuthContext}.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```tsx
|
|
59
|
+
* const client = createAuthClient({ baseUrl: '/api' })
|
|
60
|
+
*
|
|
61
|
+
* export function App() {
|
|
62
|
+
* return (
|
|
63
|
+
* <AuthProvider client={client} onSessionExpired={() => router.push('/sign-in')}>
|
|
64
|
+
* <Routes />
|
|
65
|
+
* </AuthProvider>
|
|
66
|
+
* )
|
|
67
|
+
* }
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
declare function AuthProvider({ children, client, onSessionExpired, revalidateInterval }: AuthProviderProps): ReactNode;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Lifecycle state of the authenticated session.
|
|
74
|
+
*
|
|
75
|
+
* - `'loading'` — initial mount or in-flight revalidation; user is unknown.
|
|
76
|
+
* - `'authenticated'` — a valid session exists and `user` is populated.
|
|
77
|
+
* - `'unauthenticated'` — no session; `user` is `null`.
|
|
78
|
+
*/
|
|
79
|
+
type AuthStatus = 'authenticated' | 'unauthenticated' | 'loading';
|
|
80
|
+
/**
|
|
81
|
+
* Shape of the value published by {@link AuthContext}.
|
|
82
|
+
*
|
|
83
|
+
* Hooks ({@link useSession}, {@link useAuth}, {@link useAuthStatus}) read
|
|
84
|
+
* from this surface. Method signatures mirror the typed client so callers
|
|
85
|
+
* pass the same arguments they would to `createAuthClient` directly.
|
|
86
|
+
*/
|
|
87
|
+
interface AuthContextValue {
|
|
88
|
+
/** Authenticated user, or `null` when there is no session. */
|
|
89
|
+
user: AuthUserClient | null;
|
|
90
|
+
/** Current lifecycle status of the session — see {@link AuthStatus}. */
|
|
91
|
+
status: AuthStatus;
|
|
92
|
+
/**
|
|
93
|
+
* Convenience flag that mirrors `status === 'loading'`. Kept as a
|
|
94
|
+
* discrete field so consumers can destructure it without widening
|
|
95
|
+
* their dependency on the full status union.
|
|
96
|
+
*/
|
|
97
|
+
isLoading: boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Submit credentials to the server and update context state with the
|
|
100
|
+
* resulting user on success.
|
|
101
|
+
*
|
|
102
|
+
* @param email User's primary email address.
|
|
103
|
+
* @param password Plaintext password — the server hashes on receipt.
|
|
104
|
+
* @param options Optional metadata. `tenantId` defaults to `'default'`
|
|
105
|
+
* when omitted so single-tenant apps can skip it.
|
|
106
|
+
*
|
|
107
|
+
* @returns The discriminated {@link LoginResult} — branch on
|
|
108
|
+
* `'mfaRequired' in result` to handle the MFA challenge case.
|
|
109
|
+
*/
|
|
110
|
+
login: (email: string, password: string, options?: {
|
|
111
|
+
tenantId?: string;
|
|
112
|
+
}) => Promise<LoginResult>;
|
|
113
|
+
/**
|
|
114
|
+
* Register a new account and, on success, commit the returned user
|
|
115
|
+
* to the context as the active session.
|
|
116
|
+
*
|
|
117
|
+
* @param data Payload matching `AuthClient.register` — `email`,
|
|
118
|
+
* `password`, `name`, `tenantId` — forwarded to the server DTO
|
|
119
|
+
* unchanged.
|
|
120
|
+
*
|
|
121
|
+
* @returns The {@link AuthResult} returned by the server. In cookie
|
|
122
|
+
* mode `accessToken` is the empty string; in bearer mode callers
|
|
123
|
+
* must keep the token in memory only (never in storage).
|
|
124
|
+
*
|
|
125
|
+
* @throws {AuthClientError} When the server rejects the payload
|
|
126
|
+
* (e.g. `auth.email_already_registered`, validation failures).
|
|
127
|
+
* The context state lands in `unauthenticated` before the error
|
|
128
|
+
* is re-thrown so the caller's catch branch can update its own
|
|
129
|
+
* form-error UI.
|
|
130
|
+
*/
|
|
131
|
+
register: (data: RegisterInput) => Promise<AuthResult>;
|
|
132
|
+
/**
|
|
133
|
+
* Revoke the current session server-side and clear the local
|
|
134
|
+
* context state.
|
|
135
|
+
*
|
|
136
|
+
* @throws The underlying error raised by `AuthClient.logout` when
|
|
137
|
+
* the network call fails. Local context state is STILL cleared
|
|
138
|
+
* before the error propagates — consumers can treat a rejection
|
|
139
|
+
* as "you are signed out locally, but the server revocation
|
|
140
|
+
* request did not complete" and decide whether to retry.
|
|
141
|
+
* Callers that do not care about the server-side outcome should
|
|
142
|
+
* wrap the call in a try/catch and ignore the error.
|
|
143
|
+
*/
|
|
144
|
+
logout: () => Promise<void>;
|
|
145
|
+
/**
|
|
146
|
+
* Force a session revalidation by calling `client.getMe()`.
|
|
147
|
+
* Intended for explicit refresh flows (e.g. after an action that
|
|
148
|
+
* may have changed the user's role server-side). Not required for
|
|
149
|
+
* routine session maintenance — the provider handles that
|
|
150
|
+
* automatically via the configured interval.
|
|
151
|
+
*/
|
|
152
|
+
refresh: () => Promise<void>;
|
|
153
|
+
/**
|
|
154
|
+
* Initiate a password reset. The server returns 200 regardless of
|
|
155
|
+
* whether the email is registered (anti-enumeration) — treat a
|
|
156
|
+
* resolved Promise as "request accepted", not "email known".
|
|
157
|
+
*/
|
|
158
|
+
forgotPassword: (email: string, tenantId?: string) => Promise<void>;
|
|
159
|
+
/**
|
|
160
|
+
* Submit a new password. Accepts the same discriminated-union shape
|
|
161
|
+
* as `AuthClient.resetPassword` so callers can construct the input
|
|
162
|
+
* with a single field — `token`, `otp`, or `verifiedToken`.
|
|
163
|
+
*/
|
|
164
|
+
resetPassword: (input: ResetPasswordInput) => Promise<void>;
|
|
165
|
+
/**
|
|
166
|
+
* Timestamp of the most recent successful `getMe()` call, or `null`
|
|
167
|
+
* when the provider has not yet completed its initial mount.
|
|
168
|
+
* Consumers can surface this to show a "last checked" indicator in
|
|
169
|
+
* long-lived sessions (dashboards, admin tools).
|
|
170
|
+
*/
|
|
171
|
+
lastValidation: Date | null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Read-only view of the auth session for the consuming component tree.
|
|
176
|
+
*
|
|
177
|
+
* Companion to {@link useAuth} — this hook exposes the state part of
|
|
178
|
+
* {@link AuthContextValue} (user, status, loading, last revalidation
|
|
179
|
+
* timestamp, and the explicit `refresh` trigger) while {@link useAuth}
|
|
180
|
+
* exposes the action part (login, register, logout, password reset).
|
|
181
|
+
*
|
|
182
|
+
* Splitting the two surfaces means read-heavy components (navbars,
|
|
183
|
+
* profile badges, route guards) can depend on just the subset they
|
|
184
|
+
* actually need and do not get re-rendered by unrelated action churn.
|
|
185
|
+
*/
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Shape returned by {@link useSession}.
|
|
189
|
+
*
|
|
190
|
+
* A deliberate subset of {@link AuthContextValue}: the method surface
|
|
191
|
+
* stays with {@link useAuth} so consumers of session state do not
|
|
192
|
+
* accidentally couple themselves to the login/logout imperative API.
|
|
193
|
+
*
|
|
194
|
+
* @remarks
|
|
195
|
+
* The returned object identity is not stable across renders. Treat
|
|
196
|
+
* the individual fields (`user`, `status`, `lastValidation`) as the
|
|
197
|
+
* correct memoization keys — never the container object itself, or
|
|
198
|
+
* downstream `useMemo` / `useEffect` dependency arrays will fire on
|
|
199
|
+
* every render regardless of whether the session actually changed.
|
|
200
|
+
*/
|
|
201
|
+
interface UseSessionResult {
|
|
202
|
+
/** Authenticated user, or `null` when there is no session. */
|
|
203
|
+
user: AuthUserClient | null;
|
|
204
|
+
/** Current lifecycle status of the session — see {@link AuthStatus}. */
|
|
205
|
+
status: AuthStatus;
|
|
206
|
+
/**
|
|
207
|
+
* Convenience boolean mirroring `status === 'loading'`. Exposed as
|
|
208
|
+
* a discrete field so destructuring is ergonomic in components that
|
|
209
|
+
* only branch on "are we still deciding?".
|
|
210
|
+
*/
|
|
211
|
+
isLoading: boolean;
|
|
212
|
+
/**
|
|
213
|
+
* Force a revalidation by calling `AuthClient.getMe()` through the
|
|
214
|
+
* provider. Useful after an action that may have changed the user's
|
|
215
|
+
* role server-side (e.g. tenant switch). Routine freshness is
|
|
216
|
+
* already handled by the provider's interval — reach for this only
|
|
217
|
+
* when you need a synchronous round-trip.
|
|
218
|
+
*/
|
|
219
|
+
refresh: () => Promise<void>;
|
|
220
|
+
/**
|
|
221
|
+
* Timestamp of the most recent successful `getMe()` round-trip, or
|
|
222
|
+
* `null` when the provider has not yet completed its initial probe.
|
|
223
|
+
*/
|
|
224
|
+
lastValidation: Date | null;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Read the current session state from the {@link AuthContext}.
|
|
228
|
+
*
|
|
229
|
+
* @throws When called outside of an {@link AuthProvider} subtree.
|
|
230
|
+
* The descriptive message points the developer to wrap their app
|
|
231
|
+
* rather than leaving them with a `null`-based runtime failure
|
|
232
|
+
* deeper in the call stack.
|
|
233
|
+
*
|
|
234
|
+
* @example
|
|
235
|
+
* ```tsx
|
|
236
|
+
* function Navbar(): ReactNode {
|
|
237
|
+
* const { user, isLoading } = useSession()
|
|
238
|
+
* if (isLoading) return <Spinner />
|
|
239
|
+
* return user ? <UserMenu user={user} /> : <SignInButton />
|
|
240
|
+
* }
|
|
241
|
+
* ```
|
|
242
|
+
*/
|
|
243
|
+
declare function useSession(): UseSessionResult;
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Imperative action surface of the auth session.
|
|
247
|
+
*
|
|
248
|
+
* Companion to {@link useSession} — this hook returns the mutating
|
|
249
|
+
* methods that consumers call from event handlers (login, register,
|
|
250
|
+
* logout, password-reset flows). State reading lives in
|
|
251
|
+
* {@link useSession}, so forms can take `useAuth()` without
|
|
252
|
+
* subscribing to `user` / `status` churn unless they really need it.
|
|
253
|
+
*/
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Shape returned by {@link useAuth}. Narrows {@link AuthContextValue}
|
|
257
|
+
* to its method members — state-only consumers should use
|
|
258
|
+
* {@link useSession} instead so they do not re-render when an unrelated
|
|
259
|
+
* action runs.
|
|
260
|
+
*/
|
|
261
|
+
type UseAuthResult = Pick<AuthContextValue, 'login' | 'register' | 'logout' | 'forgotPassword' | 'resetPassword'>;
|
|
262
|
+
/**
|
|
263
|
+
* Read the session-mutating methods from the {@link AuthContext}.
|
|
264
|
+
*
|
|
265
|
+
* @throws When called outside of an {@link AuthProvider} subtree. A
|
|
266
|
+
* typed error makes the misuse immediately actionable instead of
|
|
267
|
+
* surfacing as an undefined-method runtime failure inside a
|
|
268
|
+
* component handler.
|
|
269
|
+
*
|
|
270
|
+
* @example
|
|
271
|
+
* ```tsx
|
|
272
|
+
* function LoginForm(): ReactNode {
|
|
273
|
+
* const { login } = useAuth()
|
|
274
|
+
* return (
|
|
275
|
+
* <form
|
|
276
|
+
* onSubmit={async (event) => {
|
|
277
|
+
* event.preventDefault()
|
|
278
|
+
* await login(email, password)
|
|
279
|
+
* }}
|
|
280
|
+
* >
|
|
281
|
+
* ...
|
|
282
|
+
* </form>
|
|
283
|
+
* )
|
|
284
|
+
* }
|
|
285
|
+
* ```
|
|
286
|
+
*/
|
|
287
|
+
declare function useAuth(): UseAuthResult;
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Binary-flag convenience view of the auth session.
|
|
291
|
+
*
|
|
292
|
+
* Most route guards and conditional renders only need two pieces of
|
|
293
|
+
* information: "are we still figuring it out?" and "is the user
|
|
294
|
+
* signed in?". This hook collapses {@link useSession}'s status union
|
|
295
|
+
* into those two booleans so consumers can skip the string-compare
|
|
296
|
+
* boilerplate and so a future rename of the status union stays
|
|
297
|
+
* contained inside {@link useSession}.
|
|
298
|
+
*/
|
|
299
|
+
/**
|
|
300
|
+
* Shape returned by {@link useAuthStatus}.
|
|
301
|
+
*
|
|
302
|
+
* The two booleans are mutually independent — it is legal (and
|
|
303
|
+
* expected during the initial probe) to have both `isAuthenticated`
|
|
304
|
+
* and `isLoading` be `false`, representing "not signed in, no probe
|
|
305
|
+
* in flight".
|
|
306
|
+
*/
|
|
307
|
+
interface UseAuthStatusResult {
|
|
308
|
+
/**
|
|
309
|
+
* `true` only when the session status is `'authenticated'`. Safe
|
|
310
|
+
* to use as the gate for protected-route guards and "signed-in only"
|
|
311
|
+
* UI — a `loading` or `unauthenticated` status correctly evaluates
|
|
312
|
+
* to `false`.
|
|
313
|
+
*/
|
|
314
|
+
isAuthenticated: boolean;
|
|
315
|
+
/**
|
|
316
|
+
* `true` only when the session status is `'loading'`. Use it to
|
|
317
|
+
* show a skeleton or spinner while the provider completes its
|
|
318
|
+
* initial probe or an explicit `refresh()` — the `authenticated`
|
|
319
|
+
* and `unauthenticated` states both evaluate to `false`.
|
|
320
|
+
*/
|
|
321
|
+
isLoading: boolean;
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Derive the two binary session flags from {@link useSession}.
|
|
325
|
+
*
|
|
326
|
+
* @throws When called outside of an {@link AuthProvider} subtree.
|
|
327
|
+
* The error propagates from {@link useSession}, so the same
|
|
328
|
+
* descriptive message applies.
|
|
329
|
+
*
|
|
330
|
+
* @example
|
|
331
|
+
* ```tsx
|
|
332
|
+
* function ProtectedRoute({ children }: { children: ReactNode }): ReactNode {
|
|
333
|
+
* const { isAuthenticated, isLoading } = useAuthStatus()
|
|
334
|
+
* if (isLoading) return <Spinner />
|
|
335
|
+
* if (!isAuthenticated) return <Navigate to="/sign-in" />
|
|
336
|
+
* return <>{children}</>
|
|
337
|
+
* }
|
|
338
|
+
* ```
|
|
339
|
+
*/
|
|
340
|
+
declare function useAuthStatus(): UseAuthStatusResult;
|
|
341
|
+
|
|
342
|
+
export { type AuthContextValue, AuthProvider, type AuthProviderProps, type AuthStatus, type UseAuthResult, type UseAuthStatusResult, type UseSessionResult, useAuth, useAuthStatus, useSession };
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import React, { createContext, useReducer, useRef, useEffect, useCallback, useMemo, useContext } from 'react';
|
|
2
|
+
import { 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 AuthContext = createContext(null);
|
|
7
|
+
|
|
8
|
+
// src/react/AuthProvider.tsx
|
|
9
|
+
var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
|
|
10
|
+
var DEFAULT_TENANT_ID = "default";
|
|
11
|
+
var INITIAL_STATE = {
|
|
12
|
+
user: null,
|
|
13
|
+
status: "loading",
|
|
14
|
+
lastValidation: null
|
|
15
|
+
};
|
|
16
|
+
function authReducer(state, action) {
|
|
17
|
+
switch (action.type) {
|
|
18
|
+
case "SET_USER":
|
|
19
|
+
return {
|
|
20
|
+
user: action.payload.user,
|
|
21
|
+
status: "authenticated",
|
|
22
|
+
lastValidation: action.payload.timestamp
|
|
23
|
+
};
|
|
24
|
+
case "SET_LOADING":
|
|
25
|
+
return {
|
|
26
|
+
...state,
|
|
27
|
+
status: "loading"
|
|
28
|
+
};
|
|
29
|
+
case "CLEAR_SESSION":
|
|
30
|
+
return {
|
|
31
|
+
user: null,
|
|
32
|
+
status: "unauthenticated",
|
|
33
|
+
lastValidation: null
|
|
34
|
+
};
|
|
35
|
+
case "SET_ERROR":
|
|
36
|
+
return {
|
|
37
|
+
user: null,
|
|
38
|
+
status: "unauthenticated",
|
|
39
|
+
lastValidation: state.lastValidation
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
__name(authReducer, "authReducer");
|
|
44
|
+
function isSessionExpiredError(error) {
|
|
45
|
+
return error instanceof AuthClientError && error.status === 401;
|
|
46
|
+
}
|
|
47
|
+
__name(isSessionExpiredError, "isSessionExpiredError");
|
|
48
|
+
function AuthProvider({ children, client, onSessionExpired, revalidateInterval = DEFAULT_REVALIDATE_INTERVAL_MS }) {
|
|
49
|
+
const [state, dispatch] = useReducer(authReducer, INITIAL_STATE);
|
|
50
|
+
const onSessionExpiredRef = useRef(onSessionExpired);
|
|
51
|
+
const clientRef = useRef(client);
|
|
52
|
+
const statusRef = useRef(INITIAL_STATE.status);
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
onSessionExpiredRef.current = onSessionExpired;
|
|
55
|
+
}, [
|
|
56
|
+
onSessionExpired
|
|
57
|
+
]);
|
|
58
|
+
useEffect(() => {
|
|
59
|
+
clientRef.current = client;
|
|
60
|
+
}, [
|
|
61
|
+
client
|
|
62
|
+
]);
|
|
63
|
+
const syncedDispatch = useCallback((action) => {
|
|
64
|
+
dispatch(action);
|
|
65
|
+
switch (action.type) {
|
|
66
|
+
case "SET_USER":
|
|
67
|
+
statusRef.current = "authenticated";
|
|
68
|
+
return;
|
|
69
|
+
// Stryker disable next-line ConditionalExpression: reducer case label; the SET_LOADING and tick paths are exercised elsewhere and this case's presence does not change the dispatched-state outcome under test
|
|
70
|
+
case "SET_LOADING":
|
|
71
|
+
statusRef.current = "loading";
|
|
72
|
+
return;
|
|
73
|
+
case "CLEAR_SESSION":
|
|
74
|
+
case "SET_ERROR":
|
|
75
|
+
statusRef.current = "unauthenticated";
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
}, []);
|
|
79
|
+
const revalidate = useCallback(
|
|
80
|
+
async (isInitial) => {
|
|
81
|
+
try {
|
|
82
|
+
const user = await clientRef.current.getMe();
|
|
83
|
+
syncedDispatch({
|
|
84
|
+
type: "SET_USER",
|
|
85
|
+
payload: {
|
|
86
|
+
user,
|
|
87
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
} catch (error) {
|
|
91
|
+
const wasAuthenticated = statusRef.current === "authenticated";
|
|
92
|
+
if (isSessionExpiredError(error)) {
|
|
93
|
+
if (!isInitial && wasAuthenticated) {
|
|
94
|
+
try {
|
|
95
|
+
onSessionExpiredRef.current?.();
|
|
96
|
+
} catch (callbackError) {
|
|
97
|
+
console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
syncedDispatch({
|
|
101
|
+
type: "CLEAR_SESSION"
|
|
102
|
+
});
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
syncedDispatch({
|
|
106
|
+
type: "SET_ERROR"
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
// Stryker disable next-line ArrayDeclaration: deps hold only the stable `syncedDispatch`, so emptying the array does not change effect/memo behavior
|
|
111
|
+
[
|
|
112
|
+
syncedDispatch
|
|
113
|
+
]
|
|
114
|
+
);
|
|
115
|
+
useEffect(() => {
|
|
116
|
+
void revalidate(true);
|
|
117
|
+
}, [
|
|
118
|
+
revalidate
|
|
119
|
+
]);
|
|
120
|
+
useEffect(() => {
|
|
121
|
+
if (revalidateInterval <= 0) {
|
|
122
|
+
return void 0;
|
|
123
|
+
}
|
|
124
|
+
const handle = setInterval(() => {
|
|
125
|
+
void revalidate(false);
|
|
126
|
+
}, revalidateInterval);
|
|
127
|
+
return () => {
|
|
128
|
+
clearInterval(handle);
|
|
129
|
+
};
|
|
130
|
+
}, [
|
|
131
|
+
revalidate,
|
|
132
|
+
revalidateInterval
|
|
133
|
+
]);
|
|
134
|
+
const login = useCallback(
|
|
135
|
+
async (email, password, options) => {
|
|
136
|
+
const tenantId = options?.tenantId ?? DEFAULT_TENANT_ID;
|
|
137
|
+
syncedDispatch({
|
|
138
|
+
type: "SET_LOADING"
|
|
139
|
+
});
|
|
140
|
+
try {
|
|
141
|
+
const result = await clientRef.current.login({
|
|
142
|
+
email,
|
|
143
|
+
password,
|
|
144
|
+
tenantId
|
|
145
|
+
});
|
|
146
|
+
if ("mfaRequired" in result) {
|
|
147
|
+
syncedDispatch({
|
|
148
|
+
type: "CLEAR_SESSION"
|
|
149
|
+
});
|
|
150
|
+
return result;
|
|
151
|
+
}
|
|
152
|
+
syncedDispatch({
|
|
153
|
+
type: "SET_USER",
|
|
154
|
+
payload: {
|
|
155
|
+
user: result.user,
|
|
156
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
return result;
|
|
160
|
+
} catch (error) {
|
|
161
|
+
syncedDispatch({
|
|
162
|
+
type: "SET_ERROR"
|
|
163
|
+
});
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
// Stryker disable next-line ArrayDeclaration: deps hold only the stable `syncedDispatch`, so emptying the array does not change memoization
|
|
168
|
+
[
|
|
169
|
+
syncedDispatch
|
|
170
|
+
]
|
|
171
|
+
);
|
|
172
|
+
const register = useCallback(
|
|
173
|
+
async (data) => {
|
|
174
|
+
syncedDispatch({
|
|
175
|
+
type: "SET_LOADING"
|
|
176
|
+
});
|
|
177
|
+
try {
|
|
178
|
+
const result = await clientRef.current.register(data);
|
|
179
|
+
syncedDispatch({
|
|
180
|
+
type: "SET_USER",
|
|
181
|
+
payload: {
|
|
182
|
+
user: result.user,
|
|
183
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
return result;
|
|
187
|
+
} catch (error) {
|
|
188
|
+
syncedDispatch({
|
|
189
|
+
type: "SET_ERROR"
|
|
190
|
+
});
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
// Stryker disable next-line ArrayDeclaration: deps hold only the stable `syncedDispatch`, so emptying the array does not change memoization
|
|
195
|
+
[
|
|
196
|
+
syncedDispatch
|
|
197
|
+
]
|
|
198
|
+
);
|
|
199
|
+
const logout = useCallback(async () => {
|
|
200
|
+
try {
|
|
201
|
+
await clientRef.current.logout();
|
|
202
|
+
} finally {
|
|
203
|
+
syncedDispatch({
|
|
204
|
+
type: "CLEAR_SESSION"
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
}, [
|
|
208
|
+
syncedDispatch
|
|
209
|
+
]);
|
|
210
|
+
const refresh = useCallback(async () => {
|
|
211
|
+
await revalidate(false);
|
|
212
|
+
}, [
|
|
213
|
+
revalidate
|
|
214
|
+
]);
|
|
215
|
+
const forgotPassword = useCallback(
|
|
216
|
+
async (email, tenantId) => {
|
|
217
|
+
await clientRef.current.forgotPassword(email, tenantId ?? DEFAULT_TENANT_ID);
|
|
218
|
+
},
|
|
219
|
+
// Stryker disable next-line ArrayDeclaration: empty deps array with only stable references in scope; a constant-string array re-runs identically
|
|
220
|
+
[]
|
|
221
|
+
);
|
|
222
|
+
const resetPassword = useCallback(
|
|
223
|
+
async (input) => {
|
|
224
|
+
await clientRef.current.resetPassword(input);
|
|
225
|
+
},
|
|
226
|
+
// Stryker disable next-line ArrayDeclaration: empty deps array with only stable references in scope; a constant-string array re-runs identically
|
|
227
|
+
[]
|
|
228
|
+
);
|
|
229
|
+
const value = useMemo(() => ({
|
|
230
|
+
user: state.user,
|
|
231
|
+
status: state.status,
|
|
232
|
+
isLoading: state.status === "loading",
|
|
233
|
+
lastValidation: state.lastValidation,
|
|
234
|
+
login,
|
|
235
|
+
register,
|
|
236
|
+
logout,
|
|
237
|
+
refresh,
|
|
238
|
+
forgotPassword,
|
|
239
|
+
resetPassword
|
|
240
|
+
}), [
|
|
241
|
+
state.user,
|
|
242
|
+
state.status,
|
|
243
|
+
state.lastValidation,
|
|
244
|
+
login,
|
|
245
|
+
register,
|
|
246
|
+
logout,
|
|
247
|
+
refresh,
|
|
248
|
+
forgotPassword,
|
|
249
|
+
resetPassword
|
|
250
|
+
]);
|
|
251
|
+
return /* @__PURE__ */ React.createElement(AuthContext.Provider, {
|
|
252
|
+
value
|
|
253
|
+
}, children);
|
|
254
|
+
}
|
|
255
|
+
__name(AuthProvider, "AuthProvider");
|
|
256
|
+
function useSession() {
|
|
257
|
+
const ctx = useContext(AuthContext);
|
|
258
|
+
if (ctx === null) {
|
|
259
|
+
throw new Error("useSession must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient().");
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
user: ctx.user,
|
|
263
|
+
status: ctx.status,
|
|
264
|
+
isLoading: ctx.isLoading,
|
|
265
|
+
refresh: ctx.refresh,
|
|
266
|
+
lastValidation: ctx.lastValidation
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
__name(useSession, "useSession");
|
|
270
|
+
function useAuth() {
|
|
271
|
+
const ctx = useContext(AuthContext);
|
|
272
|
+
if (ctx === null) {
|
|
273
|
+
throw new Error("useAuth must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient().");
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
login: ctx.login,
|
|
277
|
+
register: ctx.register,
|
|
278
|
+
logout: ctx.logout,
|
|
279
|
+
forgotPassword: ctx.forgotPassword,
|
|
280
|
+
resetPassword: ctx.resetPassword
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
__name(useAuth, "useAuth");
|
|
284
|
+
|
|
285
|
+
// src/react/useAuthStatus.ts
|
|
286
|
+
function useAuthStatus() {
|
|
287
|
+
const { status, isLoading } = useSession();
|
|
288
|
+
return {
|
|
289
|
+
isAuthenticated: status === "authenticated",
|
|
290
|
+
isLoading
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
__name(useAuthStatus, "useAuthStatus");
|
|
294
|
+
|
|
295
|
+
export { AuthProvider, useAuth, useAuthStatus, useSession };
|