@versini/auth0-react-thin 2.19.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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +185 -0
  3. package/dist/auth-state.d.ts +15 -0
  4. package/dist/auth-state.d.ts.map +1 -0
  5. package/dist/auth0-context.d.ts +423 -0
  6. package/dist/auth0-context.d.ts.map +1 -0
  7. package/dist/auth0-provider.d.ts +96 -0
  8. package/dist/auth0-provider.d.ts.map +1 -0
  9. package/dist/auth0-react.cjs.js +830 -0
  10. package/dist/auth0-react.cjs.js.map +1 -0
  11. package/dist/auth0-react.esm.js +723 -0
  12. package/dist/auth0-react.esm.js.map +1 -0
  13. package/dist/auth0-react.js +759 -0
  14. package/dist/auth0-react.js.map +1 -0
  15. package/dist/auth0-react.min.js +2 -0
  16. package/dist/auth0-react.min.js.map +1 -0
  17. package/dist/errors.d.ts +12 -0
  18. package/dist/errors.d.ts.map +1 -0
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/reducer.d.ts +19 -0
  22. package/dist/reducer.d.ts.map +1 -0
  23. package/dist/use-auth0.d.ts +29 -0
  24. package/dist/use-auth0.d.ts.map +1 -0
  25. package/dist/utils.d.ts +10 -0
  26. package/dist/utils.d.ts.map +1 -0
  27. package/dist/with-auth0.d.ts +29 -0
  28. package/dist/with-auth0.d.ts.map +1 -0
  29. package/dist/with-authentication-required.d.ts +77 -0
  30. package/dist/with-authentication-required.d.ts.map +1 -0
  31. package/package.json +43 -0
  32. package/src/auth-state.tsx +21 -0
  33. package/src/auth0-context.tsx +506 -0
  34. package/src/auth0-provider.tsx +488 -0
  35. package/src/errors.tsx +14 -0
  36. package/src/index.tsx +100 -0
  37. package/src/reducer.tsx +59 -0
  38. package/src/use-auth0.tsx +34 -0
  39. package/src/utils.tsx +74 -0
  40. package/src/with-auth0.tsx +44 -0
  41. package/src/with-authentication-required.tsx +141 -0
