@versini/auth0-react-thin 2.22.1 → 2.24.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.
@@ -4,6 +4,25 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.reactAuth0 = {}, global.React));
5
5
  })(this, (function (exports, React) { 'use strict';
6
6
 
7
+ function _interopNamespaceDefault(e) {
8
+ var n = Object.create(null);
9
+ if (e) {
10
+ Object.keys(e).forEach(function (k) {
11
+ if (k !== 'default') {
12
+ var d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: function () { return e[k]; }
16
+ });
17
+ }
18
+ });
19
+ }
20
+ n.default = e;
21
+ return Object.freeze(n);
22
+ }
23
+
24
+ var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
25
+
7
26
  /******************************************************************************
8
27
  Copyright (c) Microsoft Corporation.
9
28
 
@@ -258,7 +277,7 @@
258
277
  deprecateRedirectUri(opts);
259
278
  return __assign(__assign({}, opts), { auth0Client: {
260
279
  name: 'auth0-react',
261
- version: '2.22.1',
280
+ version: '2.24.0',
262
281
  } });
263
282
  };
264
283
  /**
@@ -268,6 +287,22 @@
268
287
  var _a;
269
288
  window.history.replaceState({}, document.title, (_a = appState.returnTo) !== null && _a !== void 0 ? _a : window.location.pathname);
270
289
  };
290
+ /**
291
+ * @ignore
292
+ */
293
+ var createInitDeferred = function () {
294
+ var resolve;
295
+ var reject;
296
+ var promise = new Promise(function (res, rej) {
297
+ resolve = res;
298
+ reject = rej;
299
+ });
300
+ // Avoid unhandled-rejection warnings when no one is consuming the promise
301
+ // (i.e. useAuth0Suspense is not used). useAuth0Suspense attaches its own
302
+ // handler via use().
303
+ promise.catch(function () { return undefined; });
304
+ return { promise: promise, resolve: resolve, reject: reject };
305
+ };
271
306
  /**
272
307
  * ```jsx
273
308
  * <Auth0Provider
@@ -279,6 +314,11 @@
279
314
  * ```
280
315
  *
281
316
  * Provides the Auth0Context to its child components.
317
+ *
318
+ * The SDK is a client-only module (its published ESM and CommonJS bundles ship the
319
+ * `'use client'` directive), so in a Next.js App Router app you can import and render
320
+ * `Auth0Provider` directly from a Server Component such as `app/layout.tsx`.
321
+ * Components that call hooks like `useAuth0` must still be Client Components.
282
322
  */
283
323
  var Auth0Provider = function (opts) {
284
324
  var _a = opts, children = _a.children, skipRedirectCallback = _a.skipRedirectCallback, _b = _a.onRedirectCallback, onRedirectCallback = _b === void 0 ? defaultOnRedirectCallback : _b, _c = _a.context, context = _c === void 0 ? Auth0Context : _c, providedClient = _a.client, clientOpts = __rest(_a, ["children", "skipRedirectCallback", "onRedirectCallback", "context", "client"]);
@@ -289,55 +329,94 @@
289
329
  }
290
330
  var client = React.useState(function () { return providedClient !== null && providedClient !== void 0 ? providedClient : new fc(toAuth0ClientOptions(clientOpts)); })[0];
291
331
  var _d = React.useReducer((reducer), initialAuthState), state = _d[0], dispatch = _d[1];
332
+ // In state so the init retry below can swap in a fresh, non-rejected promise.
333
+ // Without that swap the first rejection would re-throw on every later render,
334
+ // making Error Boundary retries useless.
335
+ var _e = React.useState(createInitDeferred), initDeferred = _e[0], setInitDeferred = _e[1];
336
+ // Set only once initialization has genuinely rejected. State, not a ref, so
337
+ // the retry effect re-evaluates when init fails *after* the app has become
338
+ // authenticated by some other means.
339
+ var _f = React.useState(false), initFailed = _f[0], setInitFailed = _f[1];
340
+ // Guards against retrying more than once: a retry that also fails would
341
+ // otherwise re-trigger the effect for as long as the user stays signed in.
342
+ var initRetried = React.useRef(false);
292
343
  var didInitialise = React.useRef(false);
293
344
  var handleError = React.useCallback(function (error) {
294
345
  dispatch({ type: 'ERROR', error: error });
295
346
  return error;
296
347
  }, []);
348
+ // Settles `deferred` according to what initialization actually did, so
349
+ // `_initPromise` never claims success that did not happen. `allowRedirect`
350
+ // is false on a retry: the redirect callback is single-use, so a retry can
351
+ // only re-verify the session.
352
+ var runInit = React.useCallback(function (deferred, allowRedirect) { return __awaiter(void 0, void 0, void 0, function () {
353
+ var user, _a, _b, appState, response_type, result, error_1, err;
354
+ return __generator(this, function (_c) {
355
+ switch (_c.label) {
356
+ case 0:
357
+ _c.trys.push([0, 7, , 8]);
358
+ user = void 0;
359
+ if (!(allowRedirect && hasAuthParams() && !skipRedirectCallback)) return [3 /*break*/, 3];
360
+ return [4 /*yield*/, client.handleRedirectCallback()];
361
+ case 1:
362
+ _a = _c.sent(), _b = _a.appState, appState = _b === void 0 ? {} : _b, response_type = _a.response_type, result = __rest(_a, ["appState", "response_type"]);
363
+ return [4 /*yield*/, client.getUser()];
364
+ case 2:
365
+ user = _c.sent();
366
+ appState.response_type = response_type;
367
+ if (response_type === exports.ResponseType.ConnectCode) {
368
+ appState.connectedAccount = result;
369
+ }
370
+ onRedirectCallback(appState, user);
371
+ return [3 /*break*/, 6];
372
+ case 3: return [4 /*yield*/, client.checkSession()];
373
+ case 4:
374
+ _c.sent();
375
+ return [4 /*yield*/, client.getUser()];
376
+ case 5:
377
+ user = _c.sent();
378
+ _c.label = 6;
379
+ case 6:
380
+ dispatch({ type: 'INITIALISED', user: user });
381
+ deferred.resolve();
382
+ return [3 /*break*/, 8];
383
+ case 7:
384
+ error_1 = _c.sent();
385
+ err = loginError(error_1);
386
+ handleError(err);
387
+ setInitFailed(true);
388
+ deferred.reject(err);
389
+ return [3 /*break*/, 8];
390
+ case 8: return [2 /*return*/];
391
+ }
392
+ });
393
+ }); }, [client, onRedirectCallback, skipRedirectCallback, handleError]);
297
394
  React.useEffect(function () {
298
395
  if (didInitialise.current) {
299
396
  return;
300
397
  }
301
398
  didInitialise.current = true;
302
- (function () { return __awaiter(void 0, void 0, void 0, function () {
303
- var user, _a, _b, appState, response_type, result, error_1;
304
- return __generator(this, function (_c) {
305
- switch (_c.label) {
306
- case 0:
307
- _c.trys.push([0, 7, , 8]);
308
- user = void 0;
309
- if (!(hasAuthParams() && !skipRedirectCallback)) return [3 /*break*/, 3];
310
- return [4 /*yield*/, client.handleRedirectCallback()];
311
- case 1:
312
- _a = _c.sent(), _b = _a.appState, appState = _b === void 0 ? {} : _b, response_type = _a.response_type, result = __rest(_a, ["appState", "response_type"]);
313
- return [4 /*yield*/, client.getUser()];
314
- case 2:
315
- user = _c.sent();
316
- appState.response_type = response_type;
317
- if (response_type === exports.ResponseType.ConnectCode) {
318
- appState.connectedAccount = result;
319
- }
320
- onRedirectCallback(appState, user);
321
- return [3 /*break*/, 6];
322
- case 3: return [4 /*yield*/, client.checkSession()];
323
- case 4:
324
- _c.sent();
325
- return [4 /*yield*/, client.getUser()];
326
- case 5:
327
- user = _c.sent();
328
- _c.label = 6;
329
- case 6:
330
- dispatch({ type: 'INITIALISED', user: user });
331
- return [3 /*break*/, 8];
332
- case 7:
333
- error_1 = _c.sent();
334
- handleError(loginError(error_1));
335
- return [3 /*break*/, 8];
336
- case 8: return [2 /*return*/];
337
- }
338
- });
339
- }); })();
340
- }, [client, onRedirectCallback, skipRedirectCallback, handleError]);
399
+ // Always the first deferred: `didInitialise` means this only ever runs once,
400
+ // so a later swap by the retry effect re-runs this effect but returns above.
401
+ void runInit(initDeferred, true);
402
+ }, [runInit, initDeferred]);
403
+ // A rejected promise stays rejected forever, so React.use() would re-throw on
404
+ // every later render and an Error Boundary retry could never recover. Once
405
+ // init has failed but the app has since become authenticated by some other
406
+ // means (loginWithPopup, a silent token, a passkey login), re-run the session
407
+ // check against a fresh deferred. The promise then reflects a real
408
+ // checkSession() outcome rather than an assumption that things are fine --
409
+ // if the session is still bad it rejects again and the boundary keeps showing
410
+ // the error.
411
+ React.useEffect(function () {
412
+ if (!initFailed || initRetried.current || !state.isAuthenticated) {
413
+ return;
414
+ }
415
+ initRetried.current = true;
416
+ var retry = createInitDeferred();
417
+ setInitDeferred(retry);
418
+ void runInit(retry, false);
419
+ }, [initFailed, state.isAuthenticated, runInit]);
341
420
  var loginWithRedirect = React.useCallback(function (opts) {
342
421
  deprecateRedirectUri(opts);
343
422
  return client.loginWithRedirect(opts);
@@ -621,7 +700,7 @@
621
700
  }); }, [client]);
