@eventuras/fides-auth-next 0.2.0 → 0.6.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/LICENSE +21 -674
- package/README.md +6 -1
- package/dist/cookie-store.d.ts +10 -0
- package/dist/cookie-store.d.ts.map +1 -0
- package/dist/cookie-store.js +25 -0
- package/dist/cookie-store.js.map +1 -0
- package/dist/cookies.d.ts +18 -41
- package/dist/cookies.d.ts.map +1 -1
- package/dist/cookies.js +31 -29
- package/dist/cookies.js.map +1 -1
- package/dist/heartbeat-handler.d.ts +1 -1
- package/dist/heartbeat-handler.d.ts.map +1 -1
- package/dist/heartbeat-handler.js +12 -36
- package/dist/heartbeat-handler.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -11
- package/dist/oidc-callback.d.ts +5 -5
- package/dist/oidc-callback.d.ts.map +1 -1
- package/dist/oidc-callback.js +16 -38
- package/dist/oidc-callback.js.map +1 -1
- package/dist/oidc-login.d.ts.map +1 -1
- package/dist/oidc-login.js +12 -24
- package/dist/oidc-login.js.map +1 -1
- package/dist/oidc-logout.d.ts +44 -0
- package/dist/oidc-logout.d.ts.map +1 -0
- package/dist/oidc-logout.js +44 -0
- package/dist/oidc-logout.js.map +1 -0
- package/dist/request.js.map +1 -1
- package/dist/session.d.ts +24 -62
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +30 -132
- package/dist/session.js.map +1 -1
- package/dist/store/index.d.ts +2 -7
- package/dist/store/index.d.ts.map +1 -1
- package/dist/store/index.js +2 -6
- package/package.json +22 -21
- package/dist/store/configure-logger.d.ts +0 -15
- package/dist/store/configure-logger.d.ts.map +0 -1
- package/dist/store/configure-logger.js +0 -25
- package/dist/store/configure-logger.js.map +0 -1
- package/dist/store/hooks.d.ts +0 -64
- package/dist/store/hooks.d.ts.map +0 -1
- package/dist/store/hooks.js +0 -78
- package/dist/store/hooks.js.map +0 -1
- package/dist/store/session-monitor.d.ts +0 -51
- package/dist/store/session-monitor.d.ts.map +0 -1
- package/dist/store/session-monitor.js +0 -92
- package/dist/store/session-monitor.js.map +0 -1
- package/dist/store/store.d.ts +0 -83
- package/dist/store/store.d.ts.map +0 -1
- package/dist/store/store.js +0 -218
- package/dist/store/store.js.map +0 -1
- package/dist/store/use-heartbeat.d.ts +0 -65
- package/dist/store/use-heartbeat.d.ts.map +0 -1
- package/dist/store/use-heartbeat.js +0 -148
- package/dist/store/use-heartbeat.js.map +0 -1
- package/dist/store/use-session-monitor.d.ts +0 -28
- package/dist/store/use-session-monitor.d.ts.map +0 -1
- package/dist/store/use-session-monitor.js +0 -40
- package/dist/store/use-session-monitor.js.map +0 -1
package/dist/store/store.js
DELETED
|
@@ -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
|
package/dist/store/store.js.map
DELETED
|
@@ -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,GA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,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,65 +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 server-side refresh and return 2xx on success or 401
|
|
8
|
-
* when the refresh token is no longer valid.
|
|
9
|
-
* @default '/api/auth/heartbeat'
|
|
10
|
-
*/
|
|
11
|
-
endpoint?: string;
|
|
12
|
-
/**
|
|
13
|
-
* Interval between heartbeat ticks, in ms.
|
|
14
|
-
* @default 300_000 (5 minutes)
|
|
15
|
-
*/
|
|
16
|
-
intervalMs?: number;
|
|
17
|
-
/**
|
|
18
|
-
* How recently the user must have interacted for a heartbeat to fire.
|
|
19
|
-
* Prevents background tabs from extending sessions indefinitely.
|
|
20
|
-
* @default 120_000 (2 minutes)
|
|
21
|
-
*/
|
|
22
|
-
idleThresholdMs?: number;
|
|
23
|
-
/**
|
|
24
|
-
* Called when the heartbeat endpoint returns 401 — refresh token is gone.
|
|
25
|
-
*/
|
|
26
|
-
onSessionExpired?: () => void;
|
|
27
|
-
/**
|
|
28
|
-
* Called after a successful refresh tick.
|
|
29
|
-
*/
|
|
30
|
-
onRefreshed?: () => void;
|
|
31
|
-
/**
|
|
32
|
-
* Called on transient errors (network failure, 5xx). The hook keeps polling
|
|
33
|
-
* — this is just an observability hook.
|
|
34
|
-
*/
|
|
35
|
-
onError?: (error: Error) => void;
|
|
36
|
-
/**
|
|
37
|
-
* Namespace for the logger.
|
|
38
|
-
* @default 'fides:heartbeat'
|
|
39
|
-
*/
|
|
40
|
-
loggerNamespace?: string;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Activity-driven session keepalive.
|
|
44
|
-
*
|
|
45
|
-
* Polls a server-side refresh endpoint at a fixed interval, but only when the
|
|
46
|
-
* user has actually been active recently. Skips ticks when the tab is hidden,
|
|
47
|
-
* and runs an immediate refresh when the tab regains focus after a long away.
|
|
48
|
-
*
|
|
49
|
-
* Intended to be paired with {@link useSessionMonitor}: the monitor *detects*
|
|
50
|
-
* session loss; this hook *prevents* it for active users.
|
|
51
|
-
*
|
|
52
|
-
* @example
|
|
53
|
-
* ```tsx
|
|
54
|
-
* 'use client';
|
|
55
|
-
* import { useHeartbeat, useSessionMonitor } from '@eventuras/fides-auth-next/store';
|
|
56
|
-
*
|
|
57
|
-
* function AuthProvider({ children }) {
|
|
58
|
-
* useSessionMonitor(authStore, checkAuthStatus);
|
|
59
|
-
* useHeartbeat({ onSessionExpired: () => authStore.send({ type: 'sessionExpired' }) });
|
|
60
|
-
* return <>{children}</>;
|
|
61
|
-
* }
|
|
62
|
-
* ```
|
|
63
|
-
*/
|
|
64
|
-
export declare function useHeartbeat(config?: HeartbeatConfig): void;
|
|
65
|
-
//# 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":"AASA;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;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;AASD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,YAAY,CAAC,MAAM,GAAE,eAAoB,GAAG,IAAI,CAkI/D"}
|
|
@@ -1,148 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
import { Logger } from "@eventuras/logger";
|
|
3
|
-
import { useEffect, useRef } from "react";
|
|
4
|
-
import { createActivityTracker } from "@eventuras/fides-auth/activity-tracker";
|
|
5
|
-
//#region src/store/use-heartbeat.ts
|
|
6
|
-
var DEFAULTS = {
|
|
7
|
-
endpoint: "/api/auth/heartbeat",
|
|
8
|
-
intervalMs: 5 * 6e4,
|
|
9
|
-
idleThresholdMs: 2 * 6e4,
|
|
10
|
-
loggerNamespace: "fides:heartbeat"
|
|
11
|
-
};
|
|
12
|
-
/**
|
|
13
|
-
* Activity-driven session keepalive.
|
|
14
|
-
*
|
|
15
|
-
* Polls a server-side refresh endpoint at a fixed interval, but only when the
|
|
16
|
-
* user has actually been active recently. Skips ticks when the tab is hidden,
|
|
17
|
-
* and runs an immediate refresh when the tab regains focus after a long away.
|
|
18
|
-
*
|
|
19
|
-
* Intended to be paired with {@link useSessionMonitor}: the monitor *detects*
|
|
20
|
-
* session loss; this hook *prevents* it for active users.
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
* ```tsx
|
|
24
|
-
* 'use client';
|
|
25
|
-
* import { useHeartbeat, useSessionMonitor } from '@eventuras/fides-auth-next/store';
|
|
26
|
-
*
|
|
27
|
-
* function AuthProvider({ children }) {
|
|
28
|
-
* useSessionMonitor(authStore, checkAuthStatus);
|
|
29
|
-
* useHeartbeat({ onSessionExpired: () => authStore.send({ type: 'sessionExpired' }) });
|
|
30
|
-
* return <>{children}</>;
|
|
31
|
-
* }
|
|
32
|
-
* ```
|
|
33
|
-
*/
|
|
34
|
-
function useHeartbeat(config = {}) {
|
|
35
|
-
const endpoint = config.endpoint ?? DEFAULTS.endpoint;
|
|
36
|
-
const intervalMs = config.intervalMs ?? DEFAULTS.intervalMs;
|
|
37
|
-
const idleThresholdMs = config.idleThresholdMs ?? DEFAULTS.idleThresholdMs;
|
|
38
|
-
const loggerNamespace = config.loggerNamespace ?? DEFAULTS.loggerNamespace;
|
|
39
|
-
const callbacksRef = useRef({
|
|
40
|
-
onSessionExpired: config.onSessionExpired,
|
|
41
|
-
onRefreshed: config.onRefreshed,
|
|
42
|
-
onError: config.onError
|
|
43
|
-
});
|
|
44
|
-
callbacksRef.current = {
|
|
45
|
-
onSessionExpired: config.onSessionExpired,
|
|
46
|
-
onRefreshed: config.onRefreshed,
|
|
47
|
-
onError: config.onError
|
|
48
|
-
};
|
|
49
|
-
useEffect(() => {
|
|
50
|
-
if (typeof window === "undefined") return;
|
|
51
|
-
const logger = Logger.create({
|
|
52
|
-
namespace: loggerNamespace,
|
|
53
|
-
context: { component: "Heartbeat" }
|
|
54
|
-
});
|
|
55
|
-
const tracker = createActivityTracker();
|
|
56
|
-
const abortController = new AbortController();
|
|
57
|
-
let timeoutId = null;
|
|
58
|
-
let lastTickAt = Date.now();
|
|
59
|
-
let stopped = false;
|
|
60
|
-
const teardown = () => {
|
|
61
|
-
if (stopped) return;
|
|
62
|
-
stopped = true;
|
|
63
|
-
if (timeoutId) {
|
|
64
|
-
clearTimeout(timeoutId);
|
|
65
|
-
timeoutId = null;
|
|
66
|
-
}
|
|
67
|
-
abortController.abort();
|
|
68
|
-
document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
69
|
-
tracker.dispose();
|
|
70
|
-
};
|
|
71
|
-
const sendBeat = async () => {
|
|
72
|
-
if (stopped) return;
|
|
73
|
-
if (document.visibilityState === "hidden") {
|
|
74
|
-
logger.debug("Tab hidden, skipping heartbeat");
|
|
75
|
-
return;
|
|
76
|
-
}
|
|
77
|
-
if (!tracker.isActiveWithin(idleThresholdMs)) {
|
|
78
|
-
logger.debug({ idleThresholdMs }, "No recent activity, skipping heartbeat");
|
|
79
|
-
return;
|
|
80
|
-
}
|
|
81
|
-
lastTickAt = Date.now();
|
|
82
|
-
try {
|
|
83
|
-
const response = await fetch(endpoint, {
|
|
84
|
-
method: "POST",
|
|
85
|
-
credentials: "same-origin",
|
|
86
|
-
headers: { "content-type": "application/json" },
|
|
87
|
-
signal: abortController.signal
|
|
88
|
-
});
|
|
89
|
-
if (stopped) return;
|
|
90
|
-
if (response.status === 401) {
|
|
91
|
-
logger.info("Heartbeat returned 401 — session expired");
|
|
92
|
-
callbacksRef.current.onSessionExpired?.();
|
|
93
|
-
teardown();
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
if (!response.ok) throw new Error(`Heartbeat failed with status ${response.status}`);
|
|
97
|
-
logger.debug("Heartbeat refresh succeeded");
|
|
98
|
-
callbacksRef.current.onRefreshed?.();
|
|
99
|
-
} catch (error) {
|
|
100
|
-
if (stopped) return;
|
|
101
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
102
|
-
logger.warn({ error: err.message }, "Heartbeat tick failed");
|
|
103
|
-
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);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
document.addEventListener("visibilitychange", onVisibilityChange);
|
|
128
|
-
scheduleNext();
|
|
129
|
-
logger.debug({
|
|
130
|
-
intervalMs,
|
|
131
|
-
idleThresholdMs,
|
|
132
|
-
endpoint
|
|
133
|
-
}, "Heartbeat started");
|
|
134
|
-
return () => {
|
|
135
|
-
teardown();
|
|
136
|
-
logger.debug("Heartbeat stopped");
|
|
137
|
-
};
|
|
138
|
-
}, [
|
|
139
|
-
endpoint,
|
|
140
|
-
intervalMs,
|
|
141
|
-
idleThresholdMs,
|
|
142
|
-
loggerNamespace
|
|
143
|
-
]);
|
|
144
|
-
}
|
|
145
|
-
//#endregion
|
|
146
|
-
export { useHeartbeat };
|
|
147
|
-
|
|
148
|
-
//# 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 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,MAAM,WAAW,OAAO,YAAY,SAAS;CAC7C,MAAM,aAAa,OAAO,cAAc,SAAS;CACjD,MAAM,kBAAkB,OAAO,mBAAmB,SAAS;CAC3D,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,SAAS,OAAO,OAAO;GAC3B,WAAW;GACX,SAAS,EAAE,WAAW,YAAY;EACpC,CAAC;EAED,MAAM,UAA2B,sBAAsB;EACvD,MAAM,kBAAkB,IAAI,gBAAgB;EAC5C,IAAI,YAAkD;EACtD,IAAI,aAAa,KAAK,IAAI;EAC1B,IAAI,UAAU;EAEd,MAAM,iBAAuB;GAC3B,IAAI,SAAS;GACb,UAAU;GACV,IAAI,WAAW;IACb,aAAa,SAAS;IACtB,YAAY;GACd;GACA,gBAAgB,MAAM;GACtB,SAAS,oBAAoB,oBAAoB,kBAAkB;GACnE,QAAQ,QAAQ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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,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"}
|