@@ -0,0 +1,506 @@
1
+ import {
2
+ GetTokenSilentlyOptions,
3
+ GetTokenWithPopupOptions,
4
+ IdToken,
5
+ LogoutOptions as SPALogoutOptions,
6
+ PopupLoginOptions,
7
+ PopupConfigOptions,
8
+ RedirectLoginResult,
9
+ User,
10
+ GetTokenSilentlyVerboseResponse,
11
+ RedirectLoginOptions as SPARedirectLoginOptions,
12
+ type Auth0Client,
13
+ RedirectConnectAccountOptions,
14
+ ConnectAccountRedirectResult,
15
+ CustomTokenExchangeOptions,
16
+ TokenEndpointResponse,
17
+ type MfaApiClient,
18
+ type PasskeyApiClient,
19
+ type MyAccountApiClient
20
+ } from '@auth0/auth0-spa-js';
21
+ import { createContext } from 'react';
22
+ import { AuthState, initialAuthState } from './auth-state';
23
+ import { AppState } from './auth0-provider';
24
+
25
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
26
+ export interface LogoutOptions extends Omit<SPALogoutOptions, 'onRedirect'> {}
27
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
28
+ export interface RedirectLoginOptions<TAppState = AppState>
29
+ extends Omit<SPARedirectLoginOptions<TAppState>, 'onRedirect'> {}
30
+
31
+ /**
32
+ * Contains the authenticated state and authentication methods provided by the `useAuth0` hook.
33
+ */
34
+ export interface Auth0ContextInterface<TUser extends User = User>
35
+ extends AuthState<TUser> {
36
+ /**
37
+ * ```js
38
+ * const token = await getAccessTokenSilently(options);
39
+ * ```
40
+ *
41
+ * If there's a valid token stored, return it. Otherwise, opens an
42
+ * iframe with the `/authorize` URL using the parameters provided
43
+ * as arguments. Random and secure `state` and `nonce` parameters
44
+ * will be auto-generated. If the response is successful, results
45
+ * will be valid according to their expiration times.
46
+ *
47
+ * If refresh tokens are used, the token endpoint is called directly with the
48
+ * 'refresh_token' grant. If no refresh token is available to make this call,
49
+ * the SDK will only fall back to using an iframe to the '/authorize' URL if
50
+ * the `useRefreshTokensFallback` setting has been set to `true`. By default this
51
+ * setting is `false`.
52
+ *
53
+ * This method may use a web worker to perform the token call if the in-memory
54
+ * cache is used.
55
+ *
56
+ * If an `audience` value is given to this function, the SDK always falls
57
+ * back to using an iframe to make the token exchange.
58
+ *
59
+ * Note that in all cases, falling back to an iframe requires access to
60
+ * the `auth0` cookie.
61
+ */
62
+ getAccessTokenSilently: {
63
+ (
64
+ options: GetTokenSilentlyOptions & { detailedResponse: true }
65
+ ): Promise<GetTokenSilentlyVerboseResponse>;
66
+ (options?: GetTokenSilentlyOptions): Promise<string>;
67
+ (options: GetTokenSilentlyOptions): Promise<
68
+ GetTokenSilentlyVerboseResponse | string
69
+ >;
70
+ };
71
+
72
+ /**
73
+ * ```js
74
+ * const token = await getTokenWithPopup(options, config);
75
+ * ```
76
+ *
77
+ * Get an access token interactively.
78
+ *
79
+ * Opens a popup with the `/authorize` URL using the parameters
80
+ * provided as arguments. Random and secure `state` and `nonce`
81
+ * parameters will be auto-generated. If the response is successful,
82
+ * results will be valid according to their expiration times.
83
+ */
84
+ getAccessTokenWithPopup: (
85
+ options?: GetTokenWithPopupOptions,
86
+ config?: PopupConfigOptions
87
+ ) => Promise<string | undefined>;
88
+
89
+ /**
90
+ * ```js
91
+ * const claims = await getIdTokenClaims();
92
+ * ```
93
+ *
94
+ * Returns all claims from the id_token if available.
95
+ */
96
+ getIdTokenClaims: () => Promise<IdToken | undefined>;
97
+
98
+ /**
99
+ * ```js
100
+ * await loginWithCustomTokenExchange(options);
101
+ * ```
102
+ *
103
+ * Exchanges an external subject token for Auth0 tokens and logs the user in.
104
+ * This method implements the Custom Token Exchange grant as specified in RFC 8693.
105
+ *
106
+ * The exchanged tokens are automatically cached, establishing an authenticated session.
107
+ * After calling this method, you can use `getUser()`, `getIdTokenClaims()`, and
108
+ * `getTokenSilently()` to access the user's information and tokens.
109
+ *
110
+ * @param options - The options required to perform the token exchange.
111
+ *
112
+ * @returns A promise that resolves to the token endpoint response,
113
+ * which contains the issued Auth0 tokens (access_token, id_token, etc.).
114
+ *
115
+ * The request includes the following parameters:
116
+ * - `grant_type`: "urn:ietf:params:oauth:grant-type:token-exchange"
117
+ * - `subject_token`: The external token to exchange
118
+ * - `subject_token_type`: The type identifier of the external token
119
+ * - `scope`: Merged scopes from the request and SDK defaults
120
+ * - `audience`: Target audience (defaults to SDK configuration)
121
+ * - `organization`: Optional organization ID/name for org-scoped authentication
122
+ *
123
+ * **Example Usage:**
124
+ *
125
+ * ```js
126
+ * const options = {
127
+ * subject_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...',
128
+ * subject_token_type: 'urn:acme:legacy-system-token',
129
+ * scope: 'openid profile email',
130
+ * audience: 'https://api.example.com',
131
+ * organization: 'org_12345'
132
+ * };
133
+ *
134
+ * try {
135
+ * const tokenResponse = await loginWithCustomTokenExchange(options);
136
+ * console.log('Access token:', tokenResponse.access_token);
137
+ *
138
+ * // User is now logged in - access user info
139
+ * const user = await getUser();
140
+ * console.log('Logged in user:', user);
141
+ * } catch (error) {
142
+ * console.error('Token exchange failed:', error);
143
+ * }
144
+ * ```
145
+ */
146
+ loginWithCustomTokenExchange: (
147
+ options: CustomTokenExchangeOptions
148
+ ) => Promise<TokenEndpointResponse>;
149
+
150
+ /**
151
+ * ```js
152
+ * const tokenResponse = await customTokenExchange({
153
+ * subject_token: 'ey...',
154
+ * subject_token_type: 'urn:acme:legacy-system-token',
155
+ * actor_token: 'ey...',
156
+ * actor_token_type: 'https://idp.example.com/token-type/agent',
157
+ * });
158
+ * ```
159
+ *
160
+ * Exchanges an external subject token for Auth0 tokens without affecting the current session.
161
+ *
162
+ * Unlike `loginWithCustomTokenExchange`, this method has no side effects — it does not cache
163
+ * tokens, does not update the authenticated session, and does not affect `isAuthenticated`
164
+ * or `user`. Use this for delegation or impersonation scenarios where you need a downstream
165
+ * API token without changing who the current user is.
166
+ *
167
+ * When `actor_token` is present Auth0 suppresses refresh token issuance; a missing
168
+ * `refresh_token` in the response is expected and will not cause an error.
169
+ *
170
+ * @param options - The options required to perform the token exchange.
171
+ * @returns A promise that resolves to the token endpoint response.
172
+ */
173
+ customTokenExchange: (
174
+ options: CustomTokenExchangeOptions
175
+ ) => Promise<TokenEndpointResponse>;
176
+
177
+ /**
178
+ * @deprecated Use `loginWithCustomTokenExchange()` instead. This method will be removed in the next major version.
179
+ *
180
+ * ```js
181
+ * const tokenResponse = await exchangeToken({
182
+ * subject_token: 'external_token_value',
183
+ * subject_token_type: 'urn:acme:legacy-system-token',
184
+ * scope: 'openid profile email'
185
+ * });
186
+ * ```
187
+ *
188
+ * Exchanges an external subject token for Auth0 tokens and logs the user in.
189
+ *
190
+ * This method implements the token exchange grant as specified in RFC 8693.
191
+ * It performs a token exchange by sending a request to the `/oauth/token` endpoint
192
+ * with the external token and returns Auth0 tokens (access token, ID token, etc.).
193
+ *
194
+ * **Example:**
195
+ * ```js
196
+ * // Instead of:
197
+ * const tokens = await exchangeToken(options);
198
+ *
199
+ * // Use:
200
+ * const tokens = await loginWithCustomTokenExchange(options);
201
+ * ```
202
+ *
203
+ * @param options - The options required to perform the token exchange
204
+ * @returns A promise that resolves to the token endpoint response containing Auth0 tokens
205
+ */
206
+ exchangeToken: (
207
+ options: CustomTokenExchangeOptions
208
+ ) => Promise<TokenEndpointResponse>;
209
+
210
+ /**
211
+ * ```js
212
+ * await loginWithRedirect(options);
213
+ * ```
214
+ *
215
+ * Performs a redirect to `/authorize` using the parameters
216
+ * provided as arguments. Random and secure `state` and `nonce`
217
+ * parameters will be auto-generated.
218
+ */
219
+ loginWithRedirect: (
220
+ options?: RedirectLoginOptions<AppState>
221
+ ) => Promise<void>;
222
+
223
+ /**
224
+ * ```js
225
+ * await loginWithPopup(options, config);
226
+ * ```
227
+ *
228
+ * Opens a popup with the `/authorize` URL using the parameters
229
+ * provided as arguments. Random and secure `state` and `nonce`
230
+ * parameters will be auto-generated. If the response is successful,
231
+ * results will be valid according to their expiration times.
232
+ *
233
+ * IMPORTANT: This method has to be called from an event handler
234
+ * that was started by the user like a button click, for example,
235
+ * otherwise the popup will be blocked in most browsers.
236
+ */
237
+ loginWithPopup: (
238
+ options?: PopupLoginOptions,
239
+ config?: PopupConfigOptions
240
+ ) => Promise<void>;
241
+
242
+ /**
243
+ * ```js
244
+ * await connectAccountWithRedirect({
245
+ * connection: 'google-oauth2',
246
+ * scopes: ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/drive.readonly'],
247
+ * authorization_params: {
248
+ * // additional authorization params to forward to the authorization server
249
+ * }
250
+ * });
251
+ * ```
252
+ *
253
+ * Redirects to the `/connect` URL using the parameters
254
+ * provided as arguments. This then redirects to the connection's login page
255
+ * where the user can authenticate and authorize the account to be connected.
256
+ *
257
+ * If connecting the account is successful `onRedirectCallback` will be called
258
+ * with the details of the connected account.
259
+ */
260
+ connectAccountWithRedirect: (
261
+ options: RedirectConnectAccountOptions
262
+ ) => Promise<void>;
263
+
264
+ /**
265
+ * ```js
266
+ * auth0.logout({ logoutParams: { returnTo: window.location.origin } });
267
+ * ```
268
+ *
269
+ * Clears the application session and performs a redirect to `/v2/logout`, using
270
+ * the parameters provided as arguments, to clear the Auth0 session.
271
+ * If the `logoutParams.federated` option is specified, it also clears the Identity Provider session.
272
+ * [Read more about how Logout works at Auth0](https://auth0.com/docs/logout).
273
+ */
274
+ logout: (options?: LogoutOptions) => Promise<void>;
275
+
276
+ /**
277
+ * After the browser redirects back to the callback page,
278
+ * call `handleRedirectCallback` to handle success and error
279
+ * responses from Auth0. If the response is successful, results
280
+ * will be valid according to their expiration times.
281
+ *
282
+ * @param url The URL to that should be used to retrieve the `state` and `code` values. Defaults to `window.location.href` if not given.
283
+ */
284
+ handleRedirectCallback: (url?: string) => Promise<RedirectLoginResult | ConnectAccountRedirectResult>;
285
+
286
+ /**
287
+ * Returns the current DPoP nonce used for making requests to Auth0.
288
+ *
289
+ * It can return `undefined` because when starting fresh it will not
290
+ * be populated until after the first response from the server.
291
+ *
292
+ * It requires enabling the {@link Auth0ClientOptions.useDpop} option.
293
+ *
294
+ * @param nonce The nonce value.
295
+ * @param id The identifier of a nonce: if absent, it will get the nonce
296
+ * used for requests to Auth0. Otherwise, it will be used to
297
+ * select a specific non-Auth0 nonce.
298
+ */
299
+ getDpopNonce: Auth0Client['getDpopNonce'];
300
+
301
+ /**
302
+ * Sets the current DPoP nonce used for making requests to Auth0.
303
+ *
304
+ * It requires enabling the {@link Auth0ClientOptions.useDpop} option.
305
+ *
306
+ * @param nonce The nonce value.
307
+ * @param id The identifier of a nonce: if absent, it will set the nonce
308
+ * used for requests to Auth0. Otherwise, it will be used to
309
+ * select a specific non-Auth0 nonce.
310
+ */
311
+ setDpopNonce: Auth0Client['setDpopNonce'];
312
+
313
+ /**
314
+ * Returns a string to be used to demonstrate possession of the private
315
+ * key used to cryptographically bind access tokens with DPoP.
316
+ *
317
+ * It requires enabling the {@link Auth0ClientOptions.useDpop} option.
318
+ */
319
+ generateDpopProof: Auth0Client['generateDpopProof'];
320
+
321
+ /**
322
+ * Returns a new `Fetcher` class that will contain a `fetchWithAuth()` method.
323
+ * This is a drop-in replacement for the Fetch API's `fetch()` method, but will
324
+ * handle certain authentication logic for you, like building the proper auth
325
+ * headers or managing DPoP nonces and retries automatically.
326
+ *
327
+ * Check the `EXAMPLES.md` file for a deeper look into this method.
328
+ */
329
+ createFetcher: Auth0Client['createFetcher'];
330
+
331
+ /**
332
+ * ```js
333
+ * const config = getConfiguration();
334
+ * // { domain: 'tenant.auth0.com', clientId: 'abc123' }
335
+ * ```
336
+ *
337
+ * Returns a readonly copy of the initialization configuration
338
+ * containing the domain and clientId.
339
+ */
340
+ getConfiguration: Auth0Client['getConfiguration'];
341
+
342
+ /**
343
+ * ```js
344
+ * const { mfa } = useAuth0();
345
+ * const authenticators = await mfa.getAuthenticators(mfaToken);
346
+ * ```
347
+ *
348
+ * MFA API client for Multi-Factor Authentication operations.
349
+ *
350
+ * Provides access to all MFA-related methods:
351
+ * - `getAuthenticators(mfaToken)` - List enrolled authenticators
352
+ * - `enroll(params)` - Enroll new authenticators (OTP, SMS, Voice, Email, Push)
353
+ * - `challenge(params)` - Initiate MFA challenges
354
+ * - `verify(params)` - Verify MFA challenges and complete authentication
355
+ * - `getEnrollmentFactors(mfaToken)` - Get available enrollment factors
356
+ *
357
+ * @example
358
+ * ```js
359
+ * const { mfa, getAccessTokenSilently } = useAuth0();
360
+ *
361
+ * try {
362
+ * await getAccessTokenSilently();
363
+ * } catch (error) {
364
+ * if (error.error === 'mfa_required') {
365
+ * // Check if enrollment is needed
366
+ * const factors = await mfa.getEnrollmentFactors(error.mfa_token);
367
+ *
368
+ * if (factors.length > 0) {
369
+ * // Enroll in OTP
370
+ * const enrollment = await mfa.enroll({
371
+ * mfaToken: error.mfa_token,
372
+ * factorType: 'otp'
373
+ * });
374
+ * console.log('QR Code:', enrollment.barcodeUri);
375
+ * }
376
+ *
377
+ * // Get authenticators and challenge
378
+ * const authenticators = await mfa.getAuthenticators(error.mfa_token);
379
+ * await mfa.challenge({
380
+ * mfaToken: error.mfa_token,
381
+ * challengeType: 'otp',
382
+ * authenticatorId: authenticators[0].id
383
+ * });
384
+ *
385
+ * // Verify with user's code
386
+ * const tokens = await mfa.verify({
387
+ * mfaToken: error.mfa_token,
388
+ * otp: userCode
389
+ * });
390
+ * }
391
+ * }
392
+ * ```
393
+ */
394
+ mfa: MfaApiClient;
395
+
396
+ /**
397
+ * ```js
398
+ * const { passkey } = useAuth0();
399
+ * const tokens = await passkey.signup({ email: 'user@example.com' });
400
+ * ```
401
+ *
402
+ * Passkey API client for WebAuthn-based passwordless authentication.
403
+ *
404
+ * - `signup(options)` — register a new user and create a passkey credential
405
+ * - `login(options?)` — authenticate an existing user via passkey assertion
406
+ *
407
+ * Both methods exchange the WebAuthn credential for Auth0 tokens and update
408
+ * `isAuthenticated` / `user` in the same way as `loginWithPopup`.
409
+ */
410
+ passkey: PasskeyApiClient;
411
+
412
+ /**
413
+ * ```js
414
+ * const { myAccount } = useAuth0();
415
+ * const factors = await myAccount.getFactors();
416
+ * ```
417
+ *
418
+ * MyAccount API client for self-service account management operations.
419
+ *
420
+ * Provides access to methods for managing the authenticated user's authentication
421
+ * methods and factors:
422
+ * - `getFactors()` - List available authentication factors
423
+ * - `getAuthenticationMethods(type?)` - List enrolled authentication methods, optionally filtered by type
424
+ * - `getAuthenticationMethod(id)` - Get a specific authentication method by ID
425
+ * - `updateAuthenticationMethod(id, data)` - Update an authentication method (e.g. rename)
426
+ * - `deleteAuthenticationMethod(id)` - Remove an enrolled authentication method
427
+ * - `enrollmentChallenge(options)` - Initiate a two-step enrollment challenge
428
+ * - `enrollmentVerify(options)` - Complete a two-step enrollment by verifying the challenge
429
+ *
430
+ * @example
431
+ * ```js
432
+ * const { myAccount } = useAuth0();
433
+ *
434
+ * // List all enrolled authentication methods
435
+ * const methods = await myAccount.getAuthenticationMethods();
436
+ *
437
+ * // Enroll a new passkey
438
+ * const challenge = await myAccount.enrollmentChallenge({ type: 'passkey' });
439
+ * const credential = await navigator.credentials.create({ publicKey: challenge.authn_params_public_key });
440
+ * await myAccount.enrollmentVerify({ type: 'passkey', auth_session: challenge.auth_session, location: challenge.location, authn_response: credential });
441
+ *
442
+ * // Remove an authentication method
443
+ * await myAccount.deleteAuthenticationMethod('method-id');
444
+ * ```
445
+ */
446
+ myAccount: MyAccountApiClient;
447
+ }
448
+
449
+ /**
450
+ * @ignore
451
+ */
452
+ const stub = (): never => {
453
+ throw new Error('You forgot to wrap your component in <Auth0Provider>.');
454
+ };
455
+
456
+ /**
457
+ * @ignore
458
+ */
459
+ export const initialContext = {
460
+ ...initialAuthState,
461
+ buildAuthorizeUrl: stub,
462
+ buildLogoutUrl: stub,
463
+ getAccessTokenSilently: stub,
464
+ getAccessTokenWithPopup: stub,
465
+ getIdTokenClaims: stub,
466
+ loginWithCustomTokenExchange: stub,
467
+ customTokenExchange: stub,
468
+ exchangeToken: stub,
469
+ loginWithRedirect: stub,
470
+ loginWithPopup: stub,
471
+ connectAccountWithRedirect: stub,
472
+ logout: stub,
473
+ handleRedirectCallback: stub,
474
+ getDpopNonce: stub,
475
+ setDpopNonce: stub,
476
+ generateDpopProof: stub,
477
+ createFetcher: stub,
478
+ getConfiguration: stub,
479
+ mfa: {
480
+ getAuthenticators: stub,
481
+ enroll: stub,
482
+ challenge: stub,
483
+ verify: stub,
484
+ getEnrollmentFactors: stub,
485
+ } as unknown as MfaApiClient,
486
+ passkey: {
487
+ signup: stub,
488
+ login: stub,
489
+ } as unknown as PasskeyApiClient,
490
+ myAccount: {
491
+ getFactors: stub,
492
+ getAuthenticationMethods: stub,
493
+ getAuthenticationMethod: stub,
494
+ updateAuthenticationMethod: stub,
495
+ deleteAuthenticationMethod: stub,
496
+ enrollmentChallenge: stub,
497
+ enrollmentVerify: stub,
498
+ } as unknown as MyAccountApiClient,
499
+ };
500
+
501
+ /**
502
+ * The Auth0 Context
503
+ */
504
+ const Auth0Context = createContext<Auth0ContextInterface>(initialContext);
505
+
506
+ export default Auth0Context;