622
701
  var passkey = React.useMemo(function () { return ({ signup: passkeySignup, login: passkeyLogin }); }, [passkeySignup, passkeyLogin]);
623
702
  var contextValue = React.useMemo(function () {
624
- return __assign(__assign({}, state), { getAccessTokenSilently: getAccessTokenSilently, getAccessTokenWithPopup: getAccessTokenWithPopup, getIdTokenClaims: getIdTokenClaims, loginWithCustomTokenExchange: loginWithCustomTokenExchange, customTokenExchange: customTokenExchange, exchangeToken: exchangeToken, loginWithRedirect: loginWithRedirect, loginWithPopup: loginWithPopup, connectAccountWithRedirect: connectAccountWithRedirect, logout: logout, revokeRefreshToken: revokeRefreshToken, handleRedirectCallback: handleRedirectCallback, getDpopNonce: getDpopNonce, setDpopNonce: setDpopNonce, generateDpopProof: generateDpopProof, createFetcher: createFetcher, getConfiguration: getConfiguration, mfa: mfa, passkey: passkey, myAccount: myAccount });
703
+ return __assign(__assign({}, state), { getAccessTokenSilently: getAccessTokenSilently, getAccessTokenWithPopup: getAccessTokenWithPopup, getIdTokenClaims: getIdTokenClaims, loginWithCustomTokenExchange: loginWithCustomTokenExchange, customTokenExchange: customTokenExchange, exchangeToken: exchangeToken, loginWithRedirect: loginWithRedirect, loginWithPopup: loginWithPopup, connectAccountWithRedirect: connectAccountWithRedirect, logout: logout, revokeRefreshToken: revokeRefreshToken, handleRedirectCallback: handleRedirectCallback, getDpopNonce: getDpopNonce, setDpopNonce: setDpopNonce, generateDpopProof: generateDpopProof, createFetcher: createFetcher, getConfiguration: getConfiguration, mfa: mfa, passkey: passkey, myAccount: myAccount, _initPromise: initDeferred.promise });
625
704
  }, [
626
705
  state,
627
706
  getAccessTokenSilently,
@@ -644,6 +723,7 @@
644
723
  mfa,
645
724
  passkey,
646
725
  myAccount,
726
+ initDeferred,
647
727
  ]);
