@iblai/web-utils 1.8.1 → 1.9.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 (27) hide show
  1. package/dist/auth/index.d.ts +202 -0
  2. package/dist/auth/index.esm.js +363 -0
  3. package/dist/auth/index.esm.js.map +1 -0
  4. package/dist/auth/index.js +379 -0
  5. package/dist/auth/index.js.map +1 -0
  6. package/dist/auth/web-utils/src/utils/auth.d.ts +199 -0
  7. package/dist/auth/web-utils/tests/hooks/chat/use-mentor-tools.test.d.ts +1 -0
  8. package/dist/auth/web-utils/tests/hooks/subscription/class-subscription-flow.test.d.ts +1 -0
  9. package/dist/auth/web-utils/tests/hooks/subscription/constants.test.d.ts +1 -0
  10. package/dist/auth/web-utils/tests/hooks/subscription/use-subscription-handler.test.d.ts +1 -0
  11. package/dist/auth/web-utils/tests/hooks/subscription-v2/use-subscription-handler.test.d.ts +1 -0
  12. package/dist/auth/web-utils/tests/hooks/use-day-js.test.d.ts +1 -0
  13. package/dist/auth/web-utils/tests/hooks/use-mentor-settings.test.d.ts +1 -0
  14. package/dist/auth/web-utils/tests/providers/mentor-provider.test.d.ts +1 -0
  15. package/dist/auth/web-utils/tests/providers/tenant-provider.test.d.ts +1 -0
  16. package/dist/auth/web-utils/tests/setupTests.d.ts +5 -0
  17. package/dist/auth/web-utils/tests/utils/helpers.test.d.ts +1 -0
  18. package/dist/data-layer/src/features/core/api-slice.d.ts +110 -109
  19. package/dist/index.d.ts +10 -5
  20. package/dist/index.esm.js +31 -4
  21. package/dist/index.esm.js.map +1 -1
  22. package/dist/index.js +31 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/package.json +6 -1
  25. package/dist/web-utils/src/providers/auth-provider.d.ts +3 -3
  26. package/dist/web-utils/src/utils/constants.d.ts +5 -0
  27. package/package.json +6 -1
