@eventuras/fides-auth-next 0.1.12 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;C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B;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
+ {"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,0BAA0B,CA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F;;;;;;;;;;;;;AAcA,eAAsB,kBAAkB,OAAgC;CACtE,IAAI;EACF,MAAM,cAAc,MAAM,QAAQ;EAElC,KAAK,MAAM,QAAQ,OACjB,YAAY,OAAO,IAAI;EAGzB,OAAO,MAAM,EAAE,aAAa,MAAM,GAAG,uCAAuC;CAC9E,SAAS,OAAO;EACd,OAAO,MAAM;GAAE;GAAO,aAAa;EAAM,GAAG,0BAA0B;EACtE,MAAM;CACR;AACF;;;;;;;;;;;;;;AAeA,eAAsB,iBACpB,cACA,UAAkC,CAAC,GACpB;CACf,MAAM,cAAc,WAAW,cAAc;EAC3C,GAAG;EACH,GAAG;CACL,CAAC;CAED,OAAO,KAAK,oBAAoB;AAClC;;;;;;;;;;;;;;;;AAiBA,eAAsB,mBAA2C;CAC/D,OAAO,MAAM,cAAc,SAAS;AACtC;;;;;;;;;;;AAYA,eAAsB,sBAAqC;CACzD,MAAM,iBAAiB,SAAS;CAChC,OAAO,KAAK,wBAAwB;AACtC"}
@@ -0,0 +1,21 @@
1
+ import { OAuthConfig } from '@eventuras/fides-auth/oauth';
2
+ export interface HeartbeatHandlerConfig {
3
+ /** OAuth/OIDC configuration used to refresh the access token. */
4
+ oauthConfig: OAuthConfig;
5
+ }
6
+ /**
7
+ * Handles a heartbeat request — refresh the active session if there is one.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * // app/(auth)/api/auth/heartbeat/route.ts
12
+ * import { handleHeartbeat } from '@eventuras/fides-auth-next/heartbeat-handler';
13
+ * import { oauthConfig } from '@/utils/oauthConfig';
14
+ *
15
+ * export async function POST(request: Request) {
16
+ * return handleHeartbeat(request, { oauthConfig });
17
+ * }
18
+ * ```
19
+ */
20
+ export declare function handleHeartbeat(request: Request, config: HeartbeatHandlerConfig): Promise<Response>;
21
+ //# sourceMappingURL=heartbeat-handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"heartbeat-handler.d.ts","sourceRoot":"","sources":["../src/heartbeat-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAM/D,MAAM,WAAW,sBAAsB;IACrC,iEAAiE;IACjE,WAAW,EAAE,WAAW,CAAC;CAC1B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,eAAe,CACnC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,sBAAsB,GAC7B,OAAO,CAAC,QAAQ,CAAC,CAwCnB"}
@@ -0,0 +1,62 @@
1
+ import { globalPOSTRateLimit } from "./request.js";
2
+ import { getCurrentSession, refreshCurrentSession } from "./session.js";
3
+ import { Logger } from "@eventuras/logger";
4
+ //#region src/heartbeat-handler.ts
5
+ /**
6
+ * Server-side heartbeat handler for Next.js route handlers.
7
+ *
8
+ * Pairs with the client-side `useHeartbeat` hook: when the user is active, the
9
+ * client POSTs here, and this handler exchanges the current refresh token for
10
+ * a fresh access token (and rotated refresh token, if the IdP rotates).
11
+ *
12
+ * Returns:
13
+ * - 200 with `{ accessTokenExpiresAt }` on success
14
+ * - 401 when there is no session or the refresh token is dead
15
+ * - 405 for non-POST methods
16
+ * - 429 when rate-limited
17
+ */
18
+ var logger = Logger.create({ namespace: "fides-auth-next:heartbeat" });
19
+ /**
20
+ * Handles a heartbeat request — refresh the active session if there is one.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * // app/(auth)/api/auth/heartbeat/route.ts
25
+ * import { handleHeartbeat } from '@eventuras/fides-auth-next/heartbeat-handler';
26
+ * import { oauthConfig } from '@/utils/oauthConfig';
27
+ *
28
+ * export async function POST(request: Request) {
29
+ * return handleHeartbeat(request, { oauthConfig });
30
+ * }
31
+ * ```
32
+ */
33
+ async function handleHeartbeat(request, config) {
34
+ if (request.method !== "POST") return new Response(null, {
35
+ status: 405,
36
+ headers: { Allow: "POST" }
37
+ });
38
+ if (!await globalPOSTRateLimit()) {
39
+ logger.warn("Heartbeat rate limit exceeded");
40
+ return new Response(null, { status: 429 });
41
+ }
42
+ const session = await getCurrentSession();
43
+ if (!session) {
44
+ logger.debug("Heartbeat with no session");
45
+ return new Response(null, { status: 401 });
46
+ }
47
+ if (!session.tokens?.refreshToken) {
48
+ logger.warn("Heartbeat with session but no refresh token");
49
+ return new Response(null, { status: 401 });
50
+ }
51
+ const updated = await refreshCurrentSession(config.oauthConfig);
52
+ if (!updated) {
53
+ logger.info("Heartbeat refresh failed");
54
+ return new Response(null, { status: 401 });
55
+ }
56
+ logger.debug("Heartbeat refresh succeeded");
57
+ return Response.json({ accessTokenExpiresAt: updated.tokens?.accessTokenExpiresAt ?? null }, { headers: { "Cache-Control": "private, no-store" } });
58
+ }
59
+ //#endregion
60
+ export { handleHeartbeat };
61
+
62
+ //# sourceMappingURL=heartbeat-handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"heartbeat-handler.js","names":[],"sources":["../src/heartbeat-handler.ts"],"sourcesContent":["/**\n * Server-side heartbeat handler for Next.js route handlers.\n *\n * Pairs with the client-side `useHeartbeat` hook: when the user is active, the\n * client POSTs here, and this handler exchanges the current refresh token for\n * a fresh access token (and rotated refresh token, if the IdP rotates).\n *\n * Returns:\n * - 200 with `{ accessTokenExpiresAt }` on success\n * - 401 when there is no session or the refresh token is dead\n * - 405 for non-POST methods\n * - 429 when rate-limited\n */\n\nimport { Logger } from '@eventuras/logger';\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport { getCurrentSession, refreshCurrentSession } from './session';\nimport { globalPOSTRateLimit } from './request';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:heartbeat' });\n\nexport interface HeartbeatHandlerConfig {\n /** OAuth/OIDC configuration used to refresh the access token. */\n oauthConfig: OAuthConfig;\n}\n\n/**\n * Handles a heartbeat request — refresh the active session if there is one.\n *\n * @example\n * ```ts\n * // app/(auth)/api/auth/heartbeat/route.ts\n * import { handleHeartbeat } from '@eventuras/fides-auth-next/heartbeat-handler';\n * import { oauthConfig } from '@/utils/oauthConfig';\n *\n * export async function POST(request: Request) {\n * return handleHeartbeat(request, { oauthConfig });\n * }\n * ```\n */\nexport async function handleHeartbeat(\n request: Request,\n config: HeartbeatHandlerConfig,\n): Promise<Response> {\n if (request.method !== 'POST') {\n return new Response(null, { status: 405, headers: { Allow: 'POST' } });\n }\n\n if (!(await globalPOSTRateLimit())) {\n logger.warn('Heartbeat rate limit exceeded');\n return new Response(null, { status: 429 });\n }\n\n const session = await getCurrentSession();\n if (!session) {\n logger.debug('Heartbeat with no session');\n return new Response(null, { status: 401 });\n }\n\n if (!session.tokens?.refreshToken) {\n logger.warn('Heartbeat with session but no refresh token');\n return new Response(null, { status: 401 });\n }\n\n const updated = await refreshCurrentSession(config.oauthConfig);\n if (!updated) {\n // Refresh failed — most likely invalid_grant (refresh token expired).\n logger.info('Heartbeat refresh failed');\n return new Response(null, { status: 401 });\n }\n\n logger.debug('Heartbeat refresh succeeded');\n return Response.json(\n {\n accessTokenExpiresAt: updated.tokens?.accessTokenExpiresAt ?? null,\n },\n {\n // Auth/session endpoint — must never be cached by the browser or any\n // intermediary, or a stale 200 could fool the client into thinking a\n // refresh succeeded without actually hitting the server.\n headers: { 'Cache-Control': 'private, no-store' },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,4BAA4B,CAAC;;;;;;;;;;;;;;;AAqBvE,eAAsB,gBACpB,SACA,QACmB;CACnB,IAAI,QAAQ,WAAW,QACrB,OAAO,IAAI,SAAS,MAAM;EAAE,QAAQ;EAAK,SAAS,EAAE,OAAO,OAAO;CAAE,CAAC;CAGvE,IAAI,CAAE,MAAM,oBAAoB,GAAI;EAClC,OAAO,KAAK,+BAA+B;EAC3C,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;CAC3C;CAEA,MAAM,UAAU,MAAM,kBAAkB;CACxC,IAAI,CAAC,SAAS;EACZ,OAAO,MAAM,2BAA2B;EACxC,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;CAC3C;CAEA,IAAI,CAAC,QAAQ,QAAQ,cAAc;EACjC,OAAO,KAAK,6CAA6C;EACzD,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;CAC3C;CAEA,MAAM,UAAU,MAAM,sBAAsB,OAAO,WAAW;CAC9D,IAAI,CAAC,SAAS;EAEZ,OAAO,KAAK,0BAA0B;EACtC,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;CAC3C;CAEA,OAAO,MAAM,6BAA6B;CAC1C,OAAO,SAAS,KACd,EACE,sBAAsB,QAAQ,QAAQ,wBAAwB,KAChE,GACA,EAIE,SAAS,EAAE,iBAAiB,oBAAoB,EAClD,CACF;AACF"}
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export * from './session';
3
3
  export * from './cookies';
