@eventuras/fides-auth-next 0.1.5 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/LICENSE +674 -0
  2. package/dist/cookies.js +192 -53
  3. package/dist/cookies.js.map +1 -0
  4. package/dist/index.js +18 -17
  5. package/dist/oidc-callback.js +52 -22
  6. package/dist/oidc-callback.js.map +1 -0
  7. package/dist/oidc-login.js +41 -15
  8. package/dist/oidc-login.js.map +1 -0
  9. package/dist/request.js +27 -17
  10. package/dist/request.js.map +1 -0
  11. package/dist/session.js +184 -44
  12. package/dist/session.js.map +1 -0
  13. package/dist/store/configure-logger.js +21 -6
  14. package/dist/store/configure-logger.js.map +1 -0
  15. package/dist/store/hooks.js +61 -19
  16. package/dist/store/hooks.js.map +1 -0
  17. package/dist/store/index.js +6 -6
  18. package/dist/store/session-monitor.js +80 -37
  19. package/dist/store/session-monitor.js.map +1 -0
  20. package/dist/store/store.js +174 -90
  21. package/dist/store/store.js.map +1 -0
  22. package/dist/store/use-session-monitor.js +35 -8
  23. package/dist/store/use-session-monitor.js.map +1 -0
  24. package/package.json +22 -13
  25. package/dist/fides-auth/dist/build-CNL3v39v.js +0 -977
  26. package/dist/fides-auth/dist/decode_jwt-1J26fl4I.js +0 -25
  27. package/dist/fides-auth/dist/decrypt-Cahlu_6Y.js +0 -88
  28. package/dist/fides-auth/dist/deflate-koSuX7FB.js +0 -969
  29. package/dist/fides-auth/dist/logger.js +0 -46
  30. package/dist/fides-auth/dist/oauth.js +0 -165
  31. package/dist/fides-auth/dist/rate-limit.js +0 -26
  32. package/dist/fides-auth/dist/session-refresh.js +0 -27
  33. package/dist/fides-auth/dist/session-validation-BxObT3wC.js +0 -64
  34. package/dist/fides-auth/dist/silent-login.js +0 -50
  35. package/dist/fides-auth/dist/utils-ByMRF7b2.js +0 -379
package/dist/session.js CHANGED
@@ -1,61 +1,201 @@
1
- import { V as e, q as t } from "./fides-auth/dist/utils-ByMRF7b2.js";
2
- import { c as n } from "./fides-auth/dist/session-validation-BxObT3wC.js";
3
- import { r } from "./fides-auth/dist/session-refresh.js";
4
- import { deleteSessionCookie as i, getSessionCookie as a, setSessionCookie as o } from "./cookies.js";
5
- import { Logger as s } from "@eventuras/logger";
6
- import { cache as c } from "react";
1
+ import { deleteSessionCookie, getSessionCookie, setSessionCookie } from "./cookies.js";
2
+ import { Logger } from "@eventuras/logger";
3
+ import { createEncryptedJWT, getSessionSecret } from "@eventuras/fides-auth/utils";
4
+ import { validateSessionJwt } from "@eventuras/fides-auth/session-validation";
5
+ import { refreshSession } from "@eventuras/fides-auth/session-refresh";
6
+ import { cache } from "react";
7
7
  //#region src/session.ts
