@eventuras/fides-auth-next 0.1.11 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cookies.js.map +1 -1
- package/dist/oidc-callback.js.map +1 -1
- package/dist/oidc-login.js.map +1 -1
- package/dist/request.js.map +1 -1
- package/dist/session.js.map +1 -1
- package/dist/store/configure-logger.js.map +1 -1
- package/dist/store/hooks.js.map +1 -1
- package/dist/store/session-monitor.js.map +1 -1
- package/dist/store/store.js.map +1 -1
- package/dist/store/use-session-monitor.js.map +1 -1
- package/package.json +2 -2
package/dist/cookies.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookies.js","names":[],"sources":["../src/cookies.ts"],"sourcesContent":["/**\n * Cookie helpers for Next.js authentication flows.\n *\n * IMPORTANT: These functions can ONLY be used in:\n * - Server Actions (functions marked with 'use server')\n * - Route Handlers (files in app/api directory)\n * - Server Components (async React components)\n *\n * They CANNOT be used in:\n * - Client Components (marked with 'use client')\n * - Middleware (use NextResponse.cookies instead)\n * - Edge Runtime without proper configuration\n */\n\nimport { Logger } from '@eventuras/logger';\nimport { cookies } from 'next/headers';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:cookies' });\n\nexport interface CookieOptions {\n /** Cookie path (default: '/') */\n path?: string;\n /** Max age in seconds */\n maxAge?: number;\n /** SameSite policy (default: 'lax') */\n sameSite?: 'strict' | 'lax' | 'none';\n /** HTTP only flag (default: true) */\n httpOnly?: boolean;\n /** Secure flag (default: true in production) */\n secure?: boolean;\n}\n\n/**\n * Default cookie options for session cookies.\n * - Secure in production\n * - HTTP only\n * - Lax same-site policy\n * - 30 days max age\n */\nexport const defaultSessionCookieOptions: CookieOptions = {\n path: '/',\n maxAge: 60 * 60 * 24 * 30, // 30 days\n sameSite: 'lax',\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n};\n\n/**\n * Default cookie options for OAuth state/PKCE cookies.\n * - Secure in production\n * - HTTP only\n * - Lax same-site policy\n * - 10 minutes max age (short-lived for security)\n */\nexport const defaultOAuthCookieOptions: CookieOptions = {\n path: '/',\n maxAge: 60 * 10, // 10 minutes\n sameSite: 'lax',\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n};\n\n/**\n * Sets a cookie with the given name and value.\n *\n * @param name - Cookie name\n * @param value - Cookie value\n * @param options - Cookie options (defaults to session cookie options)\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await setAuthCookie('session', encryptedJwt);\n *\n * // With custom options\n * await setAuthCookie('oauth_state', state, {\n * maxAge: 60 * 10, // 10 minutes\n * });\n * ```\n */\nexport async function setAuthCookie(\n name: string,\n value: string,\n options: CookieOptions = defaultSessionCookieOptions\n): Promise<void> {\n try {\n const cookieStore = await cookies();\n const cookieOptions = { ...defaultSessionCookieOptions, ...options };\n\n cookieStore.set(name, value, cookieOptions);\n\n logger.debug({\n cookieName: name,\n maxAge: cookieOptions.maxAge,\n secure: cookieOptions.secure\n }, 'Cookie set successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to set cookie');\n throw error;\n }\n}\n\n/**\n * Gets a cookie value by name.\n *\n * @param name - Cookie name\n * @returns Cookie value or null if not found\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * const sessionCookie = await getAuthCookie('session');\n * if (sessionCookie) {\n * // Validate and use session\n * }\n * ```\n */\nexport async function getAuthCookie(name: string): Promise<string | null> {\n try {\n const cookieStore = await cookies();\n const cookie = cookieStore.get(name);\n\n if (!cookie?.value) {\n logger.debug({ cookieName: name }, 'Cookie not found');\n return null;\n }\n\n logger.debug({ cookieName: name }, 'Cookie retrieved');\n return cookie.value;\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to get cookie');\n return null;\n }\n}\n\n/**\n * Deletes a cookie by name.\n *\n * @param name - Cookie name to delete\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await deleteAuthCookie('session');\n * ```\n */\nexport async function deleteAuthCookie(name: string): Promise<void> {\n try {\n const cookieStore = await cookies();\n cookieStore.delete(name);\n\n logger.debug({ cookieName: name }, 'Cookie deleted successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to delete cookie');\n throw error;\n }\n}\n\n/**\n * Deletes multiple cookies at once.\n * Useful for cleaning up OAuth flow cookies.\n *\n * @param names - Array of cookie names to delete\n *\n * @example\n * ```ts\n * // Clean up OAuth cookies after callback\n * await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);\n * ```\n */\nexport async function deleteAuthCookies(names: string[]): Promise<void> {\n try {\n const cookieStore = await cookies();\n\n for (const name of names) {\n cookieStore.delete(name);\n }\n\n logger.debug({ cookieNames: names }, 'Multiple cookies deleted successfully');\n } catch (error) {\n logger.error({ error, cookieNames: names }, 'Failed to delete cookies');\n throw error;\n }\n}\n\n/**\n * Sets the session cookie with proper security settings.\n * This is a convenience wrapper around setAuthCookie.\n *\n * @param encryptedJwt - The encrypted JWT session token\n * @param options - Optional cookie options (merged with defaults)\n *\n * @example\n * ```ts\n * const jwt = await createSession({ ... });\n * await setSessionCookie(jwt);\n * ```\n */\nexport async function setSessionCookie(\n encryptedJwt: string,\n options: Partial<CookieOptions> = {}\n): Promise<void> {\n await setAuthCookie('session', encryptedJwt, {\n ...defaultSessionCookieOptions,\n ...options,\n });\n\n logger.info('Session cookie set');\n}\n\n/**\n * Gets the current session cookie value.\n * Returns null if no session cookie exists.\n *\n * @returns Encrypted JWT session token or null\n *\n * @example\n * ```ts\n * const sessionToken = await getSessionCookie();\n * if (sessionToken) {\n * const { status, session } = await validateSessionJwt(sessionToken);\n * // ...\n * }\n * ```\n */\nexport async function getSessionCookie(): Promise<string | null> {\n return await getAuthCookie('session');\n}\n\n/**\n * Deletes the session cookie.\n * Use this when logging out or when session validation fails.\n *\n * @example\n * ```ts\n * await deleteSessionCookie();\n * redirect('/');\n * ```\n */\nexport async function deleteSessionCookie(): Promise<void> {\n await deleteAuthCookie('session');\n logger.info('Session cookie deleted');\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,2BAA2B,CAAC;;;;;;;;AAsBtE,IAAa,8BAA6C;CACxD,MAAM;CACN,QAAQ,OAAU,KAAK;CACvB,UAAU;CACV,UAAU;CACV,QAAA,QAAA,IAAA,aAAiC;CAClC;;;;;;;;AASD,IAAa,4BAA2C;CACtD,MAAM;CACN,QAAQ;CACR,UAAU;CACV,UAAU;CACV,QAAA,QAAA,IAAA,aAAiC;CAClC;;;;;;;;;;;;;;;;;;;AAoBD,eAAsB,cACpB,MACA,OACA,UAAyB,6BACV;
|
|
1
|
+
{"version":3,"file":"cookies.js","names":[],"sources":["../src/cookies.ts"],"sourcesContent":["/**\n * Cookie helpers for Next.js authentication flows.\n *\n * IMPORTANT: These functions can ONLY be used in:\n * - Server Actions (functions marked with 'use server')\n * - Route Handlers (files in app/api directory)\n * - Server Components (async React components)\n *\n * They CANNOT be used in:\n * - Client Components (marked with 'use client')\n * - Middleware (use NextResponse.cookies instead)\n * - Edge Runtime without proper configuration\n */\n\nimport { Logger } from '@eventuras/logger';\nimport { cookies } from 'next/headers';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:cookies' });\n\nexport interface CookieOptions {\n /** Cookie path (default: '/') */\n path?: string;\n /** Max age in seconds */\n maxAge?: number;\n /** SameSite policy (default: 'lax') */\n sameSite?: 'strict' | 'lax' | 'none';\n /** HTTP only flag (default: true) */\n httpOnly?: boolean;\n /** Secure flag (default: true in production) */\n secure?: boolean;\n}\n\n/**\n * Default cookie options for session cookies.\n * - Secure in production\n * - HTTP only\n * - Lax same-site policy\n * - 30 days max age\n */\nexport const defaultSessionCookieOptions: CookieOptions = {\n path: '/',\n maxAge: 60 * 60 * 24 * 30, // 30 days\n sameSite: 'lax',\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n};\n\n/**\n * Default cookie options for OAuth state/PKCE cookies.\n * - Secure in production\n * - HTTP only\n * - Lax same-site policy\n * - 10 minutes max age (short-lived for security)\n */\nexport const defaultOAuthCookieOptions: CookieOptions = {\n path: '/',\n maxAge: 60 * 10, // 10 minutes\n sameSite: 'lax',\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n};\n\n/**\n * Sets a cookie with the given name and value.\n *\n * @param name - Cookie name\n * @param value - Cookie value\n * @param options - Cookie options (defaults to session cookie options)\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await setAuthCookie('session', encryptedJwt);\n *\n * // With custom options\n * await setAuthCookie('oauth_state', state, {\n * maxAge: 60 * 10, // 10 minutes\n * });\n * ```\n */\nexport async function setAuthCookie(\n name: string,\n value: string,\n options: CookieOptions = defaultSessionCookieOptions\n): Promise<void> {\n try {\n const cookieStore = await cookies();\n const cookieOptions = { ...defaultSessionCookieOptions, ...options };\n\n cookieStore.set(name, value, cookieOptions);\n\n logger.debug({\n cookieName: name,\n maxAge: cookieOptions.maxAge,\n secure: cookieOptions.secure\n }, 'Cookie set successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to set cookie');\n throw error;\n }\n}\n\n/**\n * Gets a cookie value by name.\n *\n * @param name - Cookie name\n * @returns Cookie value or null if not found\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * const sessionCookie = await getAuthCookie('session');\n * if (sessionCookie) {\n * // Validate and use session\n * }\n * ```\n */\nexport async function getAuthCookie(name: string): Promise<string | null> {\n try {\n const cookieStore = await cookies();\n const cookie = cookieStore.get(name);\n\n if (!cookie?.value) {\n logger.debug({ cookieName: name }, 'Cookie not found');\n return null;\n }\n\n logger.debug({ cookieName: name }, 'Cookie retrieved');\n return cookie.value;\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to get cookie');\n return null;\n }\n}\n\n/**\n * Deletes a cookie by name.\n *\n * @param name - Cookie name to delete\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await deleteAuthCookie('session');\n * ```\n */\nexport async function deleteAuthCookie(name: string): Promise<void> {\n try {\n const cookieStore = await cookies();\n cookieStore.delete(name);\n\n logger.debug({ cookieName: name }, 'Cookie deleted successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to delete cookie');\n throw error;\n }\n}\n\n/**\n * Deletes multiple cookies at once.\n * Useful for cleaning up OAuth flow cookies.\n *\n * @param names - Array of cookie names to delete\n *\n * @example\n * ```ts\n * // Clean up OAuth cookies after callback\n * await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);\n * ```\n */\nexport async function deleteAuthCookies(names: string[]): Promise<void> {\n try {\n const cookieStore = await cookies();\n\n for (const name of names) {\n cookieStore.delete(name);\n }\n\n logger.debug({ cookieNames: names }, 'Multiple cookies deleted successfully');\n } catch (error) {\n logger.error({ error, cookieNames: names }, 'Failed to delete cookies');\n throw error;\n }\n}\n\n/**\n * Sets the session cookie with proper security settings.\n * This is a convenience wrapper around setAuthCookie.\n *\n * @param encryptedJwt - The encrypted JWT session token\n * @param options - Optional cookie options (merged with defaults)\n *\n * @example\n * ```ts\n * const jwt = await createSession({ ... });\n * await setSessionCookie(jwt);\n * ```\n */\nexport async function setSessionCookie(\n encryptedJwt: string,\n options: Partial<CookieOptions> = {}\n): Promise<void> {\n await setAuthCookie('session', encryptedJwt, {\n ...defaultSessionCookieOptions,\n ...options,\n });\n\n logger.info('Session cookie set');\n}\n\n/**\n * Gets the current session cookie value.\n * Returns null if no session cookie exists.\n *\n * @returns Encrypted JWT session token or null\n *\n * @example\n * ```ts\n * const sessionToken = await getSessionCookie();\n * if (sessionToken) {\n * const { status, session } = await validateSessionJwt(sessionToken);\n * // ...\n * }\n * ```\n */\nexport async function getSessionCookie(): Promise<string | null> {\n return await getAuthCookie('session');\n}\n\n/**\n * Deletes the session cookie.\n * Use this when logging out or when session validation fails.\n *\n * @example\n * ```ts\n * await deleteSessionCookie();\n * redirect('/');\n * ```\n */\nexport async function deleteSessionCookie(): Promise<void> {\n await deleteAuthCookie('session');\n logger.info('Session cookie deleted');\n}\n"],"mappings":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E,0BAA0B;EACpE,MAAM;;;;;;;;;;;;;;;AAgBV,eAAsB,kBAAkB,OAAgC;CACtE,IAAI;EACF,MAAM,cAAc,MAAM,SAAS;EAEnC,KAAK,MAAM,QAAQ,OACjB,YAAY,OAAO,KAAK;EAG1B,OAAO,MAAM,EAAE,aAAa,OAAO,EAAE,wCAAwC;UACtE,OAAO;EACd,OAAO,MAAM;GAAE;GAAO,aAAa;GAAO,EAAE,2BAA2B;EACvE,MAAM;;;;;;;;;;;;;;;;AAiBV,eAAsB,iBACpB,cACA,UAAkC,EAAE,EACrB;CACf,MAAM,cAAc,WAAW,cAAc;EAC3C,GAAG;EACH,GAAG;EACJ,CAAC;CAEF,OAAO,KAAK,qBAAqB;;;;;;;;;;;;;;;;;AAkBnC,eAAsB,mBAA2C;CAC/D,OAAO,MAAM,cAAc,UAAU;;;;;;;;;;;;AAavC,eAAsB,sBAAqC;CACzD,MAAM,iBAAiB,UAAU;CACjC,OAAO,KAAK,yBAAyB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oidc-callback.js","names":[],"sources":["../src/oidc-callback.ts"],"sourcesContent":["/**\n * Generic OIDC callback handler for Next.js route handlers.\n *\n * Orchestrates the Next.js-specific concerns (cookies, rate limiting, HTTP responses)\n * while delegating OIDC logic to @eventuras/fides-auth.\n */\n\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport {\n buildSessionFromTokens,\n exchangeAuthorizationCode,\n validateReturnUrl,\n} from '@eventuras/fides-auth/oauth';\nimport { Logger } from '@eventuras/logger';\n\nimport {\n getAuthCookie,\n setSessionCookie,\n deleteAuthCookies,\n} from './cookies';\nimport { globalGETRateLimit } from './request';\nimport { createSession } from './session';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:oidc-callback' });\n\nexport interface OidcCallbackConfig {\n /** OAuth/OIDC configuration (issuer, clientId, clientSecret, redirect_uri, scope) */\n oauthConfig: OAuthConfig;\n\n /** Public application URL (used to reconstruct the callback URL and validate redirects) */\n applicationUrl: string;\n\n /**\n * Name of the ID token claim that contains user roles.\n * @default 'roles'\n */\n rolesClaim?: string;\n\n /**\n * Session duration in days.\n * @default 7\n */\n sessionDurationDays?: number;\n\n /**\n * Default path to redirect to after login if no returnTo cookie is set.\n * @default '/'\n */\n defaultRedirectPath?: string;\n\n /**\n * Optional function to validate the returnTo path.\n * If not provided, only same-origin paths are allowed.\n */\n validateReturnTo?: (path: string) => boolean;\n}\n\n/**\n * Handles the OIDC callback in a Next.js route handler.\n *\n * @example\n * ```ts\n * // In app/api/auth/callback/oidc/route.ts\n * import { handleOidcCallback } from '@eventuras/fides-auth-next/oidc-callback';\n *\n * export async function GET(request: Request) {\n * return handleOidcCallback(request, {\n * oauthConfig,\n * applicationUrl: 'https://example.com',\n * rolesClaim: 'roles',\n * });\n * }\n * ```\n */\nexport async function handleOidcCallback(\n request: Request,\n config: OidcCallbackConfig,\n): Promise<Response> {\n const {\n oauthConfig,\n applicationUrl,\n rolesClaim = 'roles',\n sessionDurationDays = 7,\n defaultRedirectPath = '/',\n validateReturnTo,\n } = config;\n\n // 1) Rate limit\n if (!(await globalGETRateLimit())) {\n logger.warn('Rate limit exceeded');\n return new Response('Too many requests', { status: 429 });\n }\n\n try {\n // 2) Reconstruct the public callback URL\n const currentUrl = new URL(request.url);\n const publicUrl = new URL(applicationUrl);\n publicUrl.search = currentUrl.search;\n\n // 3) Read PKCE cookies\n const storedState = await getAuthCookie('oauth_state');\n const storedCodeVerifier = await getAuthCookie('oauth_code_verifier');\n\n if (!storedState || !storedCodeVerifier) {\n logger.warn('Missing state or code verifier');\n return new Response('Please restart the login process.', { status: 400 });\n }\n\n // 4) Exchange code for tokens (generic OIDC logic in fides-auth)\n const tokens = await exchangeAuthorizationCode(\n oauthConfig,\n publicUrl,\n storedCodeVerifier,\n storedState,\n );\n\n // 5) Build session from tokens and persist\n const session = buildSessionFromTokens(tokens, rolesClaim);\n const jwt = await createSession(session, { sessionDurationDays });\n await setSessionCookie(jwt);\n\n // 7) Clean up PKCE & returnTo cookies\n const returnTo = await getAuthCookie('returnTo');\n await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);\n\n // 8) Build safe redirect URL (generic validation in fides-auth)\n const redirectUrl = validateReturnUrl(\n returnTo,\n applicationUrl,\n defaultRedirectPath,\n validateReturnTo,\n );\n redirectUrl.searchParams.set('login', 'success');\n\n logger.info({ redirectUrl: redirectUrl.toString() }, 'Login successful, redirecting');\n\n return new Response(null, {\n status: 302,\n headers: { Location: redirectUrl.toString() },\n });\n } catch (error) {\n logger.error({ error }, 'OIDC callback error');\n return new Response('An unexpected error occurred. Please restart the login process.', {\n status: 500,\n });\n }\n}\n"],"mappings":";;;;;;AAuBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,iCAAiC,CAAC;;;;;;;;;;;;;;;;;;AAmD5E,eAAsB,mBACpB,SACA,QACmB;CACnB,MAAM,EACJ,aACA,gBACA,aAAa,SACb,sBAAsB,GACtB,sBAAsB,KACtB,qBACE;
|
|
1
|
+
{"version":3,"file":"oidc-callback.js","names":[],"sources":["../src/oidc-callback.ts"],"sourcesContent":["/**\n * Generic OIDC callback handler for Next.js route handlers.\n *\n * Orchestrates the Next.js-specific concerns (cookies, rate limiting, HTTP responses)\n * while delegating OIDC logic to @eventuras/fides-auth.\n */\n\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport {\n buildSessionFromTokens,\n exchangeAuthorizationCode,\n validateReturnUrl,\n} from '@eventuras/fides-auth/oauth';\nimport { Logger } from '@eventuras/logger';\n\nimport {\n getAuthCookie,\n setSessionCookie,\n deleteAuthCookies,\n} from './cookies';\nimport { globalGETRateLimit } from './request';\nimport { createSession } from './session';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:oidc-callback' });\n\nexport interface OidcCallbackConfig {\n /** OAuth/OIDC configuration (issuer, clientId, clientSecret, redirect_uri, scope) */\n oauthConfig: OAuthConfig;\n\n /** Public application URL (used to reconstruct the callback URL and validate redirects) */\n applicationUrl: string;\n\n /**\n * Name of the ID token claim that contains user roles.\n * @default 'roles'\n */\n rolesClaim?: string;\n\n /**\n * Session duration in days.\n * @default 7\n */\n sessionDurationDays?: number;\n\n /**\n * Default path to redirect to after login if no returnTo cookie is set.\n * @default '/'\n */\n defaultRedirectPath?: string;\n\n /**\n * Optional function to validate the returnTo path.\n * If not provided, only same-origin paths are allowed.\n */\n validateReturnTo?: (path: string) => boolean;\n}\n\n/**\n * Handles the OIDC callback in a Next.js route handler.\n *\n * @example\n * ```ts\n * // In app/api/auth/callback/oidc/route.ts\n * import { handleOidcCallback } from '@eventuras/fides-auth-next/oidc-callback';\n *\n * export async function GET(request: Request) {\n * return handleOidcCallback(request, {\n * oauthConfig,\n * applicationUrl: 'https://example.com',\n * rolesClaim: 'roles',\n * });\n * }\n * ```\n */\nexport async function handleOidcCallback(\n request: Request,\n config: OidcCallbackConfig,\n): Promise<Response> {\n const {\n oauthConfig,\n applicationUrl,\n rolesClaim = 'roles',\n sessionDurationDays = 7,\n defaultRedirectPath = '/',\n validateReturnTo,\n } = config;\n\n // 1) Rate limit\n if (!(await globalGETRateLimit())) {\n logger.warn('Rate limit exceeded');\n return new Response('Too many requests', { status: 429 });\n }\n\n try {\n // 2) Reconstruct the public callback URL\n const currentUrl = new URL(request.url);\n const publicUrl = new URL(applicationUrl);\n publicUrl.search = currentUrl.search;\n\n // 3) Read PKCE cookies\n const storedState = await getAuthCookie('oauth_state');\n const storedCodeVerifier = await getAuthCookie('oauth_code_verifier');\n\n if (!storedState || !storedCodeVerifier) {\n logger.warn('Missing state or code verifier');\n return new Response('Please restart the login process.', { status: 400 });\n }\n\n // 4) Exchange code for tokens (generic OIDC logic in fides-auth)\n const tokens = await exchangeAuthorizationCode(\n oauthConfig,\n publicUrl,\n storedCodeVerifier,\n storedState,\n );\n\n // 5) Build session from tokens and persist\n const session = buildSessionFromTokens(tokens, rolesClaim);\n const jwt = await createSession(session, { sessionDurationDays });\n await setSessionCookie(jwt);\n\n // 7) Clean up PKCE & returnTo cookies\n const returnTo = await getAuthCookie('returnTo');\n await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);\n\n // 8) Build safe redirect URL (generic validation in fides-auth)\n const redirectUrl = validateReturnUrl(\n returnTo,\n applicationUrl,\n defaultRedirectPath,\n validateReturnTo,\n );\n redirectUrl.searchParams.set('login', 'success');\n\n logger.info({ redirectUrl: redirectUrl.toString() }, 'Login successful, redirecting');\n\n return new Response(null, {\n status: 302,\n headers: { Location: redirectUrl.toString() },\n });\n } catch (error) {\n logger.error({ error }, 'OIDC callback error');\n return new Response('An unexpected error occurred. Please restart the login process.', {\n status: 500,\n });\n }\n}\n"],"mappings":";;;;;;AAuBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,iCAAiC,CAAC;;;;;;;;;;;;;;;;;;AAmD5E,eAAsB,mBACpB,SACA,QACmB;CACnB,MAAM,EACJ,aACA,gBACA,aAAa,SACb,sBAAsB,GACtB,sBAAsB,KACtB,qBACE;CAGJ,IAAI,CAAE,MAAM,oBAAoB,EAAG;EACjC,OAAO,KAAK,sBAAsB;EAClC,OAAO,IAAI,SAAS,qBAAqB,EAAE,QAAQ,KAAK,CAAC;;CAG3D,IAAI;EAEF,MAAM,aAAa,IAAI,IAAI,QAAQ,IAAI;EACvC,MAAM,YAAY,IAAI,IAAI,eAAe;EACzC,UAAU,SAAS,WAAW;EAG9B,MAAM,cAAc,MAAM,cAAc,cAAc;EACtD,MAAM,qBAAqB,MAAM,cAAc,sBAAsB;EAErE,IAAI,CAAC,eAAe,CAAC,oBAAoB;GACvC,OAAO,KAAK,iCAAiC;GAC7C,OAAO,IAAI,SAAS,qCAAqC,EAAE,QAAQ,KAAK,CAAC;;EAc3E,MAAM,iBAAiB,MADL,cADF,uBAAuB,MARlB,0BACnB,aACA,WACA,oBACA,YACD,EAG8C,WACf,EAAS,EAAE,qBAAqB,CAAC,CACtC;EAG3B,MAAM,WAAW,MAAM,cAAc,WAAW;EAChD,MAAM,kBAAkB;GAAC;GAAe;GAAuB;GAAW,CAAC;EAG3E,MAAM,cAAc,kBAClB,UACA,gBACA,qBACA,iBACD;EACD,YAAY,aAAa,IAAI,SAAS,UAAU;EAEhD,OAAO,KAAK,EAAE,aAAa,YAAY,UAAU,EAAE,EAAE,gCAAgC;EAErF,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ;GACR,SAAS,EAAE,UAAU,YAAY,UAAU,EAAE;GAC9C,CAAC;UACK,OAAO;EACd,OAAO,MAAM,EAAE,OAAO,EAAE,sBAAsB;EAC9C,OAAO,IAAI,SAAS,mEAAmE,EACrF,QAAQ,KACT,CAAC"}
|
package/dist/oidc-login.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oidc-login.js","names":[],"sources":["../src/oidc-login.ts"],"sourcesContent":["/**\n * Generic OIDC login initiation handler for Next.js route handlers.\n *\n * Builds PKCE parameters, persists them in cookies, and redirects\n * to the OIDC provider's authorization endpoint.\n */\n\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport {\n buildPKCEOptions,\n discoverAndBuildAuthorizationUrl,\n} from '@eventuras/fides-auth/oauth';\nimport { Logger } from '@eventuras/logger';\nimport { cookies } from 'next/headers';\n\nimport { defaultOAuthCookieOptions } from './cookies';\nimport { globalGETRateLimit } from './request';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:oidc-login' });\n\nexport interface OidcLoginConfig {\n /** OAuth/OIDC configuration */\n oauthConfig: OAuthConfig;\n\n /**\n * Validates and sanitizes the returnTo parameter.\n * Should return a safe path or null to use the default.\n * @default Only allows relative paths starting with /\n */\n validateReturnTo?: (rawReturnTo: string) => string | null;\n}\n\nconst defaultValidateReturnTo = (raw: string): string | null =>\n /^\\/(?!\\/)/.test(raw) ? raw : null;\n\n/**\n * Handles OIDC login initiation in a Next.js route handler.\n *\n * @example\n * ```ts\n * // In app/api/auth/login/route.ts\n * import { handleOidcLogin } from '@eventuras/fides-auth-next/oidc-login';\n *\n * export async function GET(request: Request) {\n * return handleOidcLogin(request, { oauthConfig });\n * }\n * ```\n */\nexport async function handleOidcLogin(\n request: Request,\n config: OidcLoginConfig,\n): Promise<Response> {\n const { oauthConfig, validateReturnTo = defaultValidateReturnTo } = config;\n\n if (!(await globalGETRateLimit())) {\n logger.warn('Rate limit exceeded');\n return new Response('Too many requests', { status: 429 });\n }\n\n // Validate returnTo parameter\n const url = new URL(request.url);\n const rawReturnTo = url.searchParams.get('returnTo');\n const returnTo = rawReturnTo ? validateReturnTo(rawReturnTo) : null;\n\n // Build PKCE & authorization URL\n const pkce = await buildPKCEOptions(oauthConfig);\n const authorizationUrl = await discoverAndBuildAuthorizationUrl(oauthConfig, pkce);\n\n logger.info('Redirecting to OIDC provider for login');\n\n // Persist PKCE state in cookies using Next.js cookies API\n const cookieStore = await cookies();\n const cookieOpts = defaultOAuthCookieOptions;\n\n cookieStore.set('oauth_state', pkce.state, cookieOpts);\n cookieStore.set('oauth_code_verifier', pkce.code_verifier, cookieOpts);\n\n if (returnTo) {\n cookieStore.set('returnTo', returnTo, cookieOpts);\n }\n\n return new Response(null, {\n status: 302,\n headers: { Location: authorizationUrl.toString() },\n });\n}\n"],"mappings":";;;;;;AAkBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,8BAA8B,CAAC;AAczE,IAAM,2BAA2B,QAC/B,YAAY,KAAK,IAAI,GAAG,MAAM;;;;;;;;;;;;;;AAehC,eAAsB,gBACpB,SACA,QACmB;CACnB,MAAM,EAAE,aAAa,mBAAmB,4BAA4B;
|
|
1
|
+
{"version":3,"file":"oidc-login.js","names":[],"sources":["../src/oidc-login.ts"],"sourcesContent":["/**\n * Generic OIDC login initiation handler for Next.js route handlers.\n *\n * Builds PKCE parameters, persists them in cookies, and redirects\n * to the OIDC provider's authorization endpoint.\n */\n\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport {\n buildPKCEOptions,\n discoverAndBuildAuthorizationUrl,\n} from '@eventuras/fides-auth/oauth';\nimport { Logger } from '@eventuras/logger';\nimport { cookies } from 'next/headers';\n\nimport { defaultOAuthCookieOptions } from './cookies';\nimport { globalGETRateLimit } from './request';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:oidc-login' });\n\nexport interface OidcLoginConfig {\n /** OAuth/OIDC configuration */\n oauthConfig: OAuthConfig;\n\n /**\n * Validates and sanitizes the returnTo parameter.\n * Should return a safe path or null to use the default.\n * @default Only allows relative paths starting with /\n */\n validateReturnTo?: (rawReturnTo: string) => string | null;\n}\n\nconst defaultValidateReturnTo = (raw: string): string | null =>\n /^\\/(?!\\/)/.test(raw) ? raw : null;\n\n/**\n * Handles OIDC login initiation in a Next.js route handler.\n *\n * @example\n * ```ts\n * // In app/api/auth/login/route.ts\n * import { handleOidcLogin } from '@eventuras/fides-auth-next/oidc-login';\n *\n * export async function GET(request: Request) {\n * return handleOidcLogin(request, { oauthConfig });\n * }\n * ```\n */\nexport async function handleOidcLogin(\n request: Request,\n config: OidcLoginConfig,\n): Promise<Response> {\n const { oauthConfig, validateReturnTo = defaultValidateReturnTo } = config;\n\n if (!(await globalGETRateLimit())) {\n logger.warn('Rate limit exceeded');\n return new Response('Too many requests', { status: 429 });\n }\n\n // Validate returnTo parameter\n const url = new URL(request.url);\n const rawReturnTo = url.searchParams.get('returnTo');\n const returnTo = rawReturnTo ? validateReturnTo(rawReturnTo) : null;\n\n // Build PKCE & authorization URL\n const pkce = await buildPKCEOptions(oauthConfig);\n const authorizationUrl = await discoverAndBuildAuthorizationUrl(oauthConfig, pkce);\n\n logger.info('Redirecting to OIDC provider for login');\n\n // Persist PKCE state in cookies using Next.js cookies API\n const cookieStore = await cookies();\n const cookieOpts = defaultOAuthCookieOptions;\n\n cookieStore.set('oauth_state', pkce.state, cookieOpts);\n cookieStore.set('oauth_code_verifier', pkce.code_verifier, cookieOpts);\n\n if (returnTo) {\n cookieStore.set('returnTo', returnTo, cookieOpts);\n }\n\n return new Response(null, {\n status: 302,\n headers: { Location: authorizationUrl.toString() },\n });\n}\n"],"mappings":";;;;;;AAkBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,8BAA8B,CAAC;AAczE,IAAM,2BAA2B,QAC/B,YAAY,KAAK,IAAI,GAAG,MAAM;;;;;;;;;;;;;;AAehC,eAAsB,gBACpB,SACA,QACmB;CACnB,MAAM,EAAE,aAAa,mBAAmB,4BAA4B;CAEpE,IAAI,CAAE,MAAM,oBAAoB,EAAG;EACjC,OAAO,KAAK,sBAAsB;EAClC,OAAO,IAAI,SAAS,qBAAqB,EAAE,QAAQ,KAAK,CAAC;;CAK3D,MAAM,cAAc,IADJ,IAAI,QAAQ,IACR,CAAI,aAAa,IAAI,WAAW;CACpD,MAAM,WAAW,cAAc,iBAAiB,YAAY,GAAG;CAG/D,MAAM,OAAO,MAAM,iBAAiB,YAAY;CAChD,MAAM,mBAAmB,MAAM,iCAAiC,aAAa,KAAK;CAElF,OAAO,KAAK,yCAAyC;CAGrD,MAAM,cAAc,MAAM,SAAS;CACnC,MAAM,aAAa;CAEnB,YAAY,IAAI,eAAe,KAAK,OAAO,WAAW;CACtD,YAAY,IAAI,uBAAuB,KAAK,eAAe,WAAW;CAEtE,IAAI,UACF,YAAY,IAAI,YAAY,UAAU,WAAW;CAGnD,OAAO,IAAI,SAAS,MAAM;EACxB,QAAQ;EACR,SAAS,EAAE,UAAU,iBAAiB,UAAU,EAAE;EACnD,CAAC"}
|
package/dist/request.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.js","names":[],"sources":["../src/request.ts"],"sourcesContent":["import { headers } from 'next/headers';\nimport {TokenBucket} from '@eventuras/fides-auth/rate-limit';\nimport { Logger } from '@eventuras/logger';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:request' });\n\n// Initialize bucket lazily to avoid worker thread issues\nlet globalBucket: TokenBucket<string> | null = null;\n\nfunction getBucket(): TokenBucket<string> {\n if (!globalBucket) {\n globalBucket = new TokenBucket<string>(100, 1);\n }\n return globalBucket;\n}\n\nexport async function globalGETRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 1);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalGETRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalGETRateLimit');\n }\n return true;\n }\n}\n\nexport async function globalPOSTRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 3);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalPOSTRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalPOSTRateLimit');\n }\n return true;\n }\n}\n"],"mappings":";;;;AAIA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,2BAA2B,CAAC;AAGtE,IAAI,eAA2C;AAE/C,SAAS,YAAiC;
|
|
1
|
+
{"version":3,"file":"request.js","names":[],"sources":["../src/request.ts"],"sourcesContent":["import { headers } from 'next/headers';\nimport {TokenBucket} from '@eventuras/fides-auth/rate-limit';\nimport { Logger } from '@eventuras/logger';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:request' });\n\n// Initialize bucket lazily to avoid worker thread issues\nlet globalBucket: TokenBucket<string> | null = null;\n\nfunction getBucket(): TokenBucket<string> {\n if (!globalBucket) {\n globalBucket = new TokenBucket<string>(100, 1);\n }\n return globalBucket;\n}\n\nexport async function globalGETRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 1);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalGETRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalGETRateLimit');\n }\n return true;\n }\n}\n\nexport async function globalPOSTRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 3);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalPOSTRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalPOSTRateLimit');\n }\n return true;\n }\n}\n"],"mappings":";;;;AAIA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,2BAA2B,CAAC;AAGtE,IAAI,eAA2C;AAE/C,SAAS,YAAiC;CACxC,IAAI,CAAC,cACH,eAAe,IAAI,YAAoB,KAAK,EAAE;CAEhD,OAAO;;AAGT,eAAsB,qBAAuC;CAC3D,IAAI;EAEF,MAAM,YAAW,MADS,SAAS,EACN,IAAI,kBAAkB;EACnD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,WAAW,CAAC,QAAQ,UAAU,EAAE;UAChC,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,SAAS,EAC5D,OAAO,MAAM,EAAE,OAAO,EAAE,4CAA4C;OAEpE,OAAO,MAAM,EAAE,OAAO,EAAE,yCAAyC;EAEnE,OAAO;;;AAIX,eAAsB,sBAAwC;CAC5D,IAAI;EAEF,MAAM,YAAW,MADS,SAAS,EACN,IAAI,kBAAkB;EACnD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,WAAW,CAAC,QAAQ,UAAU,EAAE;UAChC,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,SAAS,EAC5D,OAAO,MAAM,EAAE,OAAO,EAAE,6CAA6C;OAErE,OAAO,MAAM,EAAE,OAAO,EAAE,0CAA0C;EAEpE,OAAO"}
|
package/dist/session.js.map
CHANGED
|
@@ -1 +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;;;;;;;;;;;;;;;;;;;;;;AAuBtE,eAAsB,cACpB,SACA,UAAgC,EAAE,EACjB;
|
|
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;;;;;;;;;;;;;;;;;;;;;;AAuBtE,eAAsB,cACpB,SACA,UAAgC,EAAE,EACjB;CACjB,OAAO,MAAM,uBAAuB;CAEpC,MAAM,EAAE,sBAAsB,MAAM;CAEpC,IAAI;EAEF,MAAM,MAAM,MAAM,mBAAmB,EAAE,GAAG,SAAS,EAAE,kBAAkB,CAAC;EAExE,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B,OAAO,KAAK,oDAAoD;EAChE,OAAO;UACA,OAAO;EAEd,MAAM,MAAM;EAGZ,IAFuB,KAAK,SAAS,+BAA+B,KAAK,UAAU,iBAIjF,OAAO,KAAK,4DAA4D;OAGxE,OAAO,MAAM,EAAE,OAAO,EAAE,oCAAoC;EAG9D,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BX,eAAsB,wBACpB,SACA,UAAgC,EAAE,EACjB;CACjB,OAAO,KAAK,sCAAsC;CAElD,IAAI;EACF,MAAM,MAAM,MAAM,cAAc,SAAS,QAAQ;EACjD,MAAM,iBAAiB,IAAI;EAE3B,OAAO,KAAK,6CAA6C;EACzD,OAAO;UACA,OAAO;EACd,OAAO,MAAM,EAAE,OAAO,EAAE,uCAAuC;EAC/D,MAAM;;;;;;;;;;;;;AAcV,eAAsB,sBAAqC;CACzD,OAAO,KAAK,2BAA2B;CAEvC,IAAI;EACF,MAAM,qBAAqB;EAC3B,OAAO,KAAK,+BAA+B;UACpC,OAAO;EACd,OAAO,MAAM,EAAE,OAAO,EAAE,0BAA0B;EAClD,MAAM"}
|
|
@@ -1 +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;
|
|
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;CAC1C,gBAAgB,EACd,OAAO,SAAS;EACd,OAAO,OAAO,OAAO,QAAQ;IAEhC,CAAC"}
|
package/dist/store/hooks.js.map
CHANGED
|
@@ -1 +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;
|
|
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;EAEzC,OADiB,YAAiB,QAAQ,aAAa,SAChD,CAAS;;;;;CAMlB,SAAS,iBAAmC;EAC1C,OAAO;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;;CAGH,OAAO;EACL;EACA;EACD"}
|
|
@@ -1 +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) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n}\n"],"mappings":";;AA+BA,IAAM,iBAAiB;CACrB,UAAU;CACV,iBAAiB;CAClB;;;;;;;;;;;;;;;;;;;;;;;;;AA0BD,SAAgB,oBACd,OACA,iBACA,SAA+B,EAAE,EACrB;CACZ,MAAM,cAAc;EAAE,GAAG;EAAgB,GAAG;EAAQ;CACpD,MAAM,SAAS,OAAO,OAAO;EAC3B,WAAW,YAAY;EACvB,SAAS,EAAE,WAAW,kBAAkB;EACzC,CAAC;
|
|
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 =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IACtD,IAAI,WAAW,mBACb,aAAa,oBAAoB,WAAW;IAC9C,IAAI,WAAW,QAAQ,aAAa,SAAS,WAAW;;GAG1D,OAAO,MAAM,cAAc,wBAAwB;GAEnD,IAAI,YAAY,WAAW,iBAAiB,OAC1C,YAAY,QAAQ,MAAM;;EAK9B,IAAI,UACF,YAAY,WAAW,MAAM,YAAY,SAAS;;CAKtD,YAAY,WAAW,MAAM,YAAY,SAAS;CAGlD,aAAa;EACX,OAAO,MAAM,2BAA2B;EACxC,WAAW;EACX,IAAI,WAAW;GACb,aAAa,UAAU;GACvB,YAAY"}
|
package/dist/store/store.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","names":[],"sources":["../../src/store/store.ts"],"sourcesContent":["import { createStore } from '@xstate/store';\nimport { Logger } from '@eventuras/logger';\nimport type { SessionUser, AuthStatus } from './types';\n\n/**\n * Authentication store context\n */\nexport type AuthStoreContext = {\n user: SessionUser | null;\n isAdmin: boolean;\n isAuthenticated: boolean;\n error: string | null;\n lastChecked: Date | null;\n isInitializing: boolean;\n};\n\n/**\n * Configuration for the auth store\n */\nexport type AuthStoreConfig = {\n /**\n * Function to check current authentication status\n */\n checkAuthStatus: () => Promise<AuthStatus>;\n\n /**\n * Optional configuration\n */\n config?: {\n /**\n * Role name that indicates admin access\n * @default 'Admin'\n */\n adminRole?: string;\n\n /**\n * Namespace for logger\n * @default 'fides-auth-next:store'\n */\n loggerNamespace?: string;\n };\n};\n\n/**\n * Default configuration values\n */\nconst DEFAULT_CONFIG = {\n adminRole: 'Admin',\n loggerNamespace: 'fides:auth-store',\n};\n\n/**\n * Creates an authentication store with XState Store\n *\n * @param options - Configuration for the auth store\n * @returns Configured XState store\n *\n * @example\n * ```typescript\n * const authStore = createAuthStore({\n * checkAuthStatus: async () => getAuthStatus(),\n * config: {\n * adminRole: 'Admin',\n * loggerNamespace: 'myapp:auth',\n * }\n * });\n * ```\n */\nexport function createAuthStore(options: AuthStoreConfig) {\n const config = { ...DEFAULT_CONFIG, ...options.config };\n const logger = Logger.create({\n namespace: config.loggerNamespace,\n context: { component: 'AuthStore' },\n });\n\n /**\n * Initial context values\n */\n const initialContext: AuthStoreContext = {\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: null,\n lastChecked: null,\n isInitializing: true,\n };\n\n /**\n * Create the store with events\n */\n const store = createStore(\n {\n context: initialContext,\n on: {\n /**\n * Initialize authentication - check current status\n */\n initialize: () => ({\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: null,\n lastChecked: null,\n isInitializing: true,\n }),\n\n /**\n * Authentication check succeeded\n */\n authSuccess: (_context: AuthStoreContext, event: { user: SessionUser; }) => {\n logger.info({ user: event.user.roles }, 'User authenticated');\n return {\n user: event.user,\n isAdmin: event.user.roles?.includes(config.adminRole) ?? false,\n isAuthenticated: true,\n error: null,\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * Authentication check failed - not authenticated\n */\n authFailed: (_context: AuthStoreContext, event: { error?: string; } = {}) => {\n logger.info('User not authenticated');\n return {\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: event.error || null,\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * Session expired\n */\n sessionExpired: () => {\n logger.warn('Session expired');\n return {\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: 'Session expired',\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * User logged out\n */\n logout: () => {\n logger.info('User logged out');\n return {\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: null,\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * Login success\n */\n loginSuccess: (_context: AuthStoreContext, event: { user: SessionUser; }) => {\n logger.info({ user: event.user.email }, 'Login successful');\n return {\n user: event.user,\n isAdmin: event.user.roles?.includes(config.adminRole) ?? false,\n isAuthenticated: true,\n error: null,\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * Update last checked timestamp\n */\n updateLastChecked: (context: AuthStoreContext) => ({\n ...context,\n lastChecked: new Date(),\n }),\n\n /**\n * Set error\n */\n setError: (context: AuthStoreContext, event: { error: string; }) => ({\n ...context,\n error: event.error,\n }),\n\n /**\n * Clear error\n */\n clearError: (context: AuthStoreContext) => ({\n ...context,\n error: null,\n }),\n },\n }\n );\n\n return store;\n}\n\n/**\n * Helper function to initialize auth by checking status\n */\nexport async function initializeAuth(\n store: ReturnType<typeof createAuthStore>,\n checkAuthStatus: () => Promise<AuthStatus>\n) {\n const logger = Logger.create({\n namespace: 'fides:auth-store',\n context: { component: 'initializeAuth' },\n });\n\n logger.debug('Initializing authentication');\n store.send({ type: 'initialize' });\n\n try {\n const result = await checkAuthStatus();\n logger.debug({ authenticated: result.authenticated }, 'Auth status checked');\n\n if (result.authenticated && result.user) {\n store.send({ type: 'authSuccess', user: result.user });\n } else {\n store.send({ type: 'authFailed' });\n }\n } catch (error) {\n logger.debug({ error }, 'Auth check returned no session');\n store.send({ type: 'authFailed' });\n }\n}\n\n/**\n * Helper function to check auth status and update store\n */\nexport async function checkAuth(\n store: ReturnType<typeof createAuthStore>,\n checkAuthStatus: () => Promise<AuthStatus>\n) {\n const logger = Logger.create({\n namespace: 'fides:auth-store',\n context: { component: 'checkAuth' },\n });\n\n logger.debug('Checking authentication status');\n\n try {\n const result = await checkAuthStatus();\n logger.debug({ authenticated: result.authenticated }, 'Auth status checked');\n\n if (result.authenticated && result.user) {\n store.send({ type: 'authSuccess', user: result.user });\n } else {\n store.send({ type: 'authFailed' });\n }\n\n store.send({ type: 'updateLastChecked' });\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 ended - refresh token expired or invalid');\n store.send({ type: 'sessionExpired' });\n } else {\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, 'Auth check error');\n store.send({\n type: 'authFailed',\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n}\n"],"mappings":";;;;;;AA8CA,IAAM,iBAAiB;CACrB,WAAW;CACX,iBAAiB;CAClB;;;;;;;;;;;;;;;;;;AAmBD,SAAgB,gBAAgB,SAA0B;CACxD,MAAM,SAAS;EAAE,GAAG;EAAgB,GAAG,QAAQ;EAAQ;CACvD,MAAM,SAAS,OAAO,OAAO;EAC3B,WAAW,OAAO;EAClB,SAAS,EAAE,WAAW,aAAa;EACpC,CAAC;AAuIF,QAtHc,YACZ;EACE,SAAS;GAbX,MAAM;GACN,SAAS;GACT,iBAAiB;GACjB,OAAO;GACP,aAAa;GACb,gBAAgB;GAQL;EACT,IAAI;;;;GAIF,mBAAmB;IACjB,MAAM;IACN,SAAS;IACT,iBAAiB;IACjB,OAAO;IACP,aAAa;IACb,gBAAgB;IACjB;;;;GAKD,cAAc,UAA4B,UAAkC;AAC1E,WAAO,KAAK,EAAE,MAAM,MAAM,KAAK,OAAO,EAAE,qBAAqB;AAC7D,WAAO;KACL,MAAM,MAAM;KACZ,SAAS,MAAM,KAAK,OAAO,SAAS,OAAO,UAAU,IAAI;KACzD,iBAAiB;KACjB,OAAO;KACP,6BAAa,IAAI,MAAM;KACvB,gBAAgB;KACjB;;;;;GAMH,aAAa,UAA4B,QAA6B,EAAE,KAAK;AAC3E,WAAO,KAAK,yBAAyB;AACrC,WAAO;KACL,MAAM;KACN,SAAS;KACT,iBAAiB;KACjB,OAAO,MAAM,SAAS;KAC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AACd,SAAO,MAAM,EAAE,OAAO,EAAE,iCAAiC;AACzD,QAAM,KAAK,EAAE,MAAM,cAAc,CAAC;;;;;;AAOtC,eAAsB,UACpB,OACA,iBACA;CACA,MAAM,SAAS,OAAO,OAAO;EAC3B,WAAW;EACX,SAAS,EAAE,WAAW,aAAa;EACpC,CAAC;AAEF,QAAO,MAAM,iCAAiC;AAE9C,KAAI;EACF,MAAM,SAAS,MAAM,iBAAiB;AACtC,SAAO,MAAM,EAAE,eAAe,OAAO,eAAe,EAAE,sBAAsB;AAE5E,MAAI,OAAO,iBAAiB,OAAO,KACjC,OAAM,KAAK;GAAE,MAAM;GAAe,MAAM,OAAO;GAAM,CAAC;MAEtD,OAAM,KAAK,EAAE,MAAM,cAAc,CAAC;AAGpC,QAAM,KAAK,EAAE,MAAM,qBAAqB,CAAC;UAClC,OAAO;EAEd,MAAM,MAAM;AAIZ,MAFE,KAAK,SAAS,+BAA+B,KAAK,UAAU,iBAE1C;AAElB,UAAO,KAAK,mDAAmD;AAC/D,SAAM,KAAK,EAAE,MAAM,kBAAkB,CAAC;SACjC;GAEL,MAAM,eAAwC,EAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,iBACnD;AAGD,OAAI,SAAS,OAAO,UAAU,UAAU;IACtC,MAAM,aAAa;AACnB,QAAI,WAAW,KAAM,cAAa,OAAO,WAAW;AACpD,QAAI,WAAW,MAAO,cAAa,QAAQ,WAAW;AACtD,QAAI,WAAW,kBACb,cAAa,oBAAoB,WAAW;AAC9C,QAAI,WAAW,OAAQ,cAAa,SAAS,WAAW;;AAG1D,UAAO,MAAM,cAAc,mBAAmB;AAC9C,SAAM,KAAK;IACT,MAAM;IACN,OAAO,iBAAiB,QAAQ,MAAM,UAAU;IACjD,CAAC"}
|
|
1
|
+
{"version":3,"file":"store.js","names":[],"sources":["../../src/store/store.ts"],"sourcesContent":["import { createStore } from '@xstate/store';\nimport { Logger } from '@eventuras/logger';\nimport type { SessionUser, AuthStatus } from './types';\n\n/**\n * Authentication store context\n */\nexport type AuthStoreContext = {\n user: SessionUser | null;\n isAdmin: boolean;\n isAuthenticated: boolean;\n error: string | null;\n lastChecked: Date | null;\n isInitializing: boolean;\n};\n\n/**\n * Configuration for the auth store\n */\nexport type AuthStoreConfig = {\n /**\n * Function to check current authentication status\n */\n checkAuthStatus: () => Promise<AuthStatus>;\n\n /**\n * Optional configuration\n */\n config?: {\n /**\n * Role name that indicates admin access\n * @default 'Admin'\n */\n adminRole?: string;\n\n /**\n * Namespace for logger\n * @default 'fides-auth-next:store'\n */\n loggerNamespace?: string;\n };\n};\n\n/**\n * Default configuration values\n */\nconst DEFAULT_CONFIG = {\n adminRole: 'Admin',\n loggerNamespace: 'fides:auth-store',\n};\n\n/**\n * Creates an authentication store with XState Store\n *\n * @param options - Configuration for the auth store\n * @returns Configured XState store\n *\n * @example\n * ```typescript\n * const authStore = createAuthStore({\n * checkAuthStatus: async () => getAuthStatus(),\n * config: {\n * adminRole: 'Admin',\n * loggerNamespace: 'myapp:auth',\n * }\n * });\n * ```\n */\nexport function createAuthStore(options: AuthStoreConfig) {\n const config = { ...DEFAULT_CONFIG, ...options.config };\n const logger = Logger.create({\n namespace: config.loggerNamespace,\n context: { component: 'AuthStore' },\n });\n\n /**\n * Initial context values\n */\n const initialContext: AuthStoreContext = {\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: null,\n lastChecked: null,\n isInitializing: true,\n };\n\n /**\n * Create the store with events\n */\n const store = createStore(\n {\n context: initialContext,\n on: {\n /**\n * Initialize authentication - check current status\n */\n initialize: () => ({\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: null,\n lastChecked: null,\n isInitializing: true,\n }),\n\n /**\n * Authentication check succeeded\n */\n authSuccess: (_context: AuthStoreContext, event: { user: SessionUser; }) => {\n logger.info({ user: event.user.roles }, 'User authenticated');\n return {\n user: event.user,\n isAdmin: event.user.roles?.includes(config.adminRole) ?? false,\n isAuthenticated: true,\n error: null,\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * Authentication check failed - not authenticated\n */\n authFailed: (_context: AuthStoreContext, event: { error?: string; } = {}) => {\n logger.info('User not authenticated');\n return {\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: event.error || null,\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * Session expired\n */\n sessionExpired: () => {\n logger.warn('Session expired');\n return {\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: 'Session expired',\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * User logged out\n */\n logout: () => {\n logger.info('User logged out');\n return {\n user: null,\n isAdmin: false,\n isAuthenticated: false,\n error: null,\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * Login success\n */\n loginSuccess: (_context: AuthStoreContext, event: { user: SessionUser; }) => {\n logger.info({ user: event.user.email }, 'Login successful');\n return {\n user: event.user,\n isAdmin: event.user.roles?.includes(config.adminRole) ?? false,\n isAuthenticated: true,\n error: null,\n lastChecked: new Date(),\n isInitializing: false,\n };\n },\n\n /**\n * Update last checked timestamp\n */\n updateLastChecked: (context: AuthStoreContext) => ({\n ...context,\n lastChecked: new Date(),\n }),\n\n /**\n * Set error\n */\n setError: (context: AuthStoreContext, event: { error: string; }) => ({\n ...context,\n error: event.error,\n }),\n\n /**\n * Clear error\n */\n clearError: (context: AuthStoreContext) => ({\n ...context,\n error: null,\n }),\n },\n }\n );\n\n return store;\n}\n\n/**\n * Helper function to initialize auth by checking status\n */\nexport async function initializeAuth(\n store: ReturnType<typeof createAuthStore>,\n checkAuthStatus: () => Promise<AuthStatus>\n) {\n const logger = Logger.create({\n namespace: 'fides:auth-store',\n context: { component: 'initializeAuth' },\n });\n\n logger.debug('Initializing authentication');\n store.send({ type: 'initialize' });\n\n try {\n const result = await checkAuthStatus();\n logger.debug({ authenticated: result.authenticated }, 'Auth status checked');\n\n if (result.authenticated && result.user) {\n store.send({ type: 'authSuccess', user: result.user });\n } else {\n store.send({ type: 'authFailed' });\n }\n } catch (error) {\n logger.debug({ error }, 'Auth check returned no session');\n store.send({ type: 'authFailed' });\n }\n}\n\n/**\n * Helper function to check auth status and update store\n */\nexport async function checkAuth(\n store: ReturnType<typeof createAuthStore>,\n checkAuthStatus: () => Promise<AuthStatus>\n) {\n const logger = Logger.create({\n namespace: 'fides:auth-store',\n context: { component: 'checkAuth' },\n });\n\n logger.debug('Checking authentication status');\n\n try {\n const result = await checkAuthStatus();\n logger.debug({ authenticated: result.authenticated }, 'Auth status checked');\n\n if (result.authenticated && result.user) {\n store.send({ type: 'authSuccess', user: result.user });\n } else {\n store.send({ type: 'authFailed' });\n }\n\n store.send({ type: 'updateLastChecked' });\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 ended - refresh token expired or invalid');\n store.send({ type: 'sessionExpired' });\n } else {\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, 'Auth check error');\n store.send({\n type: 'authFailed',\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n}\n"],"mappings":";;;;;;AA8CA,IAAM,iBAAiB;CACrB,WAAW;CACX,iBAAiB;CAClB;;;;;;;;;;;;;;;;;;AAmBD,SAAgB,gBAAgB,SAA0B;CACxD,MAAM,SAAS;EAAE,GAAG;EAAgB,GAAG,QAAQ;EAAQ;CACvD,MAAM,SAAS,OAAO,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AFE,KAAK,SAAS,+BAA+B,KAAK,UAAU,iBAE1C;GAElB,OAAO,KAAK,mDAAmD;GAC/D,MAAM,KAAK,EAAE,MAAM,kBAAkB,CAAC;SACjC;GAEL,MAAM,eAAwC,EAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,iBACnD;GAGD,IAAI,SAAS,OAAO,UAAU,UAAU;IACtC,MAAM,aAAa;IACnB,IAAI,WAAW,MAAM,aAAa,OAAO,WAAW;IACpD,IAAI,WAAW,OAAO,aAAa,QAAQ,WAAW;IACtD,IAAI,WAAW,mBACb,aAAa,oBAAoB,WAAW;IAC9C,IAAI,WAAW,QAAQ,aAAa,SAAS,WAAW;;GAG1D,OAAO,MAAM,cAAc,mBAAmB;GAC9C,MAAM,KAAK;IACT,MAAM;IACN,OAAO,iBAAiB,QAAQ,MAAM,UAAU;IACjD,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-session-monitor.js","names":[],"sources":["../../src/store/use-session-monitor.ts"],"sourcesContent":["'use client';\n\nimport { useEffect } from 'react';\nimport { startSessionMonitor, type SessionMonitorConfig } from './session-monitor';\nimport type { createAuthStore } from './store';\nimport type { AuthStatus } from './types';\n\n/**\n * React hook for session monitoring with automatic cleanup\n *\n * @param store - The auth store to update\n * @param checkAuthStatus - Function to check authentication status\n * @param config - Optional configuration\n *\n * @example\n * ```typescript\n * import { useSessionMonitor } from '@eventuras/fides-auth-next/store';\n *\n * function App() {\n * useSessionMonitor(authStore, checkAuthStatus, {\n * interval: 30_000,\n * onSessionExpired: () => {\n * toast.warn('Your session has expired');\n * }\n * });\n *\n * return <div>...</div>;\n * }\n * ```\n */\nexport function useSessionMonitor(\n store: ReturnType<typeof createAuthStore>,\n checkAuthStatus: () => Promise<AuthStatus>,\n config: SessionMonitorConfig = {}\n): void {\n useEffect(() => {\n return startSessionMonitor(store, checkAuthStatus, config);\n }, [store, checkAuthStatus, config]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,kBACd,OACA,iBACA,SAA+B,EAAE,EAC3B;
|
|
1
|
+
{"version":3,"file":"use-session-monitor.js","names":[],"sources":["../../src/store/use-session-monitor.ts"],"sourcesContent":["'use client';\n\nimport { useEffect } from 'react';\nimport { startSessionMonitor, type SessionMonitorConfig } from './session-monitor';\nimport type { createAuthStore } from './store';\nimport type { AuthStatus } from './types';\n\n/**\n * React hook for session monitoring with automatic cleanup\n *\n * @param store - The auth store to update\n * @param checkAuthStatus - Function to check authentication status\n * @param config - Optional configuration\n *\n * @example\n * ```typescript\n * import { useSessionMonitor } from '@eventuras/fides-auth-next/store';\n *\n * function App() {\n * useSessionMonitor(authStore, checkAuthStatus, {\n * interval: 30_000,\n * onSessionExpired: () => {\n * toast.warn('Your session has expired');\n * }\n * });\n *\n * return <div>...</div>;\n * }\n * ```\n */\nexport function useSessionMonitor(\n store: ReturnType<typeof createAuthStore>,\n checkAuthStatus: () => Promise<AuthStatus>,\n config: SessionMonitorConfig = {}\n): void {\n useEffect(() => {\n return startSessionMonitor(store, checkAuthStatus, config);\n }, [store, checkAuthStatus, config]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,kBACd,OACA,iBACA,SAA+B,EAAE,EAC3B;CACN,gBAAgB;EACd,OAAO,oBAAoB,OAAO,iBAAiB,OAAO;IACzD;EAAC;EAAO;EAAiB;EAAO,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eventuras/fides-auth-next",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.12",
|
|
4
4
|
"description": "Next.js bindings for @eventuras/fides-auth",
|
|
5
5
|
"homepage": "https://github.com/losol/eventuras/tree/main/libs/fides-auth-next#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
],
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@xstate/store": "^3.17.1",
|
|
47
|
-
"@eventuras/fides-auth": "0.7.
|
|
47
|
+
"@eventuras/fides-auth": "0.7.1",
|
|
48
48
|
"@eventuras/logger": "0.8.1"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|