4
4
  export * from './oidc-callback';
5
5
  export * from './oidc-login';
6
+ export * from './heartbeat-handler';
6
7
  export * from './store';
7
8
  export * from '@eventuras/fides-auth/oauth';
8
9
  export type { OAuthConfig } from '@eventuras/fides-auth/oauth';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAG7B,cAAc,SAAS,CAAC;AAGxB,cAAc,6BAA6B,CAAC;AAC5C,YAAY,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC/D,cAAc,uCAAuC,CAAC;AACtD,cAAc,0CAA0C,CAAC;AACzD,cAAc,oCAAoC,CAAC;AACnD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC;AAGpC,cAAc,SAAS,CAAC;AAGxB,cAAc,6BAA6B,CAAC;AAC5C,YAAY,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC/D,cAAc,uCAAuC,CAAC;AACtD,cAAc,0CAA0C,CAAC;AACzD,cAAc,oCAAoC,CAAC;AACnD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC"}
package/dist/index.js CHANGED
@@ -3,10 +3,12 @@ import { defaultOAuthCookieOptions, defaultSessionCookieOptions, deleteAuthCooki
3
3
  import { clearCurrentSession, createAndPersistSession, createSession, getCurrentSession, refreshCurrentSession } from "./session.js";
4
4
  import { handleOidcCallback } from "./oidc-callback.js";
5
5
  import { handleOidcLogin } from "./oidc-login.js";
6
+ import { handleHeartbeat } from "./heartbeat-handler.js";
6
7
  import { checkAuth, createAuthStore, initializeAuth } from "./store/store.js";
7
8
  import { createAuthStoreHooks } from "./store/hooks.js";
8
9
  import { startSessionMonitor } from "./store/session-monitor.js";
9
10
  import { useSessionMonitor } from "./store/use-session-monitor.js";
11
+ import { useHeartbeat } from "./store/use-heartbeat.js";
10
12
  import { configureAuthLogger } from "./store/configure-logger.js";
11
13
  import "./store/index.js";
12
14
  import { TokenBucket } from "@eventuras/fides-auth/rate-limit";
@@ -16,4 +18,4 @@ export * from "@eventuras/fides-auth/session-refresh";
16
18
  export * from "@eventuras/fides-auth/oauth";
17
19
  export * from "@eventuras/fides-auth/silent-login";
18
20
  export * from "@eventuras/fides-auth/types";
19
- export { TokenBucket, checkAuth, clearCurrentSession, configureAuthLogger, createAndPersistSession, createAuthStore, createAuthStoreHooks, createSession, defaultOAuthCookieOptions, defaultSessionCookieOptions, deleteAuthCookie, deleteAuthCookies, deleteSessionCookie, getAuthCookie, getCurrentSession, getSessionCookie, globalGETRateLimit, globalPOSTRateLimit, handleOidcCallback, handleOidcLogin, initializeAuth, refreshCurrentSession, setAuthCookie, setSessionCookie, startSessionMonitor, useSessionMonitor };
21
+ export { TokenBucket, checkAuth, clearCurrentSession, configureAuthLogger, createAndPersistSession, createAuthStore, createAuthStoreHooks, createSession, defaultOAuthCookieOptions, defaultSessionCookieOptions, deleteAuthCookie, deleteAuthCookies, deleteSessionCookie, getAuthCookie, getCurrentSession, getSessionCookie, globalGETRateLimit, globalPOSTRateLimit, handleHeartbeat, handleOidcCallback, handleOidcLogin, initializeAuth, refreshCurrentSession, setAuthCookie, setSessionCookie, startSessionMonitor, useHeartbeat, useSessionMonitor };
@@ -1 +1 @@
1
- {"version":3,"file":"oidc-callback.d.ts","sourceRoot":"","sources":["../src/oidc-callback.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAkB/D,MAAM,WAAW,kBAAkB;IACjC,qFAAqF;IACrF,WAAW,EAAE,WAAW,CAAC;IAEzB,2FAA2F;IAC3F,cAAc,EAAE,MAAM,CAAC;IAEvB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,kBAAkB,GACzB,OAAO,CAAC,QAAQ,CAAC,CAqEnB"}
1
+ {"version":3,"file":"oidc-callback.d.ts","sourceRoot":"","sources":["../src/oidc-callback.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAkB/D,MAAM,WAAW,kBAAkB;IACjC,qFAAqF;IACrF,WAAW,EAAE,WAAW,CAAC;IAEzB,2FAA2F;IAC3F,cAAc,EAAE,MAAM,CAAC;IAEvB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,kBAAkB,GACzB,OAAO,CAAC,QAAQ,CAAC,CAwEnB"}
@@ -31,6 +31,7 @@ async function handleOidcCallback(request, config) {
31
31
  try {
32
32
  const currentUrl = new URL(request.url);
33
33
  const publicUrl = new URL(applicationUrl);
34
+ publicUrl.pathname = currentUrl.pathname;
34
35
  publicUrl.search = currentUrl.search;
35
36
  const storedState = await getAuthCookie("oauth_state");
36
37
  const storedCodeVerifier = await getAuthCookie("oauth_code_verifier");
@@ -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;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"}
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. Keep the request path: behind a\n // TLS-terminating proxy applicationUrl is just the origin (\"/\"), and the\n // token-exchange redirect_uri must match the callback path used at authorize.\n const currentUrl = new URL(request.url);\n const publicUrl = new URL(applicationUrl);\n publicUrl.pathname = currentUrl.pathname;\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,gCAAgC,CAAC;;;;;;;;;;;;;;;;;;AAmD3E,eAAsB,mBACpB,SACA,QACmB;CACnB,MAAM,EACJ,aACA,gBACA,aAAa,SACb,sBAAsB,GACtB,sBAAsB,KACtB,qBACE;CAGJ,IAAI,CAAE,MAAM,mBAAmB,GAAI;EACjC,OAAO,KAAK,qBAAqB;EACjC,OAAO,IAAI,SAAS,qBAAqB,EAAE,QAAQ,IAAI,CAAC;CAC1D;CAEA,IAAI;EAIF,MAAM,aAAa,IAAI,IAAI,QAAQ,GAAG;EACtC,MAAM,YAAY,IAAI,IAAI,cAAc;EACxC,UAAU,WAAW,WAAW;EAChC,UAAU,SAAS,WAAW;EAG9B,MAAM,cAAc,MAAM,cAAc,aAAa;EACrD,MAAM,qBAAqB,MAAM,cAAc,qBAAqB;EAEpE,IAAI,CAAC,eAAe,CAAC,oBAAoB;GACvC,OAAO,KAAK,gCAAgC;GAC5C,OAAO,IAAI,SAAS,qCAAqC,EAAE,QAAQ,IAAI,CAAC;EAC1E;EAaA,MAAM,iBAAiB,MADL,cADF,uBAAuB,MARlB,0BACnB,aACA,WACA,oBACA,WACF,GAG+C,UACf,GAAS,EAAE,oBAAoB,CAAC,CACtC;EAG1B,MAAM,WAAW,MAAM,cAAc,UAAU;EAC/C,MAAM,kBAAkB;GAAC;GAAe;GAAuB;EAAU,CAAC;EAG1E,MAAM,cAAc,kBAClB,UACA,gBACA,qBACA,gBACF;EACA,YAAY,aAAa,IAAI,SAAS,SAAS;EAE/C,OAAO,KAAK,EAAE,aAAa,YAAY,SAAS,EAAE,GAAG,+BAA+B;EAEpF,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ;GACR,SAAS,EAAE,UAAU,YAAY,SAAS,EAAE;EAC9C,CAAC;CACH,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,qBAAqB;EAC7C,OAAO,IAAI,SAAS,mEAAmE,EACrF,QAAQ,IACV,CAAC;CACH;AACF"}
@@ -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;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"}
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,6BAA6B,CAAC;AAcxE,IAAM,2BAA2B,QAC/B,YAAY,KAAK,GAAG,IAAI,MAAM;;;;;;;;;;;;;;AAehC,eAAsB,gBACpB,SACA,QACmB;CACnB,MAAM,EAAE,aAAa,mBAAmB,4BAA4B;CAEpE,IAAI,CAAE,MAAM,mBAAmB,GAAI;EACjC,OAAO,KAAK,qBAAqB;EACjC,OAAO,IAAI,SAAS,qBAAqB,EAAE,QAAQ,IAAI,CAAC;CAC1D;CAIA,MAAM,cAAc,IADJ,IAAI,QAAQ,GACR,EAAI,aAAa,IAAI,UAAU;CACnD,MAAM,WAAW,cAAc,iBAAiB,WAAW,IAAI;CAG/D,MAAM,OAAO,MAAM,iBAAiB,WAAW;CAC/C,MAAM,mBAAmB,MAAM,iCAAiC,aAAa,IAAI;CAEjF,OAAO,KAAK,wCAAwC;CAGpD,MAAM,cAAc,MAAM,QAAQ;CAClC,MAAM,aAAa;CAEnB,YAAY,IAAI,eAAe,KAAK,OAAO,UAAU;CACrD,YAAY,IAAI,uBAAuB,KAAK,eAAe,UAAU;CAErE,IAAI,UACF,YAAY,IAAI,YAAY,UAAU,UAAU;CAGlD,OAAO,IAAI,SAAS,MAAM;EACxB,QAAQ;EACR,SAAS,EAAE,UAAU,iBAAiB,SAAS,EAAE;CACnD,CAAC;AACH"}
@@ -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;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"}
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,0BAA0B,CAAC;AAGrE,IAAI,eAA2C;AAE/C,SAAS,YAAiC;CACxC,IAAI,CAAC,cACH,eAAe,IAAI,YAAoB,KAAK,CAAC;CAE/C,OAAO;AACT;AAEA,eAAsB,qBAAuC;CAC3D,IAAI;EAEF,MAAM,YAAW,MADS,QAAQ,GACL,IAAI,iBAAiB;EAClD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,UAAU,EAAE,QAAQ,UAAU,CAAC;CACxC,SAAS,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,QAAQ,GAC3D,OAAO,MAAM,EAAE,MAAM,GAAG,2CAA2C;OAEnE,OAAO,MAAM,EAAE,MAAM,GAAG,wCAAwC;EAElE,OAAO;CACT;AACF;AAEA,eAAsB,sBAAwC;CAC5D,IAAI;EAEF,MAAM,YAAW,MADS,QAAQ,GACL,IAAI,iBAAiB;EAClD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,UAAU,EAAE,QAAQ,UAAU,CAAC;CACxC,SAAS,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,QAAQ,GAC3D,OAAO,MAAM,EAAE,MAAM,GAAG,4CAA4C;OAEpE,OAAO,MAAM,EAAE,MAAM,GAAG,yCAAyC;EAEnE,OAAO;CACT;AACF"}
@@ -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"],"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AAK,gCAAgC;GAC5C,OAAO;;EAGT,IAAI,CAAC,eAAe,QAAQ,cAAc;GACxC,OAAO,MAAM,uCAAuC;GACpD,OAAO;;EAIT,MAAM,iBAAiB,MAAM,eAAmB,gBAAgB,QAAQ,QAAQ;EAEhF,IAAI,CAAC,gBAAgB;GACnB,OAAO,MAAM,gCAAgC;GAC7C,OAAO;;EAOT,MAAM,iBAAiB,MAHL,cAAc,gBAAgB,QAAQ,CAG7B;EAE3B,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
+ {"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,0BAA0B,CAAC;;;;;;;;;;;;;;;;;;;;;;AAuBrE,eAAsB,cACpB,SACA,UAAgC,CAAC,GAChB;CACjB,OAAO,MAAM,sBAAsB;CAEnC,MAAM,EAAE,sBAAsB,MAAM;CAEpC,IAAI;EAEF,MAAM,MAAM,MAAM,mBAAmB,EAAE,GAAG,QAAQ,GAAG,iBAAiB,CAAC;EAEvE,OAAO,KAAK,EAAE,oBAAoB,GAAG,8BAA8B;EACnE,OAAO;CACT,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,0BAA0B;EAClD,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,oBAAoB,MAAM,OAAO,WAAuD;C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O,MAAM,EAAE,MAAM,GAAG,mCAAmC;EAG7D,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,eAAsB,wBACpB,SACA,UAAgC,CAAC,GAChB;CACjB,OAAO,KAAK,qCAAqC;CAEjD,IAAI;EACF,MAAM,MAAM,MAAM,cAAc,SAAS,OAAO;EAChD,MAAM,iBAAiB,GAAG;EAE1B,OAAO,KAAK,4CAA4C;EACxD,OAAO;CACT,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,sCAAsC;EAC9D,MAAM;CACR;AACF;;;;;;;;;;;AAYA,eAAsB,sBAAqC;CACzD,OAAO,KAAK,0BAA0B;CAEtC,IAAI;EACF,MAAM,oBAAoB;EAC1B,OAAO,KAAK,8BAA8B;CAC5C,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,yBAAyB;EACjD,MAAM;CACR;AACF"}
@@ -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;CAC1C,gBAAgB,EACd,OAAO,SAAS;EACd,OAAO,OAAO,OAAO,QAAQ;IAEhC,CAAC"}
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,OAAO;CAC9B,EACF,CAAC;AACH"}
@@ -1,4 +1,4 @@
1
- import { useSelector } from "@xstate/store/react";
1
+ import { useSelector } from "@xstate/store-react";
2
2
  //#region src/store/hooks.ts
3
3
  /**
4
4
  * Creates React hooks for interacting with the auth store
@@ -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;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
+ {"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,QAChD,EAAS;CAClB;;;;CAKA,SAAS,iBAAmC;EAC1C,OAAO;GACL,eAAe,SAAsB,MAAM,KAAK;IAAE,MAAM;IAAgB;GAAK,CAAC;GAC9E,cAAc,MAAM,KAAK,EAAE,MAAM,SAAS,CAAC;GAC3C,sBAAsB,MAAM,KAAK,EAAE,MAAM,iBAAiB,CAAC;GAC3D,cAAc,SAAsB,MAAM,KAAK;IAAE,MAAM;IAAe;GAAK,CAAC;GAC5E,aAAa,UAAmB,MAAM,KAAK;IAAE,MAAM;IAAc;GAAM,CAAC;GACxE,WAAW,UAAkB,MAAM,KAAK;IAAE,MAAM;IAAY;GAAM,CAAC;GACnE,kBAAkB,MAAM,KAAK,EAAE,MAAM,aAAa,CAAC;EACrD;CACF;CAEA,OAAO;EACL;EACA;CACF;AACF"}
@@ -102,6 +102,7 @@ export { createAuthStore, initializeAuth, checkAuth, type AuthStoreContext, type
102
102
  export { createAuthStoreHooks, type AuthStoreSelector, type AuthStoreActions, } from './hooks';
103
103
  export { startSessionMonitor, type SessionMonitorConfig, } from './session-monitor';
104
104
  export { useSessionMonitor } from './use-session-monitor';
105
+ export { useHeartbeat, type HeartbeatConfig } from './use-heartbeat';
105
106
  export { configureAuthLogger } from './configure-logger';
106
107
  export type { SessionUser, AuthStatus } from './types';
107
108
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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uthStore, initializeAuth } from "./store.js";
2
2
  import { createAuthStoreHooks } from "./hooks.js";
3
3
  import { startSessionMonitor } from "./session-monitor.js";
4
4
  import { useSessionMonitor } from "./use-session-monitor.js";
5
+ import { useHeartbeat } from "./use-heartbeat.js";
5
6
  import { configureAuthLogger } from "./configure-logger.js";
6
- export { checkAuth, configureAuthLogger, createAuthStore, createAuthStoreHooks, initializeAuth, startSessionMonitor, useSessionMonitor };
7
+ export { checkAuth, configureAuthLogger, createAuthStore, createAuthStoreHooks, initializeAuth, startSessionMonitor, useHeartbeat, useSessionMonitor };
@@ -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;CAEF,OAAO,MAAM,EAAE,UAAU,YAAY,UAAU,EAAE,2BAA2B;CAE5E,IAAI,WAAW;CACf,IAAI,YAAmC;CAEvC,MAAM,OAAO,YAA2B;EACtC,IAAI,CAAC,UAAU;EAEf,IAAI;GACF,MAAM,SAAS,MAAM,iBAAiB;GACtC,OAAO,MAAM,EAAE,eAAe,OAAO,eAAe,EAAE,wBAAwB;GAE9E,IAAI,CAAC,OAAO,eAAe;IAEzB,OAAO,KAAK,iEAAiE;IAC7E,MAAM,KAAK,EAAE,MAAM,kBAAkB,CAAC;IAEtC,IAAI,YAAY,kBACd,YAAY,kBAAkB;IAIhC;;GAGF,IAAI,OAAO,MACT,MAAM,KAAK;IAAE,MAAM;IAAe,MAAM,OAAO;IAAM,CAAC;WAEjD,OAAO;GAEd,MAAM,MAAM;GAIZ,IAFE,KAAK,SAAS,+BAA+B,KAAK,UAAU,iBAE1C;IAElB,OAAO,KAAK,sEAAsE;IAClF,MAAM,KAAK,EAAE,MAAM,kBAAkB,CAAC;IAEtC,IAAI,YAAY,kBACd,YAAY,kBAAkB;IAIhC;;GAIF,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,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"}
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;AACnB;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,oBACd,OACA,iBACA,SAA+B,CAAC,GACpB;CACZ,MAAM,cAAc;EAAE,GAAG;EAAgB,GAAG;CAAO;CACnD,MAAM,SAAS,OAAO,OAAO;EAC3B,WAAW,YAAY;EACvB,SAAS,EAAE,WAAW,iBAAiB;CACzC,CAAC;CAED,OAAO,MAAM,EAAE,UAAU,YAAY,SAAS,GAAG,0BAA0B;CAE3E,IAAI,WAAW;CACf,IAAI,YAAmC;CAEvC,MAAM,OAAO,YAA2B;EACtC,IAAI,CAAC,UAAU;EAEf,IAAI;GACF,MAAM,SAAS,MAAM,gBAAgB;GACrC,OAAO,MAAM,EAAE,eAAe,OAAO,cAAc,GAAG,uBAAuB;GAE7E,IAAI,CAAC,OAAO,eAAe;IAEzB,OAAO,KAAK,gEAAgE;IAC5E,MAAM,KAAK,EAAE,MAAM,iBAAiB,CAAC;IAErC,IAAI,YAAY,kBACd,YAAY,iBAAiB;IAI/B;GACF;GAEA,IAAI,OAAO,MACT,MAAM,KAAK;IAAE,MAAM;IAAe,MAAM,OAAO;GAAK,CAAC;EAEzD,SAAS,OAAO;GAEd,MAAM,MAAM;GAIZ,IAFE,KAAK,SAAS,+BAA+B,KAAK,UAAU,iBAE1C;IAElB,OAAO,KAAK,qEAAqE;IACjF,MAAM,KAAK,EAAE,MAAM,iBAAiB,CAAC;IAErC,IAAI,YAAY,kBACd,YAAY,iBAAiB;IAI/B;GACF;GAGA,MAAM,eAAwC,EAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,gBACpD;GAGA,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;GAC1D;GAEA,OAAO,MAAM,cAAc,uBAAuB;GAElD,IAAI,YAAY,WAAW,iBAAiB,OAC1C,YAAY,QAAQ,KAAK;EAE7B;EAGA,IAAI,UACF,YAAY,WAAW,MAAM,YAAY,QAAQ;CAErD;CAGA,YAAY,WAAW,MAAM,YAAY,QAAQ;CAGjD,aAAa;EACX,OAAO,MAAM,0BAA0B;EACvC,WAAW;EACX,IAAI,WAAW;GACb,aAAa,SAAS;GACtB,YAAY;EACd;CACF;AACF"}
@@ -69,9 +69,7 @@ export declare function createAuthStore(options: AuthStoreConfig): import('@xsta
69
69
  error: string;
70
70
  };
71
71
  clearError: unknown;
72
- }, {
73
- type: string;
74
- }>;
72
+ }, never>;
75
73
  /**
76
74
  * Helper function to initialize auth by checking status
77
75
  */
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/store/store.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAEvD;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,IAAI,EAAE,WAAW,GAAG,IAAI,CAAC;IACzB,OAAO,EAAE,OAAO,CAAC;IACjB,eAAe,EAAE,OAAO,CAAC;IACzB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,WAAW,EAAE,IAAI,GAAG,IAAI,CAAC;IACzB,cAAc,EAAE,OAAO,CAAC;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,e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;;WAGG;QACH,SAAS,CAAC,EAAE,MAAM,CAAC;QAEnB;;;WAGG;QACH,eAAe,CAAC,EAAE,MAAM,CAAC;KAC1B,CAAC;CACH,CAAC;AAUF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,eAAe;;;cAyCS,WAAW;;;gBAeV,MAAM;;;;;cA6CN,WAAW;;;;eAuBf,MAAM;;;UAiBnE;AAED;;GAEG;AACH,wBAAsB,cAAc,CAClC,KAAK,EAAE,UAAU,CAAC,OAAO,eAAe,CAAC,EACzC,eAAe,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,iBAuB3C;AAED;;GAEG;AACH,wBAAsB,SAAS,CAC7B,KAAK,EAAE,UAAU,CAAC,OAAO,eAAe,CAAC,EACzC,eAAe,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,iBAqD3C"}
@@ -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;CAuIF,OAtHc,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;IAC1E,OAAO,KAAK,EAAE,MAAM,MAAM,KAAK,OAAO,EAAE,qBAAqB;IAC7D,OAAO;KACL,MAAM,MAAM;KACZ,SAAS,MAAM,KAAK,OAAO,SAAS,OAAO,UAAU,IAAI;KACzD,iBAAiB;KACjB,OAAO;KACP,6BAAa,IAAI,MAAM;KACvB,gBAAgB;KACjB;;;;;G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
+ {"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;AACnB;;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M;GAAe,MAAM,OAAO;EAAK,CAAC;OAErD,MAAM,KAAK,EAAE,MAAM,aAAa,CAAC;EAGnC,MAAM,KAAK,EAAE,MAAM,oBAAoB,CAAC;CAC1C,SAAS,OAAO;EAEd,MAAM,MAAM;EAIZ,IAFE,KAAK,SAAS,+BAA+B,KAAK,UAAU,iBAE1C;GAElB,OAAO,KAAK,kDAAkD;GAC9D,MAAM,KAAK,EAAE,MAAM,iBAAiB,CAAC;EACvC,OAAO;GAEL,MAAM,eAAwC,EAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,gBACpD;GAGA,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;GAC1D;GAEA,OAAO,MAAM,cAAc,kBAAkB;GAC7C,MAAM,KAAK;IACT,MAAM;IACN,OAAO,iBAAiB,QAAQ,MAAM,UAAU;GAClD,CAAC;EACH;CACF;AACF"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Configuration for {@link useHeartbeat}.
3
+ */
4
+ export interface HeartbeatConfig {
5
+ /**
6
+ * Endpoint to POST to in order to refresh the session.
7
+ * The endpoint must run a server-side refresh and return 2xx with
8
+ * `{ accessTokenExpiresAt }` (ISO 8601) on success, or 401 when the refresh
9
+ * token is no longer valid.
10
+ * @default '/api/auth/heartbeat'
11
+ */
12
+ endpoint?: string;
13
+ /**
14
+ * How much of the access-token lifetime to keep as headroom: the refresh is
15
+ * scheduled when `fraction` of the TTL remains. Governs long tokens (a 1 h
16
+ * token at 0.3 refreshes ~42 min in); short tokens are dominated by
17
+ * {@link minSkewMs} instead.
18
+ * @default 0.3
19
+ */
20
+ fraction?: number;
21
+ /**
22
+ * Absolute floor for the refresh lead time (network round-trip + clock skew).
23
+ * Dominates for short-lived tokens: a 10 s token still refreshes ~5 s in.
24
+ * @default 5_000 (5 seconds)
25
+ */
26
+ minSkewMs?: number;
27
+ /**
28
+ * Floor on how often a refresh may fire, so ultra-short tokens don't hammer
29
+ * the endpoint.
30
+ * @default 5_000 (5 seconds)
31
+ */
32
+ minRefreshIntervalMs?: number;
33
+ /**
34
+ * How recently the user must have interacted for a due refresh to fire.
35
+ * Decoupled from the access-token TTL on purpose — this only suppresses
36
+ * refreshes in genuinely abandoned tabs, so keep it generous (tie it to the
37
+ * IdP's SSO/session idle, not the access token). When a refresh is suppressed
38
+ * the hook waits for the next interaction (or tab focus) and refreshes then.
39
+ * @default 1_800_000 (30 minutes)
40
+ */
41
+ idleThresholdMs?: number;
42
+ /**
43
+ * Known access-token expiry at mount (ISO 8601 string or epoch ms). When
44
+ * provided, the first refresh is scheduled from it instead of priming with an
45
+ * immediate refresh to discover the expiry.
46
+ */
47
+ initialExpiresAt?: string | number | null;
48
+ /**
49
+ * Called when the heartbeat endpoint returns 401 — refresh token is gone.
50
+ */
51
+ onSessionExpired?: () => void;
52
+ /**
53
+ * Called after a successful refresh.
54
+ */
55
+ onRefreshed?: () => void;
56
+ /**
57
+ * Called on transient errors (network failure, 5xx). The hook retries — this
58
+ * is just an observability hook.
59
+ */
60
+ onError?: (error: Error) => void;
61
+ /**
62
+ * Namespace for the logger.
63
+ * @default 'fides:heartbeat'
64
+ */
65
+ loggerNamespace?: string;
66
+ }
67
+ /**
68
+ * Expiry-driven session keepalive.
69
+ *
70
+ * Schedules each refresh from the access token's actual expiry rather than a
71
+ * fixed interval, so the cadence self-adjusts to whatever TTL the IdP issues: a
72
+ * 5-minute token refreshes ~3.5 min in; a 10-second token refreshes ~5 s in
73
+ * (skew floor). It primes with one refresh on mount to learn the current expiry
74
+ * (pass {@link HeartbeatConfig.initialExpiresAt} to skip that), retries on
75
+ * transient failure, and — for hidden or idle tabs — defers the refresh until
76
+ * the tab is focused or the user interacts again.
77
+ *
78
+ * A 401 from the endpoint (refresh token / SSO session gone) is the logout
79
+ * trigger via {@link HeartbeatConfig.onSessionExpired}; the idle gate is only an
80
+ * optimization for abandoned tabs, never a gate on access-token freshness.
81
+ *
82
+ * Intended to be paired with {@link useSessionMonitor}: the monitor *detects*
83
+ * session loss; this hook *prevents* it for active users.
84
+ *
85
+ * @example
86
+ * ```tsx
87
+ * 'use client';
88
+ * import { useHeartbeat, useSessionMonitor } from '@eventuras/fides-auth-next/store';
89
+ *
90
+ * function AuthProvider({ children }) {
91
+ * useSessionMonitor(authStore, checkAuthStatus);
92
+ * useHeartbeat({ onSessionExpired: () => authStore.send({ type: 'sessionExpired' }) });
93
+ * return <>{children}</>;
94
+ * }
95
+ * ```
96
+ */
97
+ export declare function useHeartbeat(config?: HeartbeatConfig): void;
98
+ //# sourceMappingURL=use-heartbeat.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-heartbeat.d.ts","sourceRoot":"","sources":["../../src/store/use-heartbeat.ts"],"names":[],"mappings":"AAUA;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IAE1C;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,IAAI,CAAC;IAE9B;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IAEzB;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AA2BD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,YAAY,CAAC,MAAM,GAAE,eAAoB,GAAG,IAAI,CA+L/D"}
@@ -0,0 +1,205 @@
1
+ "use client";
2
+ import { Logger } from "@eventuras/logger";
3
+ import { useEffect, useRef } from "react";
4
+ import { DEFAULT_ACTIVITY_EVENTS, createActivityTracker } from "@eventuras/fides-auth/activity-tracker";
5
+ //#region src/store/use-heartbeat.ts
6
+ var DEFAULTS = {
7
+ endpoint: "/api/auth/heartbeat",
8
+ fraction: .3,
9
+ minSkewMs: 5e3,
10
+ minRefreshIntervalMs: 5e3,
11
+ idleThresholdMs: 30 * 6e4,
12
+ loggerNamespace: "fides:heartbeat"
13
+ };
14
+ var FALLBACK_INTERVAL_MS = 6e4;
15
+ var MAX_RETRY_DELAY_MS = 6e4;
16
+ /** Parses an ISO 8601 string or epoch-ms number into epoch ms, or null. */
17
+ function toEpochMs(value) {
18
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
19
+ if (typeof value === "string") {
20
+ const t = Date.parse(value);
21
+ return Number.isFinite(t) ? t : null;
22
+ }
23
+ return null;
24
+ }
25
+ /**
26
+ * Expiry-driven session keepalive.
27
+ *
28
+ * Schedules each refresh from the access token's actual expiry rather than a
29
+ * fixed interval, so the cadence self-adjusts to whatever TTL the IdP issues: a
30
+ * 5-minute token refreshes ~3.5 min in; a 10-second token refreshes ~5 s in
31
+ * (skew floor). It primes with one refresh on mount to learn the current expiry
32
+ * (pass {@link HeartbeatConfig.initialExpiresAt} to skip that), retries on
33
+ * transient failure, and — for hidden or idle tabs — defers the refresh until
34
+ * the tab is focused or the user interacts again.
35
+ *
36
+ * A 401 from the endpoint (refresh token / SSO session gone) is the logout
37
+ * trigger via {@link HeartbeatConfig.onSessionExpired}; the idle gate is only an
38
+ * optimization for abandoned tabs, never a gate on access-token freshness.
39
+ *
40
+ * Intended to be paired with {@link useSessionMonitor}: the monitor *detects*
41
+ * session loss; this hook *prevents* it for active users.
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * 'use client';
46
+ * import { useHeartbeat, useSessionMonitor } from '@eventuras/fides-auth-next/store';
47
+ *
48
+ * function AuthProvider({ children }) {
49
+ * useSessionMonitor(authStore, checkAuthStatus);
50
+ * useHeartbeat({ onSessionExpired: () => authStore.send({ type: 'sessionExpired' }) });
51
+ * return <>{children}</>;
52
+ * }
53
+ * ```
54
+ */
55
+ function useHeartbeat(config = {}) {
56
+ const endpoint = config.endpoint ?? DEFAULTS.endpoint;
57
+ const fraction = config.fraction ?? DEFAULTS.fraction;
58
+ const minSkewMs = config.minSkewMs ?? DEFAULTS.minSkewMs;
59
+ const minRefreshIntervalMs = config.minRefreshIntervalMs ?? DEFAULTS.minRefreshIntervalMs;
60
+ const idleThresholdMs = config.idleThresholdMs ?? DEFAULTS.idleThresholdMs;
61
+ const initialExpiresAt = toEpochMs(config.initialExpiresAt);
62
+ const loggerNamespace = config.loggerNamespace ?? DEFAULTS.loggerNamespace;
63
+ const callbacksRef = useRef({
64
+ onSessionExpired: config.onSessionExpired,
65
+ onRefreshed: config.onRefreshed,
66
+ onError: config.onError
67
+ });
68
+ callbacksRef.current = {
69
+ onSessionExpired: config.onSessionExpired,
70
+ onRefreshed: config.onRefreshed,
71
+ onError: config.onError
72
+ };
73
+ useEffect(() => {
74
+ if (typeof window === "undefined") return;
75
+ const logger = Logger.create({
76
+ namespace: loggerNamespace,
77
+ context: { component: "Heartbeat" }
78
+ });
79
+ const tracker = createActivityTracker();
80
+ const abortController = new AbortController();
81
+ let timeoutId = null;
82
+ let stopped = false;
83
+ let primed = initialExpiresAt !== null;
84
+ let expiresAt = initialExpiresAt;
85
+ let failureCount = 0;
86
+ let wakerArmed = false;
87
+ const clearTimer = () => {
88
+ if (timeoutId) {
89
+ clearTimeout(timeoutId);
90
+ timeoutId = null;
91
+ }
92
+ };
93
+ const disarmWaker = () => {
94
+ if (!wakerArmed) return;
95
+ wakerArmed = false;
96
+ for (const event of DEFAULT_ACTIVITY_EVENTS) globalThis.removeEventListener(event, onWake);
97
+ document.removeEventListener("visibilitychange", onVisibleWake);
98
+ };
99
+ const teardown = () => {
100
+ if (stopped) return;
101
+ stopped = true;
102
+ clearTimer();
103
+ disarmWaker();
104
+ abortController.abort();
105
+ tracker.dispose();
106
+ };
107
+ const nextDelay = () => {
108
+ if (!primed) return 0;
109
+ if (expiresAt === null) return FALLBACK_INTERVAL_MS;
110
+ const now = Date.now();
111
+ const ttl = Math.max(0, expiresAt - now);
112
+ const lead = Math.max(minSkewMs, fraction * ttl);
113
+ return Math.max(minRefreshIntervalMs, expiresAt - lead - now);
114
+ };
115
+ const scheduleRefresh = (delay = nextDelay()) => {
116
+ if (stopped) return;
117
+ clearTimer();
118
+ timeoutId = setTimeout(onDue, delay);
119
+ };
120
+ function onWake() {
121
+ if (stopped || !wakerArmed) return;
122
+ disarmWaker();
123
+ onDue();
124
+ }
125
+ function onVisibleWake() {
126
+ if (document.visibilityState !== "visible") return;
127
+ tracker.recordActivity();
128
+ onWake();
129
+ }
130
+ const deferUntilActive = () => {
131
+ if (stopped || wakerArmed) return;
132
+ wakerArmed = true;
133
+ clearTimer();
134
+ for (const event of DEFAULT_ACTIVITY_EVENTS) globalThis.addEventListener(event, onWake, { passive: true });
135
+ document.addEventListener("visibilitychange", onVisibleWake);
136
+ };
137
+ async function onDue() {
138
+ if (stopped) return;
139
+ timeoutId = null;
140
+ if (document.visibilityState === "hidden" || !tracker.isActiveWithin(idleThresholdMs)) {
141
+ logger.debug("Refresh due but tab hidden/idle — deferring until active");
142
+ deferUntilActive();
143
+ return;
144
+ }
145
+ await beat();
146
+ }
147
+ async function beat() {
148
+ if (stopped) return;
149
+ try {
150
+ const response = await fetch(endpoint, {
151
+ method: "POST",
152
+ credentials: "same-origin",
153
+ headers: { "content-type": "application/json" },
154
+ signal: abortController.signal
155
+ });
156
+ if (stopped) return;
157
+ if (response.status === 401) {
158
+ logger.info("Heartbeat returned 401 — session expired");
159
+ callbacksRef.current.onSessionExpired?.();
160
+ teardown();
161
+ return;
162
+ }
163
+ if (!response.ok) throw new Error(`Heartbeat failed with status ${response.status}`);
164
+ failureCount = 0;
165
+ primed = true;
166
+ expiresAt = toEpochMs((await response.json().catch(() => null))?.accessTokenExpiresAt);
167
+ logger.debug({ expiresAt }, "Heartbeat refresh succeeded");
168
+ callbacksRef.current.onRefreshed?.();
169
+ scheduleRefresh();
170
+ } catch (error) {
171
+ if (stopped) return;
172
+ const err = error instanceof Error ? error : new Error(String(error));
173
+ logger.warn({ error: err.message }, "Heartbeat tick failed, will retry");
174
+ callbacksRef.current.onError?.(err);
175
+ failureCount += 1;
176
+ scheduleRefresh(Math.min(MAX_RETRY_DELAY_MS, minRefreshIntervalMs * 2 ** (failureCount - 1)));
177
+ }
178
+ }
179
+ scheduleRefresh();
180
+ logger.debug({
181
+ fraction,
182
+ minSkewMs,
183
+ minRefreshIntervalMs,
184
+ idleThresholdMs,
185
+ endpoint,
186
+ primed
187
+ }, "Heartbeat started");
188
+ return () => {
189
+ teardown();
190
+ logger.debug("Heartbeat stopped");
191
+ };
192
+ }, [
193
+ endpoint,
194
+ fraction,
195
+ minSkewMs,
196
+ minRefreshIntervalMs,
197
+ idleThresholdMs,
198
+ initialExpiresAt,
199
+ loggerNamespace
200
+ ]);
201
+ }
202
+ //#endregion
203
+ export { useHeartbeat };
204
+
205
+ //# sourceMappingURL=use-heartbeat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-heartbeat.js","names":[],"sources":["../../src/store/use-heartbeat.ts"],"sourcesContent":["'use client';\n\nimport { useEffect, useRef } from 'react';\nimport {\n createActivityTracker,\n DEFAULT_ACTIVITY_EVENTS,\n type ActivityTracker,\n} from '@eventuras/fides-auth/activity-tracker';\nimport { Logger } from '@eventuras/logger';\n\n/**\n * Configuration for {@link useHeartbeat}.\n */\nexport interface HeartbeatConfig {\n /**\n * Endpoint to POST to in order to refresh the session.\n * The endpoint must run a server-side refresh and return 2xx with\n * `{ accessTokenExpiresAt }` (ISO 8601) on success, or 401 when the refresh\n * token is no longer valid.\n * @default '/api/auth/heartbeat'\n */\n endpoint?: string;\n\n /**\n * How much of the access-token lifetime to keep as headroom: the refresh is\n * scheduled when `fraction` of the TTL remains. Governs long tokens (a 1 h\n * token at 0.3 refreshes ~42 min in); short tokens are dominated by\n * {@link minSkewMs} instead.\n * @default 0.3\n */\n fraction?: number;\n\n /**\n * Absolute floor for the refresh lead time (network round-trip + clock skew).\n * Dominates for short-lived tokens: a 10 s token still refreshes ~5 s in.\n * @default 5_000 (5 seconds)\n */\n minSkewMs?: number;\n\n /**\n * Floor on how often a refresh may fire, so ultra-short tokens don't hammer\n * the endpoint.\n * @default 5_000 (5 seconds)\n */\n minRefreshIntervalMs?: number;\n\n /**\n * How recently the user must have interacted for a due refresh to fire.\n * Decoupled from the access-token TTL on purpose — this only suppresses\n * refreshes in genuinely abandoned tabs, so keep it generous (tie it to the\n * IdP's SSO/session idle, not the access token). When a refresh is suppressed\n * the hook waits for the next interaction (or tab focus) and refreshes then.\n * @default 1_800_000 (30 minutes)\n */\n idleThresholdMs?: number;\n\n /**\n * Known access-token expiry at mount (ISO 8601 string or epoch ms). When\n * provided, the first refresh is scheduled from it instead of priming with an\n * immediate refresh to discover the expiry.\n */\n initialExpiresAt?: string | number | null;\n\n /**\n * Called when the heartbeat endpoint returns 401 — refresh token is gone.\n */\n onSessionExpired?: () => void;\n\n /**\n * Called after a successful refresh.\n */\n onRefreshed?: () => void;\n\n /**\n * Called on transient errors (network failure, 5xx). The hook retries — this\n * is just an observability hook.\n */\n onError?: (error: Error) => void;\n\n /**\n * Namespace for the logger.\n * @default 'fides:heartbeat'\n */\n loggerNamespace?: string;\n}\n\nconst DEFAULTS = {\n endpoint: '/api/auth/heartbeat',\n fraction: 0.3,\n minSkewMs: 5_000,\n minRefreshIntervalMs: 5_000,\n idleThresholdMs: 30 * 60_000,\n loggerNamespace: 'fides:heartbeat',\n} as const;\n\n// Fallback cadence when a refresh succeeds but the response carries no usable\n// expiry — keeps the session alive without busy-looping on an unknown TTL.\nconst FALLBACK_INTERVAL_MS = 60_000;\n// Upper bound for exponential backoff between transient-failure retries.\nconst MAX_RETRY_DELAY_MS = 60_000;\n\n/** Parses an ISO 8601 string or epoch-ms number into epoch ms, or null. */\nfunction toEpochMs(value: string | number | null | undefined): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null;\n if (typeof value === 'string') {\n const t = Date.parse(value);\n return Number.isFinite(t) ? t : null;\n }\n return null;\n}\n\n/**\n * Expiry-driven session keepalive.\n *\n * Schedules each refresh from the access token's actual expiry rather than a\n * fixed interval, so the cadence self-adjusts to whatever TTL the IdP issues: a\n * 5-minute token refreshes ~3.5 min in; a 10-second token refreshes ~5 s in\n * (skew floor). It primes with one refresh on mount to learn the current expiry\n * (pass {@link HeartbeatConfig.initialExpiresAt} to skip that), retries on\n * transient failure, and — for hidden or idle tabs — defers the refresh until\n * the tab is focused or the user interacts again.\n *\n * A 401 from the endpoint (refresh token / SSO session gone) is the logout\n * trigger via {@link HeartbeatConfig.onSessionExpired}; the idle gate is only an\n * optimization for abandoned tabs, never a gate on access-token freshness.\n *\n * Intended to be paired with {@link useSessionMonitor}: the monitor *detects*\n * session loss; this hook *prevents* it for active users.\n *\n * @example\n * ```tsx\n * 'use client';\n * import { useHeartbeat, useSessionMonitor } from '@eventuras/fides-auth-next/store';\n *\n * function AuthProvider({ children }) {\n * useSessionMonitor(authStore, checkAuthStatus);\n * useHeartbeat({ onSessionExpired: () => authStore.send({ type: 'sessionExpired' }) });\n * return <>{children}</>;\n * }\n * ```\n */\nexport function useHeartbeat(config: HeartbeatConfig = {}): void {\n const endpoint = config.endpoint ?? DEFAULTS.endpoint;\n const fraction = config.fraction ?? DEFAULTS.fraction;\n const minSkewMs = config.minSkewMs ?? DEFAULTS.minSkewMs;\n const minRefreshIntervalMs = config.minRefreshIntervalMs ?? DEFAULTS.minRefreshIntervalMs;\n const idleThresholdMs = config.idleThresholdMs ?? DEFAULTS.idleThresholdMs;\n const initialExpiresAt = toEpochMs(config.initialExpiresAt);\n const loggerNamespace = config.loggerNamespace ?? DEFAULTS.loggerNamespace;\n\n // Keep callbacks stable across renders without re-running the effect.\n const callbacksRef = useRef({\n onSessionExpired: config.onSessionExpired,\n onRefreshed: config.onRefreshed,\n onError: config.onError,\n });\n callbacksRef.current = {\n onSessionExpired: config.onSessionExpired,\n onRefreshed: config.onRefreshed,\n onError: config.onError,\n };\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n\n const logger = Logger.create({\n namespace: loggerNamespace,\n context: { component: 'Heartbeat' },\n });\n\n const tracker: ActivityTracker = createActivityTracker();\n const abortController = new AbortController();\n\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let stopped = false;\n let primed = initialExpiresAt !== null;\n let expiresAt: number | null = initialExpiresAt;\n let failureCount = 0;\n let wakerArmed = false;\n\n const clearTimer = (): void => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n const disarmWaker = (): void => {\n if (!wakerArmed) return;\n wakerArmed = false;\n for (const event of DEFAULT_ACTIVITY_EVENTS) {\n globalThis.removeEventListener(event, onWake);\n }\n document.removeEventListener('visibilitychange', onVisibleWake);\n };\n\n const teardown = (): void => {\n if (stopped) return;\n stopped = true;\n clearTimer();\n disarmWaker();\n abortController.abort();\n tracker.dispose();\n };\n\n // Time until the next refresh should fire, from the current known expiry.\n const nextDelay = (): number => {\n if (!primed) return 0; // prime now to discover the expiry\n if (expiresAt === null) return FALLBACK_INTERVAL_MS;\n const now = Date.now();\n const ttl = Math.max(0, expiresAt - now);\n const lead = Math.max(minSkewMs, fraction * ttl);\n return Math.max(minRefreshIntervalMs, expiresAt - lead - now);\n };\n\n const scheduleRefresh = (delay = nextDelay()): void => {\n if (stopped) return;\n clearTimer();\n timeoutId = setTimeout(onDue, delay);\n };\n\n function onWake(): void {\n if (stopped || !wakerArmed) return;\n disarmWaker();\n void onDue();\n }\n\n function onVisibleWake(): void {\n if (document.visibilityState !== 'visible') return;\n // Returning to the tab counts as activity, so a refresh deferred past\n // idleThresholdMs while hidden runs now instead of deferring again\n // (a visibility change does not touch the activity tracker on its own).\n tracker.recordActivity();\n onWake();\n }\n\n // Suspend refreshing until the tab is focused or the user interacts again.\n const deferUntilActive = (): void => {\n if (stopped || wakerArmed) return;\n wakerArmed = true;\n clearTimer();\n for (const event of DEFAULT_ACTIVITY_EVENTS) {\n globalThis.addEventListener(event, onWake, { passive: true });\n }\n document.addEventListener('visibilitychange', onVisibleWake);\n };\n\n async function onDue(): Promise<void> {\n if (stopped) return;\n timeoutId = null;\n\n // Hidden or abandoned: don't refresh now; wake on focus/interaction.\n if (document.visibilityState === 'hidden' || !tracker.isActiveWithin(idleThresholdMs)) {\n logger.debug('Refresh due but tab hidden/idle — deferring until active');\n deferUntilActive();\n return;\n }\n\n await beat();\n }\n\n async function beat(): Promise<void> {\n if (stopped) return;\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': 'application/json' },\n signal: abortController.signal,\n });\n\n // Unmounted (or 401-driven teardown) during the fetch — bail before\n // touching callbacks so we don't fire on a dead consumer.\n if (stopped) return;\n\n if (response.status === 401) {\n logger.info('Heartbeat returned 401 — session expired');\n callbacksRef.current.onSessionExpired?.();\n teardown();\n return;\n }\n\n if (!response.ok) {\n throw new Error(`Heartbeat failed with status ${response.status}`);\n }\n\n failureCount = 0;\n primed = true;\n const body = (await response.json().catch(() => null)) as\n | { accessTokenExpiresAt?: string | number | null }\n | null;\n expiresAt = toEpochMs(body?.accessTokenExpiresAt);\n\n logger.debug({ expiresAt }, 'Heartbeat refresh succeeded');\n callbacksRef.current.onRefreshed?.();\n scheduleRefresh();\n } catch (error) {\n if (stopped) return;\n const err = error instanceof Error ? error : new Error(String(error));\n logger.warn({ error: err.message }, 'Heartbeat tick failed, will retry');\n callbacksRef.current.onError?.(err);\n\n // Retry with capped exponential backoff; a real expiry resumes the\n // normal cadence once a tick succeeds.\n failureCount += 1;\n const backoff = Math.min(\n MAX_RETRY_DELAY_MS,\n minRefreshIntervalMs * 2 ** (failureCount - 1),\n );\n scheduleRefresh(backoff);\n }\n }\n\n scheduleRefresh();\n logger.debug(\n { fraction, minSkewMs, minRefreshIntervalMs, idleThresholdMs, endpoint, primed },\n 'Heartbeat started',\n );\n\n return () => {\n teardown();\n logger.debug('Heartbeat stopped');\n };\n }, [\n endpoint,\n fraction,\n minSkewMs,\n minRefreshIntervalMs,\n idleThresholdMs,\n initialExpiresAt,\n loggerNamespace,\n ]);\n}\n"],"mappings":";;;;;AAsFA,IAAM,WAAW;CACf,UAAU;CACV,UAAU;CACV,WAAW;CACX,sBAAsB;CACtB,iBAAiB,KAAK;CACtB,iBAAiB;AACnB;AAIA,IAAM,uBAAuB;AAE7B,IAAM,qBAAqB;;AAG3B,SAAS,UAAU,OAA0D;CAC3E,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;CACvE,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,IAAI,KAAK,MAAM,KAAK;EAC1B,OAAO,OAAO,SAAS,CAAC,IAAI,IAAI;CAClC;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,aAAa,SAA0B,CAAC,GAAS;CAC/D,MAAM,WAAW,OAAO,YAAY,SAAS;CAC7C,MAAM,WAAW,OAAO,YAAY,SAAS;CAC7C,MAAM,YAAY,OAAO,aAAa,SAAS;CAC/C,MAAM,uBAAuB,OAAO,wBAAwB,SAAS;CACrE,MAAM,kBAAkB,OAAO,mBAAmB,SAAS;CAC3D,MAAM,mBAAmB,UAAU,OAAO,gBAAgB;CAC1D,MAAM,kBAAkB,OAAO,mBAAmB,SAAS;CAG3D,MAAM,eAAe,OAAO;EAC1B,kBAAkB,OAAO;EACzB,aAAa,OAAO;EACpB,SAAS,OAAO;CAClB,C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A,uBAAuB,MAAM,eAAe,EAE9B,CAAO;GACzB;EACF;EAEA,gBAAgB;EAChB,OAAO,MACL;GAAE;GAAU;GAAW;GAAsB;GAAiB;GAAU;EAAO,GAC/E,mBACF;EAEA,aAAa;GACX,SAAS;GACT,OAAO,MAAM,mBAAmB;EAClC;CACF,GAAG;EACD;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH"}
@@ -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;CACN,gBAAgB;EACd,OAAO,oBAAoB,OAAO,iBAAiB,OAAO;IACzD;EAAC;EAAO;EAAiB;EAAO,CAAC"}
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,CAAC,GAC1B;CACN,gBAAgB;EACd,OAAO,oBAAoB,OAAO,iBAAiB,MAAM;CAC3D,GAAG;EAAC;EAAO;EAAiB;CAAM,CAAC;AACrC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eventuras/fides-auth-next",
3
- "version": "0.1.12",
3
+ "version": "0.3.0",
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": {
@@ -35,6 +35,10 @@
35
35
  "./oidc-login": {
36
36
  "types": "./dist/oidc-login.d.ts",
37
37
  "import": "./dist/oidc-login.js"
38
+ },
39
+ "./heartbeat-handler": {
40
+ "types": "./dist/heartbeat-handler.d.ts",
41
+ "import": "./dist/heartbeat-handler.js"
38
42
  }
39
43
  },
40
44
  "main": "./dist/index.js",
@@ -43,27 +47,37 @@
43
47
  "dist"
44
48
  ],
45
49
  "dependencies": {
46
- "@xstate/store": "^3.17.1",
47
- "@eventuras/fides-auth": "0.7.1",
50
+ "@xstate/store": "^4.0.0",
51
+ "@xstate/store-react": "^2.0.0",
52
+ "@eventuras/fides-auth": "0.9.0",
48
53
  "@eventuras/logger": "0.8.1"
49
54
  },
50
55
  "devDependencies": {
56
+ "@testing-library/jest-dom": "6.9.1",
57
+ "@testing-library/react": "^16.3.2",
51
58
  "@types/react": "^19.2.14",
52
59
  "@types/react-dom": "^19.2.3",
60
+ "jsdom": "29.1.1",
61
+ "react": "^19.2.0",
62
+ "react-dom": "^19.2.0",
53
63
  "vite": "^8.0.8",
64
+ "vitest": "^4.1.6",
54
65
  "xstate": "^5.30.0",
55
66
  "@eventuras/typescript-config": "1.0.0",
56
67
  "@eventuras/vite-config": "0.2.2"
57
68
  },
58
69
  "peerDependencies": {
59
70
  "@xstate/react": "^5.0.0 || ^6.0.0",
60
- "@xstate/store": "^3.11.0",
71
+ "@xstate/store": "^4.0.0",
72
+ "@xstate/store-react": "^2.0.0",
61
73
  "next": "^16.0.0",
62
74
  "react": "^19.0.0",
63
75
  "xstate": "^5.0.0"
64
76
  },
65
77
  "scripts": {
66
78
  "build": "vite build",
67
- "dev": "vite build --watch"
79
+ "dev": "vite build --watch",
80
+ "test": "vitest run",
81
+ "test:watch": "vitest"
68
82
  }
69
83
  }