@@ -0,0 +1,379 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Authentication and Authorization Utilities
5
+ *
6
+ * This module provides utility functions for handling authentication flows,
7
+ * including redirects to auth SPA, cookie management, and session handling.
8
+ */
9
+ /**
10
+ * Check if the current window is inside an iframe
11
+ * @returns {boolean} True if running in an iframe, false otherwise
12
+ */
13
+ function isInIframe() {
14
+ if (typeof window === "undefined") {
15
+ return false;
16
+ }
17
+ return (window === null || window === void 0 ? void 0 : window.self) !== (window === null || window === void 0 ? void 0 : window.top);
18
+ }
19
+ /**
20
+ * Send a message to the parent website (when in iframe)
21
+ * @param payload - The data to send to parent window
22
+ */
23
+ function sendMessageToParentWebsite(payload) {
24
+ window.parent.postMessage(payload, "*");
25
+ }
26
+ /**
27
+ * Delete a cookie with specific name, path, and domain
28
+ * @param name - Cookie name
29
+ * @param path - Cookie path
30
+ * @param domain - Cookie domain
31
+ */
32
+ function deleteCookie(name, path, domain) {
33
+ const expires = "expires=Thu, 01 Jan 1970 00:00:00 UTC;";
34
+ const cookieValue = `${name}=;`;
35
+ const pathValue = path ? `path=${path};` : "";
36
+ const domainValue = domain ? `domain=${domain};` : "";
37
+ document.cookie = cookieValue + expires + pathValue + domainValue;
38
+ }
39
+ /**
40
+ * Get all possible domain parts for cookie deletion
41
+ * @param domain - The domain to split
42
+ * @returns Array of domain parts
43
+ * @example
44
+ * getDomainParts('app.example.com') // returns ['app.example.com', 'example.com', 'com']
45
+ */
46
+ function getDomainParts(domain) {
47
+ const parts = domain.split(".");
48
+ const domains = [];
49
+ for (let i = parts.length - 1; i >= 0; i--) {
50
+ domains.push(parts.slice(i).join("."));
51
+ }
52
+ return domains;
53
+ }
54
+ /**
55
+ * Delete a cookie across all possible domain variations
56
+ * @param name - Cookie name to delete
57
+ * @param childDomain - The current domain
58
+ */
59
+ function deleteCookieOnAllDomains(name, childDomain) {
60
+ getDomainParts(childDomain).forEach((domainPart) => {
61
+ deleteCookie(name, "/", domainPart);
62
+ deleteCookie(name, "", domainPart);
63
+ });
64
+ }
65
+ /**
66
+ * Get the parent domain from a given domain
67
+ * @param domain - The domain to process
68
+ * @returns The parent domain (e.g., 'app.example.com' → '.example.com')
69
+ */
70
+ function getParentDomain(domain) {
71
+ if (!domain) {
72
+ return "";
73
+ }
74
+ const parts = domain.split(".");
75
+ return parts.length > 1 ? `.${parts.slice(-2).join(".")}` : domain;
76
+ }
77
+ /**
78
+ * Set a cookie for authentication with cross-domain support
79
+ * @param name - Cookie name
80
+ * @param value - Cookie value
81
+ * @param days - Number of days until expiration (default: 365)
82
+ */
83
+ function setCookieForAuth(name, value, days = 365) {
84
+ const expires = new Date();
85
+ expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
86
+ const hostname = window.location.hostname;
87
+ let baseDomain = hostname;
88
+ // Calculate base domain (skip for localhost and IP addresses)
89
+ if (hostname !== "localhost" && !/^\d+\.\d+\.\d+\.\d+$/.test(hostname)) {
90
+ const parts = hostname.split(".");
91
+ if (parts.length > 2) {
92
+ baseDomain = `.${parts.slice(-2).join(".")}`;
93
+ }
94
+ }
95
+ const domainAttr = baseDomain ? `;domain=${baseDomain}` : "";
96
+ document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/;SameSite=None;Secure${domainAttr}`;
97
+ }
98
+ /**
99
+ * Clear all cookies for the current domain
100
+ */
101
+ function clearCookies() {
102
+ const cookies = document.cookie.split(";");
103
+ for (let i = 0; i < cookies.length; i++) {
104
+ const cookie = cookies[i];
105
+ const eqPos = cookie.indexOf("=");
106
+ const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
107
+ deleteCookieOnAllDomains(name, window.location.hostname);
108
+ document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;Domain=${getParentDomain(window.location.hostname)}`;
109
+ }
110
+ }
111
+ /**
112
+ * Get the value of a cookie by name
113
+ * @param name - Cookie name
114
+ * @returns The cookie value or null if not found
115
+ */
116
+ function getCookieValue(name) {
117
+ const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
118
+ return match ? decodeURIComponent(match[1]) : null;
119
+ }
120
+ /**
121
+ * Check if user is currently logged in
122
+ * @param tokenKey - The localStorage key for the auth token (default: 'axd_token')
123
+ * @returns True if logged in, false otherwise
124
+ */
125
+ function isLoggedIn(tokenKey = "axd_token") {
126
+ return !!localStorage.getItem(tokenKey);
127
+ }
128
+ /**
129
+ * Extract platform/tenant key from URL
130
+ * @param url - The URL to parse
131
+ * @param pattern - RegExp pattern to match platform key (default matches /platform/[key]/...)
132
+ * @returns The platform key or null if not found
133
+ */
134
+ function getPlatformKey(url, pattern = /\/platform\/([^/]+)/) {
135
+ const match = url.match(pattern);
136
+ return match ? match[1] : null;
137
+ }
138
+ /**
139
+ * Redirect to authentication SPA for login/logout
140
+ *
141
+ * This function handles the complete authentication flow:
142
+ * - Clears localStorage and cookies on logout
143
+ * - Saves redirect path for post-auth return
144
+ * - Handles iframe scenarios
145
+ * - Syncs logout across multiple SPAs via cookies
146
+ *
147
+ * @param options - Configuration options for the redirect
148
+ *
149
+ * @example
150
+ * ```tsx
151
+ * // Basic usage
152
+ * redirectToAuthSpa({
153
+ * authUrl: 'https://auth.example.com',
154
+ * appName: 'mentor',
155
+ * });
156
+ *
157
+ * // With logout
158
+ * redirectToAuthSpa({
159
+ * authUrl: 'https://auth.example.com',
160
+ * appName: 'mentor',
161
+ * logout: true,
162
+ * platformKey: 'my-tenant',
163
+ * });
164
+ *
165
+ * // With custom redirect
166
+ * redirectToAuthSpa({
167
+ * authUrl: 'https://auth.example.com',
168
+ * appName: 'mentor',
169
+ * redirectTo: '/dashboard',
170
+ * platformKey: 'my-tenant',
171
+ * });
172
+ * ```
173
+ */
174
+ async function redirectToAuthSpa(options) {
175
+ const { redirectTo, platformKey, logout = false, saveRedirect = true, authUrl, appName, queryParams = {
176
+ app: "app",
177
+ redirectTo: "redirect-to",
178
+ tenant: "tenant",
179
+ }, redirectPathStorageKey = "redirect_to", cookieNames = {
180
+ currentTenant: "ibl_current_tenant",
181
+ userData: "ibl_user_data",
182
+ tenant: "ibl_tenant",
183
+ logoutTimestamp: "ibl_logout_timestamp",
184
+ loginTimestamp: "ibl_login_timestamp",
185
+ tenantSwitching: "ibl_tenant_switching",
186
+ }, hasNonExpiredAuthToken, isOffline, preserveTokenKey, authRedirectProxy, isNativeApp, forceRedirect = false, } = options;
187
+ console.log("[redirectToAuthSpa] starting redirect to auth spa", redirectTo, platformKey, logout, saveRedirect, forceRedirect);
188
+ // Skip if a tenant switch is already in progress
189
+ if (!forceRedirect &&
190
+ cookieNames.tenantSwitching &&
191
+ document.cookie.includes(cookieNames.tenantSwitching)) {
192
+ console.log("[redirectToAuthSpa] Tenant switch in progress, skipping redirect");
193
+ return;
194
+ }
195
+ // Skip if a login occurred after the last logout (login takes precedence)
196
+ // but only if this app actually has a valid auth token
197
+ if (!forceRedirect &&
198
+ hasNonExpiredAuthToken &&
199
+ cookieNames.loginTimestamp &&
200
+ cookieNames.logoutTimestamp) {
201
+ const loginTs = getCookieValue(cookieNames.loginTimestamp);
202
+ const logoutTs = getCookieValue(cookieNames.logoutTimestamp);
203
+ const hasValidToken = hasNonExpiredAuthToken();
204
+ console.log("[redirectToAuthSpa] Login/logout timestamp check", {
205
+ loginTs,
206
+ logoutTs,
207
+ hasValidToken,
208
+ loginAhead: loginTs && logoutTs ? Number(loginTs) > Number(logoutTs) : false,
209
+ });
210
+ if (!forceRedirect &&
211
+ hasValidToken &&
212
+ loginTs &&
213
+ logoutTs &&
214
+ Number(loginTs) > Number(logoutTs)) {
215
+ console.log("[redirectToAuthSpa] Login timestamp is ahead of logout timestamp, skipping redirect", { loginTs, logoutTs });
216
+ return;
217
+ }
218
+ }
219
+ // Skip redirect in offline mode
220
+ if (isOffline === null || isOffline === void 0 ? void 0 : isOffline()) {
221
+ console.log("[redirectToAuthSpa] Skipping redirect - offline mode");
222
+ return;
223
+ }
224
+ // Preserve a token before clearing localStorage if requested
225
+ const preservedToken = preserveTokenKey
226
+ ? window.localStorage.getItem(preserveTokenKey)
227
+ : null;
228
+ console.log("[redirectToAuthSpa] clearing local storage");
229
+ localStorage.clear();
230
+ if (logout || isInIframe()) {
231
+ // Delete authentication cookies for cross-SPA synchronization
232
+ const currentDomain = window.location.hostname;
233
+ if (cookieNames.currentTenant) {
234
+ deleteCookieOnAllDomains(cookieNames.currentTenant, currentDomain);
235
+ }
236
+ if (cookieNames.userData) {
237
+ deleteCookieOnAllDomains(cookieNames.userData, currentDomain);
238
+ }
239
+ if (cookieNames.tenant) {
240
+ deleteCookieOnAllDomains(cookieNames.tenant, currentDomain);
241
+ }
242
+ // Set logout timestamp cookie to trigger logout on other SPAs
243
+ if (cookieNames.logoutTimestamp && !isInIframe()) {
244
+ setCookieForAuth(cookieNames.logoutTimestamp, Date.now().toString());
245
+ }
246
+ }
247
+ // Handle iframe scenario
248
+ if (isInIframe()) {
249
+ console.log("[redirectToAuthSpa]: sending authExpired to parent");
250
+ sendMessageToParentWebsite({ authExpired: true });
251
+ return;
252
+ }
253
+ const redirectPath = redirectTo !== null && redirectTo !== void 0 ? redirectTo : `${window.location.pathname}${window.location.search}`;
254
+ // Never save sso-login routes as redirect paths
255
+ if (!redirectPath.startsWith("/sso-login") &&
256
+ !redirectPath.startsWith("/sso-login-complete") &&
257
+ saveRedirect) {
258
+ window.localStorage.setItem(redirectPathStorageKey, redirectPath);
259
+ }
260
+ const platform = platformKey !== null && platformKey !== void 0 ? platformKey : getPlatformKey(redirectPath);
261
+ const redirectToUrl = `${window.location.origin}`;
262
+ let authRedirectUrl = `${authUrl}/login?${queryParams.app}=${appName}`;
263
+ authRedirectUrl += `&${queryParams.redirectTo}=${redirectToUrl}`;
264
+ if (platform) {
265
+ authRedirectUrl += `&${queryParams.tenant}=${platform}`;
266
+ }
267
+ if (logout) {
268
+ authRedirectUrl += "&logout=1";
269
+ }
270
+ // Small delay for any pending operations
271
+ await new Promise((resolve) => setTimeout(resolve, 100));
272
+ if (isNativeApp === null || isNativeApp === void 0 ? void 0 : isNativeApp()) {
273
+ // On native apps (e.g., Tauri), pass preserved token and navigate directly
274
+ if (preservedToken && preserveTokenKey) {
275
+ authRedirectUrl += `&token=${encodeURIComponent(preservedToken)}`;
276
+ console.log("[redirectToAuthSpa] Added preserved token to auth URL");
277
+ }
278
+ console.log("[redirectToAuthSpa] Native app, navigating to auth URL:", authRedirectUrl);
279
+ window.location.href = authRedirectUrl;
280
+ }
281
+ else if (authRedirectProxy) {
282
+ // Use auth redirect proxy endpoint
283
+ window.location.href = `${authRedirectProxy}?to=${encodeURIComponent(authRedirectUrl)}`;
284
+ }
285
+ else {
286
+ window.location.href = authRedirectUrl;
287
+ }
288
+ }
289
+ /**
290
+ * Get the URL for joining a tenant (sign up flow)
291
+ * @param authUrl - Auth SPA base URL
292
+ * @param tenantKey - Tenant to join
293
+ * @param redirectUrl - URL to redirect to after joining (defaults to current URL)
294
+ * @returns The join URL
295
+ */
296
+ function getAuthSpaJoinUrl(authUrl, tenantKey, redirectUrl) {
297
+ const resolvedTenant = tenantKey || getPlatformKey(window.location.pathname) || "";
298
+ if (!resolvedTenant) {
299
+ return "";
300
+ }
301
+ const targetUrl = redirectUrl !== null && redirectUrl !== void 0 ? redirectUrl : window.location.href;
302
+ const joinUrl = `${authUrl}/join?tenant=${encodeURIComponent(resolvedTenant)}&redirect-to=${encodeURIComponent(targetUrl)}`;
303
+ return joinUrl;
304
+ }
305
+ /**
306
+ * Redirect to auth SPA's join/signup page for a specific tenant
307
+ * @param authUrl - Auth SPA base URL
308
+ * @param tenantKey - Tenant to join
309
+ * @param redirectUrl - URL to redirect to after joining (defaults to current URL)
310
+ */
311
+ function redirectToAuthSpaJoinTenant(authUrl, tenantKey, redirectUrl) {
312
+ const resolvedTenant = tenantKey || getPlatformKey(window.location.pathname) || "";
313
+ if (!resolvedTenant) {
314
+ console.log("[auth-redirect] Missing tenant key for join", {
315
+ tenantKey,
316
+ redirectUrl,
317
+ });
318
+ redirectToAuthSpa({
319
+ authUrl,
320
+ appName: "app", // Will need to be configured
321
+ redirectTo: redirectUrl,
322
+ });
323
+ return;
324
+ }
325
+ const targetUrl = redirectUrl !== null && redirectUrl !== void 0 ? redirectUrl : window.location.href;
326
+ const joinUrl = `${authUrl}/join?tenant=${encodeURIComponent(resolvedTenant)}&redirect-to=${encodeURIComponent(targetUrl)}`;
327
+ window.location.href = joinUrl;
328
+ }
329
+ /**
330
+ * Handle user logout
331
+ *
332
+ * This function:
333
+ * - Clears localStorage (preserving tenant)
334
+ * - Sets logout timestamp cookie for cross-SPA sync
335
+ * - Clears all cookies
336
+ * - Redirects to auth SPA logout endpoint
337
+ *
338
+ * @param options - Logout configuration options
339
+ *
340
+ * @example
341
+ * ```tsx
342
+ * handleLogout({
343
+ * authUrl: 'https://auth.example.com',
344
+ * redirectUrl: 'https://app.example.com',
345
+ * });
346
+ * ```
347
+ */
348
+ function handleLogout(options) {
349
+ const { redirectUrl = window.location.origin, authUrl, tenantStorageKey = "tenant", logoutTimestampCookie = "ibl_logout_timestamp", callback, } = options;
350
+ const tenant = window.localStorage.getItem(tenantStorageKey);
351
+ window.localStorage.clear();
352
+ if (tenant) {
353
+ window.localStorage.setItem(tenantStorageKey, tenant);
354
+ }
355
+ // Set logout timestamp cookie to trigger logout on other SPAs
356
+ setCookieForAuth(logoutTimestampCookie, Date.now().toString());
357
+ clearCookies();
358
+ callback === null || callback === void 0 ? void 0 : callback();
359
+ if (!isInIframe()) {
360
+ window.location.href = `${authUrl}/logout?redirect-to=${redirectUrl}${tenant ? "&tenant=" + tenant : ""}`;
361
+ }
362
+ }
363
+
364
+ exports.clearCookies = clearCookies;
365
+ exports.deleteCookie = deleteCookie;
366
+ exports.deleteCookieOnAllDomains = deleteCookieOnAllDomains;
367
+ exports.getAuthSpaJoinUrl = getAuthSpaJoinUrl;
368
+ exports.getCookieValue = getCookieValue;
369
+ exports.getDomainParts = getDomainParts;
370
+ exports.getParentDomain = getParentDomain;
371
+ exports.getPlatformKey = getPlatformKey;
372
+ exports.handleLogout = handleLogout;
373
+ exports.isInIframe = isInIframe;
374
+ exports.isLoggedIn = isLoggedIn;
375
+ exports.redirectToAuthSpa = redirectToAuthSpa;
376
+ exports.redirectToAuthSpaJoinTenant = redirectToAuthSpaJoinTenant;
377
+ exports.sendMessageToParentWebsite = sendMessageToParentWebsite;
378
+ exports.setCookieForAuth = setCookieForAuth;
379
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/utils/auth.ts"],"sourcesContent":["/**\n * Authentication and Authorization Utilities\n *\n * This module provides utility functions for handling authentication flows,\n * including redirects to auth SPA, cookie management, and session handling.\n */\n\n/**\n * Check if the current window is inside an iframe\n * @returns {boolean} True if running in an iframe, false otherwise\n */\nexport function isInIframe(): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n return window?.self !== window?.top;\n}\n\n/**\n * Send a message to the parent website (when in iframe)\n * @param payload - The data to send to parent window\n */\nexport function sendMessageToParentWebsite(payload: unknown): void {\n window.parent.postMessage(payload, \"*\");\n}\n\n/**\n * Delete a cookie with specific name, path, and domain\n * @param name - Cookie name\n * @param path - Cookie path\n * @param domain - Cookie domain\n */\nexport function deleteCookie(name: string, path: string, domain: string): void {\n const expires = \"expires=Thu, 01 Jan 1970 00:00:00 UTC;\";\n const cookieValue = `${name}=;`;\n const pathValue = path ? `path=${path};` : \"\";\n const domainValue = domain ? `domain=${domain};` : \"\";\n document.cookie = cookieValue + expires + pathValue + domainValue;\n}\n\n/**\n * Get all possible domain parts for cookie deletion\n * @param domain - The domain to split\n * @returns Array of domain parts\n * @example\n * getDomainParts('app.example.com') // returns ['app.example.com', 'example.com', 'com']\n */\nexport function getDomainParts(domain: string): string[] {\n const parts = domain.split(\".\");\n const domains: string[] = [];\n for (let i = parts.length - 1; i >= 0; i--) {\n domains.push(parts.slice(i).join(\".\"));\n }\n return domains;\n}\n\n/**\n * Delete a cookie across all possible domain variations\n * @param name - Cookie name to delete\n * @param childDomain - The current domain\n */\nexport function deleteCookieOnAllDomains(\n name: string,\n childDomain: string,\n): void {\n getDomainParts(childDomain).forEach((domainPart) => {\n deleteCookie(name, \"/\", domainPart);\n deleteCookie(name, \"\", domainPart);\n });\n}\n\n/**\n * Get the parent domain from a given domain\n * @param domain - The domain to process\n * @returns The parent domain (e.g., 'app.example.com' → '.example.com')\n */\nexport function getParentDomain(domain?: string): string {\n if (!domain) {\n return \"\";\n }\n const parts = domain.split(\".\");\n return parts.length > 1 ? `.${parts.slice(-2).join(\".\")}` : domain;\n}\n\n/**\n * Set a cookie for authentication with cross-domain support\n * @param name - Cookie name\n * @param value - Cookie value\n * @param days - Number of days until expiration (default: 365)\n */\nexport function setCookieForAuth(\n name: string,\n value: string,\n days: number = 365,\n): void {\n const expires = new Date();\n expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);\n\n const hostname = window.location.hostname;\n let baseDomain = hostname;\n\n // Calculate base domain (skip for localhost and IP addresses)\n if (hostname !== \"localhost\" && !/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(hostname)) {\n const parts = hostname.split(\".\");\n if (parts.length > 2) {\n baseDomain = `.${parts.slice(-2).join(\".\")}`;\n }\n }\n\n const domainAttr = baseDomain ? `;domain=${baseDomain}` : \"\";\n document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/;SameSite=None;Secure${domainAttr}`;\n}\n\n/**\n * Clear all cookies for the current domain\n */\nexport function clearCookies(): void {\n const cookies = document.cookie.split(\";\");\n for (let i = 0; i < cookies.length; i++) {\n const cookie = cookies[i];\n const eqPos = cookie.indexOf(\"=\");\n const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;\n deleteCookieOnAllDomains(name, window.location.hostname);\n document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;Domain=${getParentDomain(\n window.location.hostname,\n )}`;\n }\n}\n\n/**\n * Get the value of a cookie by name\n * @param name - Cookie name\n * @returns The cookie value or null if not found\n */\nexport function getCookieValue(name: string): string | null {\n const match = document.cookie.match(new RegExp(`(?:^|;\\\\s*)${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]) : null;\n}\n\n/**\n * Check if user is currently logged in\n * @param tokenKey - The localStorage key for the auth token (default: 'axd_token')\n * @returns True if logged in, false otherwise\n */\nexport function isLoggedIn(tokenKey: string = \"axd_token\"): boolean {\n return !!localStorage.getItem(tokenKey);\n}\n\n/**\n * Extract platform/tenant key from URL\n * @param url - The URL to parse\n * @param pattern - RegExp pattern to match platform key (default matches /platform/[key]/...)\n * @returns The platform key or null if not found\n */\nexport function getPlatformKey(\n url: string,\n pattern: RegExp = /\\/platform\\/([^/]+)/,\n): string | null {\n const match = url.match(pattern);\n return match ? match[1] : null;\n}\n\nexport interface RedirectToAuthSpaOptions {\n /** URL to redirect to after auth (defaults to current path + search) */\n redirectTo?: string;\n /** Platform/tenant key */\n platformKey?: string;\n /** Whether this is a logout action */\n logout?: boolean;\n /** Whether to save redirect path to localStorage (default: true) */\n saveRedirect?: boolean;\n /** Auth SPA base URL */\n authUrl: string;\n /** Current app/platform identifier (e.g., 'mentor', 'skills') */\n appName: string;\n /** Query param names */\n queryParams?: {\n app?: string;\n redirectTo?: string;\n tenant?: string;\n };\n /** localStorage key for saving redirect path */\n redirectPathStorageKey?: string;\n /** Cookie names for cross-SPA sync */\n cookieNames?: {\n currentTenant?: string;\n userData?: string;\n tenant?: string;\n logoutTimestamp?: string;\n loginTimestamp?: string;\n tenantSwitching?: string;\n };\n /** Function to check if auth token is valid and non-expired. Used to skip redirect when a recent login occurred. */\n hasNonExpiredAuthToken?: () => boolean;\n /** Function to check if the app is in offline mode (e.g., Tauri offline). Skips redirect when true. */\n isOffline?: () => boolean;\n /** localStorage key for a token to preserve before clearing storage (e.g., 'edx_jwt_token') */\n preserveTokenKey?: string;\n /** Path to an auth redirect proxy endpoint (e.g., '/api/auth-redirect'). When set, redirects via this proxy in browser. */\n authRedirectProxy?: string;\n /** Function to check if the app is running as a native app (e.g., Tauri). Affects redirect behavior. */\n isNativeApp?: () => boolean;\n forceRedirect?: boolean;\n}\n\n/**\n * Redirect to authentication SPA for login/logout\n *\n * This function handles the complete authentication flow:\n * - Clears localStorage and cookies on logout\n * - Saves redirect path for post-auth return\n * - Handles iframe scenarios\n * - Syncs logout across multiple SPAs via cookies\n *\n * @param options - Configuration options for the redirect\n *\n * @example\n * ```tsx\n * // Basic usage\n * redirectToAuthSpa({\n * authUrl: 'https://auth.example.com',\n * appName: 'mentor',\n * });\n *\n * // With logout\n * redirectToAuthSpa({\n * authUrl: 'https://auth.example.com',\n * appName: 'mentor',\n * logout: true,\n * platformKey: 'my-tenant',\n * });\n *\n * // With custom redirect\n * redirectToAuthSpa({\n * authUrl: 'https://auth.example.com',\n * appName: 'mentor',\n * redirectTo: '/dashboard',\n * platformKey: 'my-tenant',\n * });\n * ```\n */\nexport async function redirectToAuthSpa(\n options: RedirectToAuthSpaOptions,\n): Promise<void> {\n const {\n redirectTo,\n platformKey,\n logout = false,\n saveRedirect = true,\n authUrl,\n appName,\n queryParams = {\n app: \"app\",\n redirectTo: \"redirect-to\",\n tenant: \"tenant\",\n },\n redirectPathStorageKey = \"redirect_to\",\n cookieNames = {\n currentTenant: \"ibl_current_tenant\",\n userData: \"ibl_user_data\",\n tenant: \"ibl_tenant\",\n logoutTimestamp: \"ibl_logout_timestamp\",\n loginTimestamp: \"ibl_login_timestamp\",\n tenantSwitching: \"ibl_tenant_switching\",\n },\n hasNonExpiredAuthToken,\n isOffline,\n preserveTokenKey,\n authRedirectProxy,\n isNativeApp,\n forceRedirect = false,\n } = options;\n\n console.log(\n \"[redirectToAuthSpa] starting redirect to auth spa\",\n redirectTo,\n platformKey,\n logout,\n saveRedirect,\n forceRedirect,\n );\n\n // Skip if a tenant switch is already in progress\n if (\n !forceRedirect &&\n cookieNames.tenantSwitching &&\n document.cookie.includes(cookieNames.tenantSwitching)\n ) {\n console.log(\n \"[redirectToAuthSpa] Tenant switch in progress, skipping redirect\",\n );\n return;\n }\n\n // Skip if a login occurred after the last logout (login takes precedence)\n // but only if this app actually has a valid auth token\n if (\n !forceRedirect &&\n hasNonExpiredAuthToken &&\n cookieNames.loginTimestamp &&\n cookieNames.logoutTimestamp\n ) {\n const loginTs = getCookieValue(cookieNames.loginTimestamp);\n const logoutTs = getCookieValue(cookieNames.logoutTimestamp);\n const hasValidToken = hasNonExpiredAuthToken();\n console.log(\"[redirectToAuthSpa] Login/logout timestamp check\", {\n loginTs,\n logoutTs,\n hasValidToken,\n loginAhead:\n loginTs && logoutTs ? Number(loginTs) > Number(logoutTs) : false,\n });\n if (\n !forceRedirect &&\n hasValidToken &&\n loginTs &&\n logoutTs &&\n Number(loginTs) > Number(logoutTs)\n ) {\n console.log(\n \"[redirectToAuthSpa] Login timestamp is ahead of logout timestamp, skipping redirect\",\n { loginTs, logoutTs },\n );\n return;\n }\n }\n\n // Skip redirect in offline mode\n if (isOffline?.()) {\n console.log(\"[redirectToAuthSpa] Skipping redirect - offline mode\");\n return;\n }\n\n // Preserve a token before clearing localStorage if requested\n const preservedToken = preserveTokenKey\n ? window.localStorage.getItem(preserveTokenKey)\n : null;\n\n console.log(\"[redirectToAuthSpa] clearing local storage\");\n localStorage.clear();\n\n if (logout || isInIframe()) {\n // Delete authentication cookies for cross-SPA synchronization\n const currentDomain = window.location.hostname;\n if (cookieNames.currentTenant) {\n deleteCookieOnAllDomains(cookieNames.currentTenant, currentDomain);\n }\n if (cookieNames.userData) {\n deleteCookieOnAllDomains(cookieNames.userData, currentDomain);\n }\n if (cookieNames.tenant) {\n deleteCookieOnAllDomains(cookieNames.tenant, currentDomain);\n }\n\n // Set logout timestamp cookie to trigger logout on other SPAs\n if (cookieNames.logoutTimestamp && !isInIframe()) {\n setCookieForAuth(cookieNames.logoutTimestamp, Date.now().toString());\n }\n }\n\n // Handle iframe scenario\n if (isInIframe()) {\n console.log(\"[redirectToAuthSpa]: sending authExpired to parent\");\n sendMessageToParentWebsite({ authExpired: true });\n return;\n }\n\n const redirectPath =\n redirectTo ?? `${window.location.pathname}${window.location.search}`;\n\n // Never save sso-login routes as redirect paths\n if (\n !redirectPath.startsWith(\"/sso-login\") &&\n !redirectPath.startsWith(\"/sso-login-complete\") &&\n saveRedirect\n ) {\n window.localStorage.setItem(redirectPathStorageKey, redirectPath);\n }\n\n const platform = platformKey ?? getPlatformKey(redirectPath);\n\n const redirectToUrl = `${window.location.origin}`;\n\n let authRedirectUrl = `${authUrl}/login?${queryParams.app}=${appName}`;\n\n authRedirectUrl += `&${queryParams.redirectTo}=${redirectToUrl}`;\n\n if (platform) {\n authRedirectUrl += `&${queryParams.tenant}=${platform}`;\n }\n if (logout) {\n authRedirectUrl += \"&logout=1\";\n }\n\n // Small delay for any pending operations\n await new Promise((resolve) => setTimeout(resolve, 100));\n\n if (isNativeApp?.()) {\n // On native apps (e.g., Tauri), pass preserved token and navigate directly\n if (preservedToken && preserveTokenKey) {\n authRedirectUrl += `&token=${encodeURIComponent(preservedToken)}`;\n console.log(\"[redirectToAuthSpa] Added preserved token to auth URL\");\n }\n console.log(\n \"[redirectToAuthSpa] Native app, navigating to auth URL:\",\n authRedirectUrl,\n );\n window.location.href = authRedirectUrl;\n } else if (authRedirectProxy) {\n // Use auth redirect proxy endpoint\n window.location.href = `${authRedirectProxy}?to=${encodeURIComponent(authRedirectUrl)}`;\n } else {\n window.location.href = authRedirectUrl;\n }\n}\n\n/**\n * Get the URL for joining a tenant (sign up flow)\n * @param authUrl - Auth SPA base URL\n * @param tenantKey - Tenant to join\n * @param redirectUrl - URL to redirect to after joining (defaults to current URL)\n * @returns The join URL\n */\nexport function getAuthSpaJoinUrl(\n authUrl: string,\n tenantKey?: string,\n redirectUrl?: string,\n): string {\n const resolvedTenant =\n tenantKey || getPlatformKey(window.location.pathname) || \"\";\n\n if (!resolvedTenant) {\n return \"\";\n }\n\n const targetUrl = redirectUrl ?? window.location.href;\n const joinUrl = `${authUrl}/join?tenant=${encodeURIComponent(resolvedTenant)}&redirect-to=${encodeURIComponent(\n targetUrl,\n )}`;\n return joinUrl;\n}\n\n/**\n * Redirect to auth SPA's join/signup page for a specific tenant\n * @param authUrl - Auth SPA base URL\n * @param tenantKey - Tenant to join\n * @param redirectUrl - URL to redirect to after joining (defaults to current URL)\n */\nexport function redirectToAuthSpaJoinTenant(\n authUrl: string,\n tenantKey?: string,\n redirectUrl?: string,\n): void {\n const resolvedTenant =\n tenantKey || getPlatformKey(window.location.pathname) || \"\";\n\n if (!resolvedTenant) {\n console.log(\"[auth-redirect] Missing tenant key for join\", {\n tenantKey,\n redirectUrl,\n });\n redirectToAuthSpa({\n authUrl,\n appName: \"app\", // Will need to be configured\n redirectTo: redirectUrl,\n });\n return;\n }\n\n const targetUrl = redirectUrl ?? window.location.href;\n const joinUrl = `${authUrl}/join?tenant=${encodeURIComponent(resolvedTenant)}&redirect-to=${encodeURIComponent(\n targetUrl,\n )}`;\n\n window.location.href = joinUrl;\n}\n\nexport interface HandleLogoutOptions {\n /** URL to redirect to after logout (defaults to current origin) */\n redirectUrl?: string;\n /** Auth SPA base URL */\n authUrl: string;\n /** localStorage key for tenant */\n tenantStorageKey?: string;\n /** Cookie name for logout timestamp */\n logoutTimestampCookie?: string;\n /** Callback to execute before logout */\n callback?: () => void;\n}\n\n/**\n * Handle user logout\n *\n * This function:\n * - Clears localStorage (preserving tenant)\n * - Sets logout timestamp cookie for cross-SPA sync\n * - Clears all cookies\n * - Redirects to auth SPA logout endpoint\n *\n * @param options - Logout configuration options\n *\n * @example\n * ```tsx\n * handleLogout({\n * authUrl: 'https://auth.example.com',\n * redirectUrl: 'https://app.example.com',\n * });\n * ```\n */\nexport function handleLogout(options: HandleLogoutOptions): void {\n const {\n redirectUrl = window.location.origin,\n authUrl,\n tenantStorageKey = \"tenant\",\n logoutTimestampCookie = \"ibl_logout_timestamp\",\n callback,\n } = options;\n\n const tenant = window.localStorage.getItem(tenantStorageKey);\n window.localStorage.clear();\n if (tenant) {\n window.localStorage.setItem(tenantStorageKey, tenant);\n }\n\n // Set logout timestamp cookie to trigger logout on other SPAs\n setCookieForAuth(logoutTimestampCookie, Date.now().toString());\n\n clearCookies();\n callback?.();\n\n if (!isInIframe()) {\n window.location.href = `${authUrl}/logout?redirect-to=${redirectUrl}${tenant ? \"&tenant=\" + tenant : \"\"}`;\n }\n}\n"],"names":[],"mappings":";;AAAA;;;;;AAKG;AAEH;;;AAGG;SACa,UAAU,GAAA;AACxB,IAAA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;AACjC,QAAA,OAAO,KAAK;IACd;AACA,IAAA,OAAO,CAAA,MAAM,KAAA,IAAA,IAAN,MAAM,KAAA,MAAA,GAAA,MAAA,GAAN,MAAM,CAAE,IAAI,OAAK,MAAM,aAAN,MAAM,KAAA,MAAA,GAAA,MAAA,GAAN,MAAM,CAAE,GAAG,CAAA;AACrC;AAEA;;;AAGG;AACG,SAAU,0BAA0B,CAAC,OAAgB,EAAA;IACzD,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,GAAG,CAAC;AACzC;AAEA;;;;;AAKG;SACa,YAAY,CAAC,IAAY,EAAE,IAAY,EAAE,MAAc,EAAA;IACrE,MAAM,OAAO,GAAG,wCAAwC;AACxD,IAAA,MAAM,WAAW,GAAG,CAAA,EAAG,IAAI,IAAI;AAC/B,IAAA,MAAM,SAAS,GAAG,IAAI,GAAG,CAAA,KAAA,EAAQ,IAAI,CAAA,CAAA,CAAG,GAAG,EAAE;AAC7C,IAAA,MAAM,WAAW,GAAG,MAAM,GAAG,CAAA,OAAA,EAAU,MAAM,CAAA,CAAA,CAAG,GAAG,EAAE;IACrD,QAAQ,CAAC,MAAM,GAAG,WAAW,GAAG,OAAO,GAAG,SAAS,GAAG,WAAW;AACnE;AAEA;;;;;;AAMG;AACG,SAAU,cAAc,CAAC,MAAc,EAAA;IAC3C,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC;IAC/B,MAAM,OAAO,GAAa,EAAE;AAC5B,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC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MAAM,CAAC,QAAQ,CAAC,IAAI,GAAG,OAAO;AAChC;AAeA;;;;;;;;;;;;;;;;;;AAkBG;AACG,SAAU,YAAY,CAAC,OAA4B,EAAA;IACvD,MAAM,EACJ,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,EACpC,OAAO,EACP,gBAAgB,GAAG,QAAQ,EAC3B,qBAAqB,GAAG,sBAAsB,EAC9C,QAAQ,GACT,GAAG,OAAO;IAEX,MAAM,MAAM,GAAG,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,gBAAgB,CAAC;AAC5D,IAAA,MAAM,CAAC,YAAY,CAAC,KAAK,EAAE;IAC3B,IAAI,MAAM,EAAE;QACV,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,gBAAgB,EAAE,MAAM,CAAC;IACvD;;IAGA,gBAAgB,CAAC,qBAAqB,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC;AAE9D,IAAA,YAAY,EAAE;AACd,IAAA,QAAQ,KAAA,IAAA,IAAR,QAAQ,KAAA,MAAA,GAAA,MAAA,GAAR,QAAQ,EAAI;AAEZ,IAAA,IAAI,CAAC,UAAU,EAAE,EAAE;QACjB,MAAM,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAA,EAAG,OAAO,CAAA,oBAAA,EAAuB,WAAW,CAAA,EAAG,MAAM,GAAG,UAAU,GAAG,MAAM,GAAG,EAAE,CAAA,CAAE;IAC3G;AACF;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Authentication and Authorization Utilities
3
+ *
4
+ * This module provides utility functions for handling authentication flows,
5
+ * including redirects to auth SPA, cookie management, and session handling.
6
+ */
7
+ /**
8
+ * Check if the current window is inside an iframe
9
+ * @returns {boolean} True if running in an iframe, false otherwise
10
+ */
11
+ export declare function isInIframe(): boolean;
12
+ /**
13
+ * Send a message to the parent website (when in iframe)
14
+ * @param payload - The data to send to parent window
15
+ */
16
+ export declare function sendMessageToParentWebsite(payload: unknown): void;
17
+ /**
18
+ * Delete a cookie with specific name, path, and domain
19
+ * @param name - Cookie name
20
+ * @param path - Cookie path
21
+ * @param domain - Cookie domain
22
+ */
23
+ export declare function deleteCookie(name: string, path: string, domain: string): void;
24
+ /**
25
+ * Get all possible domain parts for cookie deletion
26
+ * @param domain - The domain to split
27
+ * @returns Array of domain parts
28
+ * @example
29
+ * getDomainParts('app.example.com') // returns ['app.example.com', 'example.com', 'com']
30
+ */
31
+ export declare function getDomainParts(domain: string): string[];
32
+ /**
33
+ * Delete a cookie across all possible domain variations
34
+ * @param name - Cookie name to delete
35
+ * @param childDomain - The current domain
36
+ */
37
+ export declare function deleteCookieOnAllDomains(name: string, childDomain: string): void;
38
+ /**
39
+ * Get the parent domain from a given domain
40
+ * @param domain - The domain to process
41
+ * @returns The parent domain (e.g., 'app.example.com' → '.example.com')
42
+ */
43
+ export declare function getParentDomain(domain?: string): string;
44
+ /**
45
+ * Set a cookie for authentication with cross-domain support
46
+ * @param name - Cookie name
47
+ * @param value - Cookie value
48
+ * @param days - Number of days until expiration (default: 365)
49
+ */
50
+ export declare function setCookieForAuth(name: string, value: string, days?: number): void;
51
+ /**
52
+ * Clear all cookies for the current domain
53
+ */
54
+ export declare function clearCookies(): void;
55
+ /**
56
+ * Get the value of a cookie by name
57
+ * @param name - Cookie name
58
+ * @returns The cookie value or null if not found
59
+ */
60
+ export declare function getCookieValue(name: string): string | null;
61
+ /**
62
+ * Check if user is currently logged in
63
+ * @param tokenKey - The localStorage key for the auth token (default: 'axd_token')
64
+ * @returns True if logged in, false otherwise
65
+ */
66
+ export declare function isLoggedIn(tokenKey?: string): boolean;
67
+ /**
68
+ * Extract platform/tenant key from URL
69
+ * @param url - The URL to parse
70
+ * @param pattern - RegExp pattern to match platform key (default matches /platform/[key]/...)
71
+ * @returns The platform key or null if not found
72
+ */
73
+ export declare function getPlatformKey(url: string, pattern?: RegExp): string | null;
74
+ export interface RedirectToAuthSpaOptions {
75
+ /** URL to redirect to after auth (defaults to current path + search) */
76
+ redirectTo?: string;
77
+ /** Platform/tenant key */
78
+ platformKey?: string;
79
+ /** Whether this is a logout action */
80
+ logout?: boolean;
81
+ /** Whether to save redirect path to localStorage (default: true) */
82
+ saveRedirect?: boolean;
83
+ /** Auth SPA base URL */
84
+ authUrl: string;
85
+ /** Current app/platform identifier (e.g., 'mentor', 'skills') */
86
+ appName: string;
87
+ /** Query param names */
88
+ queryParams?: {
89
+ app?: string;
90
+ redirectTo?: string;
91
+ tenant?: string;
92
+ };
93
+ /** localStorage key for saving redirect path */
94
+ redirectPathStorageKey?: string;
95
+ /** Cookie names for cross-SPA sync */
96
+ cookieNames?: {
97
+ currentTenant?: string;
98
+ userData?: string;
99
+ tenant?: string;
100
+ logoutTimestamp?: string;
101
+ loginTimestamp?: string;
102
+ tenantSwitching?: string;
103
+ };
104
+ /** Function to check if auth token is valid and non-expired. Used to skip redirect when a recent login occurred. */
105
+ hasNonExpiredAuthToken?: () => boolean;
106
+ /** Function to check if the app is in offline mode (e.g., Tauri offline). Skips redirect when true. */
107
+ isOffline?: () => boolean;
108
+ /** localStorage key for a token to preserve before clearing storage (e.g., 'edx_jwt_token') */
109
+ preserveTokenKey?: string;
110
+ /** Path to an auth redirect proxy endpoint (e.g., '/api/auth-redirect'). When set, redirects via this proxy in browser. */
111
+ authRedirectProxy?: string;
112
+ /** Function to check if the app is running as a native app (e.g., Tauri). Affects redirect behavior. */
113
+ isNativeApp?: () => boolean;
114
+ forceRedirect?: boolean;
115
+ }
116
+ /**
117
+ * Redirect to authentication SPA for login/logout
118
+ *
119
+ * This function handles the complete authentication flow:
120
+ * - Clears localStorage and cookies on logout
121
+ * - Saves redirect path for post-auth return
122
+ * - Handles iframe scenarios
123
+ * - Syncs logout across multiple SPAs via cookies
124
+ *
125
+ * @param options - Configuration options for the redirect
126
+ *
127
+ * @example
128
+ * ```tsx
129
+ * // Basic usage
130
+ * redirectToAuthSpa({
131
+ * authUrl: 'https://auth.example.com',
132
+ * appName: 'mentor',
133
+ * });
134
+ *
135
+ * // With logout
136
+ * redirectToAuthSpa({
137
+ * authUrl: 'https://auth.example.com',
138
+ * appName: 'mentor',
139
+ * logout: true,
140
+ * platformKey: 'my-tenant',
141
+ * });
142
+ *
143
+ * // With custom redirect
144
+ * redirectToAuthSpa({
145
+ * authUrl: 'https://auth.example.com',
146
+ * appName: 'mentor',
147
+ * redirectTo: '/dashboard',
148
+ * platformKey: 'my-tenant',
149
+ * });
150
+ * ```
151
+ */
152
+ export declare function redirectToAuthSpa(options: RedirectToAuthSpaOptions): Promise<void>;
153
+ /**
154
+ * Get the URL for joining a tenant (sign up flow)
155
+ * @param authUrl - Auth SPA base URL
156
+ * @param tenantKey - Tenant to join
157
+ * @param redirectUrl - URL to redirect to after joining (defaults to current URL)
158
+ * @returns The join URL
159
+ */
160
+ export declare function getAuthSpaJoinUrl(authUrl: string, tenantKey?: string, redirectUrl?: string): string;
161
+ /**
162
+ * Redirect to auth SPA's join/signup page for a specific tenant
163
+ * @param authUrl - Auth SPA base URL
164
+ * @param tenantKey - Tenant to join
165
+ * @param redirectUrl - URL to redirect to after joining (defaults to current URL)
166
+ */
167
+ export declare function redirectToAuthSpaJoinTenant(authUrl: string, tenantKey?: string, redirectUrl?: string): void;
168
+ export interface HandleLogoutOptions {
169
+ /** URL to redirect to after logout (defaults to current origin) */
170
+ redirectUrl?: string;
171
+ /** Auth SPA base URL */
172
+ authUrl: string;
173
+ /** localStorage key for tenant */
174
+ tenantStorageKey?: string;
175
+ /** Cookie name for logout timestamp */
176
+ logoutTimestampCookie?: string;
177
+ /** Callback to execute before logout */
178
+ callback?: () => void;
179
+ }
180
+ /**
181
+ * Handle user logout
182
+ *
183
+ * This function:
184
+ * - Clears localStorage (preserving tenant)
185
+ * - Sets logout timestamp cookie for cross-SPA sync
186
+ * - Clears all cookies
187
+ * - Redirects to auth SPA logout endpoint
188
+ *
189
+ * @param options - Logout configuration options
190
+ *
191
+ * @example
192
+ * ```tsx
193
+ * handleLogout({
194
+ * authUrl: 'https://auth.example.com',
195
+ * redirectUrl: 'https://app.example.com',
196
+ * });
197
+ * ```
198
+ */
199
+ export declare function handleLogout(options: HandleLogoutOptions): void;
@@ -0,0 +1,5 @@
1
+ import "@testing-library/jest-dom";
2
+ import React from "react";
3
+ export declare const createWrapper: () => ({ children }: {
4
+ children: React.ReactNode;
5
+ }) => React.FunctionComponentElement<import("react-redux").ProviderProps<import("@reduxjs/toolkit").Action<string>, unknown>>;
@@ -0,0 +1 @@
1
+ export {};