@civic/auth 0.9.6-beta.1 → 0.10.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/dist/nextjs/actions.d.ts +12 -0
- package/dist/nextjs/actions.d.ts.map +1 -0
- package/dist/nextjs/actions.js +26 -0
- package/dist/nextjs/actions.js.map +1 -0
- package/dist/nextjs/config.d.ts +2 -0
- package/dist/nextjs/config.d.ts.map +1 -1
- package/dist/nextjs/config.js +3 -2
- package/dist/nextjs/config.js.map +1 -1
- package/dist/nextjs/cookies.d.ts.map +1 -1
- package/dist/nextjs/cookies.js +45 -3
- package/dist/nextjs/cookies.js.map +1 -1
- package/dist/nextjs/hooks/useInitialAuthConfig.d.ts +31 -0
- package/dist/nextjs/hooks/useInitialAuthConfig.d.ts.map +1 -0
- package/dist/nextjs/hooks/useInitialAuthConfig.js +113 -0
- package/dist/nextjs/hooks/useInitialAuthConfig.js.map +1 -0
- package/dist/nextjs/index.d.ts +1 -0
- package/dist/nextjs/index.d.ts.map +1 -1
- package/dist/nextjs/index.js +13 -3
- package/dist/nextjs/index.js.map +1 -1
- package/dist/nextjs/providers/NextAuthProvider.d.ts +6 -7
- package/dist/nextjs/providers/NextAuthProvider.d.ts.map +1 -1
- package/dist/nextjs/providers/NextAuthProvider.js +19 -138
- package/dist/nextjs/providers/NextAuthProvider.js.map +1 -1
- package/dist/nextjs/providers/NextAuthProviderClient.d.ts +11 -0
- package/dist/nextjs/providers/NextAuthProviderClient.d.ts.map +1 -0
- package/dist/nextjs/providers/NextAuthProviderClient.js +62 -0
- package/dist/nextjs/providers/NextAuthProviderClient.js.map +1 -0
- package/dist/nextjs/providers/ServerUserContext.d.ts +2 -0
- package/dist/nextjs/providers/ServerUserContext.d.ts.map +1 -0
- package/dist/nextjs/providers/ServerUserContext.js +5 -0
- package/dist/nextjs/providers/ServerUserContext.js.map +1 -0
- package/dist/nextjs/routeHandler.d.ts.map +1 -1
- package/dist/nextjs/routeHandler.js +240 -341
- package/dist/nextjs/routeHandler.js.map +1 -1
- package/dist/react-router-7/components/UserButton.js +1 -1
- package/dist/react-router-7/components/UserButton.js.map +1 -1
- package/dist/react-router-7/routeHandler.d.ts.map +1 -1
- package/dist/react-router-7/routeHandler.js +1 -0
- package/dist/react-router-7/routeHandler.js.map +1 -1
- package/dist/react-router-7/useUser.d.ts.map +1 -1
- package/dist/react-router-7/useUser.js +13 -2
- package/dist/react-router-7/useUser.js.map +1 -1
- package/dist/reactjs/components/ButtonContentOrLoader.d.ts.map +1 -1
- package/dist/reactjs/components/ButtonContentOrLoader.js +1 -3
- package/dist/reactjs/components/ButtonContentOrLoader.js.map +1 -1
- package/dist/reactjs/components/CivicAuthIframeContainer.d.ts +2 -0
- package/dist/reactjs/components/CivicAuthIframeContainer.d.ts.map +1 -0
- package/dist/reactjs/components/CivicAuthIframeContainer.js +26 -0
- package/dist/reactjs/components/CivicAuthIframeContainer.js.map +1 -0
- package/dist/reactjs/components/SignInButton.d.ts.map +1 -1
- package/dist/reactjs/components/SignInButton.js +11 -1
- package/dist/reactjs/components/SignInButton.js.map +1 -1
- package/dist/reactjs/components/UserButton.d.ts +9 -2
- package/dist/reactjs/components/UserButton.d.ts.map +1 -1
- package/dist/reactjs/components/UserButton.js +41 -9
- package/dist/reactjs/components/UserButton.js.map +1 -1
- package/dist/reactjs/components/index.d.ts +1 -0
- package/dist/reactjs/components/index.d.ts.map +1 -1
- package/dist/reactjs/components/index.js +1 -0
- package/dist/reactjs/components/index.js.map +1 -1
- package/dist/reactjs/core/GlobalAuthManager.d.ts +26 -0
- package/dist/reactjs/core/GlobalAuthManager.d.ts.map +1 -1
- package/dist/reactjs/core/GlobalAuthManager.js +76 -5
- package/dist/reactjs/core/GlobalAuthManager.js.map +1 -1
- package/dist/reactjs/hooks/useUser.d.ts +19 -2
- package/dist/reactjs/hooks/useUser.d.ts.map +1 -1
- package/dist/reactjs/hooks/useUser.js +95 -7
- package/dist/reactjs/hooks/useUser.js.map +1 -1
- package/dist/reactjs/index.d.ts +1 -2
- package/dist/reactjs/index.d.ts.map +1 -1
- package/dist/reactjs/index.js +1 -2
- package/dist/reactjs/index.js.map +1 -1
- package/dist/server/ServerAuthenticationResolver.d.ts.map +1 -1
- package/dist/server/ServerAuthenticationResolver.js +18 -0
- package/dist/server/ServerAuthenticationResolver.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/logout.d.ts.map +1 -1
- package/dist/server/logout.js +11 -2
- package/dist/server/logout.js.map +1 -1
- package/dist/server/session.d.ts +51 -0
- package/dist/server/session.d.ts.map +1 -1
- package/dist/server/session.js +296 -17
- package/dist/server/session.js.map +1 -1
- package/dist/shared/components/SVGLoading.js +1 -1
- package/dist/shared/components/SVGLoading.js.map +1 -1
- package/dist/shared/components/UserButtonPresentation.d.ts.map +1 -0
- package/dist/shared/components/UserButtonPresentation.js.map +1 -0
- package/dist/shared/hooks/index.d.ts +1 -2
- package/dist/shared/hooks/index.d.ts.map +1 -1
- package/dist/shared/hooks/index.js +1 -2
- package/dist/shared/hooks/index.js.map +1 -1
- package/dist/shared/hooks/useBfcacheHandler.d.ts +23 -0
- package/dist/shared/hooks/useBfcacheHandler.d.ts.map +1 -0
- package/dist/shared/hooks/useBfcacheHandler.js +65 -0
- package/dist/shared/hooks/useBfcacheHandler.js.map +1 -0
- package/dist/shared/index.d.ts +1 -0
- package/dist/shared/index.d.ts.map +1 -1
- package/dist/shared/index.js +1 -0
- package/dist/shared/index.js.map +1 -1
- package/dist/shared/lib/util.d.ts +32 -0
- package/dist/shared/lib/util.d.ts.map +1 -1
- package/dist/shared/lib/util.js +79 -0
- package/dist/shared/lib/util.js.map +1 -1
- package/dist/shared/providers/AuthStatusContext.d.ts.map +1 -1
- package/dist/shared/providers/AuthStatusContext.js +2 -1
- package/dist/shared/providers/AuthStatusContext.js.map +1 -1
- package/dist/shared/providers/CivicAuthConfigContext.d.ts +2 -1
- package/dist/shared/providers/CivicAuthConfigContext.d.ts.map +1 -1
- package/dist/shared/providers/CivicAuthConfigContext.js +5 -2
- package/dist/shared/providers/CivicAuthConfigContext.js.map +1 -1
- package/dist/shared/providers/types.d.ts +1 -0
- package/dist/shared/providers/types.d.ts.map +1 -1
- package/dist/shared/providers/types.js.map +1 -1
- package/dist/shared/utils/locationChange.d.ts +34 -0
- package/dist/shared/utils/locationChange.d.ts.map +1 -0
- package/dist/shared/utils/locationChange.js +28 -0
- package/dist/shared/utils/locationChange.js.map +1 -0
- package/dist/shared/version.d.ts +1 -1
- package/dist/shared/version.d.ts.map +1 -1
- package/dist/shared/version.js +1 -1
- package/dist/shared/version.js.map +1 -1
- package/dist/vanillajs/auth/AuthenticationEvents.d.ts +10 -1
- package/dist/vanillajs/auth/AuthenticationEvents.d.ts.map +1 -1
- package/dist/vanillajs/auth/AuthenticationEvents.js +29 -0
- package/dist/vanillajs/auth/AuthenticationEvents.js.map +1 -1
- package/dist/vanillajs/auth/BackendAuthenticationRefresher.d.ts.map +1 -1
- package/dist/vanillajs/auth/BackendAuthenticationRefresher.js +2 -2
- package/dist/vanillajs/auth/BackendAuthenticationRefresher.js.map +1 -1
- package/dist/vanillajs/auth/CivicAuth.d.ts +32 -0
- package/dist/vanillajs/auth/CivicAuth.d.ts.map +1 -1
- package/dist/vanillajs/auth/CivicAuth.js +270 -55
- package/dist/vanillajs/auth/CivicAuth.js.map +1 -1
- package/dist/vanillajs/auth/SessionManager.d.ts +3 -2
- package/dist/vanillajs/auth/SessionManager.d.ts.map +1 -1
- package/dist/vanillajs/auth/SessionManager.js +33 -7
- package/dist/vanillajs/auth/SessionManager.js.map +1 -1
- package/dist/vanillajs/auth/config/ConfigProcessor.d.ts.map +1 -1
- package/dist/vanillajs/auth/config/ConfigProcessor.js +2 -14
- package/dist/vanillajs/auth/config/ConfigProcessor.js.map +1 -1
- package/dist/vanillajs/auth/handlers/IframeAuthHandler.d.ts.map +1 -1
- package/dist/vanillajs/auth/handlers/IframeAuthHandler.js +64 -11
- package/dist/vanillajs/auth/handlers/IframeAuthHandler.js.map +1 -1
- package/dist/vanillajs/auth/handlers/MessageHandler.d.ts.map +1 -1
- package/dist/vanillajs/auth/handlers/MessageHandler.js +4 -1
- package/dist/vanillajs/auth/handlers/MessageHandler.js.map +1 -1
- package/dist/vanillajs/auth/handlers/PopupHandler.d.ts.map +1 -1
- package/dist/vanillajs/auth/handlers/PopupHandler.js +3 -1
- package/dist/vanillajs/auth/handlers/PopupHandler.js.map +1 -1
- package/dist/vanillajs/auth/types/AuthTypes.d.ts +11 -1
- package/dist/vanillajs/auth/types/AuthTypes.d.ts.map +1 -1
- package/dist/vanillajs/auth/types/AuthTypes.js.map +1 -1
- package/dist/vanillajs/iframe/IframeManager.d.ts +22 -1
- package/dist/vanillajs/iframe/IframeManager.d.ts.map +1 -1
- package/dist/vanillajs/iframe/IframeManager.js +184 -22
- package/dist/vanillajs/iframe/IframeManager.js.map +1 -1
- package/dist/vanillajs/types/index.d.ts +1 -1
- package/dist/vanillajs/types/index.d.ts.map +1 -1
- package/dist/vanillajs/types/index.js +1 -1
- package/dist/vanillajs/types/index.js.map +1 -1
- package/dist/vanillajs/ui/LoadingComponents.d.ts +4 -0
- package/dist/vanillajs/ui/LoadingComponents.d.ts.map +1 -1
- package/dist/vanillajs/ui/LoadingComponents.js +51 -1
- package/dist/vanillajs/ui/LoadingComponents.js.map +1 -1
- package/package.json +3 -3
- package/dist/nextjs/hooks/index.d.ts +0 -2
- package/dist/nextjs/hooks/index.d.ts.map +0 -1
- package/dist/nextjs/hooks/index.js +0 -2
- package/dist/nextjs/hooks/index.js.map +0 -1
- package/dist/nextjs/hooks/usePrevious.d.ts +0 -2
- package/dist/nextjs/hooks/usePrevious.d.ts.map +0 -1
- package/dist/nextjs/hooks/usePrevious.js +0 -9
- package/dist/nextjs/hooks/usePrevious.js.map +0 -1
- package/dist/nextjs/hooks/useUserCookie.d.ts +0 -9
- package/dist/nextjs/hooks/useUserCookie.d.ts.map +0 -1
- package/dist/nextjs/hooks/useUserCookie.js +0 -109
- package/dist/nextjs/hooks/useUserCookie.js.map +0 -1
- package/dist/react-router-7/components/UserButtonPresentation.d.ts.map +0 -1
- package/dist/react-router-7/components/UserButtonPresentation.js.map +0 -1
- package/dist/shared/components/BlockDisplay.d.ts +0 -6
- package/dist/shared/components/BlockDisplay.d.ts.map +0 -1
- package/dist/shared/components/BlockDisplay.js +0 -30
- package/dist/shared/components/BlockDisplay.js.map +0 -1
- package/dist/shared/components/CivicAuthIframe.d.ts +0 -10
- package/dist/shared/components/CivicAuthIframe.d.ts.map +0 -1
- package/dist/shared/components/CivicAuthIframe.js +0 -49
- package/dist/shared/components/CivicAuthIframe.js.map +0 -1
- package/dist/shared/components/CivicAuthIframeContainer.d.ts +0 -15
- package/dist/shared/components/CivicAuthIframeContainer.d.ts.map +0 -1
- package/dist/shared/components/CivicAuthIframeContainer.js +0 -177
- package/dist/shared/components/CivicAuthIframeContainer.js.map +0 -1
- package/dist/shared/components/CivicAuthLogoutIframeContainer.d.ts +0 -6
- package/dist/shared/components/CivicAuthLogoutIframeContainer.d.ts.map +0 -1
- package/dist/shared/components/CivicAuthLogoutIframeContainer.js +0 -51
- package/dist/shared/components/CivicAuthLogoutIframeContainer.js.map +0 -1
- package/dist/shared/components/IFrameAndLoading.d.ts +0 -7
- package/dist/shared/components/IFrameAndLoading.d.ts.map +0 -1
- package/dist/shared/components/IFrameAndLoading.js +0 -66
- package/dist/shared/components/IFrameAndLoading.js.map +0 -1
- package/dist/shared/hooks/useAuth.d.ts +0 -3
- package/dist/shared/hooks/useAuth.d.ts.map +0 -1
- package/dist/shared/hooks/useAuth.js +0 -12
- package/dist/shared/hooks/useAuth.js.map +0 -1
- package/dist/shared/hooks/useIframe.d.ts +0 -3
- package/dist/shared/hooks/useIframe.d.ts.map +0 -1
- package/dist/shared/hooks/useIframe.js +0 -13
- package/dist/shared/hooks/useIframe.js.map +0 -1
- package/dist/shared/hooks/useIsInIframe.d.ts +0 -7
- package/dist/shared/hooks/useIsInIframe.d.ts.map +0 -1
- package/dist/shared/hooks/useIsInIframe.js +0 -23
- package/dist/shared/hooks/useIsInIframe.js.map +0 -1
- package/dist/shared/hooks/useSignIn.d.ts +0 -20
- package/dist/shared/hooks/useSignIn.d.ts.map +0 -1
- package/dist/shared/hooks/useSignIn.js +0 -358
- package/dist/shared/hooks/useSignIn.js.map +0 -1
- package/dist/shared/providers/IframeProvider.d.ts +0 -28
- package/dist/shared/providers/IframeProvider.d.ts.map +0 -1
- package/dist/shared/providers/IframeProvider.js +0 -64
- package/dist/shared/providers/IframeProvider.js.map +0 -1
- /package/dist/{react-router-7 → shared}/components/UserButtonPresentation.d.ts +0 -0
- /package/dist/{react-router-7 → shared}/components/UserButtonPresentation.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useUser.d.ts","sourceRoot":"","sources":["../../../src/reactjs/hooks/useUser.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useUser.d.ts","sourceRoot":"","sources":["../../../src/reactjs/hooks/useUser.ts"],"names":[],"mappings":"AA0CA,OAAO,KAAK,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAEL,KAAK,gBAAgB,EAEtB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAGjD,MAAM,WAAW,YAAY;IAC3B,WAAW,CAAC,EAAE,oBAAoB,CAAC;IACnC,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,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AAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;IAC9C,iBAAiB,EAAE,MAAM,OAAO,CAAC;IACjC,WAAW,CAAC,EAAE,WAAW,CAAC;CAC3B;AAED,QAAA,MAAM,OAAO,GAAI,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,mCACvC,gBAAgB,KACxB,eAAe,CAAC,CAAC,CAwSnB,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC"}
|
|
@@ -39,16 +39,54 @@
|
|
|
39
39
|
"use client";
|
|
40
40
|
import { useContext, useState, useEffect, useCallback, useMemo } from "react";
|
|
41
41
|
import { UserContext } from "../../shared/providers/UserProvider.js";
|
|
42
|
+
import { ServerUserContext } from "../../nextjs/providers/ServerUserContext.js";
|
|
42
43
|
import { GlobalAuthManager, } from "../core/GlobalAuthManager.js";
|
|
43
44
|
import { extractTokensFromSession } from "../../vanillajs/utils/auth-utils.js";
|
|
44
45
|
const useUser = (config) => {
|
|
45
46
|
// Always call context hooks unconditionally (rules of hooks)
|
|
46
47
|
const sharedContext = useContext(UserContext);
|
|
48
|
+
const serverUser = useContext(ServerUserContext);
|
|
47
49
|
// State for global manager approach
|
|
48
50
|
const [globalState, setGlobalState] = useState(null);
|
|
49
51
|
// Determine which approach to use
|
|
50
52
|
const hasProviderContext = sharedContext;
|
|
51
53
|
const shouldUseGlobal = !hasProviderContext;
|
|
54
|
+
// Helper to merge config overrides with current manager config
|
|
55
|
+
const createConfigWithOverrides = useCallback((overrides) => {
|
|
56
|
+
const manager = GlobalAuthManager.getInstance();
|
|
57
|
+
const currentConfig = manager.getConfig();
|
|
58
|
+
// Use current config from manager, or fall back to initial config if manager not initialized
|
|
59
|
+
const baseConfig = currentConfig || config || {};
|
|
60
|
+
return {
|
|
61
|
+
...baseConfig, // Complete current config from GlobalAuthManager
|
|
62
|
+
// Override specific properties while keeping the base config
|
|
63
|
+
...(overrides.displayMode && { displayMode: overrides.displayMode }),
|
|
64
|
+
...(overrides.iframeMode !== undefined && {
|
|
65
|
+
iframeMode: overrides.iframeMode,
|
|
66
|
+
}),
|
|
67
|
+
...(overrides.clientId && { clientId: overrides.clientId }),
|
|
68
|
+
...(overrides.redirectUrl && { redirectUrl: overrides.redirectUrl }),
|
|
69
|
+
...(overrides.logoutRedirectUrl && {
|
|
70
|
+
logoutRedirectUrl: overrides.logoutRedirectUrl,
|
|
71
|
+
}),
|
|
72
|
+
...(overrides.targetContainerElement && {
|
|
73
|
+
targetContainerElement: overrides.targetContainerElement,
|
|
74
|
+
}),
|
|
75
|
+
...(overrides.scopes && { scopes: overrides.scopes }),
|
|
76
|
+
...(overrides.authProcessTimeout && {
|
|
77
|
+
authProcessTimeout: overrides.authProcessTimeout,
|
|
78
|
+
}),
|
|
79
|
+
...(overrides.preloadIframe !== undefined && {
|
|
80
|
+
preloadIframe: overrides.preloadIframe,
|
|
81
|
+
}),
|
|
82
|
+
...(overrides.autoRedirect !== undefined && {
|
|
83
|
+
autoRedirect: overrides.autoRedirect,
|
|
84
|
+
}),
|
|
85
|
+
...(overrides.onSignIn && { onSignIn: overrides.onSignIn }),
|
|
86
|
+
...(overrides.onSignOut && { onSignOut: overrides.onSignOut }),
|
|
87
|
+
...(overrides.onUrlChange && { onUrlChange: overrides.onUrlChange }),
|
|
88
|
+
};
|
|
89
|
+
}, [config]);
|
|
52
90
|
// Initialize global manager if no provider context
|
|
53
91
|
useEffect(() => {
|
|
54
92
|
if (!shouldUseGlobal)
|
|
@@ -75,8 +113,13 @@ const useUser = (config) => {
|
|
|
75
113
|
return unsubscribe;
|
|
76
114
|
}, [shouldUseGlobal, config]);
|
|
77
115
|
// Global manager sign in/out functions
|
|
78
|
-
const globalSignIn = useCallback(async () => {
|
|
116
|
+
const globalSignIn = useCallback(async (signInConfig) => {
|
|
79
117
|
const manager = GlobalAuthManager.getInstance();
|
|
118
|
+
// If config is provided, reinitialize with merged config
|
|
119
|
+
if (signInConfig) {
|
|
120
|
+
const mergedConfig = createConfigWithOverrides(signInConfig);
|
|
121
|
+
await manager.initialize(mergedConfig);
|
|
122
|
+
}
|
|
80
123
|
await manager.signIn();
|
|
81
124
|
// Get the user after sign in
|
|
82
125
|
const state = manager.getState();
|
|
@@ -84,11 +127,16 @@ const useUser = (config) => {
|
|
|
84
127
|
throw new Error("Authentication succeeded but no user was returned");
|
|
85
128
|
}
|
|
86
129
|
return { user: state.user };
|
|
87
|
-
}, []);
|
|
88
|
-
const globalSignOut = useCallback(async () => {
|
|
130
|
+
}, [createConfigWithOverrides]);
|
|
131
|
+
const globalSignOut = useCallback(async (signOutConfig) => {
|
|
89
132
|
const manager = GlobalAuthManager.getInstance();
|
|
133
|
+
// If config is provided, reinitialize with merged config
|
|
134
|
+
if (signOutConfig) {
|
|
135
|
+
const mergedConfig = createConfigWithOverrides(signOutConfig);
|
|
136
|
+
await manager.initialize(mergedConfig);
|
|
137
|
+
}
|
|
90
138
|
await manager.signOut();
|
|
91
|
-
}, []);
|
|
139
|
+
}, [createConfigWithOverrides]);
|
|
92
140
|
// Global manager preloading functions
|
|
93
141
|
const globalIsAuthenticationPreloaded = useCallback(() => {
|
|
94
142
|
const manager = GlobalAuthManager.getInstance();
|
|
@@ -107,8 +155,13 @@ const useUser = (config) => {
|
|
|
107
155
|
return extractTokensFromSession(globalState?.session || null);
|
|
108
156
|
}, [globalState?.session]);
|
|
109
157
|
// Create wrapper functions for different signIn signatures
|
|
110
|
-
const wrapSharedSignIn = useCallback(async () => {
|
|
158
|
+
const wrapSharedSignIn = useCallback(async (sharedConfig) => {
|
|
111
159
|
if (sharedContext) {
|
|
160
|
+
// Note: Shared context doesn't support config overrides yet
|
|
161
|
+
// This is a limitation of the legacy provider system
|
|
162
|
+
if (sharedConfig) {
|
|
163
|
+
console.warn("Config overrides are not supported with legacy UserContext. Consider upgrading to GlobalAuthManager for full config override support.");
|
|
164
|
+
}
|
|
112
165
|
await sharedContext.signIn(); // This returns void
|
|
113
166
|
// Get user from context after sign in
|
|
114
167
|
if (sharedContext.user) {
|
|
@@ -129,9 +182,44 @@ const useUser = (config) => {
|
|
|
129
182
|
const sharedGetPreloadEnabled = useCallback(() => {
|
|
130
183
|
return false; // Not available in shared context
|
|
131
184
|
}, []);
|
|
185
|
+
// Create wrapper for sharedContext signOut with config support
|
|
186
|
+
const wrapSharedSignOut = useCallback(async (sharedConfig) => {
|
|
187
|
+
if (sharedContext) {
|
|
188
|
+
// Note: Shared context doesn't support config overrides yet
|
|
189
|
+
if (sharedConfig) {
|
|
190
|
+
console.warn("Config overrides are not supported with legacy UserContext. Consider upgrading to GlobalAuthManager for full config override support.");
|
|
191
|
+
}
|
|
192
|
+
await sharedContext.signOut();
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
throw new Error("Shared context not available");
|
|
196
|
+
}
|
|
197
|
+
}, [sharedContext]);
|
|
132
198
|
// ========================================================================
|
|
133
|
-
// FALLBACK PRIORITY SYSTEM -
|
|
199
|
+
// FALLBACK PRIORITY SYSTEM - Three authentication context approaches
|
|
134
200
|
// ========================================================================
|
|
201
|
+
// 0. NextJS ServerUserContext (HIGHEST PRIORITY - Fresh server data)
|
|
202
|
+
// This ensures client components sync with server data after revalidation
|
|
203
|
+
if (serverUser !== null) {
|
|
204
|
+
return {
|
|
205
|
+
user: serverUser,
|
|
206
|
+
idToken: null, // Not available with server-only data
|
|
207
|
+
accessToken: null, // Not available with server-only data
|
|
208
|
+
refreshToken: null, // Not available with server-only data
|
|
209
|
+
forwardedTokens: undefined, // Not available with server-only data
|
|
210
|
+
isLoading: false, // Server data is immediately available
|
|
211
|
+
authStatus: (serverUser
|
|
212
|
+
? "authenticated"
|
|
213
|
+
: "unauthenticated"),
|
|
214
|
+
error: null,
|
|
215
|
+
signIn: globalSignIn,
|
|
216
|
+
signOut: globalSignOut,
|
|
217
|
+
isAuthenticationPreloaded: globalIsAuthenticationPreloaded,
|
|
218
|
+
setPreloadEnabled: globalSetPreloadEnabled,
|
|
219
|
+
getPreloadEnabled: globalGetPreloadEnabled,
|
|
220
|
+
displayMode: config?.displayMode,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
135
223
|
// 1. DEPRECATED UserContext (ACTIVE - Used by NextJS)
|
|
136
224
|
// Framework-agnostic shared context from UserProvider
|
|
137
225
|
// Location: shared/providers/UserProvider.tsx
|
|
@@ -147,7 +235,7 @@ const useUser = (config) => {
|
|
|
147
235
|
authStatus: sharedContext.authStatus,
|
|
148
236
|
error: sharedContext.error,
|
|
149
237
|
signIn: wrapSharedSignIn,
|
|
150
|
-
signOut:
|
|
238
|
+
signOut: wrapSharedSignOut,
|
|
151
239
|
isAuthenticationPreloaded: sharedIsAuthenticationPreloaded,
|
|
152
240
|
setPreloadEnabled: sharedSetPreloadEnabled,
|
|
153
241
|
getPreloadEnabled: sharedGetPreloadEnabled,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useUser.js","sourceRoot":"","sources":["../../../src/reactjs/hooks/useUser.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,YAAY,CAAC;AACb,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAIrE,OAAO,EACL,iBAAiB,GAGlB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAsB/E,MAAM,OAAO,GAAG,CACd,MAAyB,EACL,EAAE;IACtB,6DAA6D;IAC7D,MAAM,aAAa,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;IAE9C,oCAAoC;IACpC,MAAM,CAAC,WAAW,EAAE,cAAc,CAAC,GAAG,QAAQ,CAAyB,IAAI,CAAC,CAAC;IAE7E,kCAAkC;IAClC,MAAM,kBAAkB,GAAG,aAAa,CAAC;IACzC,MAAM,eAAe,GAAG,CAA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AAiB,EAAE,uBAAuB;YAC1C,WAAW,EAAE,aAAa,CAAC,WAAW;SACvC,CAAC;IACJ,CAAC;IAED,yDAAyD;IACzD,wEAAwE;IACxE,8CAA8C;IAC9C,6EAA6E;IAC7E,yEAAyE;IACzE,IAAI,WAAW,EAAE,CAAC;QAChB,OAAO;YACL,IAAI,EAAE,WAAW,CAAC,IAAsB;YACxC,OAAO,EAAE,YAAY,CAAC,OAAO;YAC7B,WAAW,EAAE,YAAY,CAAC,WAAW;YACrC,YAAY,EAAE,YAAY,CAAC,YAAY;YACvC,eAAe,EAAE,YAAY,CAAC,eAAe;YAC7C,SAAS,EAAE,WAAW,CAAC,SAAS;YAChC,UAAU,EAAE,WAAW,CAAC,UAAwB;YAChD,KAAK,EAAE,WAAW,CAAC,KAAK;YACxB,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,aAAa;YACtB,yBAAyB,EAAE,+BAA+B;YAC1D,iBAAiB,EAAE,uBAAuB;YAC1C,iBAAiB,EAAE,uBAAuB;YAC1C,WAAW,EAAE,WAAW,CAAC,WAA0B;SACpD,CAAC;IACJ,CAAC;IAED,mEAAmE;IACnE,8FAA8F;IAC9F,OAAO;QACL,IAAI,EAAE,IAAI;QACV,OAAO,EAAE,IAAI;QACb,WAAW,EAAE,IAAI;QACjB,YAAY,EAAE,IAAI;QAClB,eAAe,EAAE,SAAS;QAC1B,SAAS,EAAE,IAAI;QACf,UAAU,EAAE,iBAA+B;QAC3C,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,YAAY;QACpB,OAAO,EAAE,aAAa;QACtB,yBAAyB,EAAE,+BAA+B;QAC1D,iBAAiB,EAAE,uBAAuB;QAC1C,iBAAiB,EAAE,uBAAuB;QAC1C,WAAW,EAAE,MAAM,EAAE,WAA0B;KAChD,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC","sourcesContent":["/**\n * useUser Hook\n *\n * A comprehensive user session hook that provides full user data including profile information,\n * authentication tokens, and authentication state. Supports generic typing for custom user data.\n *\n * Use this hook when you:\n * - Need access to user profile information (user object)\n * - Need authentication tokens (JWT, access, refresh tokens)\n * - Are working with custom user data types\n * - Need comprehensive user session data\n * - Want backward compatibility with legacy UserContext\n *\n * This hook supports two authentication patterns with automatic fallback:\n * 1. Provider-based (legacy): Uses CivicAuthProvider or CivicNextAuthProvider\n * 2. Provider-free (modern): Direct configuration via useUser(config)\n *\n * Usage Examples:\n *\n * // With provider (existing approach - NextJS/React providers)\n * <CivicAuthProvider clientId=\"...\" config={{ oauthServer: \"...\" }}>\n * const { user, isLoading, signIn } = useUser();\n * </CivicAuthProvider>\n *\n * // Without provider (new approach) - direct configuration\n * const { user, authStatus, signOut } = useUser({\n * clientId: \"your-client-id\",\n * config: { oauthServer: \"https://auth.civic.com/oauth/\" },\n * displayMode: \"iframe\", // or \"redirect\", \"popup\", etc.\n * scopes: [\"openid\", \"profile\", \"email\"],\n * onSignIn: (error) => console.log(\"Sign in completed\", error),\n * onSignOut: () => console.log(\"Sign out completed\")\n * });\n *\n * // Generic typing for custom user data\n * interface CustomUser { customField: string; }\n * const { user } = useUser<CustomUser>(); // user will be User<CustomUser> | null\n */\n\"use client\";\nimport { useContext, useState, useEffect, useCallback, useMemo } from \"react\";\nimport { UserContext } from \"../../shared/providers/UserProvider.js\";\nimport type { User, ForwardedTokens } from \"../../types.js\";\nimport type { AuthStatus } from \"../../types.js\";\nimport type { DisplayMode } from \"../../types.js\";\nimport {\n GlobalAuthManager,\n type GlobalAuthConfig,\n type GlobalAuthState,\n} from \"../core/GlobalAuthManager.js\";\nimport { extractTokensFromSession } from \"../../vanillajs/utils/auth-utils.js\";\n\nexport interface UserContextType<\n T extends Record<string, unknown> = Record<string, never>,\n> {\n user: User<T> | null;\n idToken?: string | null;\n accessToken?: string | null;\n refreshToken?: string | null;\n forwardedTokens?: ForwardedTokens;\n isLoading: boolean;\n authStatus: AuthStatus;\n error: Error | null;\n signIn: () => Promise<{ user: User<T> }>;\n signOut: () => Promise<void>;\n // Preloading methods\n isAuthenticationPreloaded: () => boolean;\n setPreloadEnabled: (enabled: boolean) => void;\n getPreloadEnabled: () => boolean;\n displayMode?: DisplayMode;\n}\n\nconst useUser = <T extends Record<string, unknown> = Record<string, never>>(\n config?: GlobalAuthConfig,\n): UserContextType<T> => {\n // Always call context hooks unconditionally (rules of hooks)\n const sharedContext = useContext(UserContext);\n\n // State for global manager approach\n const [globalState, setGlobalState] = useState<GlobalAuthState | null>(null);\n\n // Determine which approach to use\n const hasProviderContext = sharedContext;\n const shouldUseGlobal = !hasProviderContext;\n\n // Initialize global manager if no provider context\n useEffect(() => {\n if (!shouldUseGlobal) return;\n\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, initialize with it\n if (config) {\n const initializeAuth = async () => {\n try {\n await manager.initialize(config);\n } catch (error) {\n console.error(\"Failed to initialize auth:\", error);\n }\n };\n initializeAuth();\n }\n\n // Subscribe to state changes\n const unsubscribe = manager.subscribe((newState) => {\n setGlobalState(newState);\n });\n\n // Get current state\n setGlobalState(manager.getState());\n\n return unsubscribe;\n }, [shouldUseGlobal, config]);\n\n // Global manager sign in/out functions\n const globalSignIn = useCallback(async () => {\n const manager = GlobalAuthManager.getInstance();\n await manager.signIn();\n\n // Get the user after sign in\n const state = manager.getState();\n if (!state.user) {\n throw new Error(\"Authentication succeeded but no user was returned\");\n }\n\n return { user: state.user as User<T> };\n }, []);\n\n const globalSignOut = useCallback(async () => {\n const manager = GlobalAuthManager.getInstance();\n await manager.signOut();\n }, []);\n\n // Global manager preloading functions\n const globalIsAuthenticationPreloaded = useCallback(() => {\n const manager = GlobalAuthManager.getInstance();\n return manager.isAuthenticationPreloaded();\n }, []);\n\n const globalSetPreloadEnabled = useCallback((enabled: boolean) => {\n const manager = GlobalAuthManager.getInstance();\n manager.setPreloadEnabled(enabled);\n }, []);\n\n const globalGetPreloadEnabled = useCallback(() => {\n const manager = GlobalAuthManager.getInstance();\n return manager.getPreloadEnabled();\n }, []);\n\n // Extract tokens from global state\n const globalTokens = useMemo(() => {\n return extractTokensFromSession(globalState?.session || null);\n }, [globalState?.session]);\n\n // Create wrapper functions for different signIn signatures\n const wrapSharedSignIn = useCallback(async (): Promise<{ user: User<T> }> => {\n if (sharedContext) {\n await sharedContext.signIn(); // This returns void\n // Get user from context after sign in\n if (sharedContext.user) {\n return { user: sharedContext.user as User<T> };\n }\n\n // We don't return a user yet in nextjs until the next refactor\n return { user: null as unknown as User<T> };\n }\n throw new Error(\"Shared context not available\");\n }, [sharedContext]);\n\n // Shared context preloading stubs (not implemented for legacy context)\n const sharedIsAuthenticationPreloaded = useCallback(() => {\n return false; // Not available in shared context\n }, []);\n\n const sharedSetPreloadEnabled = useCallback((_enabled: boolean) => {\n console.warn(\n \"Preloading not available with legacy UserContext. Use GlobalAuthManager instead.\",\n _enabled,\n );\n }, []);\n\n const sharedGetPreloadEnabled = useCallback(() => {\n return false; // Not available in shared context\n }, []);\n\n // ========================================================================\n // FALLBACK PRIORITY SYSTEM - Two authentication context approaches\n // ========================================================================\n\n // 1. DEPRECATED UserContext (ACTIVE - Used by NextJS)\n // Framework-agnostic shared context from UserProvider\n // Location: shared/providers/UserProvider.tsx\n // Usage: NextJS example uses CivicNextAuthProvider → UserProvider → UserContext\n if (sharedContext) {\n return {\n user: sharedContext.user as User<T> | null,\n idToken: sharedContext.idToken,\n accessToken: sharedContext.accessToken,\n refreshToken: undefined, // Not available in shared context\n forwardedTokens: sharedContext.forwardedTokens,\n isLoading: sharedContext.isLoading,\n authStatus: sharedContext.authStatus,\n error: sharedContext.error,\n signIn: wrapSharedSignIn,\n signOut: sharedContext.signOut,\n isAuthenticationPreloaded: sharedIsAuthenticationPreloaded,\n setPreloadEnabled: sharedSetPreloadEnabled,\n getPreloadEnabled: sharedGetPreloadEnabled,\n displayMode: sharedContext.displayMode,\n };\n }\n\n // 2. GlobalAuthManager (MODERN - Provider-free approach)\n // Singleton-based state management, eliminates need for React providers\n // Location: reactjs/core/GlobalAuthManager.ts\n // Usage: React example uses CivicAuthProvider → GlobalAuthManager internally\n // Can also be used directly: useUser({ clientId: \"...\", config: {...} })\n if (globalState) {\n return {\n user: globalState.user as User<T> | null,\n idToken: globalTokens.idToken,\n accessToken: globalTokens.accessToken,\n refreshToken: globalTokens.refreshToken,\n forwardedTokens: globalTokens.forwardedTokens,\n isLoading: globalState.isLoading,\n authStatus: globalState.authStatus as AuthStatus,\n error: globalState.error,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: globalState.displayMode as DisplayMode,\n };\n }\n\n // If no context and no global state, provide default loading state\n // This happens when CivicAuthProvider is present but GlobalAuthManager hasn't initialized yet\n return {\n user: null,\n idToken: null,\n accessToken: null,\n refreshToken: null,\n forwardedTokens: undefined,\n isLoading: true,\n authStatus: \"unauthenticated\" as AuthStatus,\n error: null,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: config?.displayMode as DisplayMode,\n };\n};\n\nexport { useUser };\n"]}
|
|
1
|
+
{"version":3,"file":"useUser.js","sourceRoot":"","sources":["../../../src/reactjs/hooks/useUser.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,YAAY,CAAC;AACb,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAIhF,OAAO,EACL,iBAAiB,GAGlB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,wBAAwB,EA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,IAAI,WAAW,EAAE,CAAC;QAChB,OAAO;YACL,IAAI,EAAE,WAAW,CAAC,IAAsB;YACxC,OAAO,EAAE,YAAY,CAAC,OAAO;YAC7B,WAAW,EAAE,YAAY,CAAC,WAAW;YACrC,YAAY,EAAE,YAAY,CAAC,YAAY;YACvC,eAAe,EAAE,YAAY,CAAC,eAAe;YAC7C,SAAS,EAAE,WAAW,CAAC,SAAS;YAChC,UAAU,EAAE,WAAW,CAAC,UAAwB;YAChD,KAAK,EAAE,WAAW,CAAC,KAAK;YACxB,MAAM,EAAE,YAAY;YACpB,OAAO,EAAE,aAAa;YACtB,yBAAyB,EAAE,+BAA+B;YAC1D,iBAAiB,EAAE,uBAAuB;YAC1C,iBAAiB,EAAE,uBAAuB;YAC1C,WAAW,EAAE,WAAW,CAAC,WAA0B;SACpD,CAAC;IACJ,CAAC;IAED,mEAAmE;IACnE,8FAA8F;IAC9F,OAAO;QACL,IAAI,EAAE,IAAI;QACV,OAAO,EAAE,IAAI;QACb,WAAW,EAAE,IAAI;QACjB,YAAY,EAAE,IAAI;QAClB,eAAe,EAAE,SAAS;QAC1B,SAAS,EAAE,IAAI;QACf,UAAU,EAAE,iBAA+B;QAC3C,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,YAAY;QACpB,OAAO,EAAE,aAAa;QACtB,yBAAyB,EAAE,+BAA+B;QAC1D,iBAAiB,EAAE,uBAAuB;QAC1C,iBAAiB,EAAE,uBAAuB;QAC1C,WAAW,EAAE,MAAM,EAAE,WAA0B;KAChD,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,OAAO,EAAE,CAAC","sourcesContent":["/**\n * useUser Hook\n *\n * A comprehensive user session hook that provides full user data including profile information,\n * authentication tokens, and authentication state. Supports generic typing for custom user data.\n *\n * Use this hook when you:\n * - Need access to user profile information (user object)\n * - Need authentication tokens (JWT, access, refresh tokens)\n * - Are working with custom user data types\n * - Need comprehensive user session data\n * - Want backward compatibility with legacy UserContext\n *\n * This hook supports two authentication patterns with automatic fallback:\n * 1. Provider-based (legacy): Uses CivicAuthProvider or CivicNextAuthProvider\n * 2. Provider-free (modern): Direct configuration via useUser(config)\n *\n * Usage Examples:\n *\n * // With provider (existing approach - NextJS/React providers)\n * <CivicAuthProvider clientId=\"...\" config={{ oauthServer: \"...\" }}>\n * const { user, isLoading, signIn } = useUser();\n * </CivicAuthProvider>\n *\n * // Without provider (new approach) - direct configuration\n * const { user, authStatus, signOut } = useUser({\n * clientId: \"your-client-id\",\n * config: { oauthServer: \"https://auth.civic.com/oauth/\" },\n * displayMode: \"iframe\", // or \"redirect\", \"popup\", etc.\n * scopes: [\"openid\", \"profile\", \"email\"],\n * onSignIn: (error) => console.log(\"Sign in completed\", error),\n * onSignOut: () => console.log(\"Sign out completed\")\n * });\n *\n * // Generic typing for custom user data\n * interface CustomUser { customField: string; }\n * const { user } = useUser<CustomUser>(); // user will be User<CustomUser> | null\n */\n\"use client\";\nimport { useContext, useState, useEffect, useCallback, useMemo } from \"react\";\nimport { UserContext } from \"../../shared/providers/UserProvider.js\";\nimport { ServerUserContext } from \"../../nextjs/providers/ServerUserContext.js\";\nimport type { User, ForwardedTokens } from \"../../types.js\";\nimport type { AuthStatus } from \"../../types.js\";\nimport type { DisplayMode } from \"../../types.js\";\nimport {\n GlobalAuthManager,\n type GlobalAuthConfig,\n type GlobalAuthState,\n} from \"../core/GlobalAuthManager.js\";\nimport { extractTokensFromSession } from \"../../vanillajs/utils/auth-utils.js\";\nimport type { VanillaJSDisplayMode } from \"../../vanillajs/auth/types/AuthTypes.js\";\nimport type { IframeMode } from \"../../types.js\";\n\n// Configuration type for signIn and signOut functions\nexport interface SignInConfig {\n displayMode?: VanillaJSDisplayMode;\n iframeMode?: IframeMode;\n clientId?: string;\n redirectUrl?: string;\n logoutRedirectUrl?: string;\n targetContainerElement?: HTMLElement | string;\n scopes?: string[];\n authProcessTimeout?: number;\n preloadIframe?: boolean;\n autoRedirect?: boolean;\n onSignIn?: (error?: Error) => void;\n onSignOut?: () => void;\n onUrlChange?: (url: string, source?: string) => void;\n}\n\nexport interface UserContextType<\n T extends Record<string, unknown> = Record<string, never>,\n> {\n user: User<T> | null;\n idToken?: string | null;\n accessToken?: string | null;\n refreshToken?: string | null;\n forwardedTokens?: ForwardedTokens;\n isLoading: boolean;\n authStatus: AuthStatus;\n error: Error | null;\n signIn: (config?: SignInConfig) => Promise<{ user: User<T> }>;\n signOut: (config?: SignInConfig) => Promise<void>;\n // Preloading methods\n isAuthenticationPreloaded: () => boolean;\n setPreloadEnabled: (enabled: boolean) => void;\n getPreloadEnabled: () => boolean;\n displayMode?: DisplayMode;\n}\n\nconst useUser = <T extends Record<string, unknown> = Record<string, never>>(\n config?: GlobalAuthConfig,\n): UserContextType<T> => {\n // Always call context hooks unconditionally (rules of hooks)\n const sharedContext = useContext(UserContext);\n const serverUser = useContext(ServerUserContext);\n\n // State for global manager approach\n const [globalState, setGlobalState] = useState<GlobalAuthState | null>(null);\n\n // Determine which approach to use\n const hasProviderContext = sharedContext;\n const shouldUseGlobal = !hasProviderContext;\n\n // Helper to merge config overrides with current manager config\n const createConfigWithOverrides = useCallback(\n (overrides: SignInConfig): GlobalAuthConfig => {\n const manager = GlobalAuthManager.getInstance();\n const currentConfig = manager.getConfig();\n\n // Use current config from manager, or fall back to initial config if manager not initialized\n const baseConfig = currentConfig || config || {};\n\n return {\n ...baseConfig, // Complete current config from GlobalAuthManager\n // Override specific properties while keeping the base config\n ...(overrides.displayMode && { displayMode: overrides.displayMode }),\n ...(overrides.iframeMode !== undefined && {\n iframeMode: overrides.iframeMode,\n }),\n ...(overrides.clientId && { clientId: overrides.clientId }),\n ...(overrides.redirectUrl && { redirectUrl: overrides.redirectUrl }),\n ...(overrides.logoutRedirectUrl && {\n logoutRedirectUrl: overrides.logoutRedirectUrl,\n }),\n ...(overrides.targetContainerElement && {\n targetContainerElement: overrides.targetContainerElement,\n }),\n ...(overrides.scopes && { scopes: overrides.scopes }),\n ...(overrides.authProcessTimeout && {\n authProcessTimeout: overrides.authProcessTimeout,\n }),\n ...(overrides.preloadIframe !== undefined && {\n preloadIframe: overrides.preloadIframe,\n }),\n ...(overrides.autoRedirect !== undefined && {\n autoRedirect: overrides.autoRedirect,\n }),\n ...(overrides.onSignIn && { onSignIn: overrides.onSignIn }),\n ...(overrides.onSignOut && { onSignOut: overrides.onSignOut }),\n ...(overrides.onUrlChange && { onUrlChange: overrides.onUrlChange }),\n };\n },\n [config],\n );\n\n // Initialize global manager if no provider context\n useEffect(() => {\n if (!shouldUseGlobal) return;\n\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, initialize with it\n if (config) {\n const initializeAuth = async () => {\n try {\n await manager.initialize(config);\n } catch (error) {\n console.error(\"Failed to initialize auth:\", error);\n }\n };\n initializeAuth();\n }\n\n // Subscribe to state changes\n const unsubscribe = manager.subscribe((newState) => {\n setGlobalState(newState);\n });\n\n // Get current state\n setGlobalState(manager.getState());\n\n return unsubscribe;\n }, [shouldUseGlobal, config]);\n\n // Global manager sign in/out functions\n const globalSignIn = useCallback(\n async (signInConfig?: SignInConfig) => {\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, reinitialize with merged config\n if (signInConfig) {\n const mergedConfig = createConfigWithOverrides(signInConfig);\n await manager.initialize(mergedConfig);\n }\n\n await manager.signIn();\n\n // Get the user after sign in\n const state = manager.getState();\n if (!state.user) {\n throw new Error(\"Authentication succeeded but no user was returned\");\n }\n\n return { user: state.user as User<T> };\n },\n [createConfigWithOverrides],\n );\n\n const globalSignOut = useCallback(\n async (signOutConfig?: SignInConfig) => {\n const manager = GlobalAuthManager.getInstance();\n\n // If config is provided, reinitialize with merged config\n if (signOutConfig) {\n const mergedConfig = createConfigWithOverrides(signOutConfig);\n await manager.initialize(mergedConfig);\n }\n\n await manager.signOut();\n },\n [createConfigWithOverrides],\n );\n\n // Global manager preloading functions\n const globalIsAuthenticationPreloaded = useCallback(() => {\n const manager = GlobalAuthManager.getInstance();\n return manager.isAuthenticationPreloaded();\n }, []);\n\n const globalSetPreloadEnabled = useCallback((enabled: boolean) => {\n const manager = GlobalAuthManager.getInstance();\n manager.setPreloadEnabled(enabled);\n }, []);\n\n const globalGetPreloadEnabled = useCallback(() => {\n const manager = GlobalAuthManager.getInstance();\n return manager.getPreloadEnabled();\n }, []);\n\n // Extract tokens from global state\n const globalTokens = useMemo(() => {\n return extractTokensFromSession(globalState?.session || null);\n }, [globalState?.session]);\n\n // Create wrapper functions for different signIn signatures\n const wrapSharedSignIn = useCallback(\n async (sharedConfig?: SignInConfig): Promise<{ user: User<T> }> => {\n if (sharedContext) {\n // Note: Shared context doesn't support config overrides yet\n // This is a limitation of the legacy provider system\n if (sharedConfig) {\n console.warn(\n \"Config overrides are not supported with legacy UserContext. Consider upgrading to GlobalAuthManager for full config override support.\",\n );\n }\n\n await sharedContext.signIn(); // This returns void\n // Get user from context after sign in\n if (sharedContext.user) {\n return { user: sharedContext.user as User<T> };\n }\n\n // We don't return a user yet in nextjs until the next refactor\n return { user: null as unknown as User<T> };\n }\n throw new Error(\"Shared context not available\");\n },\n [sharedContext],\n );\n\n // Shared context preloading stubs (not implemented for legacy context)\n const sharedIsAuthenticationPreloaded = useCallback(() => {\n return false; // Not available in shared context\n }, []);\n\n const sharedSetPreloadEnabled = useCallback((_enabled: boolean) => {\n console.warn(\n \"Preloading not available with legacy UserContext. Use GlobalAuthManager instead.\",\n _enabled,\n );\n }, []);\n\n const sharedGetPreloadEnabled = useCallback(() => {\n return false; // Not available in shared context\n }, []);\n\n // Create wrapper for sharedContext signOut with config support\n const wrapSharedSignOut = useCallback(\n async (sharedConfig?: SignInConfig): Promise<void> => {\n if (sharedContext) {\n // Note: Shared context doesn't support config overrides yet\n if (sharedConfig) {\n console.warn(\n \"Config overrides are not supported with legacy UserContext. Consider upgrading to GlobalAuthManager for full config override support.\",\n );\n }\n\n await sharedContext.signOut();\n } else {\n throw new Error(\"Shared context not available\");\n }\n },\n [sharedContext],\n );\n\n // ========================================================================\n // FALLBACK PRIORITY SYSTEM - Three authentication context approaches\n // ========================================================================\n\n // 0. NextJS ServerUserContext (HIGHEST PRIORITY - Fresh server data)\n // This ensures client components sync with server data after revalidation\n if (serverUser !== null) {\n return {\n user: serverUser as User<T> | null,\n idToken: null, // Not available with server-only data\n accessToken: null, // Not available with server-only data\n refreshToken: null, // Not available with server-only data\n forwardedTokens: undefined, // Not available with server-only data\n isLoading: false, // Server data is immediately available\n authStatus: (serverUser\n ? \"authenticated\"\n : \"unauthenticated\") as AuthStatus,\n error: null,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: config?.displayMode as DisplayMode,\n };\n }\n\n // 1. DEPRECATED UserContext (ACTIVE - Used by NextJS)\n // Framework-agnostic shared context from UserProvider\n // Location: shared/providers/UserProvider.tsx\n // Usage: NextJS example uses CivicNextAuthProvider → UserProvider → UserContext\n if (sharedContext) {\n return {\n user: sharedContext.user as User<T> | null,\n idToken: sharedContext.idToken,\n accessToken: sharedContext.accessToken,\n refreshToken: undefined, // Not available in shared context\n forwardedTokens: sharedContext.forwardedTokens,\n isLoading: sharedContext.isLoading,\n authStatus: sharedContext.authStatus,\n error: sharedContext.error,\n signIn: wrapSharedSignIn,\n signOut: wrapSharedSignOut,\n isAuthenticationPreloaded: sharedIsAuthenticationPreloaded,\n setPreloadEnabled: sharedSetPreloadEnabled,\n getPreloadEnabled: sharedGetPreloadEnabled,\n displayMode: sharedContext.displayMode,\n };\n }\n\n // 2. GlobalAuthManager (MODERN - Provider-free approach)\n // Singleton-based state management, eliminates need for React providers\n // Location: reactjs/core/GlobalAuthManager.ts\n // Usage: React example uses CivicAuthProvider → GlobalAuthManager internally\n // Can also be used directly: useUser({ clientId: \"...\", config: {...} })\n if (globalState) {\n return {\n user: globalState.user as User<T> | null,\n idToken: globalTokens.idToken,\n accessToken: globalTokens.accessToken,\n refreshToken: globalTokens.refreshToken,\n forwardedTokens: globalTokens.forwardedTokens,\n isLoading: globalState.isLoading,\n authStatus: globalState.authStatus as AuthStatus,\n error: globalState.error,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: globalState.displayMode as DisplayMode,\n };\n }\n\n // If no context and no global state, provide default loading state\n // This happens when CivicAuthProvider is present but GlobalAuthManager hasn't initialized yet\n return {\n user: null,\n idToken: null,\n accessToken: null,\n refreshToken: null,\n forwardedTokens: undefined,\n isLoading: true,\n authStatus: \"unauthenticated\" as AuthStatus,\n error: null,\n signIn: globalSignIn,\n signOut: globalSignOut,\n isAuthenticationPreloaded: globalIsAuthenticationPreloaded,\n setPreloadEnabled: globalSetPreloadEnabled,\n getPreloadEnabled: globalGetPreloadEnabled,\n displayMode: config?.displayMode as DisplayMode,\n };\n};\n\nexport { useUser };\n"]}
|
package/dist/reactjs/index.d.ts
CHANGED
|
@@ -3,8 +3,7 @@ export { GlobalAuthManager } from "../reactjs/core/GlobalAuthManager.js";
|
|
|
3
3
|
export type { GlobalAuthConfig, GlobalAuthState, } from "../reactjs/core/GlobalAuthManager.js";
|
|
4
4
|
export { CivicAuthProvider, type CivicAuthProviderProps, } from "../reactjs/providers/CivicAuthProvider.js";
|
|
5
5
|
export { useCivicAuthContext } from "../reactjs/providers/CivicAuthContext.js";
|
|
6
|
-
export { CivicAuthIframeContainer } from "../shared/components/CivicAuthIframeContainer.js";
|
|
7
6
|
export type { CivicAuthContextType, AuthStatusEnum, } from "../reactjs/providers/CivicAuthContext.js";
|
|
8
7
|
export type { UserContextType } from "../reactjs/hooks/index.js";
|
|
9
|
-
export { UserButton, SignInButton, SignOutButton, } from "../reactjs/components/index.js";
|
|
8
|
+
export { UserButton, SignInButton, SignOutButton, CivicAuthIframeContainer, } from "../reactjs/components/index.js";
|
|
10
9
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/reactjs/index.ts"],"names":[],"mappings":"AAMA,cAAc,0BAA0B,CAAC;AAGzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AACxE,YAAY,EACV,gBAAgB,EAChB,eAAe,GAChB,MAAM,qCAAqC,CAAC;AAG7C,OAAO,EACL,iBAAiB,EACjB,KAAK,sBAAsB,GAC5B,MAAM,0CAA0C,CAAC;AAGlD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/reactjs/index.ts"],"names":[],"mappings":"AAMA,cAAc,0BAA0B,CAAC;AAGzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AACxE,YAAY,EACV,gBAAgB,EAChB,eAAe,GAChB,MAAM,qCAAqC,CAAC;AAG7C,OAAO,EACL,iBAAiB,EACjB,KAAK,sBAAsB,GAC5B,MAAM,0CAA0C,CAAC;AAGlD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAE9E,YAAY,EACV,oBAAoB,EACpB,cAAc,GACf,MAAM,yCAAyC,CAAC;AAGjD,YAAY,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAGhE,OAAO,EACL,UAAU,EACV,YAAY,EACZ,aAAa,EACb,wBAAwB,GACzB,MAAM,+BAA+B,CAAC"}
|
package/dist/reactjs/index.js
CHANGED
|
@@ -10,7 +10,6 @@ export { GlobalAuthManager } from "../reactjs/core/GlobalAuthManager.js";
|
|
|
10
10
|
export { CivicAuthProvider, } from "../reactjs/providers/CivicAuthProvider.js";
|
|
11
11
|
// Export new context and hook for advanced usage
|
|
12
12
|
export { useCivicAuthContext } from "../reactjs/providers/CivicAuthContext.js";
|
|
13
|
-
export { CivicAuthIframeContainer } from "../shared/components/CivicAuthIframeContainer.js";
|
|
14
13
|
// Export our VanillaJS-based components
|
|
15
|
-
export { UserButton, SignInButton, SignOutButton, } from "../reactjs/components/index.js";
|
|
14
|
+
export { UserButton, SignInButton, SignOutButton, CivicAuthIframeContainer, } from "../reactjs/components/index.js";
|
|
16
15
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/reactjs/index.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAChD,gHAAgH;AAChH,kGAAkG;AAClG,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,CAAC;AAEf,cAAc,0BAA0B,CAAC;AAEzC,yCAAyC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAMxE,2DAA2D;AAC3D,OAAO,EACL,iBAAiB,GAElB,MAAM,0CAA0C,CAAC;AAElD,iDAAiD;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/reactjs/index.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAChD,gHAAgH;AAChH,kGAAkG;AAClG,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,CAAC;AAEf,cAAc,0BAA0B,CAAC;AAEzC,yCAAyC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAMxE,2DAA2D;AAC3D,OAAO,EACL,iBAAiB,GAElB,MAAM,0CAA0C,CAAC;AAElD,iDAAiD;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAU9E,wCAAwC;AACxC,OAAO,EACL,UAAU,EACV,YAAY,EACZ,aAAa,EACb,wBAAwB,GACzB,MAAM,+BAA+B,CAAC","sourcesContent":["// These are the default exports of the project.\n// They are limited by design to ensure that the public API does not expose any internal implementation details.\n// Do not change this without thinking carefully about the impact on the client-facing public API.\nimport { printVersion } from \"@/shared/index.js\";\nprintVersion();\n\nexport * from \"@/reactjs/hooks/index.js\";\n\n// Global auth manager for advanced usage\nexport { GlobalAuthManager } from \"@/reactjs/core/GlobalAuthManager.js\";\nexport type {\n GlobalAuthConfig,\n GlobalAuthState,\n} from \"@/reactjs/core/GlobalAuthManager.js\";\n\n// Provider-based approach (for apps that prefer providers)\nexport {\n CivicAuthProvider,\n type CivicAuthProviderProps,\n} from \"@/reactjs/providers/CivicAuthProvider.js\";\n\n// Export new context and hook for advanced usage\nexport { useCivicAuthContext } from \"@/reactjs/providers/CivicAuthContext.js\";\n// Export new context types\nexport type {\n CivicAuthContextType,\n AuthStatusEnum,\n} from \"@/reactjs/providers/CivicAuthContext.js\";\n\n// Export types\nexport type { UserContextType } from \"@/reactjs/hooks/index.js\";\n\n// Export our VanillaJS-based components\nexport {\n UserButton,\n SignInButton,\n SignOutButton,\n CivicAuthIframeContainer,\n} from \"@/reactjs/components/index.js\";\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServerAuthenticationResolver.d.ts","sourceRoot":"","sources":["../../src/server/ServerAuthenticationResolver.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,SAAS,EACT,qBAAqB,EACrB,WAAW,EACZ,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAUrD,OAAO,KAAK,EAAE,sBAAsB,EAAgB,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"ServerAuthenticationResolver.d.ts","sourceRoot":"","sources":["../../src/server/ServerAuthenticationResolver.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,SAAS,EACT,qBAAqB,EACrB,WAAW,EACZ,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAUrD,OAAO,KAAK,EAAE,sBAAsB,EAAgB,MAAM,qBAAqB,CAAC;AAShF,qBAAa,4BAA6B,YAAW,sBAAsB;IAMvE,QAAQ,CAAC,UAAU,EAAE,UAAU;IAC/B,QAAQ,CAAC,OAAO,EAAE,WAAW;IAC7B,QAAQ,CAAC,iBAAiB,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC;IAPjD,OAAO,CAAC,YAAY,CAAsB;IAC1C,OAAO,CAAC,YAAY,CAA2B;IAC/C,OAAO,CAAC,SAAS,CAAwB;IAEzC,OAAO;IAeP;;;;OAIG;IACG,gBAAgB,CACpB,WAAW,EAAE,WAAW,GAAG,IAAI,GAC9B,OAAO,CAAC,WAAW,CAAC;IA+DvB;;;OAGG;IACG,uBAAuB,CAAC,WAAW,UAAO,GAAG,OAAO,CAAC,WAAW,CAAC;IAmDvE,IAAI,WAAW,IAAI,MAAM,CAExB;IAEK,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAuBrB,aAAa,CACjB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,qBAAqB,CAAC;IA4C3B,cAAc,IAAI,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;IAc7C,qBAAqB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;WAOxC,KAAK,CAChB,UAAU,EAAE,UAAU,EACtB,OAAO,EAAE,WAAW,EACpB,iBAAiB,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,GACrC,OAAO,CAAC,sBAAsB,CAAC;CAUnC"}
|
|
@@ -4,6 +4,8 @@ import { clearTokens, clearUser, exchangeTokens, getEndpointsWithOverrides, retr
|
|
|
4
4
|
import { DEFAULT_AUTH_SERVER } from "../constants.js";
|
|
5
5
|
import { CodeVerifier } from "../shared/lib/types.js";
|
|
6
6
|
import { loggers } from "../lib/logger.js";
|
|
7
|
+
import { getUser } from "../shared/lib/session.js";
|
|
8
|
+
import { GenericUserSession } from "../shared/lib/UserSession.js";
|
|
7
9
|
const logger = loggers.services.validation;
|
|
8
10
|
export class ServerAuthenticationResolver {
|
|
9
11
|
authConfig;
|
|
@@ -150,6 +152,22 @@ export class ServerAuthenticationResolver {
|
|
|
150
152
|
this.oauthServer, this.endpoints, // clean up types here to avoid the ! operator
|
|
151
153
|
this.authConfig.clientSecret);
|
|
152
154
|
await storeServerTokens(this.storage, tokens);
|
|
155
|
+
// Store user data in cookie (like VanillaJS implementation does)
|
|
156
|
+
try {
|
|
157
|
+
const user = await getUser(this.storage);
|
|
158
|
+
if (user) {
|
|
159
|
+
const userSession = new GenericUserSession(this.storage);
|
|
160
|
+
await userSession.set(user);
|
|
161
|
+
logger.debug("User cookie stored successfully", { hasUser: !!user });
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
logger.warn("No user found after token exchange");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
logger.error("Failed to store user cookie:", error);
|
|
169
|
+
// Don't throw - tokens are already stored, this is just for client-side convenience
|
|
170
|
+
}
|
|
153
171
|
// the code verifier should be single-use, so we delete it if using PKCE
|
|
154
172
|
if (this.pkceProducer) {
|
|
155
173
|
await this.storage.delete(CodeVerifier.COOKIE_NAME);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServerAuthenticationResolver.js","sourceRoot":"","sources":["../../src/server/ServerAuthenticationResolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAQ3C,OAAO,EACL,WAAW,EACX,SAAS,EACT,cAAc,EACd,yBAAyB,EACzB,cAAc,EACd,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EA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AM,QAAQ,GAAG,IAAI,4BAA4B,CAC/C,UAAU,EACV,OAAO,EACP,iBAAiB,CAClB,CAAC;QACF,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAEtB,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { GenericPublicClientPKCEProducer } from \"@/services/PKCE.js\";\nimport { OAuth2Client } from \"oslo/oauth2\";\nimport type {\n AuthStorage,\n Endpoints,\n OIDCTokenResponseBody,\n SessionData,\n} from \"@/types.js\";\nimport type { AuthConfig } from \"@/server/config.js\";\nimport {\n clearTokens,\n clearUser,\n exchangeTokens,\n getEndpointsWithOverrides,\n retrieveTokens,\n storeServerTokens,\n validateOauth2Tokens,\n} from \"@/shared/lib/util.js\";\nimport type { AuthenticationResolver, PKCEProducer } from \"@/services/types.ts\";\nimport { DEFAULT_AUTH_SERVER } from \"@/constants.js\";\nimport { CodeVerifier } from \"@/shared/lib/types.js\";\nimport { loggers } from \"@/lib/logger.js\";\n\nconst logger = loggers.services.validation;\n\nexport class ServerAuthenticationResolver implements AuthenticationResolver {\n private pkceProducer: PKCEProducer | null;\n private oauth2client: OAuth2Client | undefined;\n private endpoints: Endpoints | undefined;\n\n private constructor(\n readonly authConfig: AuthConfig,\n readonly storage: AuthStorage,\n readonly endpointOverrides?: Partial<Endpoints>,\n ) {\n // Determine if PKCE should be used based on config\n // Default to true\n const usePkce = authConfig.pkce !== false;\n\n // Only create PKCE producer if we're using PKCE\n this.pkceProducer = usePkce\n ? new GenericPublicClientPKCEProducer(storage)\n : null;\n }\n\n /**\n * Attempts to refresh tokens if a refresh token is available\n * @param sessionData Current session data\n * @returns Updated session data\n */\n async tryRefreshTokens(\n sessionData: SessionData | null,\n ): Promise<SessionData> {\n logger.debug(\"tryRefreshTokens\", { sessionData });\n // If there's a refresh token, attempt to refresh tokens\n if (sessionData?.refreshToken) {\n try {\n // Only attempt refresh if we have necessary components\n if (!this.oauth2client || !this.endpoints?.jwks) {\n await this.init();\n }\n\n if (!this.oauth2client || !this.endpoints?.jwks) {\n throw new Error(\n \"Failed to initialize OAuth client for token refresh\",\n );\n }\n\n // Use the oauth2client to refresh the access token\n const refreshOptions: Record<string, string> = {};\n if (this.authConfig.clientSecret) {\n refreshOptions.credentials = this.authConfig.clientSecret;\n refreshOptions.authenticateWith = \"request_body\";\n }\n\n const tokenResponseBody = (await this.oauth2client.refreshAccessToken(\n sessionData.refreshToken,\n refreshOptions,\n )) as OIDCTokenResponseBody;\n\n if (!tokenResponseBody) {\n throw new Error(\"Failed to get token response from refresh\");\n }\n\n // Validate the refreshed tokens\n await validateOauth2Tokens(\n tokenResponseBody,\n this.endpoints.jwks,\n this.oauth2client,\n this.oauthServer,\n );\n\n // Store the refreshed tokens\n await storeServerTokens(this.storage, tokenResponseBody);\n\n // Construct a refreshed session with the new tokens\n return {\n authenticated: true,\n idToken: tokenResponseBody.id_token,\n accessToken: tokenResponseBody.access_token,\n refreshToken: tokenResponseBody.refresh_token,\n oidcSessionExpiresAt: tokenResponseBody.oidc_session_expires_at,\n };\n } catch (error) {\n logger.warn(\"Failed to refresh tokens\", error);\n await clearTokens(this.storage);\n await clearUser(this.storage);\n return { ...sessionData, authenticated: false };\n }\n }\n\n // No refresh token available\n return { ...sessionData, authenticated: false };\n }\n\n /**\n * returns The session data if the session is valid, otherwise an unauthenticated session\n * @returns {Promise<SessionData>}\n */\n async validateExistingSession(autoRefresh = true): Promise<SessionData> {\n // TODO: investigate a more peformant way to validate a server session\n // other than using JWKS and JWT verification which is what validateOauth2Tokens uses\n const sessionData = await this.getSessionData();\n\n // If we don't have an ID token, try to refresh if we have a refresh token\n // Access token is no longer required for authentication\n if (!sessionData?.idToken) {\n if (autoRefresh) {\n const refreshedSessionData = await this.tryRefreshTokens(sessionData);\n if (refreshedSessionData.authenticated) {\n return refreshedSessionData;\n }\n }\n return { ...sessionData, authenticated: false };\n }\n\n // Initialize if needed\n if (!this.endpoints?.jwks || !this.oauth2client) await this.init();\n\n if (!this.endpoints?.jwks) {\n throw new Error(\"JWKS endpoint not found\");\n }\n\n try {\n // Validate existing tokens - access token validation happens only if it exists\n await validateOauth2Tokens(\n {\n access_token: sessionData.accessToken, // May be undefined\n id_token: sessionData.idToken, // Always required\n refresh_token: sessionData.refreshToken,\n oidc_session_expires_at: sessionData.oidcSessionExpiresAt,\n },\n this.endpoints.jwks,\n this.oauth2client!,\n this.oauthServer,\n );\n return sessionData;\n } catch (error) {\n logger.warn(\"Error validating tokens\", { error, autoRefresh });\n if (autoRefresh) {\n // If token validation fails, try to refresh tokens\n const refreshedSessionData = await this.tryRefreshTokens(sessionData);\n if (refreshedSessionData.authenticated) {\n return refreshedSessionData;\n }\n }\n return { ...sessionData, authenticated: false };\n }\n }\n\n get oauthServer(): string {\n return this.authConfig.oauthServer || DEFAULT_AUTH_SERVER;\n }\n\n async init(): Promise<this> {\n // Ensure clientId is present for OAuth operations\n if (!this.authConfig.clientId) {\n throw new Error(\"clientId is required for OAuth server operations\");\n }\n\n // resolve oauth config\n this.endpoints = await getEndpointsWithOverrides(\n this.oauthServer,\n this.endpointOverrides,\n );\n this.oauth2client = new OAuth2Client(\n this.authConfig.clientId,\n this.endpoints.auth,\n this.endpoints.token,\n {\n redirectURI: this.authConfig.redirectUrl,\n },\n );\n\n return this;\n }\n\n async tokenExchange(\n code: string,\n state: string,\n ): Promise<OIDCTokenResponseBody> {\n if (!this.oauth2client) await this.init();\n\n // Check if we're using PKCE and validate code verifier if needed\n if (this.pkceProducer) {\n const codeVerifier = await this.pkceProducer.getCodeVerifier();\n if (!codeVerifier) throw new Error(\"Code verifier not found in storage\");\n }\n\n // exchange auth code for tokens\n const tokens = await exchangeTokens(\n code,\n state,\n this.pkceProducer,\n this.oauth2client!, // clean up types here to avoid the ! operator\n this.oauthServer,\n this.endpoints!, // clean up types here to avoid the ! operator\n this.authConfig.clientSecret,\n );\n\n await storeServerTokens(this.storage, tokens);\n // the code verifier should be single-use, so we delete it if using PKCE\n if (this.pkceProducer) {\n await this.storage.delete(CodeVerifier.COOKIE_NAME);\n }\n return tokens;\n }\n\n async getSessionData(): Promise<SessionData | null> {\n const storageData = await retrieveTokens(this.storage);\n\n if (!storageData) return null;\n\n return {\n authenticated: !!storageData.id_token, // User is authenticated if they have an ID token\n idToken: storageData.id_token,\n accessToken: storageData.access_token, // Optional\n refreshToken: storageData.refresh_token,\n oidcSessionExpiresAt: storageData.oidc_session_expires_at,\n };\n }\n\n async getEndSessionEndpoint(): Promise<string | null> {\n if (!this.endpoints) {\n return null;\n }\n return this.endpoints.endsession;\n }\n\n static async build(\n authConfig: AuthConfig,\n storage: AuthStorage,\n endpointOverrides?: Partial<Endpoints>,\n ): Promise<AuthenticationResolver> {\n const resolver = new ServerAuthenticationResolver(\n authConfig,\n storage,\n endpointOverrides,\n );\n await resolver.init();\n\n return resolver;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ServerAuthenticationResolver.js","sourceRoot":"","sources":["../../src/server/ServerAuthenticationResolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAQ3C,OAAO,EACL,WAAW,EACX,SAAS,EACT,cAAc,EACd,yBAAyB,EACzB,cAAc,EACd,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEjE,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC;AAE3C,MAAM,OAAO,4BAA4B;IAM5B;IACA;IACA;IAPH,YAAY,CAAsB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,CAAC,QAAQ;YAC7B,WAAW,EAAE,WAAW,CAAC,YAAY,EAAE,WAAW;YAClD,YAAY,EAAE,WAAW,CAAC,aAAa;YACvC,oBAAoB,EAAE,WAAW,CAAC,uBAAuB;SAC1D,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,qBAAqB;QACzB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC;IACnC,CAAC;IAED,MAAM,CAAC,KAAK,CAAC,KAAK,CAChB,UAAsB,EACtB,OAAoB,EACpB,iBAAsC;QAEtC,MAAM,QAAQ,GAAG,IAAI,4BAA4B,CAC/C,UAAU,EACV,OAAO,EACP,iBAAiB,CAClB,CAAC;QACF,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAEtB,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { GenericPublicClientPKCEProducer } from \"@/services/PKCE.js\";\nimport { OAuth2Client } from \"oslo/oauth2\";\nimport type {\n AuthStorage,\n Endpoints,\n OIDCTokenResponseBody,\n SessionData,\n} from \"@/types.js\";\nimport type { AuthConfig } from \"@/server/config.js\";\nimport {\n clearTokens,\n clearUser,\n exchangeTokens,\n getEndpointsWithOverrides,\n retrieveTokens,\n storeServerTokens,\n validateOauth2Tokens,\n} from \"@/shared/lib/util.js\";\nimport type { AuthenticationResolver, PKCEProducer } from \"@/services/types.ts\";\nimport { DEFAULT_AUTH_SERVER } from \"@/constants.js\";\nimport { CodeVerifier } from \"@/shared/lib/types.js\";\nimport { loggers } from \"@/lib/logger.js\";\nimport { getUser } from \"@/shared/lib/session.js\";\nimport { GenericUserSession } from \"@/shared/lib/UserSession.js\";\n\nconst logger = loggers.services.validation;\n\nexport class ServerAuthenticationResolver implements AuthenticationResolver {\n private pkceProducer: PKCEProducer | null;\n private oauth2client: OAuth2Client | undefined;\n private endpoints: Endpoints | undefined;\n\n private constructor(\n readonly authConfig: AuthConfig,\n readonly storage: AuthStorage,\n readonly endpointOverrides?: Partial<Endpoints>,\n ) {\n // Determine if PKCE should be used based on config\n // Default to true\n const usePkce = authConfig.pkce !== false;\n\n // Only create PKCE producer if we're using PKCE\n this.pkceProducer = usePkce\n ? new GenericPublicClientPKCEProducer(storage)\n : null;\n }\n\n /**\n * Attempts to refresh tokens if a refresh token is available\n * @param sessionData Current session data\n * @returns Updated session data\n */\n async tryRefreshTokens(\n sessionData: SessionData | null,\n ): Promise<SessionData> {\n logger.debug(\"tryRefreshTokens\", { sessionData });\n // If there's a refresh token, attempt to refresh tokens\n if (sessionData?.refreshToken) {\n try {\n // Only attempt refresh if we have necessary components\n if (!this.oauth2client || !this.endpoints?.jwks) {\n await this.init();\n }\n\n if (!this.oauth2client || !this.endpoints?.jwks) {\n throw new Error(\n \"Failed to initialize OAuth client for token refresh\",\n );\n }\n\n // Use the oauth2client to refresh the access token\n const refreshOptions: Record<string, string> = {};\n if (this.authConfig.clientSecret) {\n refreshOptions.credentials = this.authConfig.clientSecret;\n refreshOptions.authenticateWith = \"request_body\";\n }\n\n const tokenResponseBody = (await this.oauth2client.refreshAccessToken(\n sessionData.refreshToken,\n refreshOptions,\n )) as OIDCTokenResponseBody;\n\n if (!tokenResponseBody) {\n throw new Error(\"Failed to get token response from refresh\");\n }\n\n // Validate the refreshed tokens\n await validateOauth2Tokens(\n tokenResponseBody,\n this.endpoints.jwks,\n this.oauth2client,\n this.oauthServer,\n );\n\n // Store the refreshed tokens\n await storeServerTokens(this.storage, tokenResponseBody);\n\n // Construct a refreshed session with the new tokens\n return {\n authenticated: true,\n idToken: tokenResponseBody.id_token,\n accessToken: tokenResponseBody.access_token,\n refreshToken: tokenResponseBody.refresh_token,\n oidcSessionExpiresAt: tokenResponseBody.oidc_session_expires_at,\n };\n } catch (error) {\n logger.warn(\"Failed to refresh tokens\", error);\n await clearTokens(this.storage);\n await clearUser(this.storage);\n return { ...sessionData, authenticated: false };\n }\n }\n\n // No refresh token available\n return { ...sessionData, authenticated: false };\n }\n\n /**\n * returns The session data if the session is valid, otherwise an unauthenticated session\n * @returns {Promise<SessionData>}\n */\n async validateExistingSession(autoRefresh = true): Promise<SessionData> {\n // TODO: investigate a more peformant way to validate a server session\n // other than using JWKS and JWT verification which is what validateOauth2Tokens uses\n const sessionData = await this.getSessionData();\n\n // If we don't have an ID token, try to refresh if we have a refresh token\n // Access token is no longer required for authentication\n if (!sessionData?.idToken) {\n if (autoRefresh) {\n const refreshedSessionData = await this.tryRefreshTokens(sessionData);\n if (refreshedSessionData.authenticated) {\n return refreshedSessionData;\n }\n }\n return { ...sessionData, authenticated: false };\n }\n\n // Initialize if needed\n if (!this.endpoints?.jwks || !this.oauth2client) await this.init();\n\n if (!this.endpoints?.jwks) {\n throw new Error(\"JWKS endpoint not found\");\n }\n\n try {\n // Validate existing tokens - access token validation happens only if it exists\n await validateOauth2Tokens(\n {\n access_token: sessionData.accessToken, // May be undefined\n id_token: sessionData.idToken, // Always required\n refresh_token: sessionData.refreshToken,\n oidc_session_expires_at: sessionData.oidcSessionExpiresAt,\n },\n this.endpoints.jwks,\n this.oauth2client!,\n this.oauthServer,\n );\n return sessionData;\n } catch (error) {\n logger.warn(\"Error validating tokens\", { error, autoRefresh });\n if (autoRefresh) {\n // If token validation fails, try to refresh tokens\n const refreshedSessionData = await this.tryRefreshTokens(sessionData);\n if (refreshedSessionData.authenticated) {\n return refreshedSessionData;\n }\n }\n return { ...sessionData, authenticated: false };\n }\n }\n\n get oauthServer(): string {\n return this.authConfig.oauthServer || DEFAULT_AUTH_SERVER;\n }\n\n async init(): Promise<this> {\n // Ensure clientId is present for OAuth operations\n if (!this.authConfig.clientId) {\n throw new Error(\"clientId is required for OAuth server operations\");\n }\n\n // resolve oauth config\n this.endpoints = await getEndpointsWithOverrides(\n this.oauthServer,\n this.endpointOverrides,\n );\n this.oauth2client = new OAuth2Client(\n this.authConfig.clientId,\n this.endpoints.auth,\n this.endpoints.token,\n {\n redirectURI: this.authConfig.redirectUrl,\n },\n );\n\n return this;\n }\n\n async tokenExchange(\n code: string,\n state: string,\n ): Promise<OIDCTokenResponseBody> {\n if (!this.oauth2client) await this.init();\n\n // Check if we're using PKCE and validate code verifier if needed\n if (this.pkceProducer) {\n const codeVerifier = await this.pkceProducer.getCodeVerifier();\n if (!codeVerifier) throw new Error(\"Code verifier not found in storage\");\n }\n\n // exchange auth code for tokens\n const tokens = await exchangeTokens(\n code,\n state,\n this.pkceProducer,\n this.oauth2client!, // clean up types here to avoid the ! operator\n this.oauthServer,\n this.endpoints!, // clean up types here to avoid the ! operator\n this.authConfig.clientSecret,\n );\n\n await storeServerTokens(this.storage, tokens);\n\n // Store user data in cookie (like VanillaJS implementation does)\n try {\n const user = await getUser(this.storage);\n if (user) {\n const userSession = new GenericUserSession(this.storage);\n await userSession.set(user);\n logger.debug(\"User cookie stored successfully\", { hasUser: !!user });\n } else {\n logger.warn(\"No user found after token exchange\");\n }\n } catch (error) {\n logger.error(\"Failed to store user cookie:\", error);\n // Don't throw - tokens are already stored, this is just for client-side convenience\n }\n\n // the code verifier should be single-use, so we delete it if using PKCE\n if (this.pkceProducer) {\n await this.storage.delete(CodeVerifier.COOKIE_NAME);\n }\n return tokens;\n }\n\n async getSessionData(): Promise<SessionData | null> {\n const storageData = await retrieveTokens(this.storage);\n\n if (!storageData) return null;\n\n return {\n authenticated: !!storageData.id_token, // User is authenticated if they have an ID token\n idToken: storageData.id_token,\n accessToken: storageData.access_token, // Optional\n refreshToken: storageData.refresh_token,\n oidcSessionExpiresAt: storageData.oidc_session_expires_at,\n };\n }\n\n async getEndSessionEndpoint(): Promise<string | null> {\n if (!this.endpoints) {\n return null;\n }\n return this.endpoints.endsession;\n }\n\n static async build(\n authConfig: AuthConfig,\n storage: AuthStorage,\n endpointOverrides?: Partial<Endpoints>,\n ): Promise<AuthenticationResolver> {\n const resolver = new ServerAuthenticationResolver(\n authConfig,\n storage,\n endpointOverrides,\n );\n await resolver.init();\n\n return resolver;\n }\n}\n"]}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export type { AuthConfig } from "./config.js";
|
|
|
4
4
|
export { CivicAuth } from "./session.js";
|
|
5
5
|
export { type RequestContext } from "./login.js";
|
|
6
6
|
export type { CivicAuthServerOptions } from "../server/types/express.js";
|
|
7
|
-
export type { HandleCallbackRequest, HandleCallbackParams } from "./session.js";
|
|
7
|
+
export type { HandleCallbackRequest, HandleCallbackParams, UrlDetectionRequest, } from "./session.js";
|
|
8
8
|
export { buildLoginUrl, resolveOAuthAccessCode, isLoggedIn } from "./login.js";
|
|
9
9
|
export { buildLogoutRedirectUrl } from "./logout.js";
|
|
10
10
|
export { refreshTokens } from "./refresh.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,YAAY,EACV,cAAc,EACd,qBAAqB,GACtB,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,YAAY,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAExE,YAAY,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,YAAY,EACV,cAAc,EACd,qBAAqB,GACtB,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,YAAY,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAExE,YAAY,EACV,qBAAqB,EACrB,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,aAAa,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC"}
|
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,CAAC;AAEf,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAMxD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAuB,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,CAAC;AAEf,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAMxD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAuB,MAAM,YAAY,CAAC;AASjD,OAAO,EAAE,aAAa,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC","sourcesContent":["import { printVersion } from \"@/shared/index.js\";\nprintVersion();\n\nexport { CookieStorage } from \"@/shared/lib/storage.js\";\nexport type {\n SessionStorage,\n CookieStorageSettings,\n} from \"@/shared/lib/storage.js\";\nexport type { AuthConfig } from \"./config.js\";\nexport { CivicAuth } from \"./session.js\";\nexport { type RequestContext } from \"./login.js\";\n\nexport type { CivicAuthServerOptions } from \"@/server/types/express.js\";\n\nexport type {\n HandleCallbackRequest,\n HandleCallbackParams,\n UrlDetectionRequest,\n} from \"./session.js\";\nexport { buildLoginUrl, resolveOAuthAccessCode, isLoggedIn } from \"./login.js\";\nexport { buildLogoutRedirectUrl } from \"./logout.js\";\nexport { refreshTokens } from \"./refresh.js\";\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logout.d.ts","sourceRoot":"","sources":["../../src/server/logout.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"logout.d.ts","sourceRoot":"","sources":["../../src/server/logout.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAO9C,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,UAAU,GAAG,uBAAuB,CAAC,GAC5D,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC,GAAG;IACzC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,EACH,OAAO,EAAE,WAAW,GACnB,OAAO,CAAC,GAAG,CAAC,CAuCd"}
|
package/dist/server/logout.js
CHANGED
|
@@ -2,6 +2,7 @@ import { DEFAULT_AUTH_SERVER, DEFAULT_SCOPES } from "../constants.js";
|
|
|
2
2
|
import { GenericPublicClientPKCEProducer } from "../services/PKCE.js";
|
|
3
3
|
import { GenericAuthenticationInitiator } from "../services/AuthenticationService.js";
|
|
4
4
|
import { OAuthTokenTypes } from "../shared/lib/types.js";
|
|
5
|
+
import { getEndpointsWithOverrides } from "../shared/lib/util.js";
|
|
5
6
|
export async function buildLogoutRedirectUrl(config, storage) {
|
|
6
7
|
// Ensure clientId is present for OAuth operations
|
|
7
8
|
if (!config.clientId) {
|
|
@@ -21,8 +22,16 @@ export async function buildLogoutRedirectUrl(config, storage) {
|
|
|
21
22
|
redirectUrl: config.postLogoutRedirectUrl || "/",
|
|
22
23
|
});
|
|
23
24
|
const idToken = await storage.get(OAuthTokenTypes.ID_TOKEN);
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
// OAuth logout should work without id_token_hint (it's optional per OAuth spec)
|
|
26
|
+
if (!idToken) {
|
|
27
|
+
// Build logout URL using proper endpoint discovery, without id_token_hint
|
|
28
|
+
const endpoints = await getEndpointsWithOverrides(config.oauthServer ?? DEFAULT_AUTH_SERVER);
|
|
29
|
+
const logoutUrl = new URL(endpoints.endsession);
|
|
30
|
+
logoutUrl.searchParams.append("client_id", config.clientId);
|
|
31
|
+
logoutUrl.searchParams.append("state", state);
|
|
32
|
+
logoutUrl.searchParams.append("post_logout_redirect_uri", config.postLogoutRedirectUrl || "/");
|
|
33
|
+
return logoutUrl;
|
|
34
|
+
}
|
|
26
35
|
return authInitiator.signOut(idToken);
|
|
27
36
|
}
|
|
28
37
|
//# sourceMappingURL=logout.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logout.js","sourceRoot":"","sources":["../../src/server/logout.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AACrF,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"logout.js","sourceRoot":"","sources":["../../src/server/logout.ts"],"names":[],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,IAAI,mBAAmB,CAC1C,CAAC;QACF,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QAChD,SAAS,CAAC,YAAY,CAAC,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC5D,SAAS,CAAC,YAAY,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QAC9C,SAAS,CAAC,YAAY,CAAC,MAAM,CAC3B,0BAA0B,EAC1B,MAAM,CAAC,qBAAqB,IAAI,GAAG,CACpC,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,aAAa,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import type { AuthConfig } from \"@/server/config.js\";\nimport type { AuthStorage } from \"@/types.js\";\nimport { DEFAULT_AUTH_SERVER, DEFAULT_SCOPES } from \"@/constants.js\";\nimport { GenericPublicClientPKCEProducer } from \"@/services/PKCE.js\";\nimport { GenericAuthenticationInitiator } from \"@/services/AuthenticationService.js\";\nimport { OAuthTokenTypes } from \"@/shared/lib/types.js\";\nimport { getEndpointsWithOverrides } from \"@/shared/lib/util.js\";\n\nexport async function buildLogoutRedirectUrl(\n config: Pick<AuthConfig, \"clientId\" | \"postLogoutRedirectUrl\"> &\n Partial<Pick<AuthConfig, \"oauthServer\">> & {\n scopes?: string[];\n state?: string;\n },\n storage: AuthStorage,\n): Promise<URL> {\n // Ensure clientId is present for OAuth operations\n if (!config.clientId) {\n throw new Error(\"clientId is required for OAuth logout operations\");\n }\n\n // generate a random state if not provided\n const state = config.state ?? Math.random().toString(36).substring(2);\n const scopes = config.scopes ?? DEFAULT_SCOPES;\n const pkceProducer = new GenericPublicClientPKCEProducer(storage);\n const authInitiator = new GenericAuthenticationInitiator({\n ...config,\n clientId: config.clientId,\n state,\n scopes,\n oauthServer: config.oauthServer ?? DEFAULT_AUTH_SERVER,\n pkceConsumer: pkceProducer,\n redirectUrl: config.postLogoutRedirectUrl || \"/\",\n });\n\n const idToken = await storage.get(OAuthTokenTypes.ID_TOKEN);\n\n // OAuth logout should work without id_token_hint (it's optional per OAuth spec)\n if (!idToken) {\n // Build logout URL using proper endpoint discovery, without id_token_hint\n const endpoints = await getEndpointsWithOverrides(\n config.oauthServer ?? DEFAULT_AUTH_SERVER,\n );\n const logoutUrl = new URL(endpoints.endsession);\n logoutUrl.searchParams.append(\"client_id\", config.clientId);\n logoutUrl.searchParams.append(\"state\", state);\n logoutUrl.searchParams.append(\n \"post_logout_redirect_uri\",\n config.postLogoutRedirectUrl || \"/\",\n );\n return logoutUrl;\n }\n\n return authInitiator.signOut(idToken);\n}\n"]}
|
package/dist/server/session.d.ts
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
import { type AuthStorage, type OAuthTokens, type User, type EmptyObject, type UnknownObject, type OIDCTokenResponseBody } from "../types.js";
|
|
2
2
|
import type { AuthConfig } from "../server/config.js";
|
|
3
3
|
import type { AuthenticationResolver } from "../services/types.js";
|
|
4
|
+
export type UrlDetectionRequest = {
|
|
5
|
+
url: string;
|
|
6
|
+
headers: Record<string, string | string[] | undefined>;
|
|
7
|
+
searchParams: {
|
|
8
|
+
get(name: string): string | null;
|
|
9
|
+
};
|
|
10
|
+
cookies: {
|
|
11
|
+
get(name: string): {
|
|
12
|
+
value: string;
|
|
13
|
+
} | undefined;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
4
16
|
export type HandleCallbackRequest = {
|
|
5
17
|
headers: {
|
|
6
18
|
[key: string]: string | string[] | undefined;
|
|
@@ -10,6 +22,7 @@ export type HandleCallbackRequest = {
|
|
|
10
22
|
accept?: string;
|
|
11
23
|
"sec-fetch-dest"?: string;
|
|
12
24
|
};
|
|
25
|
+
url?: string;
|
|
13
26
|
};
|
|
14
27
|
export type HandleCallbackParams = {
|
|
15
28
|
code: string;
|
|
@@ -77,6 +90,40 @@ export declare class CivicAuth {
|
|
|
77
90
|
* Clear all authentication tokens from storage
|
|
78
91
|
*/
|
|
79
92
|
clearTokens(): Promise<void>;
|
|
93
|
+
/**
|
|
94
|
+
* Framework-agnostic URL detection and resolution helpers
|
|
95
|
+
* These methods handle proxy environments and can be used by any framework
|
|
96
|
+
*/
|
|
97
|
+
/**
|
|
98
|
+
* Try to URI decode a value, returning the original value on error
|
|
99
|
+
*/
|
|
100
|
+
static tryUriDecode(value: string): string;
|
|
101
|
+
/**
|
|
102
|
+
* Get decoded query parameter from request
|
|
103
|
+
*/
|
|
104
|
+
static getDecodedQueryParam(request: UrlDetectionRequest, paramName: string): string | null;
|
|
105
|
+
/**
|
|
106
|
+
* Get value from cookie or query parameter (cookie takes precedence)
|
|
107
|
+
*/
|
|
108
|
+
static getCookieOrQueryParam(request: UrlDetectionRequest, cookieName: string, queryName: string): string | null;
|
|
109
|
+
/**
|
|
110
|
+
* Get app URL from request (for proxy environment support)
|
|
111
|
+
* Checks cookies first, then query parameters
|
|
112
|
+
*/
|
|
113
|
+
static getAppUrl(request: UrlDetectionRequest): string | null;
|
|
114
|
+
/**
|
|
115
|
+
* Get login success URL with proper base URL handling
|
|
116
|
+
* Extracts from state parameter or query parameters, resolves with baseUrl if provided
|
|
117
|
+
*/
|
|
118
|
+
static getLoginSuccessUrl(request: UrlDetectionRequest, baseUrl?: string | null): string | null;
|
|
119
|
+
/**
|
|
120
|
+
* Convert relative URL to absolute URL using appUrl for proxy environments
|
|
121
|
+
*/
|
|
122
|
+
static toAbsoluteUrl(request: UrlDetectionRequest, url: string, appUrl?: string | null): string;
|
|
123
|
+
/**
|
|
124
|
+
* Get post-logout redirect URL with proxy environment support
|
|
125
|
+
*/
|
|
126
|
+
getPostLogoutRedirectUrl(request: UrlDetectionRequest): string;
|
|
80
127
|
/**
|
|
81
128
|
* Smart callback handler that automatically detects frontend vs backend requests
|
|
82
129
|
* and redirects appropriately. Use this instead of resolveOAuthAccessCode + manual redirect.
|
|
@@ -120,5 +167,9 @@ export declare class CivicAuth {
|
|
|
120
167
|
* Generate HTML content for iframe completion that sends postMessage to parent
|
|
121
168
|
*/
|
|
122
169
|
private generateIframeCompletionHtml;
|
|
170
|
+
/**
|
|
171
|
+
* Generate HTML response that triggers same-domain callback for iframe workaround
|
|
172
|
+
*/
|
|
173
|
+
private generateSameDomainCallbackHtml;
|
|
123
174
|
}
|
|
124
175
|
//# sourceMappingURL=session.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/server/session.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,IAAI,EACT,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,qBAAqB,EAE3B,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/server/session.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,IAAI,EACT,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,qBAAqB,EAE3B,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAoBrD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAQlE,MAAM,MAAM,mBAAmB,GAAG;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IACvD,YAAY,EAAE;QACZ,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;KAClC,CAAC;IACF,OAAO,EAAE;QACP,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG;YAAE,KAAK,EAAE,MAAM,CAAA;SAAE,GAAG,SAA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