@iblai/web-utils 1.10.11 → 1.11.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/README.md +48 -0
- package/dist/auth/index.d.ts +64 -2
- package/dist/auth/index.esm.js +137 -1
- package/dist/auth/index.esm.js.map +1 -1
- package/dist/auth/index.js +146 -0
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/web-utils/src/utils/auth.d.ts +62 -0
- package/dist/data-layer/src/features/core/api-slice.d.ts +303 -1
- package/dist/data-layer/src/features/core/types.d.ts +5 -0
- package/dist/data-layer/src/features/user/api-slice.d.ts +426 -1
- package/dist/data-layer/src/features/user/constants.d.ts +5 -0
- package/dist/data-layer/src/features/user/types.d.ts +22 -1
- package/dist/index.d.ts +78 -2
- package/dist/index.esm.js +704 -539
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +713 -537
- package/dist/index.js.map +1 -1
- package/dist/package.json +1 -1
- package/dist/web-utils/src/hooks/index.d.ts +1 -0
- package/dist/web-utils/src/hooks/use-tenant-switch-sync.d.ts +13 -0
- package/dist/web-utils/src/index.web.d.ts +12 -2
- package/dist/web-utils/src/utils/__tests__/tenant-switch.test.d.ts +1 -0
- package/dist/web-utils/src/utils/auth.d.ts +62 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -126,6 +126,40 @@ function Header() {
|
|
|
126
126
|
}
|
|
127
127
|
```
|
|
128
128
|
|
|
129
|
+
### Tenant Switching
|
|
130
|
+
|
|
131
|
+
Switch the active tenant with built-in cross-tab coordination. A short-lived,
|
|
132
|
+
shared lock (localStorage) plus a `BroadcastChannel` signal prevent the
|
|
133
|
+
"ping-pong" where a stale tab in another window reverts the session to its own
|
|
134
|
+
tenant.
|
|
135
|
+
|
|
136
|
+
```tsx
|
|
137
|
+
import { handleTenantSwitch } from '@iblai/web-utils';
|
|
138
|
+
|
|
139
|
+
// e.g. from a tenant dropdown
|
|
140
|
+
await handleTenantSwitch('acme', {
|
|
141
|
+
authUrl: 'https://auth.example.com',
|
|
142
|
+
clearCurrentTenantCookie, // injected so the util stays React-free
|
|
143
|
+
saveRedirect: true,
|
|
144
|
+
});
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Gate automatic tenant "self-heal" redirects while a switch is in flight:
|
|
148
|
+
|
|
149
|
+
```tsx
|
|
150
|
+
import { isTenantSwitchInProgress } from '@iblai/web-utils';
|
|
151
|
+
|
|
152
|
+
// inside <TenantProvider onTenantMismatch={...}>
|
|
153
|
+
onTenantMismatch={() => {
|
|
154
|
+
if (isTenantSwitchInProgress()) return; // don't revert mid-switch
|
|
155
|
+
window.location.href = '/';
|
|
156
|
+
}}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Lower-level helpers are also exported: `readTenantSwitchLock`,
|
|
160
|
+
`writeTenantSwitchLock`, `refreshTenantSwitchLock`, `clearTenantSwitchLock`, and
|
|
161
|
+
`getTabId`.
|
|
162
|
+
|
|
129
163
|
## Context Providers
|
|
130
164
|
|
|
131
165
|
### Auth Provider
|
|
@@ -345,6 +379,20 @@ function TenantSettings() {
|
|
|
345
379
|
}
|
|
346
380
|
```
|
|
347
381
|
|
|
382
|
+
### Tenant Switch Sync Hook
|
|
383
|
+
|
|
384
|
+
Keep other tabs in sync during a tenant switch. Ignores this tab's own broadcast
|
|
385
|
+
echo and refreshes the shared switch lock so the tab won't auto-revert:
|
|
386
|
+
|
|
387
|
+
```tsx
|
|
388
|
+
import { useTenantSwitchSync } from '@iblai/web-utils';
|
|
389
|
+
|
|
390
|
+
function Providers({ children }) {
|
|
391
|
+
useTenantSwitchSync();
|
|
392
|
+
return <>{children}</>;
|
|
393
|
+
}
|
|
394
|
+
```
|
|
395
|
+
|
|
348
396
|
## Utility Functions
|
|
349
397
|
|
|
350
398
|
### Cookie Management
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -198,6 +198,68 @@ interface HandleLogoutOptions {
|
|
|
198
198
|
* ```
|
|
199
199
|
*/
|
|
200
200
|
declare function handleLogout(options: HandleLogoutOptions): void;
|
|
201
|
+
declare const TENANT_SWITCH_CHANNEL = "ibl-tenant-switch";
|
|
202
|
+
declare const TENANT_SWITCH_LOCK_KEY = "ibl_tenant_switch_lock";
|
|
203
|
+
declare const DEFAULT_TENANT_SWITCH_LOCK_TTL_MS = 8000;
|
|
204
|
+
interface TenantSwitchLock {
|
|
205
|
+
tenant: string;
|
|
206
|
+
/** `${ts}-${tabId}` — monotonic; newer wins. */
|
|
207
|
+
token: string;
|
|
208
|
+
ts: number;
|
|
209
|
+
senderId: string;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Stable per-tab id. Uses sessionStorage so it survives same-tab reloads while
|
|
213
|
+
* staying unique per tab/window.
|
|
214
|
+
*/
|
|
215
|
+
declare function getTabId(): string;
|
|
216
|
+
/** The active (non-expired) tenant-switch lock, or null. */
|
|
217
|
+
declare function readTenantSwitchLock(ttlMs?: number): TenantSwitchLock | null;
|
|
218
|
+
/** Write a fresh lock for `tenant` (newest intent). Returns the lock written. */
|
|
219
|
+
declare function writeTenantSwitchLock(tenant: string): TenantSwitchLock;
|
|
220
|
+
/** Extend an existing lock's window from "now" (no-op when no active lock). */
|
|
221
|
+
declare function refreshTenantSwitchLock(): void;
|
|
222
|
+
declare function clearTenantSwitchLock(): void;
|
|
223
|
+
/** True while a tenant switch is in flight — gate automatic reverts on this. */
|
|
224
|
+
declare function isTenantSwitchInProgress(ttlMs?: number): boolean;
|
|
225
|
+
interface HandleTenantSwitchOptions {
|
|
226
|
+
/** Auth SPA base URL (e.g. config.authUrl()). */
|
|
227
|
+
authUrl: string;
|
|
228
|
+
/** localStorage key for the saved redirect path (default "redirect-to"). */
|
|
229
|
+
redirectPathStorageKey?: string;
|
|
230
|
+
/** localStorage key for a JWT to forward through the switch (default "edx_jwt_token"). */
|
|
231
|
+
preserveTokenKey?: string;
|
|
232
|
+
/** localStorage key holding the tenant (default "tenant"). */
|
|
233
|
+
tenantStorageKey?: string;
|
|
234
|
+
/** Cookie name signalling a switch is in progress (default "ibl_tenant_switching"). */
|
|
235
|
+
tenantSwitchingCookie?: string;
|
|
236
|
+
/** Query-param names for the auth URL. */
|
|
237
|
+
queryParams?: {
|
|
238
|
+
tenant?: string;
|
|
239
|
+
redirectTo?: string;
|
|
240
|
+
};
|
|
241
|
+
/** Persist the current path so the app returns to it post-switch. */
|
|
242
|
+
saveRedirect?: boolean;
|
|
243
|
+
/** Explicit redirect target (defaults to window.location.origin). */
|
|
244
|
+
redirectUrl?: string;
|
|
245
|
+
/** Broadcast to other tabs + clear storage (true for user-initiated; default true). */
|
|
246
|
+
broadcast?: boolean;
|
|
247
|
+
/** Lock TTL override. */
|
|
248
|
+
lockTtlMs?: number;
|
|
249
|
+
/** Injected so this util stays React-free (mentorai passes the SDK's). */
|
|
250
|
+
clearCurrentTenantCookie?: () => void;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Switch the active tenant. Coordinates across tabs (TTL lock + BroadcastChannel),
|
|
254
|
+
* clears storage, then redirects through the auth SPA's `/login/complete`.
|
|
255
|
+
*
|
|
256
|
+
* @example
|
|
257
|
+
* await handleTenantSwitch("acme", {
|
|
258
|
+
* authUrl: config.authUrl(),
|
|
259
|
+
* clearCurrentTenantCookie,
|
|
260
|
+
* });
|
|
261
|
+
*/
|
|
262
|
+
declare function handleTenantSwitch(tenant: string, options: HandleTenantSwitchOptions): Promise<void>;
|
|
201
263
|
|
|
202
|
-
export { clearCookies, deleteCookie, deleteCookieOnAllDomains, getAuthSpaJoinUrl, getCookieValue, getDomainParts, getParentDomain, getPlatformKey, handleLogout, isInIframe, isLoggedIn, redirectToAuthSpa, redirectToAuthSpaJoinTenant, sendMessageToParentWebsite, setCookieForAuth };
|
|
203
|
-
export type { HandleLogoutOptions, RedirectToAuthSpaOptions };
|
|
264
|
+
export { DEFAULT_TENANT_SWITCH_LOCK_TTL_MS, TENANT_SWITCH_CHANNEL, TENANT_SWITCH_LOCK_KEY, clearCookies, clearTenantSwitchLock, deleteCookie, deleteCookieOnAllDomains, getAuthSpaJoinUrl, getCookieValue, getDomainParts, getParentDomain, getPlatformKey, getTabId, handleLogout, handleTenantSwitch, isInIframe, isLoggedIn, isTenantSwitchInProgress, readTenantSwitchLock, redirectToAuthSpa, redirectToAuthSpaJoinTenant, refreshTenantSwitchLock, sendMessageToParentWebsite, setCookieForAuth, writeTenantSwitchLock };
|
|
265
|
+
export type { HandleLogoutOptions, HandleTenantSwitchOptions, RedirectToAuthSpaOptions, TenantSwitchLock };
|
package/dist/auth/index.esm.js
CHANGED
|
@@ -361,6 +361,142 @@ function handleLogout(options) {
|
|
|
361
361
|
window.location.href = `${authUrl}/logout?redirect-to=${redirectUrl}${tenant ? "&tenant=" + tenant : ""}`;
|
|
362
362
|
}
|
|
363
363
|
}
|
|
364
|
+
// ── Tenant-switch coordination ─────────────────────────────────────────────
|
|
365
|
+
// Cross-tab tenant switching: a TTL lock (shared via localStorage) plus a
|
|
366
|
+
// BroadcastChannel signal let multiple tabs coordinate a switch and prevent the
|
|
367
|
+
// "ping-pong" where a stale tab reverts the session to its own route's tenant.
|
|
368
|
+
const TENANT_SWITCH_CHANNEL = "ibl-tenant-switch";
|
|
369
|
+
const TENANT_SWITCH_LOCK_KEY = "ibl_tenant_switch_lock";
|
|
370
|
+
const DEFAULT_TENANT_SWITCH_LOCK_TTL_MS = 8000;
|
|
371
|
+
let _tabId = null;
|
|
372
|
+
/**
|
|
373
|
+
* Stable per-tab id. Uses sessionStorage so it survives same-tab reloads while
|
|
374
|
+
* staying unique per tab/window.
|
|
375
|
+
*/
|
|
376
|
+
function getTabId() {
|
|
377
|
+
var _a, _b;
|
|
378
|
+
if (_tabId)
|
|
379
|
+
return _tabId;
|
|
380
|
+
try {
|
|
381
|
+
const existing = sessionStorage.getItem("ibl_tab_id");
|
|
382
|
+
if (existing)
|
|
383
|
+
return (_tabId = existing);
|
|
384
|
+
const id = (_b = (_a = crypto === null || crypto === void 0 ? void 0 : crypto.randomUUID) === null || _a === void 0 ? void 0 : _a.call(crypto)) !== null && _b !== void 0 ? _b : `${Date.now()}-${Math.random()}`;
|
|
385
|
+
sessionStorage.setItem("ibl_tab_id", id);
|
|
386
|
+
return (_tabId = id);
|
|
387
|
+
}
|
|
388
|
+
catch (_c) {
|
|
389
|
+
return (_tabId = `${Date.now()}-${Math.random()}`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
/** The active (non-expired) tenant-switch lock, or null. */
|
|
393
|
+
function readTenantSwitchLock(ttlMs = DEFAULT_TENANT_SWITCH_LOCK_TTL_MS) {
|
|
394
|
+
try {
|
|
395
|
+
const raw = localStorage.getItem(TENANT_SWITCH_LOCK_KEY);
|
|
396
|
+
if (!raw)
|
|
397
|
+
return null;
|
|
398
|
+
const lock = JSON.parse(raw);
|
|
399
|
+
if (typeof (lock === null || lock === void 0 ? void 0 : lock.ts) !== "number")
|
|
400
|
+
return null;
|
|
401
|
+
if (Date.now() - lock.ts > ttlMs)
|
|
402
|
+
return null;
|
|
403
|
+
return lock;
|
|
404
|
+
}
|
|
405
|
+
catch (_a) {
|
|
406
|
+
return null;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
/** Write a fresh lock for `tenant` (newest intent). Returns the lock written. */
|
|
410
|
+
function writeTenantSwitchLock(tenant) {
|
|
411
|
+
const lock = {
|
|
412
|
+
tenant,
|
|
413
|
+
token: `${Date.now()}-${getTabId()}`,
|
|
414
|
+
ts: Date.now(),
|
|
415
|
+
senderId: getTabId(),
|
|
416
|
+
};
|
|
417
|
+
try {
|
|
418
|
+
localStorage.setItem(TENANT_SWITCH_LOCK_KEY, JSON.stringify(lock));
|
|
419
|
+
}
|
|
420
|
+
catch (_a) { }
|
|
421
|
+
return lock;
|
|
422
|
+
}
|
|
423
|
+
/** Extend an existing lock's window from "now" (no-op when no active lock). */
|
|
424
|
+
function refreshTenantSwitchLock() {
|
|
425
|
+
const lock = readTenantSwitchLock();
|
|
426
|
+
if (!lock)
|
|
427
|
+
return;
|
|
428
|
+
try {
|
|
429
|
+
localStorage.setItem(TENANT_SWITCH_LOCK_KEY, JSON.stringify({ ...lock, ts: Date.now() }));
|
|
430
|
+
}
|
|
431
|
+
catch (_a) { }
|
|
432
|
+
}
|
|
433
|
+
function clearTenantSwitchLock() {
|
|
434
|
+
try {
|
|
435
|
+
localStorage.removeItem(TENANT_SWITCH_LOCK_KEY);
|
|
436
|
+
}
|
|
437
|
+
catch (_a) { }
|
|
438
|
+
}
|
|
439
|
+
/** True while a tenant switch is in flight — gate automatic reverts on this. */
|
|
440
|
+
function isTenantSwitchInProgress(ttlMs) {
|
|
441
|
+
return readTenantSwitchLock(ttlMs) !== null;
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Switch the active tenant. Coordinates across tabs (TTL lock + BroadcastChannel),
|
|
445
|
+
* clears storage, then redirects through the auth SPA's `/login/complete`.
|
|
446
|
+
*
|
|
447
|
+
* @example
|
|
448
|
+
* await handleTenantSwitch("acme", {
|
|
449
|
+
* authUrl: config.authUrl(),
|
|
450
|
+
* clearCurrentTenantCookie,
|
|
451
|
+
* });
|
|
452
|
+
*/
|
|
453
|
+
async function handleTenantSwitch(tenant, options) {
|
|
454
|
+
var _a, _b, _c;
|
|
455
|
+
const { authUrl, redirectPathStorageKey = "redirect-to", preserveTokenKey = "edx_jwt_token", tenantStorageKey = "tenant", tenantSwitchingCookie = "ibl_tenant_switching", queryParams = {}, saveRedirect = false, redirectUrl, broadcast = true, clearCurrentTenantCookie, } = options;
|
|
456
|
+
const tenantParam = (_a = queryParams.tenant) !== null && _a !== void 0 ? _a : "tenant";
|
|
457
|
+
const redirectToParam = (_b = queryParams.redirectTo) !== null && _b !== void 0 ? _b : "redirect-to";
|
|
458
|
+
// Guard: don't start a new user switch while one is already in progress.
|
|
459
|
+
if (broadcast && document.cookie.includes(tenantSwitchingCookie))
|
|
460
|
+
return;
|
|
461
|
+
// Guard: already on the target tenant.
|
|
462
|
+
if (tenant === localStorage.getItem(tenantStorageKey))
|
|
463
|
+
return;
|
|
464
|
+
if (broadcast) {
|
|
465
|
+
setCookieForAuth(tenantSwitchingCookie, "true");
|
|
466
|
+
writeTenantSwitchLock(tenant);
|
|
467
|
+
if (typeof BroadcastChannel !== "undefined") {
|
|
468
|
+
const channel = new BroadcastChannel(TENANT_SWITCH_CHANNEL);
|
|
469
|
+
const lock = readTenantSwitchLock(options.lockTtlMs);
|
|
470
|
+
channel.postMessage({
|
|
471
|
+
type: "TENANT_SWITCHING",
|
|
472
|
+
tenant,
|
|
473
|
+
senderId: (_c = lock === null || lock === void 0 ? void 0 : lock.senderId) !== null && _c !== void 0 ? _c : getTabId(),
|
|
474
|
+
token: lock === null || lock === void 0 ? void 0 : lock.token,
|
|
475
|
+
});
|
|
476
|
+
channel.close();
|
|
477
|
+
}
|
|
478
|
+
clearCurrentTenantCookie === null || clearCurrentTenantCookie === void 0 ? void 0 : clearCurrentTenantCookie();
|
|
479
|
+
}
|
|
480
|
+
const currentPath = `${window.location.pathname}${window.location.search}`;
|
|
481
|
+
const jwtToken = localStorage.getItem(preserveTokenKey);
|
|
482
|
+
if (broadcast)
|
|
483
|
+
localStorage.clear();
|
|
484
|
+
const params = {
|
|
485
|
+
[tenantParam]: tenant,
|
|
486
|
+
[redirectToParam]: redirectUrl !== null && redirectUrl !== void 0 ? redirectUrl : window.location.origin,
|
|
487
|
+
};
|
|
488
|
+
if (jwtToken)
|
|
489
|
+
params.token = jwtToken;
|
|
490
|
+
localStorage.setItem(tenantStorageKey, tenant);
|
|
491
|
+
if (saveRedirect)
|
|
492
|
+
localStorage.setItem(redirectPathStorageKey, currentPath);
|
|
493
|
+
// Re-persist: localStorage.clear() above wiped the pre-broadcast lock; this
|
|
494
|
+
// copy survives the redirect so stale tabs honor the switch window.
|
|
495
|
+
if (broadcast)
|
|
496
|
+
writeTenantSwitchLock(tenant);
|
|
497
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
498
|
+
window.location.href = `${authUrl}/login/complete?${new URLSearchParams(params)}`;
|
|
499
|
+
}
|
|
364
500
|
|
|
365
|
-
export { clearCookies, deleteCookie, deleteCookieOnAllDomains, getAuthSpaJoinUrl, getCookieValue, getDomainParts, getParentDomain, getPlatformKey, handleLogout, isInIframe, isLoggedIn, redirectToAuthSpa, redirectToAuthSpaJoinTenant, sendMessageToParentWebsite, setCookieForAuth };
|
|
501
|
+
export { DEFAULT_TENANT_SWITCH_LOCK_TTL_MS, TENANT_SWITCH_CHANNEL, TENANT_SWITCH_LOCK_KEY, clearCookies, clearTenantSwitchLock, deleteCookie, deleteCookieOnAllDomains, getAuthSpaJoinUrl, getCookieValue, getDomainParts, getParentDomain, getPlatformKey, getTabId, handleLogout, handleTenantSwitch, isInIframe, isLoggedIn, isTenantSwitchInProgress, readTenantSwitchLock, redirectToAuthSpa, redirectToAuthSpaJoinTenant, refreshTenantSwitchLock, sendMessageToParentWebsite, setCookieForAuth, writeTenantSwitchLock };
|
|
366
502
|
//# sourceMappingURL=index.esm.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.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 scheme?: string;\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 scheme = \"iblai-mentor\",\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 if (isNativeApp?.() && scheme) {\n authRedirectUrl += `&scheme=${scheme}`;\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,M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,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;;;;"}
|
|
1
|
+
{"version":3,"file":"index.esm.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 scheme?: string;\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 scheme = \"iblai-mentor\",\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 if (isNativeApp?.() && scheme) {\n authRedirectUrl += `&scheme=${scheme}`;\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\n// ── Tenant-switch coordination ─────────────────────────────────────────────\n// Cross-tab tenant switching: a TTL lock (shared via localStorage) plus a\n// BroadcastChannel signal let multiple tabs coordinate a switch and prevent the\n// \"ping-pong\" where a stale tab reverts the session to its own route's tenant.\nexport const TENANT_SWITCH_CHANNEL = \"ibl-tenant-switch\";\nexport const TENANT_SWITCH_LOCK_KEY = \"ibl_tenant_switch_lock\";\nexport const DEFAULT_TENANT_SWITCH_LOCK_TTL_MS = 8_000;\n\nexport interface TenantSwitchLock {\n tenant: string;\n /** `${ts}-${tabId}` — monotonic; newer wins. */\n token: string;\n ts: number;\n senderId: string;\n}\n\nlet _tabId: string | null = null;\n/**\n * Stable per-tab id. Uses sessionStorage so it survives same-tab reloads while\n * staying unique per tab/window.\n */\nexport function getTabId(): string {\n if (_tabId) return _tabId;\n try {\n const existing = sessionStorage.getItem(\"ibl_tab_id\");\n if (existing) return (_tabId = existing);\n const id = crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random()}`;\n sessionStorage.setItem(\"ibl_tab_id\", id);\n return (_tabId = id);\n } catch {\n return (_tabId = `${Date.now()}-${Math.random()}`);\n }\n}\n\n/** The active (non-expired) tenant-switch lock, or null. */\nexport function readTenantSwitchLock(\n ttlMs: number = DEFAULT_TENANT_SWITCH_LOCK_TTL_MS,\n): TenantSwitchLock | null {\n try {\n const raw = localStorage.getItem(TENANT_SWITCH_LOCK_KEY);\n if (!raw) return null;\n const lock = JSON.parse(raw) as TenantSwitchLock;\n if (typeof lock?.ts !== \"number\") return null;\n if (Date.now() - lock.ts > ttlMs) return null;\n return lock;\n } catch {\n return null;\n }\n}\n\n/** Write a fresh lock for `tenant` (newest intent). Returns the lock written. */\nexport function writeTenantSwitchLock(tenant: string): TenantSwitchLock {\n const lock: TenantSwitchLock = {\n tenant,\n token: `${Date.now()}-${getTabId()}`,\n ts: Date.now(),\n senderId: getTabId(),\n };\n try {\n localStorage.setItem(TENANT_SWITCH_LOCK_KEY, JSON.stringify(lock));\n } catch {}\n return lock;\n}\n\n/** Extend an existing lock's window from \"now\" (no-op when no active lock). */\nexport function refreshTenantSwitchLock(): void {\n const lock = readTenantSwitchLock();\n if (!lock) return;\n try {\n localStorage.setItem(\n TENANT_SWITCH_LOCK_KEY,\n JSON.stringify({ ...lock, ts: Date.now() }),\n );\n } catch {}\n}\n\nexport function clearTenantSwitchLock(): void {\n try {\n localStorage.removeItem(TENANT_SWITCH_LOCK_KEY);\n } catch {}\n}\n\n/** True while a tenant switch is in flight — gate automatic reverts on this. */\nexport function isTenantSwitchInProgress(ttlMs?: number): boolean {\n return readTenantSwitchLock(ttlMs) !== null;\n}\n\nexport interface HandleTenantSwitchOptions {\n /** Auth SPA base URL (e.g. config.authUrl()). */\n authUrl: string;\n /** localStorage key for the saved redirect path (default \"redirect-to\"). */\n redirectPathStorageKey?: string;\n /** localStorage key for a JWT to forward through the switch (default \"edx_jwt_token\"). */\n preserveTokenKey?: string;\n /** localStorage key holding the tenant (default \"tenant\"). */\n tenantStorageKey?: string;\n /** Cookie name signalling a switch is in progress (default \"ibl_tenant_switching\"). */\n tenantSwitchingCookie?: string;\n /** Query-param names for the auth URL. */\n queryParams?: { tenant?: string; redirectTo?: string };\n /** Persist the current path so the app returns to it post-switch. */\n saveRedirect?: boolean;\n /** Explicit redirect target (defaults to window.location.origin). */\n redirectUrl?: string;\n /** Broadcast to other tabs + clear storage (true for user-initiated; default true). */\n broadcast?: boolean;\n /** Lock TTL override. */\n lockTtlMs?: number;\n /** Injected so this util stays React-free (mentorai passes the SDK's). */\n clearCurrentTenantCookie?: () => void;\n}\n\n/**\n * Switch the active tenant. Coordinates across tabs (TTL lock + BroadcastChannel),\n * clears storage, then redirects through the auth SPA's `/login/complete`.\n *\n * @example\n * await handleTenantSwitch(\"acme\", {\n * authUrl: config.authUrl(),\n * clearCurrentTenantCookie,\n * });\n */\nexport async function handleTenantSwitch(\n tenant: string,\n options: HandleTenantSwitchOptions,\n): Promise<void> {\n const {\n authUrl,\n redirectPathStorageKey = \"redirect-to\",\n preserveTokenKey = \"edx_jwt_token\",\n tenantStorageKey = \"tenant\",\n tenantSwitchingCookie = \"ibl_tenant_switching\",\n queryParams = {},\n saveRedirect = false,\n redirectUrl,\n broadcast = true,\n clearCurrentTenantCookie,\n } = options;\n const tenantParam = queryParams.tenant ?? \"tenant\";\n const redirectToParam = queryParams.redirectTo ?? \"redirect-to\";\n\n // Guard: don't start a new user switch while one is already in progress.\n if (broadcast && document.cookie.includes(tenantSwitchingCookie)) return;\n // Guard: already on the target tenant.\n if (tenant === localStorage.getItem(tenantStorageKey)) return;\n\n if (broadcast) {\n setCookieForAuth(tenantSwitchingCookie, \"true\");\n writeTenantSwitchLock(tenant);\n if (typeof BroadcastChannel !== \"undefined\") {\n const channel = new BroadcastChannel(TENANT_SWITCH_CHANNEL);\n const lock = readTenantSwitchLock(options.lockTtlMs);\n channel.postMessage({\n type: \"TENANT_SWITCHING\",\n tenant,\n senderId: lock?.senderId ?? getTabId(),\n token: lock?.token,\n });\n channel.close();\n }\n clearCurrentTenantCookie?.();\n }\n\n const currentPath = `${window.location.pathname}${window.location.search}`;\n const jwtToken = localStorage.getItem(preserveTokenKey);\n if (broadcast) localStorage.clear();\n\n const params: Record<string, string> = {\n [tenantParam]: tenant,\n [redirectToParam]: redirectUrl ?? window.location.origin,\n };\n if (jwtToken) params.token = jwtToken;\n\n localStorage.setItem(tenantStorageKey, tenant);\n if (saveRedirect) localStorage.setItem(redirectPathStorageKey, currentPath);\n // Re-persist: localStorage.clear() above wiped the pre-broadcast lock; this\n // copy survives the redirect so stale tabs honor the switch window.\n if (broadcast) writeTenantSwitchLock(tenant);\n\n await new Promise((resolve) => setTimeout(resolve, 100));\n window.location.href = `${authUrl}/login/complete?${new URLSearchParams(params)}`;\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,GAA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AAC,IAAI,GAAG,CAAA,EAAG,OAAO,CAAA,gBAAA,EAAmB,IAAI,eAAe,CAAC,MAAM,CAAC,EAAE;AACnF;;;;"}
|
package/dist/auth/index.js
CHANGED
|
@@ -363,8 +363,148 @@ function handleLogout(options) {
|
|
|
363
363
|
window.location.href = `${authUrl}/logout?redirect-to=${redirectUrl}${tenant ? "&tenant=" + tenant : ""}`;
|
|
364
364
|
}
|
|
365
365
|
}
|
|
366
|
+
// ── Tenant-switch coordination ─────────────────────────────────────────────
|
|
367
|
+
// Cross-tab tenant switching: a TTL lock (shared via localStorage) plus a
|
|
368
|
+
// BroadcastChannel signal let multiple tabs coordinate a switch and prevent the
|
|
369
|
+
// "ping-pong" where a stale tab reverts the session to its own route's tenant.
|
|
370
|
+
const TENANT_SWITCH_CHANNEL = "ibl-tenant-switch";
|
|
371
|
+
const TENANT_SWITCH_LOCK_KEY = "ibl_tenant_switch_lock";
|
|
372
|
+
const DEFAULT_TENANT_SWITCH_LOCK_TTL_MS = 8000;
|
|
373
|
+
let _tabId = null;
|
|
374
|
+
/**
|
|
375
|
+
* Stable per-tab id. Uses sessionStorage so it survives same-tab reloads while
|
|
376
|
+
* staying unique per tab/window.
|
|
377
|
+
*/
|
|
378
|
+
function getTabId() {
|
|
379
|
+
var _a, _b;
|
|
380
|
+
if (_tabId)
|
|
381
|
+
return _tabId;
|
|
382
|
+
try {
|
|
383
|
+
const existing = sessionStorage.getItem("ibl_tab_id");
|
|
384
|
+
if (existing)
|
|
385
|
+
return (_tabId = existing);
|
|
386
|
+
const id = (_b = (_a = crypto === null || crypto === void 0 ? void 0 : crypto.randomUUID) === null || _a === void 0 ? void 0 : _a.call(crypto)) !== null && _b !== void 0 ? _b : `${Date.now()}-${Math.random()}`;
|
|
387
|
+
sessionStorage.setItem("ibl_tab_id", id);
|
|
388
|
+
return (_tabId = id);
|
|
389
|
+
}
|
|
390
|
+
catch (_c) {
|
|
391
|
+
return (_tabId = `${Date.now()}-${Math.random()}`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
/** The active (non-expired) tenant-switch lock, or null. */
|
|
395
|
+
function readTenantSwitchLock(ttlMs = DEFAULT_TENANT_SWITCH_LOCK_TTL_MS) {
|
|
396
|
+
try {
|
|
397
|
+
const raw = localStorage.getItem(TENANT_SWITCH_LOCK_KEY);
|
|
398
|
+
if (!raw)
|
|
399
|
+
return null;
|
|
400
|
+
const lock = JSON.parse(raw);
|
|
401
|
+
if (typeof (lock === null || lock === void 0 ? void 0 : lock.ts) !== "number")
|
|
402
|
+
return null;
|
|
403
|
+
if (Date.now() - lock.ts > ttlMs)
|
|
404
|
+
return null;
|
|
405
|
+
return lock;
|
|
406
|
+
}
|
|
407
|
+
catch (_a) {
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/** Write a fresh lock for `tenant` (newest intent). Returns the lock written. */
|
|
412
|
+
function writeTenantSwitchLock(tenant) {
|
|
413
|
+
const lock = {
|
|
414
|
+
tenant,
|
|
415
|
+
token: `${Date.now()}-${getTabId()}`,
|
|
416
|
+
ts: Date.now(),
|
|
417
|
+
senderId: getTabId(),
|
|
418
|
+
};
|
|
419
|
+
try {
|
|
420
|
+
localStorage.setItem(TENANT_SWITCH_LOCK_KEY, JSON.stringify(lock));
|
|
421
|
+
}
|
|
422
|
+
catch (_a) { }
|
|
423
|
+
return lock;
|
|
424
|
+
}
|
|
425
|
+
/** Extend an existing lock's window from "now" (no-op when no active lock). */
|
|
426
|
+
function refreshTenantSwitchLock() {
|
|
427
|
+
const lock = readTenantSwitchLock();
|
|
428
|
+
if (!lock)
|
|
429
|
+
return;
|
|
430
|
+
try {
|
|
431
|
+
localStorage.setItem(TENANT_SWITCH_LOCK_KEY, JSON.stringify({ ...lock, ts: Date.now() }));
|
|
432
|
+
}
|
|
433
|
+
catch (_a) { }
|
|
434
|
+
}
|
|
435
|
+
function clearTenantSwitchLock() {
|
|
436
|
+
try {
|
|
437
|
+
localStorage.removeItem(TENANT_SWITCH_LOCK_KEY);
|
|
438
|
+
}
|
|
439
|
+
catch (_a) { }
|
|
440
|
+
}
|
|
441
|
+
/** True while a tenant switch is in flight — gate automatic reverts on this. */
|
|
442
|
+
function isTenantSwitchInProgress(ttlMs) {
|
|
443
|
+
return readTenantSwitchLock(ttlMs) !== null;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Switch the active tenant. Coordinates across tabs (TTL lock + BroadcastChannel),
|
|
447
|
+
* clears storage, then redirects through the auth SPA's `/login/complete`.
|
|
448
|
+
*
|
|
449
|
+
* @example
|
|
450
|
+
* await handleTenantSwitch("acme", {
|
|
451
|
+
* authUrl: config.authUrl(),
|
|
452
|
+
* clearCurrentTenantCookie,
|
|
453
|
+
* });
|
|
454
|
+
*/
|
|
455
|
+
async function handleTenantSwitch(tenant, options) {
|
|
456
|
+
var _a, _b, _c;
|
|
457
|
+
const { authUrl, redirectPathStorageKey = "redirect-to", preserveTokenKey = "edx_jwt_token", tenantStorageKey = "tenant", tenantSwitchingCookie = "ibl_tenant_switching", queryParams = {}, saveRedirect = false, redirectUrl, broadcast = true, clearCurrentTenantCookie, } = options;
|
|
458
|
+
const tenantParam = (_a = queryParams.tenant) !== null && _a !== void 0 ? _a : "tenant";
|
|
459
|
+
const redirectToParam = (_b = queryParams.redirectTo) !== null && _b !== void 0 ? _b : "redirect-to";
|
|
460
|
+
// Guard: don't start a new user switch while one is already in progress.
|
|
461
|
+
if (broadcast && document.cookie.includes(tenantSwitchingCookie))
|
|
462
|
+
return;
|
|
463
|
+
// Guard: already on the target tenant.
|
|
464
|
+
if (tenant === localStorage.getItem(tenantStorageKey))
|
|
465
|
+
return;
|
|
466
|
+
if (broadcast) {
|
|
467
|
+
setCookieForAuth(tenantSwitchingCookie, "true");
|
|
468
|
+
writeTenantSwitchLock(tenant);
|
|
469
|
+
if (typeof BroadcastChannel !== "undefined") {
|
|
470
|
+
const channel = new BroadcastChannel(TENANT_SWITCH_CHANNEL);
|
|
471
|
+
const lock = readTenantSwitchLock(options.lockTtlMs);
|
|
472
|
+
channel.postMessage({
|
|
473
|
+
type: "TENANT_SWITCHING",
|
|
474
|
+
tenant,
|
|
475
|
+
senderId: (_c = lock === null || lock === void 0 ? void 0 : lock.senderId) !== null && _c !== void 0 ? _c : getTabId(),
|
|
476
|
+
token: lock === null || lock === void 0 ? void 0 : lock.token,
|
|
477
|
+
});
|
|
478
|
+
channel.close();
|
|
479
|
+
}
|
|
480
|
+
clearCurrentTenantCookie === null || clearCurrentTenantCookie === void 0 ? void 0 : clearCurrentTenantCookie();
|
|
481
|
+
}
|
|
482
|
+
const currentPath = `${window.location.pathname}${window.location.search}`;
|
|
483
|
+
const jwtToken = localStorage.getItem(preserveTokenKey);
|
|
484
|
+
if (broadcast)
|
|
485
|
+
localStorage.clear();
|
|
486
|
+
const params = {
|
|
487
|
+
[tenantParam]: tenant,
|
|
488
|
+
[redirectToParam]: redirectUrl !== null && redirectUrl !== void 0 ? redirectUrl : window.location.origin,
|
|
489
|
+
};
|
|
490
|
+
if (jwtToken)
|
|
491
|
+
params.token = jwtToken;
|
|
492
|
+
localStorage.setItem(tenantStorageKey, tenant);
|
|
493
|
+
if (saveRedirect)
|
|
494
|
+
localStorage.setItem(redirectPathStorageKey, currentPath);
|
|
495
|
+
// Re-persist: localStorage.clear() above wiped the pre-broadcast lock; this
|
|
496
|
+
// copy survives the redirect so stale tabs honor the switch window.
|
|
497
|
+
if (broadcast)
|
|
498
|
+
writeTenantSwitchLock(tenant);
|
|
499
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
500
|
+
window.location.href = `${authUrl}/login/complete?${new URLSearchParams(params)}`;
|
|
501
|
+
}
|
|
366
502
|
|
|
503
|
+
exports.DEFAULT_TENANT_SWITCH_LOCK_TTL_MS = DEFAULT_TENANT_SWITCH_LOCK_TTL_MS;
|
|
504
|
+
exports.TENANT_SWITCH_CHANNEL = TENANT_SWITCH_CHANNEL;
|
|
505
|
+
exports.TENANT_SWITCH_LOCK_KEY = TENANT_SWITCH_LOCK_KEY;
|
|
367
506
|
exports.clearCookies = clearCookies;
|
|
507
|
+
exports.clearTenantSwitchLock = clearTenantSwitchLock;
|
|
368
508
|
exports.deleteCookie = deleteCookie;
|
|
369
509
|
exports.deleteCookieOnAllDomains = deleteCookieOnAllDomains;
|
|
370
510
|
exports.getAuthSpaJoinUrl = getAuthSpaJoinUrl;
|
|
@@ -372,11 +512,17 @@ exports.getCookieValue = getCookieValue;
|
|
|
372
512
|
exports.getDomainParts = getDomainParts;
|
|
373
513
|
exports.getParentDomain = getParentDomain;
|
|
374
514
|
exports.getPlatformKey = getPlatformKey;
|
|
515
|
+
exports.getTabId = getTabId;
|
|
375
516
|
exports.handleLogout = handleLogout;
|
|
517
|
+
exports.handleTenantSwitch = handleTenantSwitch;
|
|
376
518
|
exports.isInIframe = isInIframe;
|
|
377
519
|
exports.isLoggedIn = isLoggedIn;
|
|
520
|
+
exports.isTenantSwitchInProgress = isTenantSwitchInProgress;
|
|
521
|
+
exports.readTenantSwitchLock = readTenantSwitchLock;
|
|
378
522
|
exports.redirectToAuthSpa = redirectToAuthSpa;
|
|
379
523
|
exports.redirectToAuthSpaJoinTenant = redirectToAuthSpaJoinTenant;
|
|
524
|
+
exports.refreshTenantSwitchLock = refreshTenantSwitchLock;
|
|
380
525
|
exports.sendMessageToParentWebsite = sendMessageToParentWebsite;
|
|
381
526
|
exports.setCookieForAuth = setCookieForAuth;
|
|
527
|
+
exports.writeTenantSwitchLock = writeTenantSwitchLock;
|
|
382
528
|
//# sourceMappingURL=index.js.map
|