@eventuras/fides-auth-next 0.3.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -674
  2. package/README.md +6 -1
  3. package/dist/cookie-store.d.ts +10 -0
  4. package/dist/cookie-store.d.ts.map +1 -0
  5. package/dist/cookie-store.js +25 -0
  6. package/dist/cookie-store.js.map +1 -0
  7. package/dist/cookies.d.ts +18 -41
  8. package/dist/cookies.d.ts.map +1 -1
  9. package/dist/cookies.js +31 -29
  10. package/dist/cookies.js.map +1 -1
  11. package/dist/heartbeat-handler.d.ts +1 -1
  12. package/dist/heartbeat-handler.d.ts.map +1 -1
  13. package/dist/heartbeat-handler.js +12 -36
  14. package/dist/heartbeat-handler.js.map +1 -1
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +6 -11
  18. package/dist/oidc-callback.d.ts +5 -5
  19. package/dist/oidc-callback.d.ts.map +1 -1
  20. package/dist/oidc-callback.js +16 -39
  21. package/dist/oidc-callback.js.map +1 -1
  22. package/dist/oidc-login.d.ts.map +1 -1
  23. package/dist/oidc-login.js +12 -24
  24. package/dist/oidc-login.js.map +1 -1
  25. package/dist/oidc-logout.d.ts +44 -0
  26. package/dist/oidc-logout.d.ts.map +1 -0
  27. package/dist/oidc-logout.js +44 -0
  28. package/dist/oidc-logout.js.map +1 -0
  29. package/dist/request.js.map +1 -1
  30. package/dist/session.d.ts +24 -62
  31. package/dist/session.d.ts.map +1 -1
  32. package/dist/session.js +30 -132
  33. package/dist/session.js.map +1 -1
  34. package/dist/store/index.d.ts +2 -7
  35. package/dist/store/index.d.ts.map +1 -1
  36. package/dist/store/index.js +2 -6
  37. package/package.json +24 -23
  38. package/dist/store/configure-logger.d.ts +0 -15
  39. package/dist/store/configure-logger.d.ts.map +0 -1
  40. package/dist/store/configure-logger.js +0 -25
  41. package/dist/store/configure-logger.js.map +0 -1
  42. package/dist/store/hooks.d.ts +0 -64
  43. package/dist/store/hooks.d.ts.map +0 -1
  44. package/dist/store/hooks.js +0 -78
  45. package/dist/store/hooks.js.map +0 -1
  46. package/dist/store/session-monitor.d.ts +0 -51
  47. package/dist/store/session-monitor.d.ts.map +0 -1
  48. package/dist/store/session-monitor.js +0 -92
  49. package/dist/store/session-monitor.js.map +0 -1
  50. package/dist/store/store.d.ts +0 -81
  51. package/dist/store/store.d.ts.map +0 -1
  52. package/dist/store/store.js +0 -218
  53. package/dist/store/store.js.map +0 -1
  54. package/dist/store/use-heartbeat.d.ts +0 -98
  55. package/dist/store/use-heartbeat.d.ts.map +0 -1
  56. package/dist/store/use-heartbeat.js +0 -205
  57. package/dist/store/use-heartbeat.js.map +0 -1
  58. package/dist/store/use-session-monitor.d.ts +0 -28
  59. package/dist/store/use-session-monitor.d.ts.map +0 -1
  60. package/dist/store/use-session-monitor.js +0 -40
  61. package/dist/store/use-session-monitor.js.map +0 -1