8
- var l = s.create({ namespace: "fides-auth-next:session" });
9
- async function u(n, r = {}) {
10
- l.debug("Creating new session");
11
- let { sessionDurationDays: i = 7 } = r;
8
+ var logger = Logger.create({ namespace: "fides-auth-next:session" });
9
+ /**
10
+ * Creates an encrypted JWT containing session data.
11
+ *
12
+ * @param session - Session data (tokens, user, etc.)
13
+ * @param options - Configuration options (e.g., sessionDurationDays)
14
+ * @returns Encrypted JWT string
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const jwt = await createSession({
19
+ * tokens: {
20
+ * accessToken: 'token',
21
+ * refreshToken: 'refresh',
22
+ * },
23
+ * user: {
24
+ * name: 'John Doe',
25
+ * email: 'john@example.com',
26
+ * }
27
+ * });
28
+ * ```
29
+ */
30
+ async function createSession(session, options = {}) {
31
+ logger.debug("Creating new session");
32
+ const { sessionDurationDays = 7 } = options;
12
33
  try {
13
- let r = await e({ ...n }, t());
14
- return l.info({ sessionDurationDays: i }, "Session created successfully"), r;
15
- } catch (e) {
16
- throw l.error({ error: e }, "Failed to create session"), e;
34
+ const jwt = await createEncryptedJWT({ ...session }, getSessionSecret());
35
+ logger.info({ sessionDurationDays }, "Session created successfully");
36
+ return jwt;
37
+ } catch (error) {
38
+ logger.error({ error }, "Failed to create session");
39
+ throw error;
17
40
  }
18
41
  }
19
- var d = c(async (e) => {
20
- l.debug("Retrieving current session");
42
+ /**
43
+ * Retrieves the current session from the "session" cookie, if any.
44
+ * Uses React server components' cache for performance.
45
+ *
46
+ * This function:
47
+ * 1. Gets the session cookie
48
+ * 2. Validates the JWT
49
+ * 3. Returns the session if valid, null otherwise
50
+ *
51
+ * @param config - Optional OAuth config (currently unused, kept for compatibility)
52
+ * @returns Session object or null if no valid session exists
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * // In a server component or server action
57
+ * const session = await getCurrentSession();
58
+ * if (session) {
59
+ * console.log('User:', session.user);
60
+ * } else {
61
+ * // User not logged in
62
+ * }
63
+ * ```
64
+ */
65
+ var getCurrentSession = cache(async (config) => {
66
+ logger.debug("Retrieving current session");
21
67
  try {
22
- let e = await a();
23
- if (!e) return l.debug("No session cookie found"), null;
24
- let { status: r, session: i } = await n(e, t());
25
- return r === "VALID" ? i ? (l.debug("Current session retrieved successfully"), i) : (l.warn("Session validation succeeded but no session object returned"), null) : (l.warn({ status: r }, "Session validation failed"), null);
26
- } catch (e) {
27
- return e instanceof Error && e.message.includes("worker") ? l.error({ error: e }, "Worker thread error in getCurrentSession") : l.error({ error: e }, "Unexpected error in getCurrentSession"), null;
68
+ const sessionCookie = await getSessionCookie();
69
+ if (!sessionCookie) {
70
+ logger.debug("No session cookie found");
71
+ return null;
72
+ }
73
+ const { status, session } = await validateSessionJwt(sessionCookie, getSessionSecret());
74
+ if (status !== "VALID") {
75
+ logger.warn({ status }, "Session validation failed");
76
+ return null;
77
+ }
78
+ if (!session) {
79
+ logger.warn("Session validation succeeded but no session object returned");
80
+ return null;
81
+ }
82
+ logger.debug("Current session retrieved successfully");
83
+ return session;
84
+ } catch (error) {
85
+ if (error instanceof Error && error.message.includes("worker")) logger.error({ error }, "Worker thread error in getCurrentSession");
86
+ else logger.error({ error }, "Unexpected error in getCurrentSession");
87
+ return null;
28
88
  }
29
89
  });
30
- async function f(e, t = {}) {
31
- l.info("Starting session refresh");
90
+ /**
91
+ * Refreshes the current session using the refresh token.
92
+ *
93
+ * This function:
94
+ * 1. Gets the current session
95
+ * 2. Uses the refresh token to get new access tokens
96
+ * 3. Updates the session cookie with new tokens
97
+ * 4. Returns the updated session
98
+ *
99
+ * @param config - OAuth configuration
100
+ * @param options - Session creation options
101
+ * @returns Updated session or null if refresh failed
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * const updatedSession = await refreshCurrentSession(oauthConfig);
106
+ * if (updatedSession) {
107
+ * // Session refreshed successfully
108
+ * } else {
109
+ * // Refresh failed, user needs to log in again
110
+ * redirect('/login');
111
+ * }
112
+ * ```
113
+ */
114
+ async function refreshCurrentSession(config, options = {}) {
115
+ logger.info("Starting session refresh");
32
116
  try {
33
- let n = await d();
34
- if (!n) return l.warn("No current session to refresh"), null;
35
- if (!n.tokens?.refreshToken) return l.error("Current session has no refresh token"), null;
36
- let i = await r(n, e, t);
37
- return i ? (await o(await u(i, t)), l.info("Session refreshed and cookie updated successfully"), i) : (l.error("Session refresh returned null"), null);
38
- } catch (e) {
39
- let t = e;
40
- return t?.code === "OAUTH_RESPONSE_BODY_ERROR" && t?.error === "invalid_grant" ? l.info("Session refresh failed - refresh token expired or invalid") : l.error({ error: e }, "Failed to refresh current session"), null;
117
+ const currentSession = await getCurrentSession();
118
+ if (!currentSession) {
119
+ logger.warn("No current session to refresh");
120
+ return null;
121
+ }
122
+ if (!currentSession.tokens?.refreshToken) {
123
+ logger.error("Current session has no refresh token");
124
+ return null;
125
+ }
126
+ const updatedSession = await refreshSession(currentSession, config, options);
127
+ if (!updatedSession) {
128
+ logger.error("Session refresh returned null");
129
+ return null;
130
+ }
131
+ await setSessionCookie(await createSession(updatedSession, options));
132
+ logger.info("Session refreshed and cookie updated successfully");
133
+ return updatedSession;
134
+ } catch (error) {
135
+ const err = error;
136
+ if (err?.code === "OAUTH_RESPONSE_BODY_ERROR" && err?.error === "invalid_grant") logger.info("Session refresh failed - refresh token expired or invalid");
137
+ else logger.error({ error }, "Failed to refresh current session");
138
+ return null;
41
139
  }
42
140
  }
43
- async function p(e, t = {}) {
44
- l.info("Creating and persisting new session");
141
+ /**
142
+ * Creates and persists a new session.
143
+ *
144
+ * This is a convenience function that combines createSession and setSessionCookie.
145
+ * Use this after successful authentication to establish a user session.
146
+ *
147
+ * @param session - Session data
148
+ * @param options - Session creation options
149
+ * @returns The encrypted JWT that was stored in the cookie
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * // After successful OAuth callback
154
+ * await createAndPersistSession({
155
+ * tokens: {
156
+ * accessToken: tokens.access_token,
157
+ * refreshToken: tokens.refresh_token,
158
+ * },
159
+ * user: {
160
+ * name: 'John Doe',
161
+ * email: 'john@example.com',
162
+ * }
163
+ * }, { sessionDurationDays: 30 });
164
+ * ```
165
+ */
166
+ async function createAndPersistSession(session, options = {}) {
167
+ logger.info("Creating and persisting new session");
45
168
  try {
46
- let n = await u(e, t);
47
- return await o(n), l.info("Session created and persisted successfully"), n;
48
- } catch (e) {
49
- throw l.error({ error: e }, "Failed to create and persist session"), e;
169
+ const jwt = await createSession(session, options);
170
+ await setSessionCookie(jwt);
171
+ logger.info("Session created and persisted successfully");
172
+ return jwt;
173
+ } catch (error) {
174
+ logger.error({ error }, "Failed to create and persist session");
175
+ throw error;
50
176
  }
51
177
  }
52
- async function m() {
53
- l.info("Clearing current session");
178
+ /**
179
+ * Clears the current session by deleting the session cookie.
180
+ * Use this when logging out or when session validation fails.
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * await clearCurrentSession();
185
+ * redirect('/');
186
+ * ```
187
+ */
188
+ async function clearCurrentSession() {
189
+ logger.info("Clearing current session");
54
190
  try {
55
- await i(), l.info("Session cleared successfully");
56
- } catch (e) {
57
- throw l.error({ error: e }, "Failed to clear session"), e;
191
+ await deleteSessionCookie();
192
+ logger.info("Session cleared successfully");
193
+ } catch (error) {
194
+ logger.error({ error }, "Failed to clear session");
195
+ throw error;
58
196
  }
59
197
  }
60
198
  //#endregion
61
- export { m as clearCurrentSession, p as createAndPersistSession, u as createSession, d as getCurrentSession, f as refreshCurrentSession };
199
+ export { clearCurrentSession, createAndPersistSession, createSession, getCurrentSession, refreshCurrentSession };
200
+
201
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { createEncryptedJWT, getSessionSecret } from '@eventuras/fides-auth/utils';\nimport { validateSessionJwt } from '@eventuras/fides-auth/session-validation';\nimport { refreshSession as refreshSessionCore } from '@eventuras/fides-auth/session-refresh';\nimport type { Session, CreateSessionOptions } from '@eventuras/fides-auth/types';\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport { Logger } from '@eventuras/logger';\nimport { cache } from 'react';\nimport { getSessionCookie, setSessionCookie, deleteSessionCookie } from './cookies';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:session' });\n\n/**\n * Creates an encrypted JWT containing session data.\n *\n * @param session - Session data (tokens, user, etc.)\n * @param options - Configuration options (e.g., sessionDurationDays)\n * @returns Encrypted JWT string\n *\n * @example\n * ```ts\n * const jwt = await createSession({\n * tokens: {\n * accessToken: 'token',\n * refreshToken: 'refresh',\n * },\n * user: {\n * name: 'John Doe',\n * email: 'john@example.com',\n * }\n * });\n * ```\n */\nexport async function createSession<TData = Record<string, unknown>>(\n session: Session<TData>,\n options: CreateSessionOptions = {}\n): Promise<string> {\n logger.debug('Creating new session');\n\n const { sessionDurationDays = 7 } = options;\n\n try {\n // Build the JWT payload and encrypt\n const jwt = await createEncryptedJWT({ ...session }, getSessionSecret());\n\n logger.info({ sessionDurationDays }, 'Session created successfully');\n return jwt;\n } catch (error) {\n logger.error({ error }, 'Failed to create session');\n throw error;\n }\n}\n\n/**\n * Retrieves the current session from the \"session\" cookie, if any.\n * Uses React server components' cache for performance.\n *\n * This function:\n * 1. Gets the session cookie\n * 2. Validates the JWT\n * 3. Returns the session if valid, null otherwise\n *\n * @param config - Optional OAuth config (currently unused, kept for compatibility)\n * @returns Session object or null if no valid session exists\n *\n * @example\n * ```ts\n * // In a server component or server action\n * const session = await getCurrentSession();\n * if (session) {\n * console.log('User:', session.user);\n * } else {\n * // User not logged in\n * }\n * ```\n */\nexport const getCurrentSession = cache(async (config?: OAuthConfig): Promise<Session<any> | null> => {\n logger.debug('Retrieving current session');\n\n try {\n const sessionCookie = await getSessionCookie();\n\n if (!sessionCookie) {\n logger.debug('No session cookie found');\n return null;\n }\n\n const { status, session } = await validateSessionJwt(sessionCookie, getSessionSecret());\n\n if (status !== 'VALID') {\n logger.warn({ status }, 'Session validation failed');\n return null;\n }\n\n if (!session) {\n logger.warn('Session validation succeeded but no session object returned');\n return null;\n }\n\n logger.debug('Current session retrieved successfully');\n return session;\n } catch (error) {\n // Worker thread errors should not crash the application\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in getCurrentSession');\n } else {\n logger.error({ error }, 'Unexpected error in getCurrentSession');\n }\n return null;\n }\n});\n\n/**\n * Refreshes the current session using the refresh token.\n *\n * This function:\n * 1. Gets the current session\n * 2. Uses the refresh token to get new access tokens\n * 3. Updates the session cookie with new tokens\n * 4. Returns the updated session\n *\n * @param config - OAuth configuration\n * @param options - Session creation options\n * @returns Updated session or null if refresh failed\n *\n * @example\n * ```ts\n * const updatedSession = await refreshCurrentSession(oauthConfig);\n * if (updatedSession) {\n * // Session refreshed successfully\n * } else {\n * // Refresh failed, user needs to log in again\n * redirect('/login');\n * }\n * ```\n */\nexport async function refreshCurrentSession(\n config: OAuthConfig,\n options: CreateSessionOptions = {}\n): Promise<Session | null> {\n logger.info('Starting session refresh');\n\n try {\n const currentSession = await getCurrentSession();\n\n if (!currentSession) {\n logger.warn('No current session to refresh');\n return null;\n }\n\n if (!currentSession.tokens?.refreshToken) {\n logger.error('Current session has no refresh token');\n return null;\n }\n\n // Use the core refresh function\n const updatedSession = await refreshSessionCore(currentSession, config, options);\n\n if (!updatedSession) {\n logger.error('Session refresh returned null');\n return null;\n }\n\n // Create new encrypted JWT\n const jwt = await createSession(updatedSession, options);\n\n // Update the session cookie\n await setSessionCookie(jwt);\n\n logger.info('Session refreshed and cookie updated successfully');\n return updatedSession;\n } catch (error) {\n // Check if this is an expected invalid_grant error\n const err = error as { code?: string; error?: string; };\n const isInvalidGrant = err?.code === 'OAUTH_RESPONSE_BODY_ERROR' && err?.error === 'invalid_grant';\n\n if (isInvalidGrant) {\n // Expected during logout/session expiry - log at info level\n logger.info('Session refresh failed - refresh token expired or invalid');\n } else {\n // Unexpected error - log at error level\n logger.error({ error }, 'Failed to refresh current session');\n }\n\n return null;\n }\n}\n\n/**\n * Creates and persists a new session.\n *\n * This is a convenience function that combines createSession and setSessionCookie.\n * Use this after successful authentication to establish a user session.\n *\n * @param session - Session data\n * @param options - Session creation options\n * @returns The encrypted JWT that was stored in the cookie\n *\n * @example\n * ```ts\n * // After successful OAuth callback\n * await createAndPersistSession({\n * tokens: {\n * accessToken: tokens.access_token,\n * refreshToken: tokens.refresh_token,\n * },\n * user: {\n * name: 'John Doe',\n * email: 'john@example.com',\n * }\n * }, { sessionDurationDays: 30 });\n * ```\n */\nexport async function createAndPersistSession(\n session: Session,\n options: CreateSessionOptions = {}\n): Promise<string> {\n logger.info('Creating and persisting new session');\n\n try {\n const jwt = await createSession(session, options);\n await setSessionCookie(jwt);\n\n logger.info('Session created and persisted successfully');\n return jwt;\n } catch (error) {\n logger.error({ error }, 'Failed to create and persist session');\n throw error;\n }\n}\n\n/**\n * Clears the current session by deleting the session cookie.\n * Use this when logging out or when session validation fails.\n *\n * @example\n * ```ts\n * await clearCurrentSession();\n * redirect('/');\n * ```\n */\nexport async function clearCurrentSession(): Promise<void> {\n logger.info('Clearing current session');\n\n try {\n await deleteSessionCookie();\n logger.info('Session cleared successfully');\n } catch (error) {\n logger.error({ error }, 'Failed to clear session');\n throw error;\n }\n}\n"],"mappings":";;;;;;;AASA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,2BAA2B,CAAC;;;;;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AO,MAAM,uCAAuC;AACpD,UAAO;;EAIT,MAAM,iBAAiB,MAAM,eAAmB,gBAAgB,QAAQ,QAAQ;AAEhF,MAAI,CAAC,gBAAgB;AACnB,UAAO,MAAM,gCAAgC;AAC7C,UAAO;;AAOT,QAAM,iBAAiB,MAHL,cAAc,gBAAgB,QAAQ,CAG7B;AAE3B,SAAO,KAAK,oDAAoD;AAChE,SAAO;UACA,OAAO;EAEd,MAAM,MAAM;AAGZ,MAFuB,KAAK,SAAS,+BAA+B,KAAK,UAAU,gBAIjF,QAAO,KAAK,4DAA4D;MAGxE,QAAO,MAAM,EAAE,OAAO,EAAE,oCAAoC;AAG9D,SAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BX,eAAsB,wBACpB,SACA,UAAgC,EAAE,EACjB;AACjB,QAAO,KAAK,sCAAsC;AAElD,KAAI;EACF,MAAM,MAAM,MAAM,cAAc,SAAS,QAAQ;AACjD,QAAM,iBAAiB,IAAI;AAE3B,SAAO,KAAK,6CAA6C;AACzD,SAAO;UACA,OAAO;AACd,SAAO,MAAM,EAAE,OAAO,EAAE,uCAAuC;AAC/D,QAAM;;;;;;;;;;;;;AAcV,eAAsB,sBAAqC;AACzD,QAAO,KAAK,2BAA2B;AAEvC,KAAI;AACF,QAAM,qBAAqB;AAC3B,SAAO,KAAK,+BAA+B;UACpC,OAAO;AACd,SAAO,MAAM,EAAE,OAAO,EAAE,0BAA0B;AAClD,QAAM"}
@@ -1,10 +1,25 @@
1
- import { r as e } from "../fides-auth/dist/logger.js";
2
- import { Logger as t } from "@eventuras/logger";
1
+ import { Logger } from "@eventuras/logger";
2
+ import { configureLogger } from "@eventuras/fides-auth/logger";
3
3
  //#region src/store/configure-logger.ts
4
- function n() {
5
- e({ create(e) {
6
- return t.create(e);
4
+ /**
5
+ * Configures fides-auth to use @eventuras/logger for all internal logging.
6
+ *
7
+ * Call this once at application startup, before creating the auth store.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { configureAuthLogger, createAuthStore } from '@eventuras/fides-auth-next/store';
12
+ *
13
+ * configureAuthLogger();
14
+ * const authStore = createAuthStore({ checkAuthStatus });
15
+ * ```
16
+ */
17
+ function configureAuthLogger() {
18
+ configureLogger({ create(options) {
19
+ return Logger.create(options);
7
20
  } });
8
21
  }
9
22
  //#endregion
10
- export { n as configureAuthLogger };
23
+ export { configureAuthLogger };
24
+
25
+ //# sourceMappingURL=configure-logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configure-logger.js","names":[],"sources":["../../src/store/configure-logger.ts"],"sourcesContent":["/**\n * Configures fides-auth to use @eventuras/logger for all internal logging.\n *\n * Call this once at application startup, before creating the auth store.\n *\n * @example\n * ```typescript\n * import { configureAuthLogger, createAuthStore } from '@eventuras/fides-auth-next/store';\n *\n * configureAuthLogger();\n * const authStore = createAuthStore({ checkAuthStatus });\n * ```\n */\n\nimport { configureLogger } from '@eventuras/fides-auth/logger';\nimport { Logger } from '@eventuras/logger';\n\nexport function configureAuthLogger(): void {\n configureLogger({\n create(options) {\n return Logger.create(options);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAgB,sBAA4B;AAC1C,iBAAgB,EACd,OAAO,SAAS;AACd,SAAO,OAAO,OAAO,QAAQ;IAEhC,CAAC"}
@@ -1,36 +1,78 @@
1
- import { useSelector as e } from "@xstate/store/react";
1
+ import { useSelector } from "@xstate/store/react";
2
2
  //#region src/store/hooks.ts
3
- function t(t) {
4
- function n() {
5
- return e(t, (e) => e).context;
3
+ /**
4
+ * Creates React hooks for interacting with the auth store
5
+ *
6
+ * @param store - The XState store instance
7
+ * @returns Object containing useAuthStore hook
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const authStore = createAuthStore({
12
+ * checkAuthStatus: getAuthStatus,
13
+ * });
14
+ *
15
+ * export const { useAuthStore } = createAuthStoreHooks(authStore);
16
+ *
17
+ * // In component
18
+ * function MyComponent() {
19
+ * const auth = useAuthStore();
20
+ *
21
+ * if (auth.error) {
22
+ * toast.error(auth.error);
23
+ * }
24
+ *
25
+ * if (auth.isInitializing) {
26
+ * return <Spinner />;
27
+ * }
28
+ *
29
+ * return (
30
+ * <div>
31
+ * {auth.isAuthenticated ? `Hello ${auth.user?.name}` : 'Please login'}
32
+ * </div>
33
+ * );
34
+ * }
35
+ * ```
36
+ */
37
+ function createAuthStoreHooks(store) {
38
+ /**
39
+ * Hook to access the auth store state
40
+ */
41
+ function useAuthStore() {
42
+ return useSelector(store, (snapshot) => snapshot).context;
6
43
  }
7
- function r() {
44
+ /**
45
+ * Hook to get auth store actions
46
+ */
47
+ function useAuthActions() {
8
48
  return {
9
- loginSuccess: (e) => t.send({
49
+ loginSuccess: (user) => store.send({
10
50
  type: "loginSuccess",
11
- user: e
51
+ user
12
52
  }),
13
- logout: () => t.send({ type: "logout" }),
14
- sessionExpired: () => t.send({ type: "sessionExpired" }),
15
- authSuccess: (e) => t.send({
53
+ logout: () => store.send({ type: "logout" }),
54
+ sessionExpired: () => store.send({ type: "sessionExpired" }),
55
+ authSuccess: (user) => store.send({
16
56
  type: "authSuccess",
17
- user: e
57
+ user
18
58
  }),
19
- authFailed: (e) => t.send({
59
+ authFailed: (error) => store.send({
20
60
  type: "authFailed",
21
- error: e
61
+ error
22
62
  }),
23
- setError: (e) => t.send({
63
+ setError: (error) => store.send({
24
64
  type: "setError",
25
- error: e
65
+ error
26
66
  }),
27
- clearError: () => t.send({ type: "clearError" })
67
+ clearError: () => store.send({ type: "clearError" })
28
68
  };
29
69
  }
30
70
  return {
31
- useAuthStore: n,
32
- useAuthActions: r
71
+ useAuthStore,
72
+ useAuthActions
33
73
  };
34
74
  }
35
75
  //#endregion
36
- export { t as createAuthStoreHooks };
76
+ export { createAuthStoreHooks };
77
+
78
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.js","names":[],"sources":["../../src/store/hooks.ts"],"sourcesContent":["import { useSelector as useStoreSelector } from '@xstate/store/react';\nimport type { SessionUser } from './types';\nimport type { createAuthStore } from './store';\n\n/**\n * Return type for store-based auth hooks\n */\nexport type AuthStoreSelector = {\n isAuthenticated: boolean;\n isAdmin: boolean;\n user: SessionUser | null;\n error: string | null;\n lastChecked: Date | null;\n isInitializing: boolean;\n};\n\n/**\n * Actions for store-based auth\n */\nexport type AuthStoreActions = {\n loginSuccess: (user: SessionUser) => void;\n logout: () => void;\n sessionExpired: () => void;\n authSuccess: (user: SessionUser) => void;\n authFailed: (error?: string) => void;\n setError: (error: string) => void;\n clearError: () => void;\n};\n\n/**\n * Creates React hooks for interacting with the auth store\n *\n * @param store - The XState store instance\n * @returns Object containing useAuthStore hook\n *\n * @example\n * ```typescript\n * const authStore = createAuthStore({\n * checkAuthStatus: getAuthStatus,\n * });\n *\n * export const { useAuthStore } = createAuthStoreHooks(authStore);\n *\n * // In component\n * function MyComponent() {\n * const auth = useAuthStore();\n *\n * if (auth.error) {\n * toast.error(auth.error);\n * }\n *\n * if (auth.isInitializing) {\n * return <Spinner />;\n * }\n *\n * return (\n * <div>\n * {auth.isAuthenticated ? `Hello ${auth.user?.name}` : 'Please login'}\n * </div>\n * );\n * }\n * ```\n */\nexport function createAuthStoreHooks(store: ReturnType<typeof createAuthStore>) {\n /**\n * Hook to access the auth store state\n */\n function useAuthStore(): AuthStoreSelector {\n const snapshot = useStoreSelector(store, (snapshot) => snapshot);\n return snapshot.context;\n }\n\n /**\n * Hook to get auth store actions\n */\n function useAuthActions(): AuthStoreActions {\n return {\n loginSuccess: (user: SessionUser) => store.send({ type: 'loginSuccess', user }),\n logout: () => store.send({ type: 'logout' }),\n sessionExpired: () => store.send({ type: 'sessionExpired' }),\n authSuccess: (user: SessionUser) => store.send({ type: 'authSuccess', user }),\n authFailed: (error?: string) => store.send({ type: 'authFailed', error }),\n setError: (error: string) => store.send({ type: 'setError', error }),\n clearError: () => store.send({ type: 'clearError' }),\n };\n }\n\n return {\n useAuthStore,\n useAuthActions,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,SAAgB,qBAAqB,OAA2C;;;;CAI9E,SAAS,eAAkC;AAEzC,SADiB,YAAiB,QAAQ,aAAa,SAChD,CAAS;;;;;CAMlB,SAAS,iBAAmC;AAC1C,SAAO;GACL,eAAe,SAAsB,MAAM,KAAK;IAAE,MAAM;IAAgB;IAAM,CAAC;GAC/E,cAAc,MAAM,KAAK,EAAE,MAAM,UAAU,CAAC;GAC5C,sBAAsB,MAAM,KAAK,EAAE,MAAM,kBAAkB,CAAC;GAC5D,cAAc,SAAsB,MAAM,KAAK;IAAE,MAAM;IAAe;IAAM,CAAC;GAC7E,aAAa,UAAmB,MAAM,KAAK;IAAE,MAAM;IAAc;IAAO,CAAC;GACzE,WAAW,UAAkB,MAAM,KAAK;IAAE,MAAM;IAAY;IAAO,CAAC;GACpE,kBAAkB,MAAM,KAAK,EAAE,MAAM,cAAc,CAAC;GACrD;;AAGH,QAAO;EACL;EACA;EACD"}
@@ -1,6 +1,6 @@
1
- import { checkAuth as e, createAuthStore as t, initializeAuth as n } from "./store.js";
2
- import { createAuthStoreHooks as r } from "./hooks.js";
3
- import { startSessionMonitor as i } from "./session-monitor.js";
4
- import { useSessionMonitor as a } from "./use-session-monitor.js";
5
- import { configureAuthLogger as o } from "./configure-logger.js";
6
- export { e as checkAuth, o as configureAuthLogger, t as createAuthStore, r as createAuthStoreHooks, n as initializeAuth, i as startSessionMonitor, a as useSessionMonitor };
1
+ import { checkAuth, createAuthStore, initializeAuth } from "./store.js";
2
+ import { createAuthStoreHooks } from "./hooks.js";
3
+ import { startSessionMonitor } from "./session-monitor.js";
4
+ import { useSessionMonitor } from "./use-session-monitor.js";
5
+ import { configureAuthLogger } from "./configure-logger.js";
6
+ export { checkAuth, configureAuthLogger, createAuthStore, createAuthStoreHooks, initializeAuth, startSessionMonitor, useSessionMonitor };
@@ -1,49 +1,92 @@
1
- import { Logger as e } from "@eventuras/logger";
1
+ import { Logger } from "@eventuras/logger";
2
2
  //#region src/store/session-monitor.ts
3
- var t = {
3
+ var DEFAULT_CONFIG = {
4
4
  interval: 3e4,
5
5
  loggerNamespace: "fides:session-monitor"
6
6
  };
7
- function n(n, r, i = {}) {
8
- let a = {
9
- ...t,
10
- ...i
11
- }, o = e.create({
12
- namespace: a.loggerNamespace,
7
+ /**
8
+ * Creates a session monitor that polls auth status at regular intervals
9
+ *
10
+ * This is designed to be used with React's useEffect for cleanup.
11
+ *
12
+ * @param store - The auth store to update
13
+ * @param checkAuthStatus - Function to check authentication status
14
+ * @param config - Optional configuration
15
+ * @returns Cleanup function to stop monitoring
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * useEffect(() => {
20
+ * const cleanup = startSessionMonitor(authStore, checkAuthStatus, {
21
+ * interval: 30_000,
22
+ * onSessionExpired: () => {
23
+ * toast.warn('Your session has expired');
24
+ * }
25
+ * });
26
+ *
27
+ * return cleanup;
28
+ * }, []);
29
+ * ```
30
+ */
31
+ function startSessionMonitor(store, checkAuthStatus, config = {}) {
32
+ const finalConfig = {
33
+ ...DEFAULT_CONFIG,
34
+ ...config
35
+ };
36
+ const logger = Logger.create({
37
+ namespace: finalConfig.loggerNamespace,
13
38
  context: { component: "SessionMonitor" }
14
39
  });
15
- o.debug({ interval: a.interval }, "Starting session monitor");
16
- let s = !0, c = null, l = async () => {
17
- if (s) {
18
- try {
19
- let e = await r();
20
- if (o.debug({ authenticated: e.authenticated }, "Session monitor check"), !e.authenticated) {
21
- o.info("Session monitor detected unauthenticated state - session ended"), n.send({ type: "sessionExpired" }), a.onSessionExpired && a.onSessionExpired();
22
- return;
23
- }
24
- e.user && n.send({
25
- type: "authSuccess",
26
- user: e.user
27
- });
28
- } catch (e) {
29
- let t = e;
30
- if (t?.code === "OAUTH_RESPONSE_BODY_ERROR" && t?.error === "invalid_grant") {
31
- o.info("Session monitor detected expired refresh token - user session ended"), n.send({ type: "sessionExpired" }), a.onSessionExpired && a.onSessionExpired();
32
- return;
33
- }
34
- let r = { message: e instanceof Error ? e.message : "Unknown error" };
35
- if (e && typeof e == "object") {
36
- let t = e;
37
- t.code && (r.code = t.code), t.error && (r.error = t.error), t.error_description && (r.error_description = t.error_description), t.status && (r.status = t.status);
38
- }
39
- o.error(r, "Session monitor error"), a.onError && e instanceof Error && a.onError(e);
40
+ logger.debug({ interval: finalConfig.interval }, "Starting session monitor");
41
+ let isActive = true;
42
+ let timeoutId = null;
43
+ const poll = async () => {
44
+ if (!isActive) return;
45
+ try {
46
+ const result = await checkAuthStatus();
47
+ logger.debug({ authenticated: result.authenticated }, "Session monitor check");
48
+ if (!result.authenticated) {
49
+ logger.info("Session monitor detected unauthenticated state - session ended");
50
+ store.send({ type: "sessionExpired" });
51
+ if (finalConfig.onSessionExpired) finalConfig.onSessionExpired();
52
+ return;
53
+ }
54
+ if (result.user) store.send({
55
+ type: "authSuccess",
56
+ user: result.user
57
+ });
58
+ } catch (error) {
59
+ const err = error;
60
+ if (err?.code === "OAUTH_RESPONSE_BODY_ERROR" && err?.error === "invalid_grant") {
61
+ logger.info("Session monitor detected expired refresh token - user session ended");
62
+ store.send({ type: "sessionExpired" });
63
+ if (finalConfig.onSessionExpired) finalConfig.onSessionExpired();
64
+ return;
40
65
  }
41
- s && (c = setTimeout(l, a.interval));
66
+ const errorDetails = { message: error instanceof Error ? error.message : "Unknown error" };
67
+ if (error && typeof error === "object") {
68
+ const oauthError = error;
69
+ if (oauthError.code) errorDetails.code = oauthError.code;
70
+ if (oauthError.error) errorDetails.error = oauthError.error;
71
+ if (oauthError.error_description) errorDetails.error_description = oauthError.error_description;
72
+ if (oauthError.status) errorDetails.status = oauthError.status;
73
+ }
74
+ logger.error(errorDetails, "Session monitor error");
75
+ if (finalConfig.onError && error instanceof Error) finalConfig.onError(error);
42
76
  }
77
+ if (isActive) timeoutId = setTimeout(poll, finalConfig.interval);
43
78
  };
44
- return c = setTimeout(l, a.interval), () => {
45
- o.debug("Stopping session monitor"), s = !1, c &&= (clearTimeout(c), null);
79
+ timeoutId = setTimeout(poll, finalConfig.interval);
80
+ return () => {
81
+ logger.debug("Stopping session monitor");
82
+ isActive = false;
83
+ if (timeoutId) {
84
+ clearTimeout(timeoutId);
85
+ timeoutId = null;
86
+ }
46
87
  };
47
88
  }
48
89
  //#endregion
49
- export { n as startSessionMonitor };
90
+ export { startSessionMonitor };
91
+
92
+ //# sourceMappingURL=session-monitor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-monitor.js","names":[],"sources":["../../src/store/session-monitor.ts"],"sourcesContent":["import { Logger } from '@eventuras/logger';\nimport type { createAuthStore } from './store';\nimport type { AuthStatus } from './types';\n\n/**\n * Configuration for session monitoring\n */\nexport type SessionMonitorConfig = {\n /**\n * Interval in milliseconds for session monitoring polling\n * @default 30000 (30 seconds)\n */\n interval?: number;\n\n /**\n * Namespace for logger\n * @default 'fides:session-monitor'\n */\n loggerNamespace?: string;\n\n /**\n * Callback when session expires\n */\n onSessionExpired?: () => void;\n\n /**\n * Callback when session check fails\n */\n onError?: (error: Error) => void;\n};\n\nconst DEFAULT_CONFIG = {\n interval: 30_000, // 30 seconds\n loggerNamespace: 'fides:session-monitor',\n};\n\n/**\n * Creates a session monitor that polls auth status at regular intervals\n *\n * This is designed to be used with React's useEffect for cleanup.\n *\n * @param store - The auth store to update\n * @param checkAuthStatus - Function to check authentication status\n * @param config - Optional configuration\n * @returns Cleanup function to stop monitoring\n *\n * @example\n * ```typescript\n * useEffect(() => {\n * const cleanup = startSessionMonitor(authStore, checkAuthStatus, {\n * interval: 30_000,\n * onSessionExpired: () => {\n * toast.warn('Your session has expired');\n * }\n * });\n *\n * return cleanup;\n * }, []);\n * ```\n */\nexport function startSessionMonitor(\n store: ReturnType<typeof createAuthStore>,\n checkAuthStatus: () => Promise<AuthStatus>,\n config: SessionMonitorConfig = {}\n): () => void {\n const finalConfig = { ...DEFAULT_CONFIG, ...config };\n const logger = Logger.create({\n namespace: finalConfig.loggerNamespace,\n context: { component: 'SessionMonitor' },\n });\n\n logger.debug({ interval: finalConfig.interval }, 'Starting session monitor');\n\n let isActive = true;\n let timeoutId: NodeJS.Timeout | null = null;\n\n const poll = async (): Promise<void> => {\n if (!isActive) return;\n\n try {\n const result = await checkAuthStatus();\n logger.debug({ authenticated: result.authenticated }, 'Session monitor check');\n\n if (!result.authenticated) {\n // User is no longer authenticated - session ended\n logger.info('Session monitor detected unauthenticated state - session ended');\n store.send({ type: 'sessionExpired' });\n\n if (finalConfig.onSessionExpired) {\n finalConfig.onSessionExpired();\n }\n\n // Stop monitoring after session expires\n return;\n }\n\n if (result.user) {\n store.send({ type: 'authSuccess', user: result.user });\n }\n } catch (error) {\n // Check if this is an expected invalid_grant error (expired refresh token)\n const err = error as { code?: string; error?: string; error_description?: string; };\n const isInvalidGrant =\n err?.code === 'OAUTH_RESPONSE_BODY_ERROR' && err?.error === 'invalid_grant';\n\n if (isInvalidGrant) {\n // This is expected during logout or session expiry - log at info level\n logger.info('Session monitor detected expired refresh token - user session ended');\n store.send({ type: 'sessionExpired' });\n\n if (finalConfig.onSessionExpired) {\n finalConfig.onSessionExpired();\n }\n\n // Stop monitoring after session expires\n return;\n }\n\n // Unexpected error during auth check - log with details\n const errorDetails: Record<string, unknown> = {\n message: error instanceof Error ? error.message : 'Unknown error',\n };\n\n // Extract OAuth error details if present\n if (error && typeof error === 'object') {\n const oauthError = error as any;\n if (oauthError.code) errorDetails.code = oauthError.code;\n if (oauthError.error) errorDetails.error = oauthError.error;\n if (oauthError.error_description)\n errorDetails.error_description = oauthError.error_description;\n if (oauthError.status) errorDetails.status = oauthError.status;\n }\n\n logger.error(errorDetails, 'Session monitor error');\n\n if (finalConfig.onError && error instanceof Error) {\n finalConfig.onError(error);\n }\n }\n\n // Schedule next poll if still active\n if (isActive) {\n timeoutId = setTimeout(poll, finalConfig.interval);\n }\n };\n\n // Start first poll\n timeoutId = setTimeout(poll, finalConfig.interval);\n\n // Return cleanup function\n return () => {\n logger.debug('Stopping session monitor');\n isActive = false;\n if (timeoutId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