@eventuras/fides-auth-next 0.2.0 → 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.
- package/dist/oidc-callback.d.ts.map +1 -1
- package/dist/oidc-callback.js +1 -0
- package/dist/oidc-callback.js.map +1 -1
- package/dist/store/hooks.js +1 -1
- package/dist/store/hooks.js.map +1 -1
- package/dist/store/store.d.ts +1 -3
- package/dist/store/store.d.ts.map +1 -1
- package/dist/store/use-heartbeat.d.ts +48 -15
- package/dist/store/use-heartbeat.d.ts.map +1 -1
- package/dist/store/use-heartbeat.js +106 -49
- package/dist/store/use-heartbeat.js.map +1 -1
- package/package.json +8 -6
|
@@ -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,
|
|
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"}
|
package/dist/oidc-callback.js
CHANGED
|
@@ -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,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;
|
|
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"}
|
package/dist/store/hooks.js
CHANGED
package/dist/store/hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.js","names":[],"sources":["../../src/store/hooks.ts"],"sourcesContent":["import { useSelector as useStoreSelector } from '@xstate/store
|
|
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":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U,CAAC,iBAuB3C;AAED;;GAEG;AACH,wBAAsB,SAAS,CAC7B,KAAK,EAAE,UAAU,CAAC,OAAO,eAAe,CAAC,EACzC,eAAe,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,iBAqD3C"}
|
|
@@ -4,33 +4,58 @@
|
|
|
4
4
|
export interface HeartbeatConfig {
|
|
5
5
|
/**
|
|
6
6
|
* Endpoint to POST to in order to refresh the session.
|
|
7
|
-
* The endpoint must run server-side refresh and return 2xx
|
|
8
|
-
*
|
|
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.
|
|
9
10
|
* @default '/api/auth/heartbeat'
|
|
10
11
|
*/
|
|
11
12
|
endpoint?: string;
|
|
12
13
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
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
|
|
15
19
|
*/
|
|
16
|
-
|
|
20
|
+
fraction?: number;
|
|
17
21
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* @default
|
|
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)
|
|
21
40
|
*/
|
|
22
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;
|
|
23
48
|
/**
|
|
24
49
|
* Called when the heartbeat endpoint returns 401 — refresh token is gone.
|
|
25
50
|
*/
|
|
26
51
|
onSessionExpired?: () => void;
|
|
27
52
|
/**
|
|
28
|
-
* Called after a successful refresh
|
|
53
|
+
* Called after a successful refresh.
|
|
29
54
|
*/
|
|
30
55
|
onRefreshed?: () => void;
|
|
31
56
|
/**
|
|
32
|
-
* Called on transient errors (network failure, 5xx). The hook
|
|
33
|
-
*
|
|
57
|
+
* Called on transient errors (network failure, 5xx). The hook retries — this
|
|
58
|
+
* is just an observability hook.
|
|
34
59
|
*/
|
|
35
60
|
onError?: (error: Error) => void;
|
|
36
61
|
/**
|
|
@@ -40,11 +65,19 @@ export interface HeartbeatConfig {
|
|
|
40
65
|
loggerNamespace?: string;
|
|
41
66
|
}
|
|
42
67
|
/**
|
|
43
|
-
*
|
|
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.
|
|
44
77
|
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
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.
|
|
48
81
|
*
|
|
49
82
|
* Intended to be paired with {@link useSessionMonitor}: the monitor *detects*
|
|
50
83
|
* session loss; this hook *prevents* it for active users.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-heartbeat.d.ts","sourceRoot":"","sources":["../../src/store/use-heartbeat.ts"],"names":[],"mappings":"
|
|
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"}
|
|
@@ -1,20 +1,41 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { Logger } from "@eventuras/logger";
|
|
3
3
|
import { useEffect, useRef } from "react";
|
|
4
|
-
import { createActivityTracker } from "@eventuras/fides-auth/activity-tracker";
|
|
4
|
+
import { DEFAULT_ACTIVITY_EVENTS, createActivityTracker } from "@eventuras/fides-auth/activity-tracker";
|
|
5
5
|
//#region src/store/use-heartbeat.ts
|
|
6
6
|
var DEFAULTS = {
|
|
7
7
|
endpoint: "/api/auth/heartbeat",
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
fraction: .3,
|
|
9
|
+
minSkewMs: 5e3,
|
|
10
|
+
minRefreshIntervalMs: 5e3,
|
|
11
|
+
idleThresholdMs: 30 * 6e4,
|
|
10
12
|
loggerNamespace: "fides:heartbeat"
|
|
11
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
|
+
}
|
|
12
25
|
/**
|
|
13
|
-
*
|
|
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.
|
|
14
35
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
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.
|
|
18
39
|
*
|
|
19
40
|
* Intended to be paired with {@link useSessionMonitor}: the monitor *detects*
|
|
20
41
|
* session loss; this hook *prevents* it for active users.
|
|
@@ -33,8 +54,11 @@ var DEFAULTS = {
|
|
|
33
54
|
*/
|
|
34
55
|
function useHeartbeat(config = {}) {
|
|
35
56
|
const endpoint = config.endpoint ?? DEFAULTS.endpoint;
|
|
36
|
-
const
|
|
57
|
+
const fraction = config.fraction ?? DEFAULTS.fraction;
|
|
58
|
+
const minSkewMs = config.minSkewMs ?? DEFAULTS.minSkewMs;
|
|
59
|
+
const minRefreshIntervalMs = config.minRefreshIntervalMs ?? DEFAULTS.minRefreshIntervalMs;
|
|
37
60
|
const idleThresholdMs = config.idleThresholdMs ?? DEFAULTS.idleThresholdMs;
|
|
61
|
+
const initialExpiresAt = toEpochMs(config.initialExpiresAt);
|
|
38
62
|
const loggerNamespace = config.loggerNamespace ?? DEFAULTS.loggerNamespace;
|
|
39
63
|
const callbacksRef = useRef({
|
|
40
64
|
onSessionExpired: config.onSessionExpired,
|
|
@@ -55,30 +79,73 @@ function useHeartbeat(config = {}) {
|
|
|
55
79
|
const tracker = createActivityTracker();
|
|
56
80
|
const abortController = new AbortController();
|
|
57
81
|
let timeoutId = null;
|
|
58
|
-
let lastTickAt = Date.now();
|
|
59
82
|
let stopped = false;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
83
|
+
let primed = initialExpiresAt !== null;
|
|
84
|
+
let expiresAt = initialExpiresAt;
|
|
85
|
+
let failureCount = 0;
|
|
86
|
+
let wakerArmed = false;
|
|
87
|
+
const clearTimer = () => {
|
|
63
88
|
if (timeoutId) {
|
|
64
89
|
clearTimeout(timeoutId);
|
|
65
90
|
timeoutId = null;
|
|
66
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();
|
|
67
104
|
abortController.abort();
|
|
68
|
-
document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
69
105
|
tracker.dispose();
|
|
70
106
|
};
|
|
71
|
-
const
|
|
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()) => {
|
|
72
116
|
if (stopped) return;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
if (!
|
|
78
|
-
|
|
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();
|
|
79
143
|
return;
|
|
80
144
|
}
|
|
81
|
-
|
|
145
|
+
await beat();
|
|
146
|
+
}
|
|
147
|
+
async function beat() {
|
|
148
|
+
if (stopped) return;
|
|
82
149
|
try {
|
|
83
150
|
const response = await fetch(endpoint, {
|
|
84
151
|
method: "POST",
|
|
@@ -94,42 +161,29 @@ function useHeartbeat(config = {}) {
|
|
|
94
161
|
return;
|
|
95
162
|
}
|
|
96
163
|
if (!response.ok) throw new Error(`Heartbeat failed with status ${response.status}`);
|
|
97
|
-
|
|
164
|
+
failureCount = 0;
|
|
165
|
+
primed = true;
|
|
166
|
+
expiresAt = toEpochMs((await response.json().catch(() => null))?.accessTokenExpiresAt);
|
|
167
|
+
logger.debug({ expiresAt }, "Heartbeat refresh succeeded");
|
|
98
168
|
callbacksRef.current.onRefreshed?.();
|
|
169
|
+
scheduleRefresh();
|
|
99
170
|
} catch (error) {
|
|
100
171
|
if (stopped) return;
|
|
101
172
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
102
|
-
logger.warn({ error: err.message }, "Heartbeat tick failed");
|
|
173
|
+
logger.warn({ error: err.message }, "Heartbeat tick failed, will retry");
|
|
103
174
|
callbacksRef.current.onError?.(err);
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const scheduleNext = () => {
|
|
107
|
-
if (stopped) return;
|
|
108
|
-
timeoutId = setTimeout(async () => {
|
|
109
|
-
timeoutId = null;
|
|
110
|
-
await sendBeat();
|
|
111
|
-
scheduleNext();
|
|
112
|
-
}, intervalMs);
|
|
113
|
-
};
|
|
114
|
-
function onVisibilityChange() {
|
|
115
|
-
if (stopped) return;
|
|
116
|
-
if (document.visibilityState !== "visible") return;
|
|
117
|
-
const sinceLast = Date.now() - lastTickAt;
|
|
118
|
-
if (sinceLast >= intervalMs) {
|
|
119
|
-
logger.debug({ sinceLast }, "Tab regained focus after long away, beating now");
|
|
120
|
-
if (timeoutId) {
|
|
121
|
-
clearTimeout(timeoutId);
|
|
122
|
-
timeoutId = null;
|
|
123
|
-
}
|
|
124
|
-
sendBeat().then(scheduleNext);
|
|
175
|
+
failureCount += 1;
|
|
176
|
+
scheduleRefresh(Math.min(MAX_RETRY_DELAY_MS, minRefreshIntervalMs * 2 ** (failureCount - 1)));
|
|
125
177
|
}
|
|
126
178
|
}
|
|
127
|
-
|
|
128
|
-
scheduleNext();
|
|
179
|
+
scheduleRefresh();
|
|
129
180
|
logger.debug({
|
|
130
|
-
|
|
181
|
+
fraction,
|
|
182
|
+
minSkewMs,
|
|
183
|
+
minRefreshIntervalMs,
|
|
131
184
|
idleThresholdMs,
|
|
132
|
-
endpoint
|
|
185
|
+
endpoint,
|
|
186
|
+
primed
|
|
133
187
|
}, "Heartbeat started");
|
|
134
188
|
return () => {
|
|
135
189
|
teardown();
|
|
@@ -137,8 +191,11 @@ function useHeartbeat(config = {}) {
|
|
|
137
191
|
};
|
|
138
192
|
}, [
|
|
139
193
|
endpoint,
|
|
140
|
-
|
|
194
|
+
fraction,
|
|
195
|
+
minSkewMs,
|
|
196
|
+
minRefreshIntervalMs,
|
|
141
197
|
idleThresholdMs,
|
|
198
|
+
initialExpiresAt,
|
|
142
199
|
loggerNamespace
|
|
143
200
|
]);
|
|
144
201
|
}
|
|
@@ -1 +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 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 server-side refresh and return 2xx on success or 401\n * when the refresh token is no longer valid.\n * @default '/api/auth/heartbeat'\n */\n endpoint?: string;\n\n /**\n * Interval between heartbeat ticks, in ms.\n * @default 300_000 (5 minutes)\n */\n intervalMs?: number;\n\n /**\n * How recently the user must have interacted for a heartbeat to fire.\n * Prevents background tabs from extending sessions indefinitely.\n * @default 120_000 (2 minutes)\n */\n idleThresholdMs?: number;\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 tick.\n */\n onRefreshed?: () => void;\n\n /**\n * Called on transient errors (network failure, 5xx). The hook keeps polling\n * — this 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 intervalMs: 5 * 60_000,\n idleThresholdMs: 2 * 60_000,\n loggerNamespace: 'fides:heartbeat',\n} as const;\n\n/**\n * Activity-driven session keepalive.\n *\n * Polls a server-side refresh endpoint at a fixed interval, but only when the\n * user has actually been active recently. Skips ticks when the tab is hidden,\n * and runs an immediate refresh when the tab regains focus after a long away.\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 intervalMs = config.intervalMs ?? DEFAULTS.intervalMs;\n const idleThresholdMs = config.idleThresholdMs ?? DEFAULTS.idleThresholdMs;\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 let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let lastTickAt = Date.now();\n let stopped = false;\n\n const teardown = (): void => {\n if (stopped) return;\n stopped = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n abortController.abort();\n document.removeEventListener('visibilitychange', onVisibilityChange);\n tracker.dispose();\n };\n\n const sendBeat = async (): Promise<void> => {\n if (stopped) return;\n\n // Skip while hidden — focus listener will catch up when tab returns.\n if (document.visibilityState === 'hidden') {\n logger.debug('Tab hidden, skipping heartbeat');\n return;\n }\n\n if (!tracker.isActiveWithin(idleThresholdMs)) {\n logger.debug({ idleThresholdMs }, 'No recent activity, skipping heartbeat');\n return;\n }\n\n lastTickAt = Date.now();\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 // Component unmounted (or 401-driven teardown) during the fetch —\n // bail before 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 // Tear down eagerly so listeners and tracker don't linger until unmount.\n teardown();\n return;\n }\n\n if (!response.ok) {\n throw new Error(`Heartbeat failed with status ${response.status}`);\n }\n\n logger.debug('Heartbeat refresh succeeded');\n callbacksRef.current.onRefreshed?.();\n } catch (error) {\n // Suppress AbortError-from-teardown and any error reported after stop.\n if (stopped) return;\n const err = error instanceof Error ? error : new Error(String(error));\n logger.warn({ error: err.message }, 'Heartbeat tick failed');\n callbacksRef.current.onError?.(err);\n }\n };\n\n const scheduleNext = (): void => {\n if (stopped) return;\n timeoutId = setTimeout(async () => {\n timeoutId = null;\n await sendBeat();\n scheduleNext();\n }, intervalMs);\n };\n\n function onVisibilityChange(): void {\n if (stopped) return;\n if (document.visibilityState !== 'visible') return;\n\n // Tab regained focus. If we've been away longer than one tick, beat now —\n // but cancel the pending tick first so we don't fire twice back-to-back.\n const sinceLast = Date.now() - lastTickAt;\n if (sinceLast >= intervalMs) {\n logger.debug({ sinceLast }, 'Tab regained focus after long away, beating now');\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n void sendBeat().then(scheduleNext);\n }\n }\n\n document.addEventListener('visibilitychange', onVisibilityChange);\n scheduleNext();\n\n logger.debug({ intervalMs, idleThresholdMs, endpoint }, 'Heartbeat started');\n\n return () => {\n teardown();\n logger.debug('Heartbeat stopped');\n };\n }, [endpoint, intervalMs, idleThresholdMs, loggerNamespace]);\n}\n"],"mappings":";;;;;AAyDA,IAAM,WAAW;CACf,UAAU;CACV,YAAY,IAAI;CAChB,iBAAiB,IAAI;CACrB,iBAAiB;AACnB;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,aAAa,SAA0B,CAAC,GAAS;CAC/D,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,aAAa,QAAQ,mBAAmB;KAExC,SAAS;KACT;IACF;IAEA,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,gCAAgC,SAAS,QAAQ;IAGnE,OAAO,MAAM,6BAA6B;IAC1C,aAAa,QAAQ,cAAc;GACrC,SAAS,OAAO;IAEd,IAAI,SAAS;IACb,MAAM,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;IACpE,OAAO,KAAK,EAAE,OAAO,IAAI,QAAQ,GAAG,uBAAuB;IAC3D,aAAa,QAAQ,UAAU,GAAG;GACpC;EACF;EAEA,MAAM,qBAA2B;GAC/B,IAAI,SAAS;GACb,YAAY,WAAW,YAAY;IACjC,YAAY;IACZ,MAAM,SAAS;IACf,aAAa;GACf,GAAG,UAAU;EACf;EAEA,SAAS,qBAA2B;GAClC,IAAI,SAAS;GACb,IAAI,SAAS,oBAAoB,WAAW;GAI5C,MAAM,YAAY,KAAK,IAAI,IAAI;GAC/B,IAAI,aAAa,YAAY;IAC3B,OAAO,MAAM,EAAE,UAAU,GAAG,iDAAiD;IAC7E,IAAI,WAAW;KACb,aAAa,SAAS;KACtB,YAAY;IACd;IACA,SAAc,EAAE,KAAK,YAAY;GACnC;EACF;EAEA,SAAS,iBAAiB,oBAAoB,kBAAkB;EAChE,aAAa;EAEb,OAAO,MAAM;GAAE;GAAY;GAAiB;EAAS,GAAG,mBAAmB;EAE3E,aAAa;GACX,SAAS;GACT,OAAO,MAAM,mBAAmB;EAClC;CACF,GAAG;EAAC;EAAU;EAAY;EAAiB;CAAe,CAAC;AAC7D"}
|
|
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,OAA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,QAAQ,UAAU,GAAG;IAIlC,gBAAgB;IAKhB,gBAJgB,KAAK,IACnB,oBACA,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eventuras/fides-auth-next",
|
|
3
|
-
"version": "0.
|
|
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": {
|
|
@@ -47,8 +47,9 @@
|
|
|
47
47
|
"dist"
|
|
48
48
|
],
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@xstate/store": "^
|
|
51
|
-
"@
|
|
50
|
+
"@xstate/store": "^4.0.0",
|
|
51
|
+
"@xstate/store-react": "^2.0.0",
|
|
52
|
+
"@eventuras/fides-auth": "0.9.0",
|
|
52
53
|
"@eventuras/logger": "0.8.1"
|
|
53
54
|
},
|
|
54
55
|
"devDependencies": {
|
|
@@ -62,12 +63,13 @@
|
|
|
62
63
|
"vite": "^8.0.8",
|
|
63
64
|
"vitest": "^4.1.6",
|
|
64
65
|
"xstate": "^5.30.0",
|
|
65
|
-
"@eventuras/
|
|
66
|
-
"@eventuras/
|
|
66
|
+
"@eventuras/typescript-config": "1.0.0",
|
|
67
|
+
"@eventuras/vite-config": "0.2.2"
|
|
67
68
|
},
|
|
68
69
|
"peerDependencies": {
|
|
69
70
|
"@xstate/react": "^5.0.0 || ^6.0.0",
|
|
70
|
-
"@xstate/store": "^
|
|
71
|
+
"@xstate/store": "^4.0.0",
|
|
72
|
+
"@xstate/store-react": "^2.0.0",
|
|
71
73
|
"next": "^16.0.0",
|
|
72
74
|
"react": "^19.0.0",
|
|
73
75
|
"xstate": "^5.0.0"
|