@usehercules/auth 1.0.28 → 1.0.30
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 +15 -0
- package/dist/convex-react/index.d.mts.map +1 -0
- package/dist/convex-react/index.mjs +45 -0
- package/dist/convex-react/index.mjs.map +1 -0
- package/dist/react/index.d.mts +62 -0
- package/dist/react/index.d.mts.map +1 -0
- package/dist/react/index.mjs +211 -0
- package/dist/react/index.mjs.map +1 -0
- package/package.json +12 -18
- package/src/convex-react/ConvexProviderWithHercules.tsx +5 -5
- package/src/react/auth-callback-hook.tsx +277 -0
- package/src/react/index.ts +1 -1
- package/{tsup.config.ts → tsdown.config.ts} +3 -4
- package/dist/convex-react/index.cjs +0 -2
- package/dist/convex-react/index.cjs.map +0 -1
- package/dist/convex-react/index.d.cts +0 -10
- package/dist/convex-react/index.d.ts +0 -10
- package/dist/convex-react/index.js +0 -2
- package/dist/convex-react/index.js.map +0 -1
- package/dist/react/index.cjs +0 -2
- package/dist/react/index.cjs.map +0 -1
- package/dist/react/index.d.cts +0 -35
- package/dist/react/index.d.ts +0 -35
- package/dist/react/index.js +0 -2
- package/dist/react/index.js.map +0 -1
- package/src/react/AuthCallbackPage.tsx +0 -38
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ReactNode } from "react";
|
|
2
|
+
import * as react_jsx_runtime0 from "react/jsx-runtime";
|
|
3
|
+
import { ConvexReactClient } from "convex/react";
|
|
4
|
+
|
|
5
|
+
//#region src/convex-react/ConvexProviderWithHercules.d.ts
|
|
6
|
+
declare function ConvexProviderWithHerculesAuth({
|
|
7
|
+
children,
|
|
8
|
+
client
|
|
9
|
+
}: {
|
|
10
|
+
children: ReactNode;
|
|
11
|
+
client: ConvexReactClient;
|
|
12
|
+
}): react_jsx_runtime0.JSX.Element;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { ConvexProviderWithHerculesAuth };
|
|
15
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":[],"mappings":";;;;;iBAgBgB,8BAAA;;;AAAhB;YAIY;UACF;AALV,CAAA,CAAA,EAMC,kBAAA,CAAA,GAAA,CAAA,OAN6C"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { useCallback, useMemo } from "react";
|
|
2
|
+
import { useAuth } from "react-oidc-context";
|
|
3
|
+
import { jsx } from "react/jsx-runtime";
|
|
4
|
+
import { ConvexProviderWithAuth } from "convex/react";
|
|
5
|
+
|
|
6
|
+
//#region src/convex-react/ConvexProviderWithHercules.tsx
|
|
7
|
+
/**
|
|
8
|
+
* A wrapper React component which provides a {@link ConvexReactClient}
|
|
9
|
+
* authenticated with Hercules Auth.
|
|
10
|
+
*
|
|
11
|
+
* It must be wrapped by a configured `{@link HerculesAuthProvider}`.
|
|
12
|
+
*
|
|
13
|
+
* @public
|
|
14
|
+
*/
|
|
15
|
+
function ConvexProviderWithHerculesAuth({ children, client }) {
|
|
16
|
+
return /* @__PURE__ */ jsx(ConvexProviderWithAuth, {
|
|
17
|
+
client,
|
|
18
|
+
useAuth: useUseAuthFromHercules,
|
|
19
|
+
children
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
function useUseAuthFromHercules() {
|
|
23
|
+
const { isAuthenticated, user, isLoading, signinSilent } = useAuth();
|
|
24
|
+
const idToken = user?.id_token;
|
|
25
|
+
const fetchAccessToken = useCallback(async ({ forceRefreshToken: _ignore }) => {
|
|
26
|
+
try {
|
|
27
|
+
return idToken ?? null;
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}, [idToken, signinSilent]);
|
|
32
|
+
return useMemo(() => ({
|
|
33
|
+
isLoading,
|
|
34
|
+
isAuthenticated,
|
|
35
|
+
fetchAccessToken
|
|
36
|
+
}), [
|
|
37
|
+
isLoading,
|
|
38
|
+
isAuthenticated,
|
|
39
|
+
fetchAccessToken
|
|
40
|
+
]);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
//#endregion
|
|
44
|
+
export { ConvexProviderWithHerculesAuth };
|
|
45
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +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 { useCallback, useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\nimport type { HerculesAuthProvider } from \"../react/HerculesAuthProvider\";\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 `{@link 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\nfunction useUseAuthFromHercules() {\n const { isAuthenticated, user, isLoading, signinSilent } = useAuth();\n const idToken = user?.id_token;\n const fetchAccessToken = useCallback(\n async ({ forceRefreshToken: _ignore }: { forceRefreshToken: boolean }) => {\n try {\n // if (forceRefreshToken) {\n // const user = await signinSilent();\n // return user?.id_token ?? null;\n // }\n return idToken ?? null;\n } catch {\n return null;\n }\n },\n [idToken, signinSilent],\n );\n return useMemo(\n () => ({\n isLoading,\n isAuthenticated,\n fetchAccessToken,\n }),\n [isLoading, isAuthenticated, fetchAccessToken],\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,SAAgB,+BAA+B,EAC7C,UACA,UAIC;AACD,QACE,oBAAC;EAA+B;EAAQ,SAAS;EAC9C;GACsB;;AAI7B,SAAS,yBAAyB;CAChC,MAAM,EAAE,iBAAiB,MAAM,WAAW,iBAAiB,SAAS;CACpE,MAAM,UAAU,MAAM;CACtB,MAAM,mBAAmB,YACvB,OAAO,EAAE,mBAAmB,cAA8C;AACxE,MAAI;AAKF,UAAO,WAAW;UACZ;AACN,UAAO;;IAGX,CAAC,SAAS,aAAa,CACxB;AACD,QAAO,eACE;EACL;EACA;EACA;EACD,GACD;EAAC;EAAW;EAAiB;EAAiB,CAC/C"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import * as react_oidc_context0 from "react-oidc-context";
|
|
2
|
+
import { AuthContextProps, AuthProviderUserManagerProps, hasAuthParams, useAuth } from "react-oidc-context";
|
|
3
|
+
import * as oidc_client_ts0 from "oidc-client-ts";
|
|
4
|
+
import { UserManagerSettings } from "oidc-client-ts";
|
|
5
|
+
import * as react_jsx_runtime0 from "react/jsx-runtime";
|
|
6
|
+
|
|
7
|
+
//#region src/react/auth-callback-hook.d.ts
|
|
8
|
+
type AuthCallbackStatus = "processing-oauth" | "waiting-backend" | "syncing" | "success" | "error";
|
|
9
|
+
interface UseAuthCallbackOptions {
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
isBackendAuthenticated?: boolean;
|
|
12
|
+
onSync?: () => Promise<void>;
|
|
13
|
+
onSuccess?: () => void;
|
|
14
|
+
onNoAuthParams?: () => void;
|
|
15
|
+
}
|
|
16
|
+
interface UseAuthCallbackResult {
|
|
17
|
+
status: AuthCallbackStatus;
|
|
18
|
+
error: string | null;
|
|
19
|
+
isLoading: boolean;
|
|
20
|
+
isSuccess: boolean;
|
|
21
|
+
isError: boolean;
|
|
22
|
+
retry: () => Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
declare function useAuthCallback(options?: UseAuthCallbackOptions): UseAuthCallbackResult;
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/react/HerculesAuthProvider.d.ts
|
|
27
|
+
type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
|
|
28
|
+
userManagerSettings?: Partial<UserManagerSettings>;
|
|
29
|
+
authority: string;
|
|
30
|
+
client_id: string;
|
|
31
|
+
};
|
|
32
|
+
declare function HerculesAuthProvider({
|
|
33
|
+
children,
|
|
34
|
+
userManagerSettings,
|
|
35
|
+
authority,
|
|
36
|
+
client_id,
|
|
37
|
+
...props
|
|
38
|
+
}: HerculesAuthProviderProps): react_jsx_runtime0.JSX.Element;
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/react/use-user.d.ts
|
|
41
|
+
declare function useUser(): {
|
|
42
|
+
id: string | undefined;
|
|
43
|
+
name: string | undefined;
|
|
44
|
+
email: string | undefined;
|
|
45
|
+
avatar: string | undefined;
|
|
46
|
+
isAuthenticated: boolean;
|
|
47
|
+
isLoading: boolean;
|
|
48
|
+
error: react_oidc_context0.ErrorContext | undefined;
|
|
49
|
+
id_token?: string;
|
|
50
|
+
session_state?: string | null | undefined;
|
|
51
|
+
access_token?: string | undefined;
|
|
52
|
+
refresh_token?: string;
|
|
53
|
+
token_type?: string | undefined;
|
|
54
|
+
scope?: string;
|
|
55
|
+
profile?: oidc_client_ts0.IdTokenClaims | undefined;
|
|
56
|
+
expires_at?: number;
|
|
57
|
+
state?: unknown;
|
|
58
|
+
url_state?: string;
|
|
59
|
+
};
|
|
60
|
+
//#endregion
|
|
61
|
+
export { AuthCallbackStatus, type AuthContextProps, HerculesAuthProvider, HerculesAuthProviderProps, UseAuthCallbackOptions, UseAuthCallbackResult, hasAuthParams, useAuth, useAuthCallback, useUser };
|
|
62
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts"],"sourcesContent":[],"mappings":";;;;;;;KAWY,kBAAA;UAWK,sBAAA;;;iBAkBA;;;AA7BjB;AAWiB,UAsCA,qBAAA,CAtCsB;EAsCtB,MAAA,EAEP,kBAF4B;EAqDtB,KAAA,EAAA,MAAA,GAAA,IAAe;;;;ECpGnB,KAAA,EAAA,GAAA,GDgEG,OChEH,CAAA,IAAA,CAAA;;AAA4B,iBDoGxB,eAAA,CCpGwB,OAAA,CAAA,EDqG7B,sBCrG6B,CAAA,EDsGrC,qBCtGqC;;;KAA5B,yBAAA,GAA4B,KACtC;wBAGsB,QAAQ;;;;ADNpB,iBC8BI,oBAAA,CD9Bc;EAAA,QAAA;EAAA,mBAAA;EAAA,SAAA;EAAA,SAAA;EAAA,GAAA;AAAA,CAAA,ECoC3B,yBDpC2B,CAAA,ECoCF,kBAAA,CAAA,GAAA,CAAA,ODpCE;;;iBEDd,OAAA,CAAA;;;;;;;EFCJ,KAAA,EEDW,mBAAA,CAAA,YAAA,GFCO,SAAA;EAWb,QAAA,CAAA,EAAA,MAAA;EAsCA,aAAA,CAAA,EAAA,MAAA,GAAqB,IAAA,GAAA,SAE5B;EAmDM,YAAA,CAAA,EAAA,MAAe,GAAA,SACpB;;;;ECrGC,OAAA,CAAA,ECHW,eAAA,CAAA,aAAA,GDGc,SAAA;EACnC,UAAA,CAAA,EAAA,MAAA;EADsC,KAAA,CAAA,EAAA,OAAA;EAIR,SAAA,CAAA,EAAA,MAAA;CAAR"}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import { AuthProvider, hasAuthParams, hasAuthParams as hasAuthParams$1, useAuth, useAuth as useAuth$1 } from "react-oidc-context";
|
|
3
|
+
import { UserManager, WebStorageStateStore } from "oidc-client-ts";
|
|
4
|
+
import { jsx } from "react/jsx-runtime";
|
|
5
|
+
|
|
6
|
+
//#region src/react/auth-callback-hook.tsx
|
|
7
|
+
const DEFAULT_TIMEOUT_MS = 2e4;
|
|
8
|
+
/**
|
|
9
|
+
* A hook for handling OAuth/OIDC callback flows.
|
|
10
|
+
*
|
|
11
|
+
* This hook manages the complete authentication callback lifecycle:
|
|
12
|
+
* 1. Processing the OAuth callback from the identity provider
|
|
13
|
+
* 2. Waiting for backend authentication (e.g., Convex)
|
|
14
|
+
* 3. Syncing user data with your backend
|
|
15
|
+
* 4. Handling success and error states
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* function AuthCallback() {
|
|
20
|
+
* const navigate = useNavigate();
|
|
21
|
+
* const { isAuthenticated } = useConvexAuth();
|
|
22
|
+
* const updateUser = useMutation(api.users.updateCurrentUser);
|
|
23
|
+
*
|
|
24
|
+
* const { status, error, retry } = useAuthCallback({
|
|
25
|
+
* isBackendAuthenticated: isAuthenticated,
|
|
26
|
+
* onSync: () => updateUser(),
|
|
27
|
+
* onSuccess: () => navigate("/", { replace: true }),
|
|
28
|
+
* onNoAuthParams: () => navigate("/", { replace: true }),
|
|
29
|
+
* });
|
|
30
|
+
*
|
|
31
|
+
* if (status === "error") {
|
|
32
|
+
* return <ErrorState message={error} onRetry={retry} />;
|
|
33
|
+
* }
|
|
34
|
+
*
|
|
35
|
+
* return <LoadingSpinner />;
|
|
36
|
+
* }
|
|
37
|
+
* ```
|
|
38
|
+
*
|
|
39
|
+
* @public
|
|
40
|
+
*/
|
|
41
|
+
function useAuthCallback(options = {}) {
|
|
42
|
+
const { timeoutMs = DEFAULT_TIMEOUT_MS, isBackendAuthenticated = true, onSync, onSuccess, onNoAuthParams } = options;
|
|
43
|
+
const { isLoading: isAuthLoading, isAuthenticated: isOidcAuthenticated, error: oidcError, signinRedirect } = useAuth$1();
|
|
44
|
+
const [status, setStatus] = useState("processing-oauth");
|
|
45
|
+
const [error, setError] = useState(null);
|
|
46
|
+
const mountedRef = useRef(true);
|
|
47
|
+
const hadAuthParams = useRef(hasAuthParams$1());
|
|
48
|
+
const syncStarted = useRef(false);
|
|
49
|
+
useEffect(() => {
|
|
50
|
+
return () => {
|
|
51
|
+
mountedRef.current = false;
|
|
52
|
+
};
|
|
53
|
+
}, []);
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
if (status === "success" || status === "error") return;
|
|
56
|
+
const timeout = setTimeout(() => {
|
|
57
|
+
if (mountedRef.current) {
|
|
58
|
+
setStatus("error");
|
|
59
|
+
setError("Authentication timed out. Please try again.");
|
|
60
|
+
}
|
|
61
|
+
}, timeoutMs);
|
|
62
|
+
return () => clearTimeout(timeout);
|
|
63
|
+
}, [status, timeoutMs]);
|
|
64
|
+
useEffect(() => {
|
|
65
|
+
if (status !== "processing-oauth" && status !== "waiting-backend") return;
|
|
66
|
+
if (oidcError) {
|
|
67
|
+
setStatus("error");
|
|
68
|
+
setError(oidcError.message || "Authentication failed");
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (!hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated) {
|
|
72
|
+
onNoAuthParams?.();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (!isAuthLoading && isOidcAuthenticated && status === "processing-oauth") {
|
|
76
|
+
setStatus("waiting-backend");
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated && !oidcError && status === "processing-oauth") {
|
|
80
|
+
const failureTimeout = setTimeout(() => {
|
|
81
|
+
if (mountedRef.current && !isOidcAuthenticated) {
|
|
82
|
+
setStatus("error");
|
|
83
|
+
setError("Authentication was cancelled or failed. Please try again.");
|
|
84
|
+
}
|
|
85
|
+
}, 500);
|
|
86
|
+
return () => clearTimeout(failureTimeout);
|
|
87
|
+
}
|
|
88
|
+
}, [
|
|
89
|
+
isAuthLoading,
|
|
90
|
+
isOidcAuthenticated,
|
|
91
|
+
oidcError,
|
|
92
|
+
status,
|
|
93
|
+
onNoAuthParams
|
|
94
|
+
]);
|
|
95
|
+
useEffect(() => {
|
|
96
|
+
if (status !== "waiting-backend" || !isBackendAuthenticated) return;
|
|
97
|
+
if (syncStarted.current) return;
|
|
98
|
+
syncStarted.current = true;
|
|
99
|
+
async function performSync() {
|
|
100
|
+
if (!mountedRef.current) return;
|
|
101
|
+
setStatus("syncing");
|
|
102
|
+
try {
|
|
103
|
+
if (onSync) await onSync();
|
|
104
|
+
if (mountedRef.current) setStatus("success");
|
|
105
|
+
} catch (err) {
|
|
106
|
+
console.error("Auth callback sync failed:", err);
|
|
107
|
+
if (!mountedRef.current) return;
|
|
108
|
+
const errorMessage = err instanceof Error && err.message.includes("UNAUTHENTICATED") ? "Your session expired. Please sign in again." : "Failed to complete authentication. Please try again.";
|
|
109
|
+
setStatus("error");
|
|
110
|
+
setError(errorMessage);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
performSync();
|
|
114
|
+
}, [
|
|
115
|
+
status,
|
|
116
|
+
isBackendAuthenticated,
|
|
117
|
+
onSync
|
|
118
|
+
]);
|
|
119
|
+
useEffect(() => {
|
|
120
|
+
if (status === "success") onSuccess?.();
|
|
121
|
+
}, [status, onSuccess]);
|
|
122
|
+
const retry = useCallback(async () => {
|
|
123
|
+
try {
|
|
124
|
+
await signinRedirect();
|
|
125
|
+
} catch (err) {
|
|
126
|
+
console.error("Failed to restart auth:", err);
|
|
127
|
+
}
|
|
128
|
+
}, [signinRedirect]);
|
|
129
|
+
return {
|
|
130
|
+
status,
|
|
131
|
+
error,
|
|
132
|
+
isLoading: status !== "success" && status !== "error",
|
|
133
|
+
isSuccess: status === "success",
|
|
134
|
+
isError: status === "error",
|
|
135
|
+
retry
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
//#endregion
|
|
140
|
+
//#region src/react/HerculesAuthProvider.tsx
|
|
141
|
+
function onSigninCallback() {
|
|
142
|
+
window.history.replaceState({}, document.title, window.location.pathname);
|
|
143
|
+
}
|
|
144
|
+
function onSignoutCallback() {
|
|
145
|
+
window.location.pathname = "";
|
|
146
|
+
}
|
|
147
|
+
const DEFAULT_AUTH_CONFIG = {
|
|
148
|
+
onSignoutCallback,
|
|
149
|
+
onSigninCallback
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* A wrapper React component which provides a {@link ReactAuthProvider}
|
|
153
|
+
* configured with Hercules Auth.
|
|
154
|
+
*
|
|
155
|
+
* @public
|
|
156
|
+
*/
|
|
157
|
+
function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, ...props }) {
|
|
158
|
+
const [userManager] = useState(() => new UserManager({
|
|
159
|
+
...userManagerSettings,
|
|
160
|
+
authority: userManagerSettings?.authority ?? authority,
|
|
161
|
+
client_id: userManagerSettings?.client_id ?? client_id,
|
|
162
|
+
prompt: userManagerSettings?.prompt ?? "select_account",
|
|
163
|
+
response_type: userManagerSettings?.response_type ?? "code",
|
|
164
|
+
scope: userManagerSettings?.scope ?? "openid profile email offline_access",
|
|
165
|
+
redirect_uri: userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
|
|
166
|
+
post_logout_redirect_uri: userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
|
|
167
|
+
userStore: userManagerSettings?.userStore ?? new WebStorageStateStore({ store: window.localStorage })
|
|
168
|
+
}));
|
|
169
|
+
return /* @__PURE__ */ jsx(AuthProvider, {
|
|
170
|
+
userManager,
|
|
171
|
+
...DEFAULT_AUTH_CONFIG,
|
|
172
|
+
...props,
|
|
173
|
+
children
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
//#endregion
|
|
178
|
+
//#region src/react/use-user.ts
|
|
179
|
+
/**
|
|
180
|
+
* A hook that returns the current user if authenticated
|
|
181
|
+
*
|
|
182
|
+
* @public
|
|
183
|
+
*/
|
|
184
|
+
function useUser() {
|
|
185
|
+
const { user, isLoading, error, isAuthenticated } = useAuth$1();
|
|
186
|
+
return useMemo(() => {
|
|
187
|
+
const id = user?.profile.sub;
|
|
188
|
+
const name = user?.profile.name;
|
|
189
|
+
const email = user?.profile.email;
|
|
190
|
+
const avatar = user?.profile.picture;
|
|
191
|
+
return {
|
|
192
|
+
...user ?? {},
|
|
193
|
+
id,
|
|
194
|
+
name,
|
|
195
|
+
email,
|
|
196
|
+
avatar,
|
|
197
|
+
isAuthenticated,
|
|
198
|
+
isLoading,
|
|
199
|
+
error
|
|
200
|
+
};
|
|
201
|
+
}, [
|
|
202
|
+
user,
|
|
203
|
+
isAuthenticated,
|
|
204
|
+
isLoading,
|
|
205
|
+
error
|
|
206
|
+
]);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
//#endregion
|
|
210
|
+
export { HerculesAuthProvider, hasAuthParams, useAuth, useAuthCallback, useUser };
|
|
211
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["useAuth","hasAuthParams","DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps>","ReactAuthProvider","useAuth"],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState, useRef, useCallback } from \"react\";\nimport { useAuth, hasAuthParams } from \"react-oidc-context\";\n\nconst DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout\n\n/**\n * Authentication callback status states\n * @public\n */\nexport type AuthCallbackStatus =\n | \"processing-oauth\" // OIDC is processing the callback\n | \"waiting-backend\" // OIDC authenticated, waiting for backend\n | \"syncing\" // Syncing user with backend (e.g., creating user record)\n | \"success\" // All done\n | \"error\"; // Something went wrong\n\n/**\n * Options for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackOptions {\n /**\n * Timeout in milliseconds before the callback is considered failed.\n * @default 20000\n */\n timeoutMs?: number;\n\n /**\n * Whether the backend (e.g., Convex) is authenticated.\n * The hook will wait for this to be true before calling onSync.\n */\n isBackendAuthenticated?: boolean;\n\n /**\n * Called when the backend is authenticated and ready to sync.\n * Use this to create/update the user in your backend.\n * Return a promise that resolves when sync is complete.\n */\n onSync?: () => Promise<void>;\n\n /**\n * Called when authentication is successful and sync is complete.\n * Use this to redirect the user.\n */\n onSuccess?: () => void;\n\n /**\n * Called when OIDC is not authenticated and there are no auth params.\n * This typically means the user navigated directly to the callback page.\n * Use this to redirect them away.\n */\n onNoAuthParams?: () => void;\n}\n\n/**\n * Return type for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackResult {\n /** Current status of the auth callback flow */\n status: AuthCallbackStatus;\n\n /** Error message if status is \"error\" */\n error: string | null;\n\n /** Whether the auth callback is still in progress */\n isLoading: boolean;\n\n /** Whether the auth callback completed successfully */\n isSuccess: boolean;\n\n /** Whether there was an error */\n isError: boolean;\n\n /** Retry the authentication flow by redirecting to the auth provider */\n retry: () => Promise<void>;\n}\n\n/**\n * A hook for handling OAuth/OIDC callback flows.\n *\n * This hook manages the complete authentication callback lifecycle:\n * 1. Processing the OAuth callback from the identity provider\n * 2. Waiting for backend authentication (e.g., Convex)\n * 3. Syncing user data with your backend\n * 4. Handling success and error states\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const navigate = useNavigate();\n * const { isAuthenticated } = useConvexAuth();\n * const updateUser = useMutation(api.users.updateCurrentUser);\n *\n * const { status, error, retry } = useAuthCallback({\n * isBackendAuthenticated: isAuthenticated,\n * onSync: () => updateUser(),\n * onSuccess: () => navigate(\"/\", { replace: true }),\n * onNoAuthParams: () => navigate(\"/\", { replace: true }),\n * });\n *\n * if (status === \"error\") {\n * return <ErrorState message={error} onRetry={retry} />;\n * }\n *\n * return <LoadingSpinner />;\n * }\n * ```\n *\n * @public\n */\nexport function useAuthCallback(\n options: UseAuthCallbackOptions = {},\n): UseAuthCallbackResult {\n const {\n timeoutMs = DEFAULT_TIMEOUT_MS,\n isBackendAuthenticated = true,\n onSync,\n onSuccess,\n onNoAuthParams,\n } = options;\n\n const {\n isLoading: isAuthLoading,\n isAuthenticated: isOidcAuthenticated,\n error: oidcError,\n signinRedirect,\n } = useAuth();\n\n const [status, setStatus] = useState<AuthCallbackStatus>(\"processing-oauth\");\n const [error, setError] = useState<string | null>(null);\n\n // Track mount state to prevent state updates after unmount\n const mountedRef = useRef(true);\n // Track if we had auth params on mount (won't change during lifecycle)\n const hadAuthParams = useRef(hasAuthParams());\n // Track if we've already started sync to prevent double execution\n const syncStarted = useRef(false);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Timeout protection with state awareness\n useEffect(() => {\n if (status === \"success\" || status === \"error\") return;\n\n const timeout = setTimeout(() => {\n if (mountedRef.current) {\n setStatus(\"error\");\n setError(\"Authentication timed out. Please try again.\");\n }\n }, timeoutMs);\n\n return () => clearTimeout(timeout);\n }, [status, timeoutMs]);\n\n // Track OIDC authentication progression\n useEffect(() => {\n // Don't update if we're already past processing or in an error state\n if (status !== \"processing-oauth\" && status !== \"waiting-backend\") return;\n\n // Handle OIDC errors\n if (oidcError) {\n setStatus(\"error\");\n setError(oidcError.message || \"Authentication failed\");\n return;\n }\n\n // No auth params and not authenticated - navigated here directly\n if (!hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated) {\n onNoAuthParams?.();\n return;\n }\n\n // OIDC is done loading and authenticated - move to waiting for backend\n if (\n !isAuthLoading &&\n isOidcAuthenticated &&\n status === \"processing-oauth\"\n ) {\n setStatus(\"waiting-backend\");\n return;\n }\n\n // OIDC finished but not authenticated (and we had auth params)\n // Wait a bit before declaring failure to avoid race conditions\n if (\n hadAuthParams.current &&\n !isAuthLoading &&\n !isOidcAuthenticated &&\n !oidcError &&\n status === \"processing-oauth\"\n ) {\n // Use a small delay to avoid race condition during OIDC state transitions\n const failureTimeout = setTimeout(() => {\n if (mountedRef.current && !isOidcAuthenticated) {\n setStatus(\"error\");\n setError(\"Authentication was cancelled or failed. Please try again.\");\n }\n }, 500);\n\n return () => clearTimeout(failureTimeout);\n }\n\n return;\n }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);\n\n // Sync with backend once backend is authenticated\n useEffect(() => {\n if (status !== \"waiting-backend\" || !isBackendAuthenticated) return;\n if (syncStarted.current) return;\n\n syncStarted.current = true;\n\n async function performSync() {\n if (!mountedRef.current) return;\n\n setStatus(\"syncing\");\n\n try {\n if (onSync) {\n await onSync();\n }\n\n if (mountedRef.current) {\n setStatus(\"success\");\n }\n } catch (err) {\n console.error(\"Auth callback sync failed:\", err);\n\n if (!mountedRef.current) return;\n\n // Check if it's an authentication error\n const errorMessage =\n err instanceof Error && err.message.includes(\"UNAUTHENTICATED\")\n ? \"Your session expired. Please sign in again.\"\n : \"Failed to complete authentication. Please try again.\";\n\n setStatus(\"error\");\n setError(errorMessage);\n }\n }\n\n performSync();\n }, [status, isBackendAuthenticated, onSync]);\n\n // Handle successful completion\n useEffect(() => {\n if (status === \"success\") {\n onSuccess?.();\n }\n }, [status, onSuccess]);\n\n // Retry handler\n const retry = useCallback(async () => {\n try {\n await signinRedirect();\n } catch (err) {\n console.error(\"Failed to restart auth:\", err);\n }\n }, [signinRedirect]);\n\n return {\n status,\n error,\n isLoading: status !== \"success\" && status !== \"error\",\n isSuccess: status === \"success\",\n isError: status === \"error\",\n retry,\n };\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n} from \"react-oidc-context\";\nimport {\n UserManager,\n WebStorageStateStore,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\n\nexport type HerculesAuthProviderProps = Omit<\n AuthProviderUserManagerProps,\n \"userManager\"\n> & {\n userManagerSettings?: Partial<UserManagerSettings>;\n authority: string;\n client_id: string;\n};\n\nfunction onSigninCallback() {\n window.history.replaceState({}, document.title, window.location.pathname);\n}\n\nfunction onSignoutCallback() {\n window.location.pathname = \"\";\n}\n\nconst DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {\n onSignoutCallback,\n onSigninCallback,\n};\n\n/**\n * A wrapper React component which provides a {@link ReactAuthProvider}\n * configured with Hercules Auth.\n *\n * @public\n */\nexport function HerculesAuthProvider({\n children,\n userManagerSettings,\n authority,\n client_id,\n ...props\n}: HerculesAuthProviderProps) {\n const [userManager] = useState(\n () =>\n new UserManager({\n ...userManagerSettings,\n authority: userManagerSettings?.authority ?? authority,\n client_id: userManagerSettings?.client_id ?? client_id,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope:\n userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri:\n userManagerSettings?.redirect_uri ??\n `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ??\n window.location.origin,\n userStore:\n userManagerSettings?.userStore ??\n new WebStorageStateStore({ store: window.localStorage }),\n }),\n );\n\n return (\n <ReactAuthProvider\n userManager={userManager}\n {...DEFAULT_AUTH_CONFIG}\n {...props}\n >\n {children}\n </ReactAuthProvider>\n );\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\n/**\n * A hook that returns the current user if authenticated\n *\n * @public\n */\nexport function useUser() {\n const { user, isLoading, error, isAuthenticated } = useAuth();\n\n return useMemo(() => {\n const id = user?.profile.sub;\n const name = user?.profile.name;\n const email = user?.profile.email;\n const avatar = user?.profile.picture;\n return {\n ...(user ?? {}),\n id,\n name,\n email,\n avatar,\n isAuthenticated,\n isLoading,\n error,\n };\n }, [user, isAuthenticated, isLoading, error]);\n}\n"],"mappings":";;;;;;AAKA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4G3B,SAAgB,gBACd,UAAkC,EAAE,EACb;CACvB,MAAM,EACJ,YAAY,oBACZ,yBAAyB,MACzB,QACA,WACA,mBACE;CAEJ,MAAM,EACJ,WAAW,eACX,iBAAiB,qBACjB,OAAO,WACP,mBACEA,WAAS;CAEb,MAAM,CAAC,QAAQ,aAAa,SAA6B,mBAAmB;CAC5E,MAAM,CAAC,OAAO,YAAY,SAAwB,KAAK;CAGvD,MAAM,aAAa,OAAO,KAAK;CAE/B,MAAM,gBAAgB,OAAOC,iBAAe,CAAC;CAE7C,MAAM,cAAc,OAAO,MAAM;AAGjC,iBAAgB;AACd,eAAa;AACX,cAAW,UAAU;;IAEtB,EAAE,CAAC;AAGN,iBAAgB;AACd,MAAI,WAAW,aAAa,WAAW,QAAS;EAEhD,MAAM,UAAU,iBAAiB;AAC/B,OAAI,WAAW,SAAS;AACtB,cAAU,QAAQ;AAClB,aAAS,8CAA8C;;KAExD,UAAU;AAEb,eAAa,aAAa,QAAQ;IACjC,CAAC,QAAQ,UAAU,CAAC;AAGvB,iBAAgB;AAEd,MAAI,WAAW,sBAAsB,WAAW,kBAAmB;AAGnE,MAAI,WAAW;AACb,aAAU,QAAQ;AAClB,YAAS,UAAU,WAAW,wBAAwB;AACtD;;AAIF,MAAI,CAAC,cAAc,WAAW,CAAC,iBAAiB,CAAC,qBAAqB;AACpE,qBAAkB;AAClB;;AAIF,MACE,CAAC,iBACD,uBACA,WAAW,oBACX;AACA,aAAU,kBAAkB;AAC5B;;AAKF,MACE,cAAc,WACd,CAAC,iBACD,CAAC,uBACD,CAAC,aACD,WAAW,oBACX;GAEA,MAAM,iBAAiB,iBAAiB;AACtC,QAAI,WAAW,WAAW,CAAC,qBAAqB;AAC9C,eAAU,QAAQ;AAClB,cAAS,4DAA4D;;MAEtE,IAAI;AAEP,gBAAa,aAAa,eAAe;;IAI1C;EAAC;EAAe;EAAqB;EAAW;EAAQ;EAAe,CAAC;AAG3E,iBAAgB;AACd,MAAI,WAAW,qBAAqB,CAAC,uBAAwB;AAC7D,MAAI,YAAY,QAAS;AAEzB,cAAY,UAAU;EAEtB,eAAe,cAAc;AAC3B,OAAI,CAAC,WAAW,QAAS;AAEzB,aAAU,UAAU;AAEpB,OAAI;AACF,QAAI,OACF,OAAM,QAAQ;AAGhB,QAAI,WAAW,QACb,WAAU,UAAU;YAEf,KAAK;AACZ,YAAQ,MAAM,8BAA8B,IAAI;AAEhD,QAAI,CAAC,WAAW,QAAS;IAGzB,MAAM,eACJ,eAAe,SAAS,IAAI,QAAQ,SAAS,kBAAkB,GAC3D,gDACA;AAEN,cAAU,QAAQ;AAClB,aAAS,aAAa;;;AAI1B,eAAa;IACZ;EAAC;EAAQ;EAAwB;EAAO,CAAC;AAG5C,iBAAgB;AACd,MAAI,WAAW,UACb,cAAa;IAEd,CAAC,QAAQ,UAAU,CAAC;CAGvB,MAAM,QAAQ,YAAY,YAAY;AACpC,MAAI;AACF,SAAM,gBAAgB;WACf,KAAK;AACZ,WAAQ,MAAM,2BAA2B,IAAI;;IAE9C,CAAC,eAAe,CAAC;AAEpB,QAAO;EACL;EACA;EACA,WAAW,WAAW,aAAa,WAAW;EAC9C,WAAW,WAAW;EACtB,SAAS,WAAW;EACpB;EACD;;;;;AC7PH,SAAS,mBAAmB;AAC1B,QAAO,QAAQ,aAAa,EAAE,EAAE,SAAS,OAAO,OAAO,SAAS,SAAS;;AAG3E,SAAS,oBAAoB;AAC3B,QAAO,SAAS,WAAW;;AAG7B,MAAMC,sBAA0D;CAC9D;CACA;CACD;;;;;;;AAQD,SAAgB,qBAAqB,EACnC,UACA,qBACA,WACA,WACA,GAAG,SACyB;CAC5B,MAAM,CAAC,eAAe,eAElB,IAAI,YAAY;EACd,GAAG;EACH,WAAW,qBAAqB,aAAa;EAC7C,WAAW,qBAAqB,aAAa;EAC7C,QAAQ,qBAAqB,UAAU;EACvC,eAAe,qBAAqB,iBAAiB;EACrD,OACE,qBAAqB,SAAS;EAChC,cACE,qBAAqB,gBACrB,GAAG,OAAO,SAAS,OAAO;EAC5B,0BACE,qBAAqB,4BACrB,OAAO,SAAS;EAClB,WACE,qBAAqB,aACrB,IAAI,qBAAqB,EAAE,OAAO,OAAO,cAAc,CAAC;EAC3D,CAAC,CACL;AAED,QACE,oBAACC;EACc;EACb,GAAI;EACJ,GAAI;EAEH;GACiB;;;;;;;;;;ACnExB,SAAgB,UAAU;CACxB,MAAM,EAAE,MAAM,WAAW,OAAO,oBAAoBC,WAAS;AAE7D,QAAO,cAAc;EACnB,MAAM,KAAK,MAAM,QAAQ;EACzB,MAAM,OAAO,MAAM,QAAQ;EAC3B,MAAM,QAAQ,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,QAAQ;AAC7B,SAAO;GACL,GAAI,QAAQ,EAAE;GACd;GACA;GACA;GACA;GACA;GACA;GACA;GACD;IACA;EAAC;EAAM;EAAiB;EAAW;EAAM,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,17 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usehercules/auth",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.30",
|
|
4
4
|
"description": "Authentication utilities for Hercules applications using OIDC",
|
|
5
5
|
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
6
7
|
"exports": {
|
|
7
|
-
"./react":
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
},
|
|
11
|
-
"./convex-react": {
|
|
12
|
-
"types": "./dist/convex-react/index.d.ts",
|
|
13
|
-
"import": "./dist/convex-react/index.js"
|
|
14
|
-
}
|
|
8
|
+
"./convex-react": "./dist/convex-react/index.mjs",
|
|
9
|
+
"./react": "./dist/react/index.mjs",
|
|
10
|
+
"./package.json": "./package.json"
|
|
15
11
|
},
|
|
16
12
|
"author": "Hercules Team",
|
|
17
13
|
"license": "MIT",
|
|
@@ -24,13 +20,13 @@
|
|
|
24
20
|
"dist",
|
|
25
21
|
"src",
|
|
26
22
|
"tsconfig.json",
|
|
27
|
-
"
|
|
23
|
+
"tsdown.config.ts"
|
|
28
24
|
],
|
|
29
25
|
"publishConfig": {
|
|
30
26
|
"access": "public"
|
|
31
27
|
},
|
|
32
28
|
"dependencies": {
|
|
33
|
-
"convex": "^1.29.
|
|
29
|
+
"convex": "^1.29.3",
|
|
34
30
|
"oidc-client-ts": "^3.4.1",
|
|
35
31
|
"react-oidc-context": "^3.3.0"
|
|
36
32
|
},
|
|
@@ -38,16 +34,14 @@
|
|
|
38
34
|
"react": "^18.0.0 || ^19.0.0"
|
|
39
35
|
},
|
|
40
36
|
"devDependencies": {
|
|
41
|
-
"@types/react": "^
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"react-dom": "^18.3.1",
|
|
45
|
-
"tsup": "^8.5.1",
|
|
37
|
+
"@types/react": "^19.2.6",
|
|
38
|
+
"react": "^19.2.0",
|
|
39
|
+
"tsdown": "^0.16.6",
|
|
46
40
|
"typescript": "^5.9.3"
|
|
47
41
|
},
|
|
48
42
|
"scripts": {
|
|
49
|
-
"build": "
|
|
50
|
-
"dev": "
|
|
43
|
+
"build": "tsdown",
|
|
44
|
+
"dev": "tsdown --watch",
|
|
51
45
|
"test": "exit 0"
|
|
52
46
|
}
|
|
53
47
|
}
|
|
@@ -32,12 +32,12 @@ function useUseAuthFromHercules() {
|
|
|
32
32
|
const { isAuthenticated, user, isLoading, signinSilent } = useAuth();
|
|
33
33
|
const idToken = user?.id_token;
|
|
34
34
|
const fetchAccessToken = useCallback(
|
|
35
|
-
async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
|
|
35
|
+
async ({ forceRefreshToken: _ignore }: { forceRefreshToken: boolean }) => {
|
|
36
36
|
try {
|
|
37
|
-
if (forceRefreshToken) {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
}
|
|
37
|
+
// if (forceRefreshToken) {
|
|
38
|
+
// const user = await signinSilent();
|
|
39
|
+
// return user?.id_token ?? null;
|
|
40
|
+
// }
|
|
41
41
|
return idToken ?? null;
|
|
42
42
|
} catch {
|
|
43
43
|
return null;
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { useEffect, useState, useRef, useCallback } from "react";
|
|
4
|
+
import { useAuth, hasAuthParams } from "react-oidc-context";
|
|
5
|
+
|
|
6
|
+
const DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Authentication callback status states
|
|
10
|
+
* @public
|
|
11
|
+
*/
|
|
12
|
+
export type AuthCallbackStatus =
|
|
13
|
+
| "processing-oauth" // OIDC is processing the callback
|
|
14
|
+
| "waiting-backend" // OIDC authenticated, waiting for backend
|
|
15
|
+
| "syncing" // Syncing user with backend (e.g., creating user record)
|
|
16
|
+
| "success" // All done
|
|
17
|
+
| "error"; // Something went wrong
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Options for the useAuthCallback hook
|
|
21
|
+
* @public
|
|
22
|
+
*/
|
|
23
|
+
export interface UseAuthCallbackOptions {
|
|
24
|
+
/**
|
|
25
|
+
* Timeout in milliseconds before the callback is considered failed.
|
|
26
|
+
* @default 20000
|
|
27
|
+
*/
|
|
28
|
+
timeoutMs?: number;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Whether the backend (e.g., Convex) is authenticated.
|
|
32
|
+
* The hook will wait for this to be true before calling onSync.
|
|
33
|
+
*/
|
|
34
|
+
isBackendAuthenticated?: boolean;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Called when the backend is authenticated and ready to sync.
|
|
38
|
+
* Use this to create/update the user in your backend.
|
|
39
|
+
* Return a promise that resolves when sync is complete.
|
|
40
|
+
*/
|
|
41
|
+
onSync?: () => Promise<void>;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Called when authentication is successful and sync is complete.
|
|
45
|
+
* Use this to redirect the user.
|
|
46
|
+
*/
|
|
47
|
+
onSuccess?: () => void;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Called when OIDC is not authenticated and there are no auth params.
|
|
51
|
+
* This typically means the user navigated directly to the callback page.
|
|
52
|
+
* Use this to redirect them away.
|
|
53
|
+
*/
|
|
54
|
+
onNoAuthParams?: () => void;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Return type for the useAuthCallback hook
|
|
59
|
+
* @public
|
|
60
|
+
*/
|
|
61
|
+
export interface UseAuthCallbackResult {
|
|
62
|
+
/** Current status of the auth callback flow */
|
|
63
|
+
status: AuthCallbackStatus;
|
|
64
|
+
|
|
65
|
+
/** Error message if status is "error" */
|
|
66
|
+
error: string | null;
|
|
67
|
+
|
|
68
|
+
/** Whether the auth callback is still in progress */
|
|
69
|
+
isLoading: boolean;
|
|
70
|
+
|
|
71
|
+
/** Whether the auth callback completed successfully */
|
|
72
|
+
isSuccess: boolean;
|
|
73
|
+
|
|
74
|
+
/** Whether there was an error */
|
|
75
|
+
isError: boolean;
|
|
76
|
+
|
|
77
|
+
/** Retry the authentication flow by redirecting to the auth provider */
|
|
78
|
+
retry: () => Promise<void>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* A hook for handling OAuth/OIDC callback flows.
|
|
83
|
+
*
|
|
84
|
+
* This hook manages the complete authentication callback lifecycle:
|
|
85
|
+
* 1. Processing the OAuth callback from the identity provider
|
|
86
|
+
* 2. Waiting for backend authentication (e.g., Convex)
|
|
87
|
+
* 3. Syncing user data with your backend
|
|
88
|
+
* 4. Handling success and error states
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* ```tsx
|
|
92
|
+
* function AuthCallback() {
|
|
93
|
+
* const navigate = useNavigate();
|
|
94
|
+
* const { isAuthenticated } = useConvexAuth();
|
|
95
|
+
* const updateUser = useMutation(api.users.updateCurrentUser);
|
|
96
|
+
*
|
|
97
|
+
* const { status, error, retry } = useAuthCallback({
|
|
98
|
+
* isBackendAuthenticated: isAuthenticated,
|
|
99
|
+
* onSync: () => updateUser(),
|
|
100
|
+
* onSuccess: () => navigate("/", { replace: true }),
|
|
101
|
+
* onNoAuthParams: () => navigate("/", { replace: true }),
|
|
102
|
+
* });
|
|
103
|
+
*
|
|
104
|
+
* if (status === "error") {
|
|
105
|
+
* return <ErrorState message={error} onRetry={retry} />;
|
|
106
|
+
* }
|
|
107
|
+
*
|
|
108
|
+
* return <LoadingSpinner />;
|
|
109
|
+
* }
|
|
110
|
+
* ```
|
|
111
|
+
*
|
|
112
|
+
* @public
|
|
113
|
+
*/
|
|
114
|
+
export function useAuthCallback(
|
|
115
|
+
options: UseAuthCallbackOptions = {},
|
|
116
|
+
): UseAuthCallbackResult {
|
|
117
|
+
const {
|
|
118
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
119
|
+
isBackendAuthenticated = true,
|
|
120
|
+
onSync,
|
|
121
|
+
onSuccess,
|
|
122
|
+
onNoAuthParams,
|
|
123
|
+
} = options;
|
|
124
|
+
|
|
125
|
+
const {
|
|
126
|
+
isLoading: isAuthLoading,
|
|
127
|
+
isAuthenticated: isOidcAuthenticated,
|
|
128
|
+
error: oidcError,
|
|
129
|
+
signinRedirect,
|
|
130
|
+
} = useAuth();
|
|
131
|
+
|
|
132
|
+
const [status, setStatus] = useState<AuthCallbackStatus>("processing-oauth");
|
|
133
|
+
const [error, setError] = useState<string | null>(null);
|
|
134
|
+
|
|
135
|
+
// Track mount state to prevent state updates after unmount
|
|
136
|
+
const mountedRef = useRef(true);
|
|
137
|
+
// Track if we had auth params on mount (won't change during lifecycle)
|
|
138
|
+
const hadAuthParams = useRef(hasAuthParams());
|
|
139
|
+
// Track if we've already started sync to prevent double execution
|
|
140
|
+
const syncStarted = useRef(false);
|
|
141
|
+
|
|
142
|
+
// Cleanup on unmount
|
|
143
|
+
useEffect(() => {
|
|
144
|
+
return () => {
|
|
145
|
+
mountedRef.current = false;
|
|
146
|
+
};
|
|
147
|
+
}, []);
|
|
148
|
+
|
|
149
|
+
// Timeout protection with state awareness
|
|
150
|
+
useEffect(() => {
|
|
151
|
+
if (status === "success" || status === "error") return;
|
|
152
|
+
|
|
153
|
+
const timeout = setTimeout(() => {
|
|
154
|
+
if (mountedRef.current) {
|
|
155
|
+
setStatus("error");
|
|
156
|
+
setError("Authentication timed out. Please try again.");
|
|
157
|
+
}
|
|
158
|
+
}, timeoutMs);
|
|
159
|
+
|
|
160
|
+
return () => clearTimeout(timeout);
|
|
161
|
+
}, [status, timeoutMs]);
|
|
162
|
+
|
|
163
|
+
// Track OIDC authentication progression
|
|
164
|
+
useEffect(() => {
|
|
165
|
+
// Don't update if we're already past processing or in an error state
|
|
166
|
+
if (status !== "processing-oauth" && status !== "waiting-backend") return;
|
|
167
|
+
|
|
168
|
+
// Handle OIDC errors
|
|
169
|
+
if (oidcError) {
|
|
170
|
+
setStatus("error");
|
|
171
|
+
setError(oidcError.message || "Authentication failed");
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// No auth params and not authenticated - navigated here directly
|
|
176
|
+
if (!hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated) {
|
|
177
|
+
onNoAuthParams?.();
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// OIDC is done loading and authenticated - move to waiting for backend
|
|
182
|
+
if (
|
|
183
|
+
!isAuthLoading &&
|
|
184
|
+
isOidcAuthenticated &&
|
|
185
|
+
status === "processing-oauth"
|
|
186
|
+
) {
|
|
187
|
+
setStatus("waiting-backend");
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// OIDC finished but not authenticated (and we had auth params)
|
|
192
|
+
// Wait a bit before declaring failure to avoid race conditions
|
|
193
|
+
if (
|
|
194
|
+
hadAuthParams.current &&
|
|
195
|
+
!isAuthLoading &&
|
|
196
|
+
!isOidcAuthenticated &&
|
|
197
|
+
!oidcError &&
|
|
198
|
+
status === "processing-oauth"
|
|
199
|
+
) {
|
|
200
|
+
// Use a small delay to avoid race condition during OIDC state transitions
|
|
201
|
+
const failureTimeout = setTimeout(() => {
|
|
202
|
+
if (mountedRef.current && !isOidcAuthenticated) {
|
|
203
|
+
setStatus("error");
|
|
204
|
+
setError("Authentication was cancelled or failed. Please try again.");
|
|
205
|
+
}
|
|
206
|
+
}, 500);
|
|
207
|
+
|
|
208
|
+
return () => clearTimeout(failureTimeout);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return;
|
|
212
|
+
}, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);
|
|
213
|
+
|
|
214
|
+
// Sync with backend once backend is authenticated
|
|
215
|
+
useEffect(() => {
|
|
216
|
+
if (status !== "waiting-backend" || !isBackendAuthenticated) return;
|
|
217
|
+
if (syncStarted.current) return;
|
|
218
|
+
|
|
219
|
+
syncStarted.current = true;
|
|
220
|
+
|
|
221
|
+
async function performSync() {
|
|
222
|
+
if (!mountedRef.current) return;
|
|
223
|
+
|
|
224
|
+
setStatus("syncing");
|
|
225
|
+
|
|
226
|
+
try {
|
|
227
|
+
if (onSync) {
|
|
228
|
+
await onSync();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (mountedRef.current) {
|
|
232
|
+
setStatus("success");
|
|
233
|
+
}
|
|
234
|
+
} catch (err) {
|
|
235
|
+
console.error("Auth callback sync failed:", err);
|
|
236
|
+
|
|
237
|
+
if (!mountedRef.current) return;
|
|
238
|
+
|
|
239
|
+
// Check if it's an authentication error
|
|
240
|
+
const errorMessage =
|
|
241
|
+
err instanceof Error && err.message.includes("UNAUTHENTICATED")
|
|
242
|
+
? "Your session expired. Please sign in again."
|
|
243
|
+
: "Failed to complete authentication. Please try again.";
|
|
244
|
+
|
|
245
|
+
setStatus("error");
|
|
246
|
+
setError(errorMessage);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
performSync();
|
|
251
|
+
}, [status, isBackendAuthenticated, onSync]);
|
|
252
|
+
|
|
253
|
+
// Handle successful completion
|
|
254
|
+
useEffect(() => {
|
|
255
|
+
if (status === "success") {
|
|
256
|
+
onSuccess?.();
|
|
257
|
+
}
|
|
258
|
+
}, [status, onSuccess]);
|
|
259
|
+
|
|
260
|
+
// Retry handler
|
|
261
|
+
const retry = useCallback(async () => {
|
|
262
|
+
try {
|
|
263
|
+
await signinRedirect();
|
|
264
|
+
} catch (err) {
|
|
265
|
+
console.error("Failed to restart auth:", err);
|
|
266
|
+
}
|
|
267
|
+
}, [signinRedirect]);
|
|
268
|
+
|
|
269
|
+
return {
|
|
270
|
+
status,
|
|
271
|
+
error,
|
|
272
|
+
isLoading: status !== "success" && status !== "error",
|
|
273
|
+
isSuccess: status === "success",
|
|
274
|
+
isError: status === "error",
|
|
275
|
+
retry,
|
|
276
|
+
};
|
|
277
|
+
}
|
package/src/react/index.ts
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import { defineConfig } from "
|
|
1
|
+
import { defineConfig } from "tsdown";
|
|
2
2
|
|
|
3
3
|
export default defineConfig((options) => [
|
|
4
4
|
{
|
|
5
5
|
...options,
|
|
6
6
|
entry: ["src/react/index.ts", "src/convex-react/index.ts"],
|
|
7
|
-
format: ["cjs", "esm"],
|
|
8
7
|
external: ["react", "react/jsx-runtime"],
|
|
9
8
|
dts: true,
|
|
10
|
-
clean: true,
|
|
11
9
|
sourcemap: true,
|
|
12
|
-
|
|
10
|
+
exports: true,
|
|
11
|
+
ignoreWatch: [".turbo"],
|
|
13
12
|
},
|
|
14
13
|
]);
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var u=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var p=(t,e)=>{for(var o in e)u(t,o,{get:e[o],enumerable:!0})},v=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of f(e))!m.call(t,r)&&r!==o&&u(t,r,{get:()=>e[r],enumerable:!(n=d(e,r))||n.enumerable});return t};var A=t=>v(u({},"__esModule",{value:!0}),t);var x={};p(x,{ConvexProviderWithHerculesAuth:()=>C});module.exports=A(x);var s=require("convex/react"),i=require("react"),l=require("react-oidc-context"),h=require("react/jsx-runtime");function C({children:t,client:e}){return(0,h.jsx)(s.ConvexProviderWithAuth,{client:e,useAuth:k,children:t})}function k(){let{isAuthenticated:t,user:e,isLoading:o,signinSilent:n}=(0,l.useAuth)(),r=e?.id_token,c=(0,i.useCallback)(async({forceRefreshToken:a})=>{try{return a?(await n())?.id_token??null:r??null}catch{return null}},[r,n]);return(0,i.useMemo)(()=>({isLoading:o,isAuthenticated:t,fetchAccessToken:c}),[o,t,c])}0&&(module.exports={ConvexProviderWithHerculesAuth});
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/convex-react/index.ts","../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":["export * from \"./ConvexProviderWithHercules\";\n","\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { ConvexProviderWithAuth, type ConvexReactClient } from \"convex/react\";\nimport { useCallback, useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\nimport type { HerculesAuthProvider } from \"../react/HerculesAuthProvider\";\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 `{@link 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\nfunction useUseAuthFromHercules() {\n const { isAuthenticated, user, isLoading, signinSilent } = useAuth();\n const idToken = user?.id_token;\n const fetchAccessToken = useCallback(\n async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {\n try {\n if (forceRefreshToken) {\n const user = await signinSilent();\n return user?.id_token ?? null;\n }\n return idToken ?? null;\n } catch {\n return null;\n }\n },\n [idToken, signinSilent],\n );\n return useMemo(\n () => ({\n isLoading,\n isAuthenticated,\n fetchAccessToken,\n }),\n [isLoading, isAuthenticated, fetchAccessToken],\n );\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oCAAAE,IAAA,eAAAC,EAAAH,GCGA,IAAAI,EAA+D,wBAC/DA,EAAqC,iBACrCC,EAAwB,8BAmBpBC,EAAA,6BARG,SAASC,EAA+B,CAC7C,SAAAC,EACA,OAAAC,CACF,EAGG,CACD,SACE,OAAC,0BAAuB,OAAQA,EAAQ,QAASC,EAC9C,SAAAF,EACH,CAEJ,CAEA,SAASE,GAAyB,CAChC,GAAM,CAAE,gBAAAC,EAAiB,KAAAC,EAAM,UAAAC,EAAW,aAAAC,CAAa,KAAI,WAAQ,EAC7DC,EAAUH,GAAM,SAChBI,KAAmB,eACvB,MAAO,CAAE,kBAAAC,CAAkB,IAAsC,CAC/D,GAAI,CACF,OAAIA,GACW,MAAMH,EAAa,IACnB,UAAY,KAEpBC,GAAW,IACpB,MAAQ,CACN,OAAO,IACT,CACF,EACA,CAACA,EAASD,CAAY,CACxB,EACA,SAAO,WACL,KAAO,CACL,UAAAD,EACA,gBAAAF,EACA,iBAAAK,CACF,GACA,CAACH,EAAWF,EAAiBK,CAAgB,CAC/C,CACF","names":["convex_react_exports","__export","ConvexProviderWithHerculesAuth","__toCommonJS","import_react","import_react_oidc_context","import_jsx_runtime","ConvexProviderWithHerculesAuth","children","client","useUseAuthFromHercules","isAuthenticated","user","isLoading","signinSilent","idToken","fetchAccessToken","forceRefreshToken"]}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
-
import { ReactNode } from 'react';
|
|
3
|
-
import { ConvexReactClient } from 'convex/react';
|
|
4
|
-
|
|
5
|
-
declare function ConvexProviderWithHerculesAuth({ children, client, }: {
|
|
6
|
-
children: ReactNode;
|
|
7
|
-
client: ConvexReactClient;
|
|
8
|
-
}): react_jsx_runtime.JSX.Element;
|
|
9
|
-
|
|
10
|
-
export { ConvexProviderWithHerculesAuth };
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
-
import { ReactNode } from 'react';
|
|
3
|
-
import { ConvexReactClient } from 'convex/react';
|
|
4
|
-
|
|
5
|
-
declare function ConvexProviderWithHerculesAuth({ children, client, }: {
|
|
6
|
-
children: ReactNode;
|
|
7
|
-
client: ConvexReactClient;
|
|
8
|
-
}): react_jsx_runtime.JSX.Element;
|
|
9
|
-
|
|
10
|
-
export { ConvexProviderWithHerculesAuth };
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{ConvexProviderWithAuth as c}from"convex/react";import{useCallback as s,useMemo as l}from"react";import{useAuth as h}from"react-oidc-context";import{jsx as d}from"react/jsx-runtime";function A({children:e,client:t}){return d(c,{client:t,useAuth:a,children:e})}function a(){let{isAuthenticated:e,user:t,isLoading:r,signinSilent:o}=h(),n=t?.id_token,i=s(async({forceRefreshToken:u})=>{try{return u?(await o())?.id_token??null:n??null}catch{return null}},[n,o]);return l(()=>({isLoading:r,isAuthenticated:e,fetchAccessToken:i}),[r,e,i])}export{A as ConvexProviderWithHerculesAuth};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { ConvexProviderWithAuth, type ConvexReactClient } from \"convex/react\";\nimport { useCallback, useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\nimport type { HerculesAuthProvider } from \"../react/HerculesAuthProvider\";\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 `{@link 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\nfunction useUseAuthFromHercules() {\n const { isAuthenticated, user, isLoading, signinSilent } = useAuth();\n const idToken = user?.id_token;\n const fetchAccessToken = useCallback(\n async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {\n try {\n if (forceRefreshToken) {\n const user = await signinSilent();\n return user?.id_token ?? null;\n }\n return idToken ?? null;\n } catch {\n return null;\n }\n },\n [idToken, signinSilent],\n );\n return useMemo(\n () => ({\n isLoading,\n isAuthenticated,\n fetchAccessToken,\n }),\n [isLoading, isAuthenticated, fetchAccessToken],\n );\n}\n"],"mappings":"AAGA,OAAS,0BAAAA,MAAsD,eAC/D,OAAS,eAAAC,EAAa,WAAAC,MAAe,QACrC,OAAS,WAAAC,MAAe,qBAmBpB,cAAAC,MAAA,oBARG,SAASC,EAA+B,CAC7C,SAAAC,EACA,OAAAC,CACF,EAGG,CACD,OACEH,EAACJ,EAAA,CAAuB,OAAQO,EAAQ,QAASC,EAC9C,SAAAF,EACH,CAEJ,CAEA,SAASE,GAAyB,CAChC,GAAM,CAAE,gBAAAC,EAAiB,KAAAC,EAAM,UAAAC,EAAW,aAAAC,CAAa,EAAIT,EAAQ,EAC7DU,EAAUH,GAAM,SAChBI,EAAmBb,EACvB,MAAO,CAAE,kBAAAc,CAAkB,IAAsC,CAC/D,GAAI,CACF,OAAIA,GACW,MAAMH,EAAa,IACnB,UAAY,KAEpBC,GAAW,IACpB,MAAQ,CACN,OAAO,IACT,CACF,EACA,CAACA,EAASD,CAAY,CACxB,EACA,OAAOV,EACL,KAAO,CACL,UAAAS,EACA,gBAAAF,EACA,iBAAAK,CACF,GACA,CAACH,EAAWF,EAAiBK,CAAgB,CAC/C,CACF","names":["ConvexProviderWithAuth","useCallback","useMemo","useAuth","jsx","ConvexProviderWithHerculesAuth","children","client","useUseAuthFromHercules","isAuthenticated","user","isLoading","signinSilent","idToken","fetchAccessToken","forceRefreshToken"]}
|
package/dist/react/index.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var s=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var _=(t,e)=>{for(var o in e)s(t,o,{get:e[o],enumerable:!0})},y=(t,e,o,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of A(e))!P.call(t,r)&&r!==o&&s(t,r,{get:()=>e[r],enumerable:!(i=w(e,r))||i.enumerable});return t};var v=t=>y(s({},"__esModule",{value:!0}),t);var L={};_(L,{HerculesAuthProvider:()=>H,hasAuthParams:()=>c.hasAuthParams,useAuth:()=>c.useAuth,useUser:()=>k});module.exports=v(L);var g=require("react"),x=require("react-oidc-context"),S=require("react/jsx-runtime");var u=require("react"),l=require("react-oidc-context"),n=require("oidc-client-ts"),p=require("react/jsx-runtime");function U(){window.history.replaceState({},document.title,window.location.pathname)}function b(){window.location.pathname=""}var C={onSignoutCallback:b,onSigninCallback:U};function H({children:t,userManagerSettings:e,authority:o,client_id:i,...r}){let[a]=(0,u.useState)(()=>new n.UserManager({...e,authority:e?.authority??o,client_id:e?.client_id??i,prompt:e?.prompt??"select_account",response_type:e?.response_type??"code",scope:e?.scope??"openid profile email offline_access",redirect_uri:e?.redirect_uri??`${window.location.origin}/auth/callback`,post_logout_redirect_uri:e?.post_logout_redirect_uri??window.location.origin,userStore:e?.userStore??new n.WebStorageStateStore({store:window.localStorage})}));return(0,p.jsx)(l.AuthProvider,{userManager:a,...C,...r,children:t})}var d=require("react"),h=require("react-oidc-context");function k(){let{user:t,isLoading:e,error:o,isAuthenticated:i}=(0,h.useAuth)();return(0,d.useMemo)(()=>{let r=t?.profile.sub,a=t?.profile.name,m=t?.profile.email,f=t?.profile.picture;return{...t??{},id:r,name:a,email:m,avatar:f,isAuthenticated:i,isLoading:e,error:o}},[t,i,e,o])}var c=require("react-oidc-context");0&&(module.exports={HerculesAuthProvider,hasAuthParams,useAuth,useUser});
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
package/dist/react/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/index.ts","../../src/react/AuthCallbackPage.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts"],"sourcesContent":["export * from \"./AuthCallbackPage\";\nexport * from \"./HerculesAuthProvider\";\nexport * from \"./use-user\";\n\n// rexports of react-oidc-context\nexport {\n type AuthContextProps,\n hasAuthParams,\n useAuth,\n} from \"react-oidc-context\";\n","import { useEffect } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\nexport default function AuthCallback() {\n const { isLoading, isAuthenticated, error } = useAuth();\n\n useEffect(() => {\n // Redirect to home after auth completes\n if (!isLoading && isAuthenticated) {\n window.history.replaceState({}, document.title, \"/\");\n }\n // Handle auth errors\n else if (!isLoading && error) {\n console.error(\"Authentication error:\", error);\n window.history.replaceState({}, document.title, \"/\");\n }\n // Handle auth cancellation/failure\n else if (!isLoading && !isAuthenticated && !error) {\n console.warn(\n \"Authentication completed without success or explicit error\",\n );\n window.history.replaceState({}, document.title, \"/\");\n }\n }, [isLoading, isAuthenticated, error]);\n\n return (\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n height: \"100vh\",\n }}\n >\n Loading...\n </div>\n );\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n} from \"react-oidc-context\";\nimport {\n UserManager,\n WebStorageStateStore,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\n\nexport type HerculesAuthProviderProps = Omit<\n AuthProviderUserManagerProps,\n \"userManager\"\n> & {\n userManagerSettings?: Partial<UserManagerSettings>;\n authority: string;\n client_id: string;\n};\n\nfunction onSigninCallback() {\n window.history.replaceState({}, document.title, window.location.pathname);\n}\n\nfunction onSignoutCallback() {\n window.location.pathname = \"\";\n}\n\nconst DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {\n onSignoutCallback,\n onSigninCallback,\n};\n\n/**\n * A wrapper React component which provides a {@link ReactAuthProvider}\n * configured with Hercules Auth.\n *\n * @public\n */\nexport function HerculesAuthProvider({\n children,\n userManagerSettings,\n authority,\n client_id,\n ...props\n}: HerculesAuthProviderProps) {\n const [userManager] = useState(\n () =>\n new UserManager({\n ...userManagerSettings,\n authority: userManagerSettings?.authority ?? authority,\n client_id: userManagerSettings?.client_id ?? client_id,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope:\n userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri:\n userManagerSettings?.redirect_uri ??\n `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ??\n window.location.origin,\n userStore:\n userManagerSettings?.userStore ??\n new WebStorageStateStore({ store: window.localStorage }),\n }),\n );\n\n return (\n <ReactAuthProvider\n userManager={userManager}\n {...DEFAULT_AUTH_CONFIG}\n {...props}\n >\n {children}\n </ReactAuthProvider>\n );\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\n/**\n * A hook that returns the current user if authenticated\n *\n * @public\n */\nexport function useUser() {\n const { user, isLoading, error, isAuthenticated } = useAuth();\n\n return useMemo(() => {\n const id = user?.profile.sub;\n const name = user?.profile.name;\n const email = user?.profile.email;\n const avatar = user?.profile.picture;\n return {\n ...(user ?? {}),\n id,\n name,\n email,\n avatar,\n isAuthenticated,\n isLoading,\n error,\n };\n }, [user, isAuthenticated, isLoading, error]);\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,0BAAAE,EAAA,oEAAAC,IAAA,eAAAC,EAAAJ,GCAA,IAAAK,EAA0B,iBAC1BC,EAAwB,8BAyBpBC,EAAA,6BCxBJ,IAAAC,EAAyB,iBACzBC,EAGO,8BACPC,EAIO,0BA4DHC,EAAA,6BAjDJ,SAASC,GAAmB,CAC1B,OAAO,QAAQ,aAAa,CAAC,EAAG,SAAS,MAAO,OAAO,SAAS,QAAQ,CAC1E,CAEA,SAASC,GAAoB,CAC3B,OAAO,SAAS,SAAW,EAC7B,CAEA,IAAMC,EAA0D,CAC9D,kBAAAD,EACA,iBAAAD,CACF,EAQO,SAASG,EAAqB,CACnC,SAAAC,EACA,oBAAAC,EACA,UAAAC,EACA,UAAAC,EACA,GAAGC,CACL,EAA8B,CAC5B,GAAM,CAACC,CAAW,KAAI,YACpB,IACE,IAAI,cAAY,CACd,GAAGJ,EACH,UAAWA,GAAqB,WAAaC,EAC7C,UAAWD,GAAqB,WAAaE,EAC7C,OAAQF,GAAqB,QAAU,iBACvC,cAAeA,GAAqB,eAAiB,OACrD,MACEA,GAAqB,OAAS,sCAChC,aACEA,GAAqB,cACrB,GAAG,OAAO,SAAS,MAAM,iBAC3B,yBACEA,GAAqB,0BACrB,OAAO,SAAS,OAClB,UACEA,GAAqB,WACrB,IAAI,uBAAqB,CAAE,MAAO,OAAO,YAAa,CAAC,CAC3D,CAAC,CACL,EAEA,SACE,OAAC,EAAAK,aAAA,CACC,YAAaD,EACZ,GAAGP,EACH,GAAGM,EAEH,SAAAJ,EACH,CAEJ,CC7EA,IAAAO,EAAwB,iBACxBC,EAAwB,8BAOjB,SAASC,GAAU,CACxB,GAAM,CAAE,KAAAC,EAAM,UAAAC,EAAW,MAAAC,EAAO,gBAAAC,CAAgB,KAAI,WAAQ,EAE5D,SAAO,WAAQ,IAAM,CACnB,IAAMC,EAAKJ,GAAM,QAAQ,IACnBK,EAAOL,GAAM,QAAQ,KACrBM,EAAQN,GAAM,QAAQ,MACtBO,EAASP,GAAM,QAAQ,QAC7B,MAAO,CACL,GAAIA,GAAQ,CAAC,EACb,GAAAI,EACA,KAAAC,EACA,MAAAC,EACA,OAAAC,EACA,gBAAAJ,EACA,UAAAF,EACA,MAAAC,CACF,CACF,EAAG,CAACF,EAAMG,EAAiBF,EAAWC,CAAK,CAAC,CAC9C,CHxBA,IAAAM,EAIO","names":["react_exports","__export","HerculesAuthProvider","useUser","__toCommonJS","import_react","import_react_oidc_context","import_jsx_runtime","import_react","import_react_oidc_context","import_oidc_client_ts","import_jsx_runtime","onSigninCallback","onSignoutCallback","DEFAULT_AUTH_CONFIG","HerculesAuthProvider","children","userManagerSettings","authority","client_id","props","userManager","ReactAuthProvider","import_react","import_react_oidc_context","useUser","user","isLoading","error","isAuthenticated","id","name","email","avatar","import_react_oidc_context"]}
|
package/dist/react/index.d.cts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
-
import * as react_oidc_context from 'react-oidc-context';
|
|
3
|
-
import { AuthProviderUserManagerProps } from 'react-oidc-context';
|
|
4
|
-
export { AuthContextProps, hasAuthParams, useAuth } from 'react-oidc-context';
|
|
5
|
-
import * as oidc_client_ts from 'oidc-client-ts';
|
|
6
|
-
import { UserManagerSettings } from 'oidc-client-ts';
|
|
7
|
-
|
|
8
|
-
type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
|
|
9
|
-
userManagerSettings?: Partial<UserManagerSettings>;
|
|
10
|
-
authority: string;
|
|
11
|
-
client_id: string;
|
|
12
|
-
};
|
|
13
|
-
declare function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, ...props }: HerculesAuthProviderProps): react_jsx_runtime.JSX.Element;
|
|
14
|
-
|
|
15
|
-
declare function useUser(): {
|
|
16
|
-
id: string | undefined;
|
|
17
|
-
name: string | undefined;
|
|
18
|
-
email: string | undefined;
|
|
19
|
-
avatar: string | undefined;
|
|
20
|
-
isAuthenticated: boolean;
|
|
21
|
-
isLoading: boolean;
|
|
22
|
-
error: react_oidc_context.ErrorContext | undefined;
|
|
23
|
-
id_token?: string;
|
|
24
|
-
session_state?: string | null | undefined;
|
|
25
|
-
access_token?: string | undefined;
|
|
26
|
-
refresh_token?: string;
|
|
27
|
-
token_type?: string | undefined;
|
|
28
|
-
scope?: string;
|
|
29
|
-
profile?: oidc_client_ts.IdTokenClaims | undefined;
|
|
30
|
-
expires_at?: number;
|
|
31
|
-
state?: unknown;
|
|
32
|
-
url_state?: string;
|
|
33
|
-
};
|
|
34
|
-
|
|
35
|
-
export { HerculesAuthProvider, type HerculesAuthProviderProps, useUser };
|
package/dist/react/index.d.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
-
import * as react_oidc_context from 'react-oidc-context';
|
|
3
|
-
import { AuthProviderUserManagerProps } from 'react-oidc-context';
|
|
4
|
-
export { AuthContextProps, hasAuthParams, useAuth } from 'react-oidc-context';
|
|
5
|
-
import * as oidc_client_ts from 'oidc-client-ts';
|
|
6
|
-
import { UserManagerSettings } from 'oidc-client-ts';
|
|
7
|
-
|
|
8
|
-
type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
|
|
9
|
-
userManagerSettings?: Partial<UserManagerSettings>;
|
|
10
|
-
authority: string;
|
|
11
|
-
client_id: string;
|
|
12
|
-
};
|
|
13
|
-
declare function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, ...props }: HerculesAuthProviderProps): react_jsx_runtime.JSX.Element;
|
|
14
|
-
|
|
15
|
-
declare function useUser(): {
|
|
16
|
-
id: string | undefined;
|
|
17
|
-
name: string | undefined;
|
|
18
|
-
email: string | undefined;
|
|
19
|
-
avatar: string | undefined;
|
|
20
|
-
isAuthenticated: boolean;
|
|
21
|
-
isLoading: boolean;
|
|
22
|
-
error: react_oidc_context.ErrorContext | undefined;
|
|
23
|
-
id_token?: string;
|
|
24
|
-
session_state?: string | null | undefined;
|
|
25
|
-
access_token?: string | undefined;
|
|
26
|
-
refresh_token?: string;
|
|
27
|
-
token_type?: string | undefined;
|
|
28
|
-
scope?: string;
|
|
29
|
-
profile?: oidc_client_ts.IdTokenClaims | undefined;
|
|
30
|
-
expires_at?: number;
|
|
31
|
-
state?: unknown;
|
|
32
|
-
url_state?: string;
|
|
33
|
-
};
|
|
34
|
-
|
|
35
|
-
export { HerculesAuthProvider, type HerculesAuthProviderProps, useUser };
|
package/dist/react/index.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{useEffect as _}from"react";import{useAuth as v}from"react-oidc-context";import{jsx as x}from"react/jsx-runtime";import{useState as s}from"react";import{AuthProvider as u}from"react-oidc-context";import{UserManager as l,WebStorageStateStore as p}from"oidc-client-ts";import{jsx as f}from"react/jsx-runtime";function d(){window.history.replaceState({},document.title,window.location.pathname)}function h(){window.location.pathname=""}var m={onSignoutCallback:h,onSigninCallback:d};function H({children:t,userManagerSettings:e,authority:o,client_id:r,...i}){let[n]=s(()=>new l({...e,authority:e?.authority??o,client_id:e?.client_id??r,prompt:e?.prompt??"select_account",response_type:e?.response_type??"code",scope:e?.scope??"openid profile email offline_access",redirect_uri:e?.redirect_uri??`${window.location.origin}/auth/callback`,post_logout_redirect_uri:e?.post_logout_redirect_uri??window.location.origin,userStore:e?.userStore??new p({store:window.localStorage})}));return f(u,{userManager:n,...m,...i,children:t})}import{useMemo as w}from"react";import{useAuth as A}from"react-oidc-context";function I(){let{user:t,isLoading:e,error:o,isAuthenticated:r}=A();return w(()=>{let i=t?.profile.sub,n=t?.profile.name,c=t?.profile.email,a=t?.profile.picture;return{...t??{},id:i,name:n,email:c,avatar:a,isAuthenticated:r,isLoading:e,error:o}},[t,r,e,o])}import{hasAuthParams as N,useAuth as W}from"react-oidc-context";export{H as HerculesAuthProvider,N as hasAuthParams,W as useAuth,I as useUser};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
package/dist/react/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/AuthCallbackPage.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts","../../src/react/index.ts"],"sourcesContent":["import { useEffect } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\nexport default function AuthCallback() {\n const { isLoading, isAuthenticated, error } = useAuth();\n\n useEffect(() => {\n // Redirect to home after auth completes\n if (!isLoading && isAuthenticated) {\n window.history.replaceState({}, document.title, \"/\");\n }\n // Handle auth errors\n else if (!isLoading && error) {\n console.error(\"Authentication error:\", error);\n window.history.replaceState({}, document.title, \"/\");\n }\n // Handle auth cancellation/failure\n else if (!isLoading && !isAuthenticated && !error) {\n console.warn(\n \"Authentication completed without success or explicit error\",\n );\n window.history.replaceState({}, document.title, \"/\");\n }\n }, [isLoading, isAuthenticated, error]);\n\n return (\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n height: \"100vh\",\n }}\n >\n Loading...\n </div>\n );\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n} from \"react-oidc-context\";\nimport {\n UserManager,\n WebStorageStateStore,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\n\nexport type HerculesAuthProviderProps = Omit<\n AuthProviderUserManagerProps,\n \"userManager\"\n> & {\n userManagerSettings?: Partial<UserManagerSettings>;\n authority: string;\n client_id: string;\n};\n\nfunction onSigninCallback() {\n window.history.replaceState({}, document.title, window.location.pathname);\n}\n\nfunction onSignoutCallback() {\n window.location.pathname = \"\";\n}\n\nconst DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {\n onSignoutCallback,\n onSigninCallback,\n};\n\n/**\n * A wrapper React component which provides a {@link ReactAuthProvider}\n * configured with Hercules Auth.\n *\n * @public\n */\nexport function HerculesAuthProvider({\n children,\n userManagerSettings,\n authority,\n client_id,\n ...props\n}: HerculesAuthProviderProps) {\n const [userManager] = useState(\n () =>\n new UserManager({\n ...userManagerSettings,\n authority: userManagerSettings?.authority ?? authority,\n client_id: userManagerSettings?.client_id ?? client_id,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope:\n userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri:\n userManagerSettings?.redirect_uri ??\n `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ??\n window.location.origin,\n userStore:\n userManagerSettings?.userStore ??\n new WebStorageStateStore({ store: window.localStorage }),\n }),\n );\n\n return (\n <ReactAuthProvider\n userManager={userManager}\n {...DEFAULT_AUTH_CONFIG}\n {...props}\n >\n {children}\n </ReactAuthProvider>\n );\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\n/**\n * A hook that returns the current user if authenticated\n *\n * @public\n */\nexport function useUser() {\n const { user, isLoading, error, isAuthenticated } = useAuth();\n\n return useMemo(() => {\n const id = user?.profile.sub;\n const name = user?.profile.name;\n const email = user?.profile.email;\n const avatar = user?.profile.picture;\n return {\n ...(user ?? {}),\n id,\n name,\n email,\n avatar,\n isAuthenticated,\n isLoading,\n error,\n };\n }, [user, isAuthenticated, isLoading, error]);\n}\n","export * from \"./AuthCallbackPage\";\nexport * from \"./HerculesAuthProvider\";\nexport * from \"./use-user\";\n\n// rexports of react-oidc-context\nexport {\n type AuthContextProps,\n hasAuthParams,\n useAuth,\n} from \"react-oidc-context\";\n"],"mappings":"AAAA,OAAS,aAAAA,MAAiB,QAC1B,OAAS,WAAAC,MAAe,qBAyBpB,cAAAC,MAAA,oBCxBJ,OAAS,YAAAC,MAAgB,QACzB,OACE,gBAAgBC,MAEX,qBACP,OACE,eAAAC,EACA,wBAAAC,MAEK,iBA4DH,cAAAC,MAAA,oBAjDJ,SAASC,GAAmB,CAC1B,OAAO,QAAQ,aAAa,CAAC,EAAG,SAAS,MAAO,OAAO,SAAS,QAAQ,CAC1E,CAEA,SAASC,GAAoB,CAC3B,OAAO,SAAS,SAAW,EAC7B,CAEA,IAAMC,EAA0D,CAC9D,kBAAAD,EACA,iBAAAD,CACF,EAQO,SAASG,EAAqB,CACnC,SAAAC,EACA,oBAAAC,EACA,UAAAC,EACA,UAAAC,EACA,GAAGC,CACL,EAA8B,CAC5B,GAAM,CAACC,CAAW,EAAId,EACpB,IACE,IAAIE,EAAY,CACd,GAAGQ,EACH,UAAWA,GAAqB,WAAaC,EAC7C,UAAWD,GAAqB,WAAaE,EAC7C,OAAQF,GAAqB,QAAU,iBACvC,cAAeA,GAAqB,eAAiB,OACrD,MACEA,GAAqB,OAAS,sCAChC,aACEA,GAAqB,cACrB,GAAG,OAAO,SAAS,MAAM,iBAC3B,yBACEA,GAAqB,0BACrB,OAAO,SAAS,OAClB,UACEA,GAAqB,WACrB,IAAIP,EAAqB,CAAE,MAAO,OAAO,YAAa,CAAC,CAC3D,CAAC,CACL,EAEA,OACEC,EAACH,EAAA,CACC,YAAaa,EACZ,GAAGP,EACH,GAAGM,EAEH,SAAAJ,EACH,CAEJ,CC7EA,OAAS,WAAAM,MAAe,QACxB,OAAS,WAAAC,MAAe,qBAOjB,SAASC,GAAU,CACxB,GAAM,CAAE,KAAAC,EAAM,UAAAC,EAAW,MAAAC,EAAO,gBAAAC,CAAgB,EAAIL,EAAQ,EAE5D,OAAOD,EAAQ,IAAM,CACnB,IAAMO,EAAKJ,GAAM,QAAQ,IACnBK,EAAOL,GAAM,QAAQ,KACrBM,EAAQN,GAAM,QAAQ,MACtBO,EAASP,GAAM,QAAQ,QAC7B,MAAO,CACL,GAAIA,GAAQ,CAAC,EACb,GAAAI,EACA,KAAAC,EACA,MAAAC,EACA,OAAAC,EACA,gBAAAJ,EACA,UAAAF,EACA,MAAAC,CACF,CACF,EAAG,CAACF,EAAMG,EAAiBF,EAAWC,CAAK,CAAC,CAC9C,CCxBA,OAEE,iBAAAM,EACA,WAAAC,MACK","names":["useEffect","useAuth","jsx","useState","ReactAuthProvider","UserManager","WebStorageStateStore","jsx","onSigninCallback","onSignoutCallback","DEFAULT_AUTH_CONFIG","HerculesAuthProvider","children","userManagerSettings","authority","client_id","props","userManager","useMemo","useAuth","useUser","user","isLoading","error","isAuthenticated","id","name","email","avatar","hasAuthParams","useAuth"]}
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { useEffect } from "react";
|
|
2
|
-
import { useAuth } from "react-oidc-context";
|
|
3
|
-
|
|
4
|
-
export default function AuthCallback() {
|
|
5
|
-
const { isLoading, isAuthenticated, error } = useAuth();
|
|
6
|
-
|
|
7
|
-
useEffect(() => {
|
|
8
|
-
// Redirect to home after auth completes
|
|
9
|
-
if (!isLoading && isAuthenticated) {
|
|
10
|
-
window.history.replaceState({}, document.title, "/");
|
|
11
|
-
}
|
|
12
|
-
// Handle auth errors
|
|
13
|
-
else if (!isLoading && error) {
|
|
14
|
-
console.error("Authentication error:", error);
|
|
15
|
-
window.history.replaceState({}, document.title, "/");
|
|
16
|
-
}
|
|
17
|
-
// Handle auth cancellation/failure
|
|
18
|
-
else if (!isLoading && !isAuthenticated && !error) {
|
|
19
|
-
console.warn(
|
|
20
|
-
"Authentication completed without success or explicit error",
|
|
21
|
-
);
|
|
22
|
-
window.history.replaceState({}, document.title, "/");
|
|
23
|
-
}
|
|
24
|
-
}, [isLoading, isAuthenticated, error]);
|
|
25
|
-
|
|
26
|
-
return (
|
|
27
|
-
<div
|
|
28
|
-
style={{
|
|
29
|
-
display: "flex",
|
|
30
|
-
alignItems: "center",
|
|
31
|
-
justifyContent: "center",
|
|
32
|
-
height: "100vh",
|
|
33
|
-
}}
|
|
34
|
-
>
|
|
35
|
-
Loading...
|
|
36
|
-
</div>
|
|
37
|
-
);
|
|
38
|
-
}
|