@usehercules/auth 1.2.0 → 1.2.2
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/dist/convex-react/index.d.mts +1 -8
- package/dist/convex-react/index.d.mts.map +1 -1
- package/dist/convex-react/index.mjs +5 -6
- package/dist/convex-react/index.mjs.map +1 -1
- package/dist/react/index.d.mts +25 -45
- package/dist/react/index.d.mts.map +1 -1
- package/dist/react/index.mjs +168 -31
- package/dist/react/index.mjs.map +1 -1
- package/dist/{refresh-lock-Cv63qcNd.mjs → refresh-lock-RJUGj8im.mjs} +2 -3
- package/dist/{refresh-lock-Cv63qcNd.mjs.map → refresh-lock-RJUGj8im.mjs.map} +1 -1
- package/package.json +13 -13
- package/src/convex-react/ConvexProviderWithHercules.tsx +1 -2
- package/src/internal/user-manager.test.tsx +487 -0
- package/src/internal/user-manager.ts +70 -0
- package/src/react/HerculesAuthProvider.storage.test.tsx +66 -0
- package/src/react/HerculesAuthProvider.test.tsx +50 -1
- package/src/react/HerculesAuthProvider.tsx +94 -21
- package/src/react/auth-callback-hook.test.tsx +156 -0
- package/src/react/auth-callback-hook.tsx +38 -4
|
@@ -1,14 +1,7 @@
|
|
|
1
1
|
import { ReactNode } from "react";
|
|
2
2
|
import { ConvexReactClient } from "convex/react";
|
|
3
|
-
|
|
4
|
-
//#region src/convex-react/ConvexProviderWithHercules.d.ts
|
|
5
|
-
declare function ConvexProviderWithHerculesAuth({
|
|
6
|
-
children,
|
|
7
|
-
client
|
|
8
|
-
}: {
|
|
3
|
+
export declare function ConvexProviderWithHerculesAuth({ children, client }: {
|
|
9
4
|
children: ReactNode;
|
|
10
5
|
client: ConvexReactClient;
|
|
11
6
|
}): import("react").JSX.Element;
|
|
12
|
-
//#endregion
|
|
13
|
-
export { ConvexProviderWithHerculesAuth };
|
|
14
7
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"mappings":";;wBAoFgB,iCACd,UACA;EAEA,UAAU;EACV,QAAQ;oBACT,IAAA"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { t as withRefreshLock } from "../refresh-lock-
|
|
1
|
+
import { t as withRefreshLock } from "../refresh-lock-RJUGj8im.mjs";
|
|
2
2
|
import { useCallback, useMemo, useRef } from "react";
|
|
3
3
|
import { useAuth } from "react-oidc-context";
|
|
4
|
+
import { jwtDecode } from "jwt-decode";
|
|
4
5
|
import { jsx } from "react/jsx-runtime";
|
|
5
6
|
import { ConvexProviderWithAuth } from "convex/react";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const REFRESH_THRESHOLD_MS = 3600 * 1e3;
|
|
7
|
+
// src/convex-react/ConvexProviderWithHercules.tsx
|
|
8
|
+
const REFRESH_THRESHOLD_MS = 36e5;
|
|
9
9
|
function tokenExpiresWithin(token, ms) {
|
|
10
10
|
try {
|
|
11
11
|
return jwtDecode(token).exp * 1e3 - Date.now() < ms;
|
|
@@ -56,7 +56,7 @@ function useUseAuthFromHercules() {
|
|
|
56
56
|
* A wrapper React component which provides a {@link ConvexReactClient}
|
|
57
57
|
* authenticated with Hercules Auth.
|
|
58
58
|
*
|
|
59
|
-
* It must be wrapped by a configured `
|
|
59
|
+
* It must be wrapped by a configured `HerculesAuthProvider`.
|
|
60
60
|
*
|
|
61
61
|
* @public
|
|
62
62
|
*/
|
|
@@ -67,7 +67,6 @@ function ConvexProviderWithHerculesAuth({ children, client }) {
|
|
|
67
67
|
children
|
|
68
68
|
});
|
|
69
69
|
}
|
|
70
|
-
//#endregion
|
|
71
70
|
export { ConvexProviderWithHerculesAuth };
|
|
72
71
|
|
|
73
72
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { ConvexProviderWithAuth, type ConvexReactClient } from \"convex/react\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { useCallback, useMemo, useRef } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { ConvexProviderWithAuth, type ConvexReactClient } from \"convex/react\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { useCallback, useMemo, useRef } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\n\nconst REFRESH_THRESHOLD_MS = 60 * 60 * 1000; // 1 hour\n\nfunction tokenExpiresWithin(token: string, ms: number): boolean {\n try {\n const payload = jwtDecode(token);\n return payload.exp! * 1000 - Date.now() < ms;\n } catch {\n return true;\n }\n}\n\nfunction useUseAuthFromHercules() {\n const { isAuthenticated, user, isLoading, signinSilent } = useAuth();\n const idToken = user?.id_token;\n const issuer = user?.profile?.iss;\n const subject = user?.profile?.sub;\n\n const idTokenRef = useRef(idToken);\n idTokenRef.current = idToken;\n\n const signinSilentRef = useRef(signinSilent);\n signinSilentRef.current = signinSilent;\n\n const inFlightRefresh = useRef<Promise<string | null> | null>(null);\n\n const fetchAccessToken = useCallback(\n async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {\n const currentToken = idTokenRef.current;\n if (!forceRefreshToken) {\n return currentToken ?? null;\n }\n if (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) {\n return currentToken;\n }\n if (inFlightRefresh.current) {\n return inFlightRefresh.current;\n }\n const refresh = withRefreshLock(async () => {\n const tokenAfterLock = idTokenRef.current;\n if (tokenAfterLock != null && !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)) {\n return tokenAfterLock;\n }\n try {\n const refreshed = await signinSilentRef.current();\n return refreshed?.id_token ?? null;\n } catch {\n return null;\n }\n }).finally(() => {\n inFlightRefresh.current = null;\n });\n inFlightRefresh.current = refresh;\n return refresh;\n },\n [issuer, subject],\n );\n\n return useMemo(\n () => ({\n isLoading: isAuthenticated ? false : isLoading,\n isAuthenticated,\n fetchAccessToken,\n }),\n [isLoading, isAuthenticated, fetchAccessToken],\n );\n}\n\n/**\n * A wrapper React component which provides a {@link ConvexReactClient}\n * authenticated with Hercules Auth.\n *\n * It must be wrapped by a configured `HerculesAuthProvider`.\n *\n * @public\n */\nexport function ConvexProviderWithHerculesAuth({\n children,\n client,\n}: {\n children: ReactNode;\n client: ConvexReactClient;\n}) {\n return (\n <ConvexProviderWithAuth client={client} useAuth={useUseAuthFromHercules}>\n {children}\n </ConvexProviderWithAuth>\n );\n}\n"],"mappings":";;;;;;;AASA,MAAM,uBAAuB;AAE7B,SAAS,mBAAmB,OAAe,IAAqB;CAC9D,IAAI;EAEF,OADgB,UAAU,KACb,CAAC,CAAC,MAAO,MAAO,KAAK,IAAI,IAAI;CAC5C,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,yBAAyB;CAChC,MAAM,EAAE,iBAAiB,MAAM,WAAW,iBAAiB,QAAQ;CACnE,MAAM,UAAU,MAAM;CACtB,MAAM,SAAS,MAAM,SAAS;CAC9B,MAAM,UAAU,MAAM,SAAS;CAE/B,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CAErB,MAAM,kBAAkB,OAAO,YAAY;CAC3C,gBAAgB,UAAU;CAE1B,MAAM,kBAAkB,OAAsC,IAAI;CAElE,MAAM,mBAAmB,YACvB,OAAO,EAAE,wBAAwD;EAC/D,MAAM,eAAe,WAAW;EAChC,IAAI,CAAC,mBACH,OAAO,gBAAgB;EAEzB,IAAI,gBAAgB,QAAQ,CAAC,mBAAmB,cAAc,oBAAoB,GAChF,OAAO;EAET,IAAI,gBAAgB,SAClB,OAAO,gBAAgB;EAEzB,MAAM,UAAU,gBAAgB,YAAY;GAC1C,MAAM,iBAAiB,WAAW;GAClC,IAAI,kBAAkB,QAAQ,CAAC,mBAAmB,gBAAgB,oBAAoB,GACpF,OAAO;GAET,IAAI;IAEF,QAAO,MADiB,gBAAgB,QAAQ,EAAA,EAC9B,YAAY;GAChC,QAAQ;IACN,OAAO;GACT;EACF,CAAC,CAAC,CAAC,cAAc;GACf,gBAAgB,UAAU;EAC5B,CAAC;EACD,gBAAgB,UAAU;EAC1B,OAAO;CACT,GACA,CAAC,QAAQ,OAAO,CAClB;CAEA,OAAO,eACE;EACL,WAAW,kBAAkB,QAAQ;EACrC;EACA;CACF,IACA;EAAC;EAAW;EAAiB;CAAgB,CAC/C;AACF;;;;;;;;;AAUA,SAAgB,+BAA+B,EAC7C,UACA,UAIC;CACD,OACE,oBAAC,wBAAD;EAAgC;EAAQ,SAAS;EAC9C;CACqB,CAAA;AAE5B"}
|
package/dist/react/index.d.mts
CHANGED
|
@@ -1,17 +1,15 @@
|
|
|
1
1
|
import { ReactNode } from "react";
|
|
2
2
|
import { AuthContextProps as AuthContextProps$1, AuthProviderUserManagerProps, hasAuthParams } from "react-oidc-context";
|
|
3
3
|
import { UserManager, UserManagerSettings } from "oidc-client-ts";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
type AuthCallbackStatus = "processing-oauth" | "waiting-backend" | "syncing" | "success" | "error";
|
|
7
|
-
interface UseAuthCallbackOptions {
|
|
4
|
+
export type AuthCallbackStatus = "processing-oauth" | "waiting-backend" | "syncing" | "success" | "error";
|
|
5
|
+
export interface UseAuthCallbackOptions {
|
|
8
6
|
timeoutMs?: number;
|
|
9
7
|
isBackendAuthenticated?: boolean;
|
|
10
8
|
onSync?: () => Promise<void>;
|
|
11
9
|
onSuccess?: () => void;
|
|
12
10
|
onNoAuthParams?: () => void;
|
|
13
11
|
}
|
|
14
|
-
interface UseAuthCallbackResult {
|
|
12
|
+
export interface UseAuthCallbackResult {
|
|
15
13
|
status: AuthCallbackStatus;
|
|
16
14
|
error: string | null;
|
|
17
15
|
isLoading: boolean;
|
|
@@ -19,10 +17,8 @@ interface UseAuthCallbackResult {
|
|
|
19
17
|
isError: boolean;
|
|
20
18
|
retry: () => Promise<void>;
|
|
21
19
|
}
|
|
22
|
-
declare function useAuthCallback(options?: UseAuthCallbackOptions): UseAuthCallbackResult;
|
|
23
|
-
|
|
24
|
-
//#region src/react/HerculesAuthProvider.d.ts
|
|
25
|
-
type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
|
|
20
|
+
export declare function useAuthCallback(options?: UseAuthCallbackOptions): UseAuthCallbackResult;
|
|
21
|
+
export type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
|
|
26
22
|
userManagerSettings?: Partial<UserManagerSettings>;
|
|
27
23
|
authority: string;
|
|
28
24
|
client_id: string;
|
|
@@ -33,40 +29,20 @@ interface HerculesAuthProviderContext {
|
|
|
33
29
|
impersonationStorageKey: string;
|
|
34
30
|
}
|
|
35
31
|
declare const HerculesAuthProviderContext: import("react").Context<HerculesAuthProviderContext | null>;
|
|
36
|
-
declare function useHerculesAuthProvider(): HerculesAuthProviderContext;
|
|
37
|
-
declare function HerculesAuthProvider({
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
...props
|
|
44
|
-
}: HerculesAuthProviderProps): import("react").JSX.Element;
|
|
45
|
-
//#endregion
|
|
46
|
-
//#region src/react/impersonation-core.d.ts
|
|
47
|
-
declare const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
|
|
48
|
-
declare const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
|
|
49
|
-
declare function getHerculesImpersonationStorageKey(authority: string, clientId: string): string;
|
|
50
|
-
declare function rememberHerculesImpersonationSession(storageKey: string, sessionId: string): void;
|
|
51
|
-
//#endregion
|
|
52
|
-
//#region src/react/impersonation.d.ts
|
|
53
|
-
type HerculesImpersonationState = {
|
|
32
|
+
export declare function useHerculesAuthProvider(): HerculesAuthProviderContext;
|
|
33
|
+
export declare function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, loadingFallback, ...props }: HerculesAuthProviderProps): import("react").JSX.Element;
|
|
34
|
+
export declare const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
|
|
35
|
+
export declare const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
|
|
36
|
+
export declare function getHerculesImpersonationStorageKey(authority: string, clientId: string): string;
|
|
37
|
+
export declare function rememberHerculesImpersonationSession(storageKey: string, sessionId: string): void;
|
|
38
|
+
export type HerculesImpersonationState = {
|
|
54
39
|
isImpersonating: boolean;
|
|
55
40
|
sessionId: string | null;
|
|
56
41
|
actorSub: string | null;
|
|
57
42
|
stopImpersonating: () => Promise<void>;
|
|
58
43
|
};
|
|
59
|
-
declare function useHerculesImpersonation(): HerculesImpersonationState;
|
|
60
|
-
|
|
61
|
-
//#region src/react/use-user.d.ts
|
|
62
|
-
declare function useUser(): {
|
|
63
|
-
id: string | undefined;
|
|
64
|
-
name: string | undefined;
|
|
65
|
-
email: string | undefined;
|
|
66
|
-
avatar: string | undefined;
|
|
67
|
-
isAuthenticated: boolean;
|
|
68
|
-
isLoading: boolean;
|
|
69
|
-
error: import("react-oidc-context").ErrorContext | undefined;
|
|
44
|
+
export declare function useHerculesImpersonation(): HerculesImpersonationState;
|
|
45
|
+
export declare function useUser(): {
|
|
70
46
|
id_token?: string;
|
|
71
47
|
session_state?: string | null | undefined;
|
|
72
48
|
access_token?: string | undefined;
|
|
@@ -77,17 +53,21 @@ declare function useUser(): {
|
|
|
77
53
|
expires_at?: number;
|
|
78
54
|
state?: unknown;
|
|
79
55
|
url_state?: string;
|
|
56
|
+
id: string | undefined;
|
|
57
|
+
name: string | undefined;
|
|
58
|
+
email: string | undefined;
|
|
59
|
+
avatar: string | undefined;
|
|
60
|
+
isAuthenticated: boolean;
|
|
61
|
+
isLoading: boolean;
|
|
62
|
+
error: import("react-oidc-context").ErrorContext | undefined;
|
|
80
63
|
};
|
|
81
|
-
|
|
82
|
-
//#region src/react/use-auth.d.ts
|
|
83
|
-
interface SigninOptions {
|
|
64
|
+
export interface SigninOptions {
|
|
84
65
|
returnTo?: string;
|
|
85
66
|
}
|
|
86
|
-
interface AuthContextProps extends AuthContextProps$1 {
|
|
67
|
+
export interface AuthContextProps extends AuthContextProps$1 {
|
|
87
68
|
signout: () => Promise<void>;
|
|
88
69
|
signin: (options?: SigninOptions) => Promise<void>;
|
|
89
70
|
}
|
|
90
|
-
declare function useAuth(): AuthContextProps;
|
|
91
|
-
|
|
92
|
-
export { AuthCallbackStatus, AuthContextProps, HERCULES_IMPERSONATION_SESSION_ID_PARAM, HERCULES_IMPERSONATION_TOKEN_PARAM, HerculesAuthProvider, HerculesAuthProviderProps, HerculesImpersonationState, SigninOptions, UseAuthCallbackOptions, UseAuthCallbackResult, getHerculesImpersonationStorageKey, hasAuthParams, rememberHerculesImpersonationSession, useAuth, useAuthCallback, useHerculesAuthProvider, useHerculesImpersonation, useUser };
|
|
71
|
+
export declare function useAuth(): AuthContextProps;
|
|
72
|
+
export { hasAuthParams };
|
|
93
73
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/impersonation-core.ts","../../src/react/impersonation.ts","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["OidcAuthContextProps"],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/impersonation-core.ts","../../src/react/impersonation.ts","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"mappings":";;;YAyCY;iBAWK;EAMf;EAMA;EAOA,eAAe;EAMf;EAOA;;iBAOe;EAEf,QAAQ;EAGR;EAGA;EAGA;EAGA;EAGA,aAAa;;wBAoCC,gBAAgB,UAAS,yBAA8B;YCrH3D,4BAA4B,KAAK;EAC3C,sBAAsB,QAAQ;EAC9B;EACA;EACA,kBAAkB;;UAgBV;EACR,aAAa;EACb;;cAGI,6CAA2B,QAAA;wBAEjB,2BAAuB;wBAgIvB,uBACd,UACA,qBACA,WACA,WACA,oBACG,SACF,4CAAyB,IAAA;qBC3Lf;qBACA;wBAOG,mCAAmC,mBAAmB;wBAItD,qCAAqC,oBAAoB;YCE7D;EACV;EACA;EACA;EACA,yBAAyB;;wBAGX,4BAA4B;wBCb5B;;;;;;;;;;;;;;;;;;;iBCHC;EAOf;;iBAGe,yBAAyBA;EACxC,eAAe;EACf,SAAS,UAAU,kBAAkB;;wBAGvB,WAAW"}
|
package/dist/react/index.mjs
CHANGED
|
@@ -1,13 +1,32 @@
|
|
|
1
|
-
import { t as withRefreshLock } from "../refresh-lock-
|
|
1
|
+
import { t as withRefreshLock } from "../refresh-lock-RJUGj8im.mjs";
|
|
2
2
|
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
3
3
|
import { AuthProvider, hasAuthParams, hasAuthParams as hasAuthParams$1, useAuth as useAuth$1 } from "react-oidc-context";
|
|
4
4
|
import { ConvexError } from "convex/values";
|
|
5
5
|
import * as z from "zod";
|
|
6
|
-
import { UserManager, WebStorageStateStore } from "oidc-client-ts";
|
|
6
|
+
import { InMemoryWebStorage, UserManager, WebStorageStateStore } from "oidc-client-ts";
|
|
7
|
+
import { jwtDecode } from "jwt-decode";
|
|
7
8
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
8
|
-
|
|
9
|
+
// src/react/auth-callback-hook.tsx
|
|
9
10
|
const DEFAULT_TIMEOUT_MS = 2e4;
|
|
11
|
+
const MIN_TIMEOUT_AFTER_TOKENS_MS = 6e4;
|
|
12
|
+
const MISSING_STATE_MESSAGE = "No matching state found in storage";
|
|
13
|
+
const MISSING_STATE_RETRY_KEY = "hercules-auth:missing-state-retry";
|
|
10
14
|
const convexErrorSchema = z.object({ message: z.string() });
|
|
15
|
+
function claimMissingStateRetry(error) {
|
|
16
|
+
if (error.source !== "signinCallback" || error.message !== MISSING_STATE_MESSAGE) return false;
|
|
17
|
+
const url = new URL(window.location.href);
|
|
18
|
+
if (!url.searchParams.has("code")) return false;
|
|
19
|
+
try {
|
|
20
|
+
if (window.sessionStorage.getItem(MISSING_STATE_RETRY_KEY) !== null) return false;
|
|
21
|
+
window.sessionStorage.setItem(MISSING_STATE_RETRY_KEY, "1");
|
|
22
|
+
} catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
url.searchParams.delete("code");
|
|
26
|
+
url.searchParams.delete("state");
|
|
27
|
+
window.history.replaceState({}, document.title, url.toString());
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
11
30
|
/**
|
|
12
31
|
* A hook for handling OAuth/OIDC callback flows.
|
|
13
32
|
*
|
|
@@ -49,6 +68,7 @@ function useAuthCallback(options = {}) {
|
|
|
49
68
|
const mountedRef = useRef(true);
|
|
50
69
|
const hadAuthParams = useRef(hasAuthParams$1());
|
|
51
70
|
const syncStarted = useRef(false);
|
|
71
|
+
const missingStateRetryError = useRef(null);
|
|
52
72
|
useEffect(() => {
|
|
53
73
|
mountedRef.current = true;
|
|
54
74
|
syncStarted.current = false;
|
|
@@ -63,12 +83,18 @@ function useAuthCallback(options = {}) {
|
|
|
63
83
|
setStatus("error");
|
|
64
84
|
setError("Authentication timed out. Please try again.");
|
|
65
85
|
}
|
|
66
|
-
}, timeoutMs);
|
|
86
|
+
}, status === "processing-oauth" ? timeoutMs : Math.max(timeoutMs, MIN_TIMEOUT_AFTER_TOKENS_MS));
|
|
67
87
|
return () => clearTimeout(timeout);
|
|
68
88
|
}, [status, timeoutMs]);
|
|
69
89
|
useEffect(() => {
|
|
70
90
|
if (status !== "processing-oauth" && status !== "waiting-backend") return;
|
|
71
91
|
if (oidcError) {
|
|
92
|
+
if (oidcError === missingStateRetryError.current) return;
|
|
93
|
+
if (claimMissingStateRetry(oidcError)) {
|
|
94
|
+
missingStateRetryError.current = oidcError;
|
|
95
|
+
signinRedirect();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
72
98
|
setStatus("error");
|
|
73
99
|
setError(oidcError.message || "Authentication failed");
|
|
74
100
|
return;
|
|
@@ -95,7 +121,8 @@ function useAuthCallback(options = {}) {
|
|
|
95
121
|
isOidcAuthenticated,
|
|
96
122
|
oidcError,
|
|
97
123
|
status,
|
|
98
|
-
onNoAuthParams
|
|
124
|
+
onNoAuthParams,
|
|
125
|
+
signinRedirect
|
|
99
126
|
]);
|
|
100
127
|
useEffect(() => {
|
|
101
128
|
if (status !== "waiting-backend" || !isBackendAuthenticated) return;
|
|
@@ -148,8 +175,59 @@ function useAuthCallback(options = {}) {
|
|
|
148
175
|
retry
|
|
149
176
|
};
|
|
150
177
|
}
|
|
151
|
-
|
|
152
|
-
|
|
178
|
+
// src/internal/user-manager.ts
|
|
179
|
+
function logoutRedirectUrl(requestUrl, clientId) {
|
|
180
|
+
const url = new URL(requestUrl);
|
|
181
|
+
const hints = url.searchParams.getAll("id_token_hint");
|
|
182
|
+
const idToken = hints[0];
|
|
183
|
+
if (!idToken || hints.length !== 1) return requestUrl;
|
|
184
|
+
let sessionId;
|
|
185
|
+
try {
|
|
186
|
+
sessionId = jwtDecode(idToken).sid;
|
|
187
|
+
} catch {
|
|
188
|
+
return requestUrl;
|
|
189
|
+
}
|
|
190
|
+
if (typeof sessionId === "string" && sessionId.length > 0) return requestUrl;
|
|
191
|
+
const clients = url.searchParams.getAll("client_id");
|
|
192
|
+
if (clients.length > 1 || clients.length === 1 && clients[0] !== clientId) return requestUrl;
|
|
193
|
+
url.searchParams.delete("id_token_hint");
|
|
194
|
+
url.searchParams.set("client_id", clientId);
|
|
195
|
+
return url.toString();
|
|
196
|
+
}
|
|
197
|
+
const END_SESSION_TIMEOUT_MS = 5e3;
|
|
198
|
+
function isFramed() {
|
|
199
|
+
if (typeof window === "undefined") return false;
|
|
200
|
+
try {
|
|
201
|
+
return window.self !== window.top;
|
|
202
|
+
} catch {
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
async function endSessionInBackground(url) {
|
|
207
|
+
await fetch(url, {
|
|
208
|
+
mode: "no-cors",
|
|
209
|
+
credentials: "omit",
|
|
210
|
+
signal: AbortSignal.timeout(END_SESSION_TIMEOUT_MS)
|
|
211
|
+
}).catch(() => void 0);
|
|
212
|
+
return { url };
|
|
213
|
+
}
|
|
214
|
+
var HerculesUserManager = class extends UserManager {
|
|
215
|
+
_signoutStart(args = {}, handle) {
|
|
216
|
+
if (args.request_type !== "so:r") return super._signoutStart(args, handle);
|
|
217
|
+
return super._signoutStart(args, {
|
|
218
|
+
close: () => handle.close(),
|
|
219
|
+
navigate: (params) => {
|
|
220
|
+
const url = logoutRedirectUrl(params.url, this.settings.client_id);
|
|
221
|
+
if (this.settings.redirectTarget !== "top" && isFramed()) return endSessionInBackground(url);
|
|
222
|
+
return handle.navigate({
|
|
223
|
+
...params,
|
|
224
|
+
url
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
// src/react/impersonation-core.ts
|
|
153
231
|
const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
|
|
154
232
|
const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
|
|
155
233
|
function getHerculesImpersonationStorageKey(authority, clientId) {
|
|
@@ -167,8 +245,7 @@ function clearHerculesImpersonationParamsFromUrl(url) {
|
|
|
167
245
|
url.searchParams.delete(HERCULES_IMPERSONATION_TOKEN_PARAM);
|
|
168
246
|
return url;
|
|
169
247
|
}
|
|
170
|
-
|
|
171
|
-
//#region src/react/HerculesAuthProvider.tsx
|
|
248
|
+
// src/react/HerculesAuthProvider.tsx
|
|
172
249
|
const RECOVERY_TIMEOUT_MS = 1e4;
|
|
173
250
|
function onSigninCallback() {
|
|
174
251
|
window.history.replaceState({}, document.title, window.location.pathname);
|
|
@@ -186,6 +263,64 @@ function useHerculesAuthProvider() {
|
|
|
186
263
|
if (!context) throw new Error("HerculesAuthProviderContext not found");
|
|
187
264
|
return context;
|
|
188
265
|
}
|
|
266
|
+
/**
|
|
267
|
+
* Browsers that deny storage to a frame, such as a third-party iframe with
|
|
268
|
+
* third-party cookies blocked, throw `SecurityError` from the `localStorage`
|
|
269
|
+
* getter. Firefox still allows `sessionStorage` there, which keeps the OIDC
|
|
270
|
+
* state across the sign-in redirect. Memory is the last resort: the app
|
|
271
|
+
* renders, but a redirect sign-in cannot complete in that frame. The state
|
|
272
|
+
* store needs this too: the oidc-client-ts default reads `localStorage`.
|
|
273
|
+
*/
|
|
274
|
+
function getAuthStorage() {
|
|
275
|
+
try {
|
|
276
|
+
return window.localStorage;
|
|
277
|
+
} catch {
|
|
278
|
+
try {
|
|
279
|
+
return window.sessionStorage;
|
|
280
|
+
} catch {
|
|
281
|
+
return new InMemoryWebStorage();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
function DefaultLoadingFallback() {
|
|
286
|
+
return /* @__PURE__ */ jsx("div", {
|
|
287
|
+
role: "status",
|
|
288
|
+
"aria-label": "Loading",
|
|
289
|
+
style: {
|
|
290
|
+
position: "fixed",
|
|
291
|
+
inset: 0,
|
|
292
|
+
display: "grid",
|
|
293
|
+
placeItems: "center",
|
|
294
|
+
pointerEvents: "none"
|
|
295
|
+
},
|
|
296
|
+
children: /* @__PURE__ */ jsxs("svg", {
|
|
297
|
+
width: "32",
|
|
298
|
+
height: "32",
|
|
299
|
+
viewBox: "0 0 24 24",
|
|
300
|
+
fill: "none",
|
|
301
|
+
stroke: "currentColor",
|
|
302
|
+
strokeWidth: "2.5",
|
|
303
|
+
"aria-hidden": "true",
|
|
304
|
+
children: [/* @__PURE__ */ jsx("circle", {
|
|
305
|
+
cx: "12",
|
|
306
|
+
cy: "12",
|
|
307
|
+
r: "10",
|
|
308
|
+
opacity: "0.25"
|
|
309
|
+
}), /* @__PURE__ */ jsx("path", {
|
|
310
|
+
d: "M22 12a10 10 0 0 0-10-10",
|
|
311
|
+
strokeLinecap: "round",
|
|
312
|
+
children: /* @__PURE__ */ jsx("animateTransform", {
|
|
313
|
+
attributeName: "transform",
|
|
314
|
+
type: "rotate",
|
|
315
|
+
from: "0 12 12",
|
|
316
|
+
to: "360 12 12",
|
|
317
|
+
dur: "0.8s",
|
|
318
|
+
repeatCount: "indefinite"
|
|
319
|
+
})
|
|
320
|
+
})]
|
|
321
|
+
})
|
|
322
|
+
});
|
|
323
|
+
}
|
|
189
324
|
function AuthRecoveryGate({ children, loadingFallback, skipRecovery }) {
|
|
190
325
|
const { user, isLoading, signinSilent } = useAuth$1();
|
|
191
326
|
const userExpired = user?.expired === true;
|
|
@@ -230,30 +365,36 @@ function AuthRecoveryGate({ children, loadingFallback, skipRecovery }) {
|
|
|
230
365
|
*
|
|
231
366
|
* @public
|
|
232
367
|
*/
|
|
233
|
-
function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, loadingFallback =
|
|
368
|
+
function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, loadingFallback = /* @__PURE__ */ jsx(DefaultLoadingFallback, {}), ...props }) {
|
|
234
369
|
const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;
|
|
235
370
|
const [{ userManager, impersonationStorageKey }] = useState(() => {
|
|
236
371
|
const effectiveAuthority = userManagerSettings?.authority ?? authority;
|
|
237
372
|
const effectiveClientId = userManagerSettings?.client_id ?? client_id;
|
|
373
|
+
const userManager = new HerculesUserManager({
|
|
374
|
+
...userManagerSettings,
|
|
375
|
+
authority: effectiveAuthority,
|
|
376
|
+
client_id: effectiveClientId,
|
|
377
|
+
prompt: userManagerSettings?.prompt ?? "select_account",
|
|
378
|
+
response_type: userManagerSettings?.response_type ?? "code",
|
|
379
|
+
scope: userManagerSettings?.scope ?? "openid profile email offline_access",
|
|
380
|
+
redirect_uri: userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
|
|
381
|
+
post_logout_redirect_uri: userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
|
|
382
|
+
userStore: userManagerSettings?.userStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
|
|
383
|
+
stateStore: userManagerSettings?.stateStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
|
|
384
|
+
automaticSilentRenew: false,
|
|
385
|
+
silentRequestTimeoutInSeconds: userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1e3
|
|
386
|
+
});
|
|
387
|
+
Object.assign(userManager.settings, { automaticSilentRenew: automaticSilentRenewExplicit });
|
|
238
388
|
return {
|
|
239
|
-
userManager
|
|
240
|
-
...userManagerSettings,
|
|
241
|
-
authority: effectiveAuthority,
|
|
242
|
-
client_id: effectiveClientId,
|
|
243
|
-
prompt: userManagerSettings?.prompt ?? "select_account",
|
|
244
|
-
response_type: userManagerSettings?.response_type ?? "code",
|
|
245
|
-
scope: userManagerSettings?.scope ?? "openid profile email offline_access",
|
|
246
|
-
redirect_uri: userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
|
|
247
|
-
post_logout_redirect_uri: userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
|
|
248
|
-
userStore: userManagerSettings?.userStore ?? new WebStorageStateStore({ store: window.localStorage }),
|
|
249
|
-
automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
|
|
250
|
-
silentRequestTimeoutInSeconds: userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1e3
|
|
251
|
-
}),
|
|
389
|
+
userManager,
|
|
252
390
|
impersonationStorageKey: getHerculesImpersonationStorageKey(effectiveAuthority, effectiveClientId)
|
|
253
391
|
};
|
|
254
392
|
});
|
|
255
393
|
useEffect(() => {
|
|
256
|
-
if (automaticSilentRenewExplicit)
|
|
394
|
+
if (automaticSilentRenewExplicit) {
|
|
395
|
+
userManager.startSilentRenew();
|
|
396
|
+
return () => userManager.stopSilentRenew();
|
|
397
|
+
}
|
|
257
398
|
let retryTimerId = null;
|
|
258
399
|
let timeoutRetryCount = 0;
|
|
259
400
|
let stopped = false;
|
|
@@ -343,8 +484,7 @@ function hasCompleteImpersonationHandoff() {
|
|
|
343
484
|
const params = new URL(window.location.href).searchParams;
|
|
344
485
|
return params.has("hercules_impersonation_session_id") && params.has("hercules_impersonation_token");
|
|
345
486
|
}
|
|
346
|
-
|
|
347
|
-
//#region src/react/impersonation.ts
|
|
487
|
+
// src/react/impersonation.ts
|
|
348
488
|
function useHerculesImpersonation() {
|
|
349
489
|
const { userManager, impersonationStorageKey } = useHerculesAuthProvider();
|
|
350
490
|
const auth = useAuth$1();
|
|
@@ -400,8 +540,7 @@ function readStoredImpersonationSessionId(storageKey) {
|
|
|
400
540
|
return null;
|
|
401
541
|
}
|
|
402
542
|
}
|
|
403
|
-
|
|
404
|
-
//#region src/react/use-user.ts
|
|
543
|
+
// src/react/use-user.ts
|
|
405
544
|
/**
|
|
406
545
|
* A hook that returns the current user if authenticated
|
|
407
546
|
*
|
|
@@ -431,8 +570,7 @@ function useUser() {
|
|
|
431
570
|
error
|
|
432
571
|
]);
|
|
433
572
|
}
|
|
434
|
-
|
|
435
|
-
//#region src/react/use-auth.ts
|
|
573
|
+
// src/react/use-auth.ts
|
|
436
574
|
function useAuth() {
|
|
437
575
|
const { userManager } = useHerculesAuthProvider();
|
|
438
576
|
const auth = useAuth$1();
|
|
@@ -461,7 +599,6 @@ function useAuth() {
|
|
|
461
599
|
signin
|
|
462
600
|
]);
|
|
463
601
|
}
|
|
464
|
-
//#endregion
|
|
465
602
|
export { HERCULES_IMPERSONATION_SESSION_ID_PARAM, HERCULES_IMPERSONATION_TOKEN_PARAM, HerculesAuthProvider, getHerculesImpersonationStorageKey, hasAuthParams, rememberHerculesImpersonationSession, useAuth, useAuthCallback, useHerculesAuthProvider, useHerculesImpersonation, useUser };
|
|
466
603
|
|
|
467
604
|
//# sourceMappingURL=index.mjs.map
|