648
728
  return React.createElement(context.Provider, { value: contextValue }, children);
649
729
  };
@@ -677,6 +757,50 @@
677
757
  return React.useContext(context);
678
758
  };
679
759
 
760
+ /**
761
+ * ```jsx
762
+ * <Suspense fallback={<Spinner />}>
763
+ * <Profile />
764
+ * </Suspense>
765
+ *
766
+ * function Profile() {
767
+ * const { user, isAuthenticated } = useAuth0Suspense();
768
+ * return isAuthenticated ? <p>Hello {user.name}</p> : <p>Please log in</p>;
769
+ * }
770
+ * ```
771
+ *
772
+ * Suspense-enabled variant of `useAuth0`. Suspends the component until Auth0
773
+ * initialization completes (letting the nearest `<Suspense>` fallback render),
774
+ * and throws initialization errors so the nearest Error Boundary can handle
775
+ * them. Requires React 19 or later.
776
+ *
777
+ * If initialization fails and the app later becomes authenticated by other
778
+ * means, the session is re-checked once; retrying the Error Boundary then
779
+ * renders if that check succeeded, or throws again if it did not.
780
+ *
781
+ * TUser is an optional type param to provide a type to the `user` field.
782
+ */
783
+ var useAuth0Suspense = function (context) {
784
+ if (context === void 0) { context = Auth0Context; }
785
+ if (typeof React__namespace.use !== 'function') {
786
+ throw new Error('useAuth0Suspense requires React 19 or later (React.use is unavailable).');
787
+ }
788
+ var ctx = React__namespace.useContext(context);
789
+ if (!ctx._initPromise) {
790
+ throw new Error('useAuth0Suspense must be used within an <Auth0Provider>.');
791
+ }
792
+ // Suspends until the init promise resolves; re-throws if it rejected.
793
+ React__namespace.use(ctx._initPromise);
794
+ // Memoized so the returned object is referentially stable across renders,
795
+ // matching useAuth0, which hands back the provider's memoized context.
796
+ // Without this, `useEffect(..., [auth])` in a consumer re-runs every render.
797
+ return React__namespace.useMemo(function () {
798
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
799
+ ctx.isLoading; ctx._initPromise; var rest = __rest(ctx, ["isLoading", "_initPromise"]);
800
+ return rest;
801
+ }, [ctx]);
802
+ };
803
+
680
804
  /**
681
805
  * ```jsx
682
806
  * class MyComponent extends Component {
@@ -716,7 +840,12 @@
716
840
  * @ignore
717
841
  */
718
842
  var defaultReturnTo = function () {
719
- return "".concat(window.location.pathname).concat(window.location.search);
843
+ // Normalize the pathname to prevent protocol-relative open redirects.
844
+ // A URL like https://app.example.com//evil.com produces a pathname of
845
+ // //evil.com, which routers (react-router, next.js, gatsby) interpret as a
846
+ // protocol-relative URL and redirect the user to an external host.
847
+ var pathname = window.location.pathname.replace(/^\/\/+/, '/');
848
+ return "".concat(pathname).concat(window.location.search);
720
849
  };
721
850
  /**
722
851
  * ```js
@@ -794,6 +923,7 @@
794
923
  exports.User = ct;
795
924
  exports.initialContext = initialContext;
796
925
  exports.useAuth0 = useAuth0;
926
+ exports.useAuth0Suspense = useAuth0Suspense;
797
927
  exports.withAuth0 = withAuth0;
798
928
  exports.withAuthenticationRequired = withAuthenticationRequired;
799
929