@@ -1,218 +0,0 @@
1
- import { Logger } from "@eventuras/logger";
2
- import { createStore } from "@xstate/store";
3
- //#region src/store/store.ts
4
- /**
5
- * Default configuration values
6
- */
7
- var DEFAULT_CONFIG = {
8
- adminRole: "Admin",
9
- loggerNamespace: "fides:auth-store"
10
- };
11
- /**
12
- * Creates an authentication store with XState Store
13
- *
14
- * @param options - Configuration for the auth store
15
- * @returns Configured XState store
16
- *
17
- * @example
18
- * ```typescript
19
- * const authStore = createAuthStore({
20
- * checkAuthStatus: async () => getAuthStatus(),
21
- * config: {
22
- * adminRole: 'Admin',
23
- * loggerNamespace: 'myapp:auth',
24
- * }
25
- * });
26
- * ```
27
- */
28
- function createAuthStore(options) {
29
- const config = {
30
- ...DEFAULT_CONFIG,
31
- ...options.config
32
- };
33
- const logger = Logger.create({
34
- namespace: config.loggerNamespace,
35
- context: { component: "AuthStore" }
36
- });
37
- return createStore({
38
- context: {
39
- user: null,
40
- isAdmin: false,
41
- isAuthenticated: false,
42
- error: null,
43
- lastChecked: null,
44
- isInitializing: true
45
- },
46
- on: {
47
- /**
48
- * Initialize authentication - check current status
49
- */
50
- initialize: () => ({
51
- user: null,
52
- isAdmin: false,
53
- isAuthenticated: false,
54
- error: null,
55
- lastChecked: null,
56
- isInitializing: true
57
- }),
58
- /**
59
- * Authentication check succeeded
60
- */
61
- authSuccess: (_context, event) => {
62
- logger.info({ user: event.user.roles }, "User authenticated");
63
- return {
64
- user: event.user,
65
- isAdmin: event.user.roles?.includes(config.adminRole) ?? false,
66
- isAuthenticated: true,
67
- error: null,
68
- lastChecked: /* @__PURE__ */ new Date(),
69
- isInitializing: false
70
- };
71
- },
72
- /**
73
- * Authentication check failed - not authenticated
74
- */
75
- authFailed: (_context, event = {}) => {
76
- logger.info("User not authenticated");
77
- return {
78
- user: null,
79
- isAdmin: false,
80
- isAuthenticated: false,
81
- error: event.error || null,
82
- lastChecked: /* @__PURE__ */ new Date(),
83
- isInitializing: false
84
- };
85
- },
86
- /**
87
- * Session expired
88
- */
89
- sessionExpired: () => {
90
- logger.warn("Session expired");
91
- return {
92
- user: null,
93
- isAdmin: false,
94
- isAuthenticated: false,
95
- error: "Session expired",
96
- lastChecked: /* @__PURE__ */ new Date(),
97
- isInitializing: false
98
- };
99
- },
100
- /**
101
- * User logged out
102
- */
103
- logout: () => {
104
- logger.info("User logged out");
105
- return {
106
- user: null,
107
- isAdmin: false,
108
- isAuthenticated: false,
109
- error: null,
110
- lastChecked: /* @__PURE__ */ new Date(),
111
- isInitializing: false
112
- };
113
- },
114
- /**
115
- * Login success
116
- */
117
- loginSuccess: (_context, event) => {
118
- logger.info({ user: event.user.email }, "Login successful");
119
- return {
120
- user: event.user,
121
- isAdmin: event.user.roles?.includes(config.adminRole) ?? false,
122
- isAuthenticated: true,
123
- error: null,
124
- lastChecked: /* @__PURE__ */ new Date(),
125
- isInitializing: false
126
- };
127
- },
128
- /**
129
- * Update last checked timestamp
130
- */
131
- updateLastChecked: (context) => ({
132
- ...context,
133
- lastChecked: /* @__PURE__ */ new Date()
134
- }),
135
- /**
136
- * Set error
137
- */
138
- setError: (context, event) => ({
139
- ...context,
140
- error: event.error
141
- }),
142
- /**
143
- * Clear error
144
- */
145
- clearError: (context) => ({
146
- ...context,
147
- error: null
148
- })
149
- }
150
- });
151
- }
152
- /**
153
- * Helper function to initialize auth by checking status
154
- */
155
- async function initializeAuth(store, checkAuthStatus) {
156
- const logger = Logger.create({
157
- namespace: "fides:auth-store",
158
- context: { component: "initializeAuth" }
159
- });
160
- logger.debug("Initializing authentication");
161
- store.send({ type: "initialize" });
162
- try {
163
- const result = await checkAuthStatus();
164
- logger.debug({ authenticated: result.authenticated }, "Auth status checked");
165
- if (result.authenticated && result.user) store.send({
166
- type: "authSuccess",
167
- user: result.user
168
- });
169
- else store.send({ type: "authFailed" });
170
- } catch (error) {
171
- logger.debug({ error }, "Auth check returned no session");
172
- store.send({ type: "authFailed" });
173
- }
174
- }
175
- /**
176
- * Helper function to check auth status and update store
177
- */
178
- async function checkAuth(store, checkAuthStatus) {
179
- const logger = Logger.create({
180
- namespace: "fides:auth-store",
181
- context: { component: "checkAuth" }
182
- });
183
- logger.debug("Checking authentication status");
184
- try {
185
- const result = await checkAuthStatus();
186
- logger.debug({ authenticated: result.authenticated }, "Auth status checked");
187
- if (result.authenticated && result.user) store.send({
188
- type: "authSuccess",
189
- user: result.user
190
- });
191
- else store.send({ type: "authFailed" });
192
- store.send({ type: "updateLastChecked" });
193
- } catch (error) {
194
- const err = error;
195
- if (err?.code === "OAUTH_RESPONSE_BODY_ERROR" && err?.error === "invalid_grant") {
196
- logger.info("Session ended - refresh token expired or invalid");
197
- store.send({ type: "sessionExpired" });
198
- } else {
199
- const errorDetails = { message: error instanceof Error ? error.message : "Unknown error" };
200
- if (error && typeof error === "object") {
201
- const oauthError = error;
202
- if (oauthError.code) errorDetails.code = oauthError.code;
203
- if (oauthError.error) errorDetails.error = oauthError.error;
204
- if (oauthError.error_description) errorDetails.error_description = oauthError.error_description;
205
- if (oauthError.status) errorDetails.status = oauthError.status;
206
- }
207
- logger.error(errorDetails, "Auth check error");
208
- store.send({
209
- type: "authFailed",
210
- error: error instanceof Error ? error.message : "Unknown error"
211
- });
212
- }
213
- }
214
- }
215
- //#endregion
216
- export { checkAuth, createAuthStore, initializeAuth };
217
-
218
- //# sourceMappingURL=store.js.map
@@ -1 +0,0 @@
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;AACnB;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAgB,SAA0B;CACxD,MAAM,SAAS;EAAE,GAAG;EAAgB,GAAG,QAAQ;CAAO;CACtD,MAAM,SAAS,OAAO,OAAO;EAC3B,WAAW,OAAO;EAClB,SAAS,EAAE,WAAW,YAAY;CACpC,CAAC;CAuID,OAtHc,YACZ;EACE,SAAS;GAbX,MAAM;GACN,SAAS;GACT,iBAAiB;GACjB,OAAO;GACP,aAAa;GACb,gBAAgB;EAQL;EACT,IAAI;;;;GAIF,mBAAmB;IACjB,MAAM;IACN,SAAS;IACT,iBAAiB;IACjB,OAAO;IACP,aAAa;IACb,gBAAgB;GAClB;;;;GAKA,cAAc,UAA4B,UAAkC;IAC1E,OAAO,KAAK,EAAE,MAAM,MAAM,KAAK,MAAM,GAAG,oBAAoB;IAC5D,OAAO;KACL,MAAM,MAAM;KACZ,SAAS,MAAM,KAAK,OAAO,SAAS,OAAO,SAAS,KAAK;KACzD,iBAAiB;KACjB,OAAO;KACP,6BAAa,IAAI,KAAK;KACtB,gBAAgB;IAClB;GACF;;;;GAKA,aAAa,UAA4B,QAA6B,CAAC,MAAM;IAC3E,OAAO,KAAK,wBAAwB;IACpC,OAAO;KACL,MAAM;KACN,SAAS;KACT,iBAAiB;KACjB,OAAO,MAAM,SAAS;KACtB,6BAAa,IAAI,KAAK;KACtB,gBAAgB;IAClB;GACF;;;;GAKA,sBAAsB;IACpB,OAAO,KAAK,iBAAiB;IAC7B,OAAO;KACL,MAAM;KACN,SAAS;KACT,iBAAiB;KACjB,OAAO;KACP,6BAAa,IAAI,KAAK;KACtB,gBAAgB;IAClB;G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SAAS,EAAE,WAAW,YAAY;CACpC,CAAC;CAED,OAAO,MAAM,gCAAgC;CAE7C,IAAI;EACF,MAAM,SAAS,MAAM,gBAAgB;EACrC,OAAO,MAAM,EAAE,eAAe,OAAO,cAAc,GAAG,qBAAqB;EAE3E,IAAI,OAAO,iBAAiB,OAAO,MACjC,MAAM,KAAK;GAAE,MAAM;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"}
@@ -1,98 +0,0 @@
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
@@ -1 +0,0 @@
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,205 +0,0 @@
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
@@ -1 +0,0 @@
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,CAAC;CACD,aAAa,UAAU;EACrB,kBAAkB,OAAO;EACzB,aAAa,OAAO;EACpB,SAAS,OAAO;CAClB;CAEA,gBAAgB;EACd,IAAI,OAAO,WAAW,aAAa;EAEnC,MAAM,S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aAAa;GACX,SAAS;GACT,OAAO,MAAM,mBAAmB;EAClC;CACF,GAAG;EACD;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH"}
@@ -1,28 +0,0 @@
1
- import { SessionMonitorConfig } from './session-monitor';
2
- import { createAuthStore } from './store';
3
- import { AuthStatus } from './types';
4
- /**
5
- * React hook for session monitoring with automatic cleanup
6
- *
7
- * @param store - The auth store to update
8
- * @param checkAuthStatus - Function to check authentication status
9
- * @param config - Optional configuration
10
- *
11
- * @example
12
- * ```typescript
13
- * import { useSessionMonitor } from '@eventuras/fides-auth-next/store';
14
- *
15
- * function App() {
16
- * useSessionMonitor(authStore, checkAuthStatus, {
17
- * interval: 30_000,
18
- * onSessionExpired: () => {
19
- * toast.warn('Your session has expired');
20
- * }
21
- * });
22
- *
23
- * return <div>...</div>;
24
- * }
25
- * ```
26
- */
27
- export declare function useSessionMonitor(store: ReturnType<typeof createAuthStore>, checkAuthStatus: () => Promise<AuthStatus>, config?: SessionMonitorConfig): void;
28
- //# sourceMappingURL=use-session-monitor.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-session-monitor.d.ts","sourceRoot":"","sources":["../../src/store/use-session-monitor.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuB,KAAK,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACnF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE1C;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,UAAU,CAAC,OAAO,eAAe,CAAC,EACzC,eAAe,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,EAC1C,MAAM,GAAE,oBAAyB,GAChC,IAAI,CAIN"}
@@ -1,40 +0,0 @@
1
- "use client";
2
- import { startSessionMonitor } from "./session-monitor.js";
3
- import { useEffect } from "react";
4
- //#region src/store/use-session-monitor.ts
5
- /**
6
- * React hook for session monitoring with automatic cleanup
7
- *
8
- * @param store - The auth store to update
9
- * @param checkAuthStatus - Function to check authentication status
10
- * @param config - Optional configuration
11
- *
12
- * @example
13
- * ```typescript
14
- * import { useSessionMonitor } from '@eventuras/fides-auth-next/store';
15
- *
16
- * function App() {
17
- * useSessionMonitor(authStore, checkAuthStatus, {
18
- * interval: 30_000,
19
- * onSessionExpired: () => {
20
- * toast.warn('Your session has expired');
21
- * }
22
- * });
23
- *
24
- * return <div>...</div>;
25
- * }
26
- * ```
27
- */
28
- function useSessionMonitor(store, checkAuthStatus, config = {}) {
29
- useEffect(() => {
30
- return startSessionMonitor(store, checkAuthStatus, config);
31
- }, [
32
- store,
33
- checkAuthStatus,
34
- config
35
- ]);
36
- }
37
- //#endregion
38
- export { useSessionMonitor };
39
-
40
- //# sourceMappingURL=use-session-monitor.js.map
@@ -1 +0,0 @@
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"}