@asgardeo/browser 0.1.0 → 0.1.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.
package/dist/index.js CHANGED
@@ -1919,11 +1919,10 @@ import {
1919
1919
 
1920
1920
  // src/__legacy__/clients/main-thread-client.ts
1921
1921
  import {
1922
- AsgardeoAuthClient as AsgardeoAuthClient5,
1922
+ AsgardeoAuthClient as AsgardeoAuthClient4,
1923
1923
  OIDCRequestConstants as OIDCRequestConstants3,
1924
- extractPkceStorageKeyFromState as extractPkceStorageKeyFromState2,
1925
- initializeApplicationNativeAuthentication,
1926
- handleApplicationNativeAuthentication
1924
+ extractPkceStorageKeyFromState,
1925
+ initializeEmbeddedSignInFlow
1927
1926
  } from "@asgardeo/javascript";
1928
1927
 
1929
1928
  // src/__legacy__/constants/messages-types.ts
@@ -1994,11 +1993,8 @@ var STATE_QUERY = "state";
1994
1993
  // src/__legacy__/constants/errors.ts
1995
1994
  var ACCESS_TOKEN_INVALID = "Access token is invalid";
1996
1995
 
1997
- // src/__legacy__/helpers/authentication-helper.ts
1998
- import {
1999
- AsgardeoAuthException,
2000
- extractPkceStorageKeyFromState
2001
- } from "@asgardeo/javascript";
1996
+ // src/__legacy__/helpers/session-management-helper.ts
1997
+ import { AsgardeoAuthClient as AsgardeoAuthClient2, OIDCRequestConstants as OIDCRequestConstants2 } from "@asgardeo/javascript";
2002
1998
 
2003
1999
  // src/__legacy__/utils/message-utils.ts
2004
2000
  var MessageUtils = class {
@@ -2212,665 +2208,156 @@ __publicField(_SPAUtils, "until", (condition, timeout = 500) => {
2212
2208
  });
2213
2209
  var SPAUtils = _SPAUtils;
2214
2210
 
2215
- // src/__legacy__/helpers/authentication-helper.ts
2216
- var AuthenticationHelper = class {
2217
- constructor(authClient, spaHelper) {
2218
- __publicField(this, "_authenticationClient");
2219
- __publicField(this, "_storageManager");
2220
- __publicField(this, "_spaHelper");
2221
- __publicField(this, "_instanceID");
2222
- __publicField(this, "_isTokenRefreshing");
2223
- this._authenticationClient = authClient;
2224
- this._storageManager = this._authenticationClient.getStorageManager();
2225
- this._spaHelper = spaHelper;
2226
- this._instanceID = this._authenticationClient.getInstanceId();
2227
- this._isTokenRefreshing = false;
2228
- }
2229
- enableHttpHandler(httpClient) {
2230
- httpClient?.enableHandler && httpClient.enableHandler();
2231
- }
2232
- disableHttpHandler(httpClient) {
2233
- httpClient?.disableHandler && httpClient.disableHandler();
2234
- }
2235
- initializeSessionManger(config, oidcEndpoints, getSessionState, getAuthzURL, sessionManagementHelper) {
2236
- sessionManagementHelper.initialize(
2237
- config.clientId,
2238
- oidcEndpoints.checkSessionIframe ?? "",
2239
- getSessionState,
2240
- config.checkSessionInterval ?? 3,
2241
- config.sessionRefreshInterval ?? 300,
2242
- config.afterSignInUrl,
2243
- getAuthzURL
2244
- );
2245
- }
2246
- async exchangeToken(config, enableRetrievingSignOutURLFromSession) {
2247
- let useDefaultEndpoint = true;
2248
- let matches = false;
2249
- if (config?.tokenEndpoint) {
2250
- useDefaultEndpoint = false;
2251
- for (const baseUrl of [
2252
- ...(await this._storageManager.getConfigData())?.resourceServerURLs ?? [],
2253
- config.baseUrl
2254
- ]) {
2255
- if (baseUrl && config.tokenEndpoint?.startsWith(baseUrl)) {
2256
- matches = true;
2257
- break;
2258
- }
2259
- }
2211
+ // src/__legacy__/helpers/session-management-helper.ts
2212
+ var SessionManagementHelper = /* @__PURE__ */ (() => {
2213
+ let _clientID;
2214
+ let _checkSessionEndpoint;
2215
+ let _sessionState;
2216
+ let _interval;
2217
+ let _redirectURL;
2218
+ let _sessionRefreshInterval;
2219
+ let _signOut;
2220
+ let _sessionRefreshIntervalTimeout;
2221
+ let _checkSessionIntervalTimeout;
2222
+ let _storage;
2223
+ let _setSessionState;
2224
+ let _getSignInUrl;
2225
+ const initialize = (clientId, checkSessionEndpoint, getSessionState, interval, sessionRefreshInterval, redirectURL, getSignInUrl) => {
2226
+ _clientID = clientId;
2227
+ _checkSessionEndpoint = checkSessionEndpoint;
2228
+ _sessionState = getSessionState;
2229
+ _interval = interval;
2230
+ _redirectURL = redirectURL;
2231
+ _sessionRefreshInterval = sessionRefreshInterval;
2232
+ _getSignInUrl = getSignInUrl;
2233
+ if (_interval > -1) {
2234
+ initiateCheckSession();
2260
2235
  }
2261
- if (config.shouldReplayAfterRefresh) {
2262
- this._storageManager.setTemporaryDataParameter(CUSTOM_GRANT_CONFIG, JSON.stringify(config));
2236
+ if (_sessionRefreshInterval > -1) {
2237
+ sessionRefreshInterval = setInterval(() => {
2238
+ sendPromptNoneRequest();
2239
+ }, _sessionRefreshInterval * 1e3);
2263
2240
  }
2264
- if (useDefaultEndpoint || matches) {
2265
- return this._authenticationClient.exchangeToken(config).then(async (response) => {
2266
- if (enableRetrievingSignOutURLFromSession && typeof enableRetrievingSignOutURLFromSession === "function") {
2267
- enableRetrievingSignOutURLFromSession(config);
2268
- }
2269
- if (config.returnsSession) {
2270
- this._spaHelper.refreshAccessTokenAutomatically(this);
2271
- return this._authenticationClient.getUser();
2272
- } else {
2273
- return response;
2274
- }
2275
- }).catch((error) => {
2276
- return Promise.reject(error);
2277
- });
2278
- } else {
2279
- return Promise.reject(
2280
- new AsgardeoAuthException(
2281
- "SPA-MAIN_THREAD_CLIENT-RCG-IV01",
2282
- "Request to the provided endpoint is prohibited.",
2283
- "Requests can only be sent to resource servers specified by the `resourceServerURLs` attribute while initializing the SDK. The specified token endpoint in this request cannot be found among the `resourceServerURLs`"
2284
- )
2285
- );
2241
+ };
2242
+ const initiateCheckSession = async () => {
2243
+ if (!_checkSessionEndpoint || !_clientID || !_redirectURL) {
2244
+ return;
2286
2245
  }
2287
- }
2288
- async getCustomGrantConfigData() {
2289
- const configString = await this._storageManager.getTemporaryDataParameter(CUSTOM_GRANT_CONFIG);
2290
- if (configString) {
2291
- return JSON.parse(configString);
2292
- } else {
2293
- return null;
2246
+ const OP_IFRAME2 = "opIFrame";
2247
+ async function checkSession() {
2248
+ const sessionState = await _sessionState();
2249
+ if (Boolean(_clientID) && Boolean(sessionState)) {
2250
+ const message = `${_clientID} ${sessionState}`;
2251
+ const rpIFrame2 = document.getElementById(RP_IFRAME);
2252
+ const opIframe2 = rpIFrame2?.contentDocument?.getElementById(OP_IFRAME2);
2253
+ const win = opIframe2.contentWindow;
2254
+ win?.postMessage(message, _checkSessionEndpoint);
2255
+ }
2294
2256
  }
2295
- }
2296
- async refreshAccessToken(enableRetrievingSignOutURLFromSession) {
2297
- try {
2298
- await this._authenticationClient.refreshAccessToken();
2299
- const customGrantConfig = await this.getCustomGrantConfigData();
2300
- if (customGrantConfig) {
2301
- await this.exchangeToken(customGrantConfig, enableRetrievingSignOutURLFromSession);
2257
+ const rpIFrame = document.getElementById(RP_IFRAME);
2258
+ const opIframe = rpIFrame?.contentDocument?.getElementById(OP_IFRAME2);
2259
+ opIframe.src = _checkSessionEndpoint + "?client_id=" + _clientID + "&redirect_uri=" + _redirectURL;
2260
+ _checkSessionIntervalTimeout = setInterval(checkSession, _interval * 1e3);
2261
+ listenToResponseFromOPIFrame();
2262
+ };
2263
+ const reset = () => {
2264
+ clearInterval(_checkSessionIntervalTimeout);
2265
+ clearInterval(_sessionRefreshIntervalTimeout);
2266
+ };
2267
+ const listenToResponseFromOPIFrame = () => {
2268
+ async function receiveMessage(e) {
2269
+ const targetOrigin = _checkSessionEndpoint;
2270
+ if (!targetOrigin || targetOrigin?.indexOf(e.origin) < 0 || e?.data?.type === SET_SESSION_STATE_FROM_IFRAME) {
2271
+ return;
2302
2272
  }
2303
- this._spaHelper.refreshAccessTokenAutomatically(this);
2304
- return this._authenticationClient.getUser();
2305
- } catch (error) {
2306
- const refreshTokenError = {
2307
- type: REFRESH_ACCESS_TOKEN_ERR0R
2273
+ if (e.data === "unchanged") {
2274
+ } else if (e.data === "error") {
2275
+ window.location.href = await _signOut();
2276
+ } else if (e.data === "changed") {
2277
+ sendPromptNoneRequest();
2278
+ }
2279
+ }
2280
+ window?.addEventListener("message", receiveMessage, false);
2281
+ };
2282
+ const sendPromptNoneRequest = async () => {
2283
+ const rpIFrame = document.getElementById(RP_IFRAME);
2284
+ const promptNoneIFrame = rpIFrame?.contentDocument?.getElementById(
2285
+ PROMPT_NONE_IFRAME
2286
+ );
2287
+ if (SPAUtils.canSendPromptNoneRequest()) {
2288
+ SPAUtils.setPromptNoneRequestSent(true);
2289
+ const receiveMessageListener = (e) => {
2290
+ if (e?.data?.type === SET_SESSION_STATE_FROM_IFRAME) {
2291
+ _setSessionState(e?.data?.data ?? "");
2292
+ window?.removeEventListener("message", receiveMessageListener);
2293
+ }
2308
2294
  };
2309
- window.postMessage(refreshTokenError);
2310
- return Promise.reject(error);
2295
+ if (_storage === "browserMemory" /* BrowserMemory */ || _storage === "webWorker" /* WebWorker */) {
2296
+ window?.addEventListener("message", receiveMessageListener);
2297
+ }
2298
+ const promptNoneURL = await _getSignInUrl({
2299
+ prompt: "none",
2300
+ response_mode: "query",
2301
+ state: STATE
2302
+ });
2303
+ promptNoneIFrame.src = promptNoneURL;
2311
2304
  }
2312
- }
2313
- async retryFailedRequests(failedRequest) {
2314
- const httpClient = failedRequest.httpClient;
2315
- const requestConfig = failedRequest.requestConfig;
2316
- const isHttpHandlerEnabled = failedRequest.isHttpHandlerEnabled;
2317
- const httpErrorCallback = failedRequest.httpErrorCallback;
2318
- const httpFinishCallback = failedRequest.httpFinishCallback;
2319
- await SPAUtils.until(() => !this._isTokenRefreshing);
2320
- try {
2321
- const httpResponse = await httpClient.request(requestConfig);
2322
- return Promise.resolve(httpResponse);
2323
- } catch (error) {
2324
- if (isHttpHandlerEnabled) {
2325
- if (typeof httpErrorCallback === "function") {
2326
- await httpErrorCallback(error);
2305
+ };
2306
+ const receivePromptNoneResponse = async (setSessionState) => {
2307
+ const state = new URL(window.location.href).searchParams.get(STATE_QUERY);
2308
+ const sessionState = new URL(window.location.href).searchParams.get(OIDCRequestConstants2.Params.SESSION_STATE);
2309
+ const parent = window.parent.parent;
2310
+ if (state !== null && (state.includes(STATE) || state.includes(SILENT_SIGN_IN_STATE))) {
2311
+ const code = new URL(window.location.href).searchParams.get("code");
2312
+ if (code !== null && code.length !== 0) {
2313
+ if (state.includes(SILENT_SIGN_IN_STATE)) {
2314
+ const message = {
2315
+ data: {
2316
+ code,
2317
+ sessionState: sessionState ?? "",
2318
+ state
2319
+ },
2320
+ type: CHECK_SESSION_SIGNED_IN
2321
+ };
2322
+ sessionStorage.setItem(INITIALIZED_SILENT_SIGN_IN, "false");
2323
+ parent.postMessage(message, parent.origin);
2324
+ SPAUtils.setPromptNoneRequestSent(false);
2325
+ window.location.href = "about:blank";
2326
+ await SPAUtils.waitTillPageRedirect();
2327
+ return true;
2327
2328
  }
2328
- if (typeof httpFinishCallback === "function") {
2329
- httpFinishCallback();
2329
+ const newSessionState = new URL(window.location.href).searchParams.get("session_state");
2330
+ if (_storage === "localStorage" /* LocalStorage */ || _storage === "sessionStorage" /* SessionStorage */) {
2331
+ setSessionState && await setSessionState(newSessionState);
2332
+ } else {
2333
+ const message = {
2334
+ data: newSessionState ?? "",
2335
+ type: SET_SESSION_STATE_FROM_IFRAME
2336
+ };
2337
+ window?.parent?.parent?.postMessage(message);
2338
+ }
2339
+ SPAUtils.setPromptNoneRequestSent(false);
2340
+ window.location.href = "about:blank";
2341
+ await SPAUtils.waitTillPageRedirect();
2342
+ return true;
2343
+ } else {
2344
+ if (state.includes(SILENT_SIGN_IN_STATE)) {
2345
+ const message = {
2346
+ type: CHECK_SESSION_SIGNED_OUT
2347
+ };
2348
+ window.parent.parent.postMessage(message, parent.origin);
2349
+ SPAUtils.setPromptNoneRequestSent(false);
2350
+ window.location.href = "about:blank";
2351
+ await SPAUtils.waitTillPageRedirect();
2352
+ return true;
2330
2353
  }
2331
- }
2332
- return Promise.reject(error);
2333
- }
2334
- }
2335
- async httpRequest(httpClient, requestConfig, isHttpHandlerEnabled, httpErrorCallback, httpFinishCallback, enableRetrievingSignOutURLFromSession) {
2336
- let matches = false;
2337
- const config = await this._storageManager.getConfigData();
2338
- for (const baseUrl of [...await config?.resourceServerURLs ?? [], config.baseUrl]) {
2339
- if (baseUrl && requestConfig?.url?.startsWith(baseUrl)) {
2340
- matches = true;
2341
- break;
2342
- }
2343
- }
2344
- if (matches) {
2345
- return httpClient.request(requestConfig).then((response) => {
2346
- return Promise.resolve(response);
2347
- }).catch(async (error) => {
2348
- if (error?.response?.status === 401 || !error?.response) {
2349
- if (this._isTokenRefreshing) {
2350
- return this.retryFailedRequests({
2351
- enableRetrievingSignOutURLFromSession,
2352
- httpClient,
2353
- httpErrorCallback,
2354
- httpFinishCallback,
2355
- isHttpHandlerEnabled,
2356
- requestConfig
2357
- });
2358
- }
2359
- this._isTokenRefreshing = true;
2360
- let refreshAccessTokenResponse;
2361
- try {
2362
- refreshAccessTokenResponse = await this.refreshAccessToken(enableRetrievingSignOutURLFromSession);
2363
- this._isTokenRefreshing = false;
2364
- } catch (refreshError) {
2365
- this._isTokenRefreshing = false;
2366
- if (isHttpHandlerEnabled) {
2367
- if (typeof httpErrorCallback === "function") {
2368
- await httpErrorCallback({
2369
- ...error,
2370
- code: ACCESS_TOKEN_INVALID
2371
- });
2372
- }
2373
- if (typeof httpFinishCallback === "function") {
2374
- httpFinishCallback();
2375
- }
2376
- }
2377
- throw new AsgardeoAuthException(
2378
- "SPA-AUTH_HELPER-HR-SE01",
2379
- refreshError?.name ?? "Refresh token request failed.",
2380
- refreshError?.message ?? "An error occurred while trying to refresh the access token following a 401 response from the server."
2381
- );
2382
- }
2383
- if (refreshAccessTokenResponse) {
2384
- try {
2385
- const httpResponse = await httpClient.request(requestConfig);
2386
- return Promise.resolve(httpResponse);
2387
- } catch (error2) {
2388
- if (isHttpHandlerEnabled) {
2389
- if (typeof httpErrorCallback === "function") {
2390
- await httpErrorCallback(error2);
2391
- }
2392
- if (typeof httpFinishCallback === "function") {
2393
- httpFinishCallback();
2394
- }
2395
- }
2396
- return Promise.reject(error2);
2397
- }
2398
- }
2399
- }
2400
- if (isHttpHandlerEnabled) {
2401
- if (typeof httpErrorCallback === "function") {
2402
- await httpErrorCallback(error);
2403
- }
2404
- if (typeof httpFinishCallback === "function") {
2405
- httpFinishCallback();
2406
- }
2407
- }
2408
- return Promise.reject(error);
2409
- });
2410
- } else {
2411
- return Promise.reject(
2412
- new AsgardeoAuthException(
2413
- "SPA-AUTH_HELPER-HR-IV02",
2414
- "Request to the provided endpoint is prohibited.",
2415
- "Requests can only be sent to resource servers specified by the `resourceServerURLs` attribute while initializing the SDK. The specified endpoint in this request cannot be found among the `resourceServerURLs`"
2416
- )
2417
- );
2418
- }
2419
- }
2420
- async httpRequestAll(requestConfigs, httpClient, isHttpHandlerEnabled, httpErrorCallback, httpFinishCallback) {
2421
- let matches = true;
2422
- const config = await this._storageManager.getConfigData();
2423
- for (const requestConfig of requestConfigs) {
2424
- let urlMatches = false;
2425
- for (const baseUrl of [...(await config)?.resourceServerURLs ?? [], config.baseUrl]) {
2426
- if (baseUrl && requestConfig.url?.startsWith(baseUrl)) {
2427
- urlMatches = true;
2428
- break;
2429
- }
2430
- }
2431
- if (!urlMatches) {
2432
- matches = false;
2433
- break;
2434
- }
2435
- }
2436
- const requests = [];
2437
- if (matches) {
2438
- requestConfigs.forEach((request) => {
2439
- requests.push(httpClient.request(request));
2440
- });
2441
- return httpClient?.all && httpClient.all(requests).then((responses) => {
2442
- return Promise.resolve(responses);
2443
- }).catch(async (error) => {
2444
- if (error?.response?.status === 401 || !error?.response) {
2445
- let refreshTokenResponse;
2446
- try {
2447
- refreshTokenResponse = await this._authenticationClient.refreshAccessToken();
2448
- } catch (refreshError) {
2449
- if (isHttpHandlerEnabled) {
2450
- if (typeof httpErrorCallback === "function") {
2451
- await httpErrorCallback({
2452
- ...error,
2453
- code: ACCESS_TOKEN_INVALID
2454
- });
2455
- }
2456
- if (typeof httpFinishCallback === "function") {
2457
- httpFinishCallback();
2458
- }
2459
- }
2460
- throw new AsgardeoAuthException(
2461
- "SPA-AUTH_HELPER-HRA-SE01",
2462
- refreshError?.name ?? "Refresh token request failed.",
2463
- refreshError?.message ?? "An error occurred while trying to refresh the access token following a 401 response from the server."
2464
- );
2465
- }
2466
- if (refreshTokenResponse) {
2467
- return httpClient.all && httpClient.all(requests).then((response) => {
2468
- return Promise.resolve(response);
2469
- }).catch(async (error2) => {
2470
- if (isHttpHandlerEnabled) {
2471
- if (typeof httpErrorCallback === "function") {
2472
- await httpErrorCallback(error2);
2473
- }
2474
- if (typeof httpFinishCallback === "function") {
2475
- httpFinishCallback();
2476
- }
2477
- }
2478
- return Promise.reject(error2);
2479
- });
2480
- }
2481
- }
2482
- if (isHttpHandlerEnabled) {
2483
- if (typeof httpErrorCallback === "function") {
2484
- await httpErrorCallback(error);
2485
- }
2486
- if (typeof httpFinishCallback === "function") {
2487
- httpFinishCallback();
2488
- }
2489
- }
2490
- return Promise.reject(error);
2491
- });
2492
- } else {
2493
- throw new AsgardeoAuthException(
2494
- "SPA-AUTH_HELPER-HRA-IV02",
2495
- "Request to the provided endpoint is prohibited.",
2496
- "Requests can only be sent to resource servers specified by the `resourceServerURLs` attribute while initializing the SDK. The specified endpoint in this request cannot be found among the `resourceServerURLs`"
2497
- );
2498
- }
2499
- }
2500
- async requestAccessToken(authorizationCode, sessionState, checkSession, pkce, state, tokenRequestConfig) {
2501
- const config = await this._storageManager.getConfigData();
2502
- if (config.storage === "browserMemory" /* BrowserMemory */ && config.enablePKCE && sessionState) {
2503
- const pkce2 = SPAUtils.getPKCE(extractPkceStorageKeyFromState(sessionState));
2504
- await this._authenticationClient.setPKCECode(extractPkceStorageKeyFromState(sessionState), pkce2);
2505
- } else if (config.storage === "webWorker" /* WebWorker */ && pkce) {
2506
- await this._authenticationClient.setPKCECode(pkce, state ?? "");
2507
- }
2508
- if (authorizationCode) {
2509
- return this._authenticationClient.requestAccessToken(authorizationCode, sessionState ?? "", state ?? "", void 0, tokenRequestConfig).then(async () => {
2510
- if (config.storage !== "webWorker" /* WebWorker */) {
2511
- SPAUtils.setSignOutURL(await this._authenticationClient.getSignOutUrl(), config.clientId, this._instanceID);
2512
- if (this._spaHelper) {
2513
- this._spaHelper.clearRefreshTokenTimeout();
2514
- this._spaHelper.refreshAccessTokenAutomatically(this);
2515
- }
2516
- if (checkSession && typeof checkSession === "function" && config.enableOIDCSessionManagement) {
2517
- checkSession();
2518
- }
2519
- } else {
2520
- if (this._spaHelper) {
2521
- this._spaHelper.refreshAccessTokenAutomatically(this);
2522
- }
2523
- }
2524
- return this._authenticationClient.getUser();
2525
- }).catch((error) => {
2526
- return Promise.reject(error);
2527
- });
2528
- }
2529
- return Promise.reject(
2530
- new AsgardeoAuthException(
2531
- "SPA-AUTH_HELPER-RAT1-NF01",
2532
- "No authorization code.",
2533
- "No authorization code was found."
2534
- )
2535
- );
2536
- }
2537
- async trySignInSilently(constructSilentSignInUrl, requestAccessToken, sessionManagementHelper, additionalParams, tokenRequestConfig) {
2538
- if (SPAUtils.isInitializedSilentSignIn()) {
2539
- await sessionManagementHelper.receivePromptNoneResponse();
2540
- return Promise.resolve({
2541
- allowedScopes: "",
2542
- displayName: "",
2543
- email: "",
2544
- sessionState: "",
2545
- sub: "",
2546
- tenantDomain: "",
2547
- username: ""
2548
- });
2549
- }
2550
- const rpIFrame = document.getElementById(RP_IFRAME);
2551
- const promptNoneIFrame = rpIFrame?.contentDocument?.getElementById(
2552
- PROMPT_NONE_IFRAME
2553
- );
2554
- try {
2555
- const url = await constructSilentSignInUrl(additionalParams);
2556
- promptNoneIFrame.src = url;
2557
- } catch (error) {
2558
- return Promise.reject(error);
2559
- }
2560
- return new Promise((resolve, reject) => {
2561
- const timer = setTimeout(() => {
2562
- resolve(false);
2563
- }, 1e4);
2564
- const listenToPromptNoneIFrame = async (e) => {
2565
- const data = e.data;
2566
- if (data?.type == CHECK_SESSION_SIGNED_OUT) {
2567
- window.removeEventListener("message", listenToPromptNoneIFrame);
2568
- clearTimeout(timer);
2569
- resolve(false);
2570
- }
2571
- if (data?.type == CHECK_SESSION_SIGNED_IN && data?.data?.code) {
2572
- requestAccessToken(data?.data?.code, data?.data?.sessionState, data?.data?.state, tokenRequestConfig).then((response) => {
2573
- window.removeEventListener("message", listenToPromptNoneIFrame);
2574
- resolve(response);
2575
- }).catch((error) => {
2576
- window.removeEventListener("message", listenToPromptNoneIFrame);
2577
- reject(error);
2578
- }).finally(() => {
2579
- clearTimeout(timer);
2580
- });
2581
- }
2582
- };
2583
- window.addEventListener("message", listenToPromptNoneIFrame);
2584
- });
2585
- }
2586
- async handleSignIn(shouldStopAuthn, checkSession, tryRetrievingUserInfo) {
2587
- const config = await this._storageManager.getConfigData();
2588
- if (await shouldStopAuthn()) {
2589
- return Promise.resolve({
2590
- allowedScopes: "",
2591
- displayName: "",
2592
- email: "",
2593
- sessionState: "",
2594
- sub: "",
2595
- tenantDomain: "",
2596
- username: ""
2597
- });
2598
- }
2599
- if (config.storage !== "webWorker" /* WebWorker */) {
2600
- if (await this._authenticationClient.isSignedIn()) {
2601
- this._spaHelper.clearRefreshTokenTimeout();
2602
- this._spaHelper.refreshAccessTokenAutomatically(this);
2603
- if (config.enableOIDCSessionManagement) {
2604
- checkSession();
2605
- }
2606
- return Promise.resolve(await this._authenticationClient.getUser());
2607
- }
2608
- }
2609
- const error = new URL(window.location.href).searchParams.get(ERROR);
2610
- const errorDescription = new URL(window.location.href).searchParams.get(ERROR_DESCRIPTION);
2611
- if (error) {
2612
- const url = new URL(window.location.href);
2613
- url.searchParams.delete(ERROR);
2614
- url.searchParams.delete(ERROR_DESCRIPTION);
2615
- history.pushState(null, document.title, url.toString());
2616
- throw new AsgardeoAuthException("SPA-AUTH_HELPER-SI-SE01", error, errorDescription ?? "");
2617
- }
2618
- if (config.storage === "webWorker" /* WebWorker */ && tryRetrievingUserInfo) {
2619
- const basicUserInfo = await tryRetrievingUserInfo();
2620
- if (basicUserInfo) {
2621
- return basicUserInfo;
2622
- }
2623
- }
2624
- return Promise.resolve(void 0);
2625
- }
2626
- async attachTokenToRequestConfig(request) {
2627
- const requestConfig = { attachToken: true, ...request };
2628
- if (requestConfig.attachToken) {
2629
- if (requestConfig.shouldAttachIDPAccessToken) {
2630
- request.headers = {
2631
- ...request.headers,
2632
- Authorization: `Bearer ${await this.getIDPAccessToken()}`
2633
- };
2634
- } else {
2635
- request.headers = {
2636
- ...request.headers,
2637
- Authorization: `Bearer ${await this.getAccessToken()}`
2638
- };
2639
- }
2640
- }
2641
- }
2642
- async getUser() {
2643
- return this._authenticationClient.getUser();
2644
- }
2645
- async getDecodedIdToken() {
2646
- return this._authenticationClient.getDecodedIdToken();
2647
- }
2648
- async getDecodedIDPIDToken() {
2649
- return this._authenticationClient.getDecodedIdToken();
2650
- }
2651
- async getCrypto() {
2652
- return this._authenticationClient.getCrypto();
2653
- }
2654
- async getIdToken() {
2655
- return this._authenticationClient.getIdToken();
2656
- }
2657
- async getOpenIDProviderEndpoints() {
2658
- return this._authenticationClient.getOpenIDProviderEndpoints();
2659
- }
2660
- async getAccessToken() {
2661
- return this._authenticationClient.getAccessToken();
2662
- }
2663
- async getIDPAccessToken() {
2664
- return (await this._storageManager.getSessionData())?.access_token;
2665
- }
2666
- getStorageManager() {
2667
- return this._storageManager;
2668
- }
2669
- async isSignedIn() {
2670
- return this._authenticationClient.isSignedIn();
2671
- }
2672
- };
2673
-
2674
- // src/__legacy__/helpers/spa-helper.ts
2675
- import { TokenConstants } from "@asgardeo/javascript";
2676
- var SPAHelper = class {
2677
- constructor(authClient) {
2678
- __publicField(this, "_authenticationClient");
2679
- __publicField(this, "_storageManager");
2680
- this._authenticationClient = authClient;
2681
- this._storageManager = this._authenticationClient.getStorageManager();
2682
- }
2683
- async refreshAccessTokenAutomatically(authenticationHelper) {
2684
- const shouldRefreshAutomatically = (await this._storageManager.getConfigData())?.periodicTokenRefresh ?? false;
2685
- if (!shouldRefreshAutomatically) {
2686
- return;
2687
- }
2688
- const sessionData = await this._storageManager.getSessionData();
2689
- if (sessionData.refresh_token) {
2690
- const expiryTime = parseInt(sessionData.expires_in);
2691
- const time = expiryTime <= 10 ? expiryTime : expiryTime - 10;
2692
- const timer = setTimeout(async () => {
2693
- await authenticationHelper.refreshAccessToken();
2694
- }, time * 1e3);
2695
- await this._storageManager.setTemporaryDataParameter(
2696
- TokenConstants.Storage.StorageKeys.REFRESH_TOKEN_TIMER,
2697
- JSON.stringify(timer)
2698
- );
2699
- }
2700
- }
2701
- async getRefreshTimeoutTimer() {
2702
- if (await this._storageManager.getTemporaryDataParameter(TokenConstants.Storage.StorageKeys.REFRESH_TOKEN_TIMER)) {
2703
- return JSON.parse(
2704
- await this._storageManager.getTemporaryDataParameter(
2705
- TokenConstants.Storage.StorageKeys.REFRESH_TOKEN_TIMER
2706
- )
2707
- );
2708
- }
2709
- return -1;
2710
- }
2711
- async clearRefreshTokenTimeout(timer) {
2712
- if (timer) {
2713
- clearTimeout(timer);
2714
- return;
2715
- }
2716
- const refreshTimer = await this.getRefreshTimeoutTimer();
2717
- if (refreshTimer !== -1) {
2718
- clearTimeout(refreshTimer);
2719
- }
2720
- }
2721
- };
2722
-
2723
- // src/__legacy__/helpers/session-management-helper.ts
2724
- import { AsgardeoAuthClient as AsgardeoAuthClient4, OIDCRequestConstants as OIDCRequestConstants2 } from "@asgardeo/javascript";
2725
- var SessionManagementHelper = /* @__PURE__ */ (() => {
2726
- let _clientID;
2727
- let _checkSessionEndpoint;
2728
- let _sessionState;
2729
- let _interval;
2730
- let _redirectURL;
2731
- let _sessionRefreshInterval;
2732
- let _signOut;
2733
- let _sessionRefreshIntervalTimeout;
2734
- let _checkSessionIntervalTimeout;
2735
- let _storage;
2736
- let _setSessionState;
2737
- let _getSignInUrl;
2738
- const initialize = (clientId, checkSessionEndpoint, getSessionState, interval, sessionRefreshInterval, redirectURL, getSignInUrl) => {
2739
- _clientID = clientId;
2740
- _checkSessionEndpoint = checkSessionEndpoint;
2741
- _sessionState = getSessionState;
2742
- _interval = interval;
2743
- _redirectURL = redirectURL;
2744
- _sessionRefreshInterval = sessionRefreshInterval;
2745
- _getSignInUrl = getSignInUrl;
2746
- if (_interval > -1) {
2747
- initiateCheckSession();
2748
- }
2749
- if (_sessionRefreshInterval > -1) {
2750
- sessionRefreshInterval = setInterval(() => {
2751
- sendPromptNoneRequest();
2752
- }, _sessionRefreshInterval * 1e3);
2753
- }
2754
- };
2755
- const initiateCheckSession = async () => {
2756
- if (!_checkSessionEndpoint || !_clientID || !_redirectURL) {
2757
- return;
2758
- }
2759
- const OP_IFRAME2 = "opIFrame";
2760
- async function checkSession() {
2761
- const sessionState = await _sessionState();
2762
- if (Boolean(_clientID) && Boolean(sessionState)) {
2763
- const message = `${_clientID} ${sessionState}`;
2764
- const rpIFrame2 = document.getElementById(RP_IFRAME);
2765
- const opIframe2 = rpIFrame2?.contentDocument?.getElementById(OP_IFRAME2);
2766
- const win = opIframe2.contentWindow;
2767
- win?.postMessage(message, _checkSessionEndpoint);
2768
- }
2769
- }
2770
- const rpIFrame = document.getElementById(RP_IFRAME);
2771
- const opIframe = rpIFrame?.contentDocument?.getElementById(OP_IFRAME2);
2772
- opIframe.src = _checkSessionEndpoint + "?client_id=" + _clientID + "&redirect_uri=" + _redirectURL;
2773
- _checkSessionIntervalTimeout = setInterval(checkSession, _interval * 1e3);
2774
- listenToResponseFromOPIFrame();
2775
- };
2776
- const reset = () => {
2777
- clearInterval(_checkSessionIntervalTimeout);
2778
- clearInterval(_sessionRefreshIntervalTimeout);
2779
- };
2780
- const listenToResponseFromOPIFrame = () => {
2781
- async function receiveMessage(e) {
2782
- const targetOrigin = _checkSessionEndpoint;
2783
- if (!targetOrigin || targetOrigin?.indexOf(e.origin) < 0 || e?.data?.type === SET_SESSION_STATE_FROM_IFRAME) {
2784
- return;
2785
- }
2786
- if (e.data === "unchanged") {
2787
- } else if (e.data === "error") {
2788
- window.location.href = await _signOut();
2789
- } else if (e.data === "changed") {
2790
- sendPromptNoneRequest();
2791
- }
2792
- }
2793
- window?.addEventListener("message", receiveMessage, false);
2794
- };
2795
- const sendPromptNoneRequest = async () => {
2796
- const rpIFrame = document.getElementById(RP_IFRAME);
2797
- const promptNoneIFrame = rpIFrame?.contentDocument?.getElementById(
2798
- PROMPT_NONE_IFRAME
2799
- );
2800
- if (SPAUtils.canSendPromptNoneRequest()) {
2801
- SPAUtils.setPromptNoneRequestSent(true);
2802
- const receiveMessageListener = (e) => {
2803
- if (e?.data?.type === SET_SESSION_STATE_FROM_IFRAME) {
2804
- _setSessionState(e?.data?.data ?? "");
2805
- window?.removeEventListener("message", receiveMessageListener);
2806
- }
2807
- };
2808
- if (_storage === "browserMemory" /* BrowserMemory */ || _storage === "webWorker" /* WebWorker */) {
2809
- window?.addEventListener("message", receiveMessageListener);
2810
- }
2811
- const promptNoneURL = await _getSignInUrl({
2812
- prompt: "none",
2813
- response_mode: "query",
2814
- state: STATE
2815
- });
2816
- promptNoneIFrame.src = promptNoneURL;
2817
- }
2818
- };
2819
- const receivePromptNoneResponse = async (setSessionState) => {
2820
- const state = new URL(window.location.href).searchParams.get(STATE_QUERY);
2821
- const sessionState = new URL(window.location.href).searchParams.get(OIDCRequestConstants2.Params.SESSION_STATE);
2822
- const parent = window.parent.parent;
2823
- if (state !== null && (state.includes(STATE) || state.includes(SILENT_SIGN_IN_STATE))) {
2824
- const code = new URL(window.location.href).searchParams.get("code");
2825
- if (code !== null && code.length !== 0) {
2826
- if (state.includes(SILENT_SIGN_IN_STATE)) {
2827
- const message = {
2828
- data: {
2829
- code,
2830
- sessionState: sessionState ?? "",
2831
- state
2832
- },
2833
- type: CHECK_SESSION_SIGNED_IN
2834
- };
2835
- sessionStorage.setItem(INITIALIZED_SILENT_SIGN_IN, "false");
2836
- parent.postMessage(message, parent.origin);
2837
- SPAUtils.setPromptNoneRequestSent(false);
2838
- window.location.href = "about:blank";
2839
- await SPAUtils.waitTillPageRedirect();
2840
- return true;
2841
- }
2842
- const newSessionState = new URL(window.location.href).searchParams.get("session_state");
2843
- if (_storage === "localStorage" /* LocalStorage */ || _storage === "sessionStorage" /* SessionStorage */) {
2844
- setSessionState && await setSessionState(newSessionState);
2845
- } else {
2846
- const message = {
2847
- data: newSessionState ?? "",
2848
- type: SET_SESSION_STATE_FROM_IFRAME
2849
- };
2850
- window?.parent?.parent?.postMessage(message);
2851
- }
2852
- SPAUtils.setPromptNoneRequestSent(false);
2853
- window.location.href = "about:blank";
2854
- await SPAUtils.waitTillPageRedirect();
2855
- return true;
2856
- } else {
2857
- if (state.includes(SILENT_SIGN_IN_STATE)) {
2858
- const message = {
2859
- type: CHECK_SESSION_SIGNED_OUT
2860
- };
2861
- window.parent.parent.postMessage(message, parent.origin);
2862
- SPAUtils.setPromptNoneRequestSent(false);
2863
- window.location.href = "about:blank";
2864
- await SPAUtils.waitTillPageRedirect();
2865
- return true;
2866
- }
2867
- SPAUtils.setPromptNoneRequestSent(false);
2868
- const signOutURL = await _signOut();
2869
- await AsgardeoAuthClient4.clearSession();
2870
- parent.location.href = signOutURL;
2871
- window.location.href = "about:blank";
2872
- await SPAUtils.waitTillPageRedirect();
2873
- return true;
2354
+ SPAUtils.setPromptNoneRequestSent(false);
2355
+ const signOutURL = await _signOut();
2356
+ await AsgardeoAuthClient2.clearSession();
2357
+ parent.location.href = signOutURL;
2358
+ window.location.href = "about:blank";
2359
+ await SPAUtils.waitTillPageRedirect();
2360
+ return true;
2874
2361
  }
2875
2362
  }
2876
2363
  return false;
@@ -2915,6 +2402,55 @@ var SessionManagementHelper = /* @__PURE__ */ (() => {
2915
2402
  };
2916
2403
  })();
2917
2404
 
2405
+ // src/__legacy__/helpers/spa-helper.ts
2406
+ import { TokenConstants } from "@asgardeo/javascript";
2407
+ var SPAHelper = class {
2408
+ constructor(authClient) {
2409
+ __publicField(this, "_authenticationClient");
2410
+ __publicField(this, "_storageManager");
2411
+ this._authenticationClient = authClient;
2412
+ this._storageManager = this._authenticationClient.getStorageManager();
2413
+ }
2414
+ async refreshAccessTokenAutomatically(authenticationHelper) {
2415
+ const shouldRefreshAutomatically = (await this._storageManager.getConfigData())?.periodicTokenRefresh ?? false;
2416
+ if (!shouldRefreshAutomatically) {
2417
+ return;
2418
+ }
2419
+ const sessionData = await this._storageManager.getSessionData();
2420
+ if (sessionData.refresh_token) {
2421
+ const expiryTime = parseInt(sessionData.expires_in);
2422
+ const time = expiryTime <= 10 ? expiryTime : expiryTime - 10;
2423
+ const timer = setTimeout(async () => {
2424
+ await authenticationHelper.refreshAccessToken();
2425
+ }, time * 1e3);
2426
+ await this._storageManager.setTemporaryDataParameter(
2427
+ TokenConstants.Storage.StorageKeys.REFRESH_TOKEN_TIMER,
2428
+ JSON.stringify(timer)
2429
+ );
2430
+ }
2431
+ }
2432
+ async getRefreshTimeoutTimer() {
2433
+ if (await this._storageManager.getTemporaryDataParameter(TokenConstants.Storage.StorageKeys.REFRESH_TOKEN_TIMER)) {
2434
+ return JSON.parse(
2435
+ await this._storageManager.getTemporaryDataParameter(
2436
+ TokenConstants.Storage.StorageKeys.REFRESH_TOKEN_TIMER
2437
+ )
2438
+ );
2439
+ }
2440
+ return -1;
2441
+ }
2442
+ async clearRefreshTokenTimeout(timer) {
2443
+ if (timer) {
2444
+ clearTimeout(timer);
2445
+ return;
2446
+ }
2447
+ const refreshTimer = await this.getRefreshTimeoutTimer();
2448
+ if (refreshTimer !== -1) {
2449
+ clearTimeout(refreshTimer);
2450
+ }
2451
+ }
2452
+ };
2453
+
2918
2454
  // src/__legacy__/http-client/clients/axios-http-client.ts
2919
2455
  import axios from "axios";
2920
2456
 
@@ -3067,461 +2603,881 @@ var HttpClient = class {
3067
2603
  HttpClient.isHandlerEnabled = false;
3068
2604
  }
3069
2605
  /**
3070
- * Disables the handler for a given period of time.
2606
+ * Disables the handler for a given period of time.
2607
+ *
2608
+ * @param {number} timeout - Timeout in milliseconds.
2609
+ */
2610
+ disableHandlerWithTimeout(timeout = HttpClient.DEFAULT_HANDLER_DISABLE_TIMEOUT) {
2611
+ HttpClient.isHandlerEnabled = false;
2612
+ setTimeout(() => {
2613
+ HttpClient.isHandlerEnabled = true;
2614
+ }, timeout);
2615
+ }
2616
+ setHttpRequestStartCallback(callback) {
2617
+ this.requestStartCallback = callback;
2618
+ }
2619
+ setHttpRequestSuccessCallback(callback) {
2620
+ this.requestSuccessCallback = callback;
2621
+ }
2622
+ setHttpRequestErrorCallback(callback) {
2623
+ this.requestErrorCallback = callback;
2624
+ }
2625
+ setHttpRequestFinishCallback(callback) {
2626
+ this.requestFinishCallback = callback;
2627
+ }
2628
+ };
2629
+ __publicField(HttpClient, "axiosInstance");
2630
+ __publicField(HttpClient, "clientInstance");
2631
+ __publicField(HttpClient, "isHandlerEnabled");
2632
+ __publicField(HttpClient, "DEFAULT_HANDLER_DISABLE_TIMEOUT", 1e3);
2633
+ HttpClient = __decorateClass([
2634
+ staticDecorator()
2635
+ ], HttpClient);
2636
+
2637
+ // src/__legacy__/stores/local-store.ts
2638
+ var LocalStore = class {
2639
+ async setData(key, value) {
2640
+ localStorage.setItem(key, value);
2641
+ }
2642
+ async getData(key) {
2643
+ return localStorage.getItem(key) ?? "{}";
2644
+ }
2645
+ async removeData(key) {
2646
+ localStorage.removeItem(key);
2647
+ }
2648
+ };
2649
+
2650
+ // src/__legacy__/stores/memory-store.ts
2651
+ var MemoryStore = class {
2652
+ constructor() {
2653
+ __publicField(this, "_data");
2654
+ this._data = /* @__PURE__ */ new Map();
2655
+ }
2656
+ async setData(key, value) {
2657
+ this._data.set(key, value);
2658
+ }
2659
+ async getData(key) {
2660
+ return this._data?.get(key) ?? "{}";
2661
+ }
2662
+ async removeData(key) {
2663
+ this._data.delete(key);
2664
+ }
2665
+ };
2666
+
2667
+ // src/__legacy__/stores/session-store.ts
2668
+ var SessionStore = class {
2669
+ async setData(key, value) {
2670
+ sessionStorage.setItem(key, value);
2671
+ }
2672
+ async getData(key) {
2673
+ return sessionStorage.getItem(key) ?? "{}";
2674
+ }
2675
+ async removeData(key) {
2676
+ sessionStorage.removeItem(key);
2677
+ }
2678
+ };
2679
+
2680
+ // src/__legacy__/utils/crypto-utils.ts
2681
+ var import_buffer = __toESM(require_buffer(), 1);
2682
+ var import_randombytes = __toESM(require_browser(), 1);
2683
+ import { AsgardeoAuthException } from "@asgardeo/javascript";
2684
+ import base64url from "base64url";
2685
+ import sha256 from "fast-sha256";
2686
+ import { createLocalJWKSet, jwtVerify } from "jose";
2687
+ var SPACryptoUtils = class {
2688
+ /**
2689
+ * Get URL encoded string.
3071
2690
  *
3072
- * @param {number} timeout - Timeout in milliseconds.
2691
+ * @returns {string} base 64 url encoded value.
3073
2692
  */
3074
- disableHandlerWithTimeout(timeout = HttpClient.DEFAULT_HANDLER_DISABLE_TIMEOUT) {
3075
- HttpClient.isHandlerEnabled = false;
3076
- setTimeout(() => {
3077
- HttpClient.isHandlerEnabled = true;
3078
- }, timeout);
2693
+ base64URLEncode(value) {
2694
+ return base64url.encode(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
3079
2695
  }
3080
- setHttpRequestStartCallback(callback) {
3081
- this.requestStartCallback = callback;
2696
+ base64URLDecode(value) {
2697
+ return base64url.decode(value).toString();
3082
2698
  }
3083
- setHttpRequestSuccessCallback(callback) {
3084
- this.requestSuccessCallback = callback;
2699
+ hashSha256(data) {
2700
+ return import_buffer.Buffer.from(sha256(new TextEncoder().encode(data)));
3085
2701
  }
3086
- setHttpRequestErrorCallback(callback) {
3087
- this.requestErrorCallback = callback;
2702
+ generateRandomBytes(length) {
2703
+ return (0, import_randombytes.default)(length);
3088
2704
  }
3089
- setHttpRequestFinishCallback(callback) {
3090
- this.requestFinishCallback = callback;
2705
+ verifyJwt(idToken, jwk, algorithms, clientId, issuer, subject, clockTolerance, validateJwtIssuer) {
2706
+ const jwtVerifyOptions = {
2707
+ algorithms,
2708
+ audience: clientId,
2709
+ clockTolerance,
2710
+ subject
2711
+ };
2712
+ if (validateJwtIssuer ?? true) {
2713
+ jwtVerifyOptions["issuer"] = issuer;
2714
+ }
2715
+ return jwtVerify(
2716
+ idToken,
2717
+ createLocalJWKSet({
2718
+ keys: [jwk]
2719
+ }),
2720
+ jwtVerifyOptions
2721
+ ).then(() => {
2722
+ return Promise.resolve(true);
2723
+ }).catch((error) => {
2724
+ return Promise.reject(
2725
+ new AsgardeoAuthException(
2726
+ "SPA-CRYPTO-UTILS-VJ-IV01",
2727
+ error?.reason ?? JSON.stringify(error),
2728
+ `${error?.code} ${error?.claim}`
2729
+ )
2730
+ );
2731
+ });
3091
2732
  }
3092
2733
  };
3093
- __publicField(HttpClient, "axiosInstance");
3094
- __publicField(HttpClient, "clientInstance");
3095
- __publicField(HttpClient, "isHandlerEnabled");
3096
- __publicField(HttpClient, "DEFAULT_HANDLER_DISABLE_TIMEOUT", 1e3);
3097
- HttpClient = __decorateClass([
3098
- staticDecorator()
3099
- ], HttpClient);
3100
2734
 
3101
- // src/__legacy__/stores/local-store.ts
3102
- var LocalStore = class {
3103
- async setData(key, value) {
3104
- localStorage.setItem(key, value);
3105
- }
3106
- async getData(key) {
3107
- return localStorage.getItem(key) ?? "{}";
3108
- }
3109
- async removeData(key) {
3110
- localStorage.removeItem(key);
2735
+ // src/__legacy__/clients/main-thread-client.ts
2736
+ var initiateStore = (store) => {
2737
+ switch (store) {
2738
+ case "localStorage" /* LocalStorage */:
2739
+ return new LocalStore();
2740
+ case "sessionStorage" /* SessionStorage */:
2741
+ return new SessionStore();
2742
+ case "browserMemory" /* BrowserMemory */:
2743
+ return new MemoryStore();
2744
+ default:
2745
+ return new SessionStore();
3111
2746
  }
3112
2747
  };
2748
+ var MainThreadClient = async (instanceID, config, getAuthHelper) => {
2749
+ const _store = initiateStore(config.storage);
2750
+ const _cryptoUtils = new SPACryptoUtils();
2751
+ const _authenticationClient = new AsgardeoAuthClient4();
2752
+ await _authenticationClient.initialize(config, _store, _cryptoUtils, instanceID);
2753
+ const _spaHelper = new SPAHelper(_authenticationClient);
2754
+ const _dataLayer = _authenticationClient.getStorageManager();
2755
+ const _sessionManagementHelper = await SessionManagementHelper(
2756
+ async () => _authenticationClient.getSignOutUrl(),
2757
+ config.storage ?? "sessionStorage" /* SessionStorage */,
2758
+ (sessionState) => _dataLayer.setSessionDataParameter(
2759
+ OIDCRequestConstants3.Params.SESSION_STATE,
2760
+ sessionState ?? ""
2761
+ )
2762
+ );
2763
+ const _authenticationHelper = getAuthHelper(_authenticationClient, _spaHelper);
2764
+ let _getSignOutURLFromSessionStorage = false;
2765
+ const _httpClient = HttpClient.getInstance();
2766
+ let _isHttpHandlerEnabled = true;
2767
+ let _httpErrorCallback;
2768
+ let _httpFinishCallback;
2769
+ const attachToken = async (request) => {
2770
+ await _authenticationHelper.attachTokenToRequestConfig(request);
2771
+ };
2772
+ _httpClient?.init && await _httpClient.init(true, attachToken);
2773
+ const setHttpRequestStartCallback = (callback) => {
2774
+ _httpClient?.setHttpRequestStartCallback && _httpClient.setHttpRequestStartCallback(callback);
2775
+ };
2776
+ const setHttpRequestSuccessCallback = (callback) => {
2777
+ _httpClient?.setHttpRequestSuccessCallback && _httpClient.setHttpRequestSuccessCallback(callback);
2778
+ };
2779
+ const setHttpRequestFinishCallback = (callback) => {
2780
+ _httpClient?.setHttpRequestFinishCallback && _httpClient.setHttpRequestFinishCallback(callback);
2781
+ };
2782
+ const setHttpRequestErrorCallback = (callback) => {
2783
+ _httpErrorCallback = callback;
2784
+ };
2785
+ const httpRequest = async (requestConfig) => _authenticationHelper.httpRequest(
2786
+ _httpClient,
2787
+ requestConfig,
2788
+ _isHttpHandlerEnabled,
2789
+ _httpErrorCallback,
2790
+ _httpFinishCallback
2791
+ );
2792
+ const httpRequestAll = async (requestConfigs) => _authenticationHelper.httpRequestAll(
2793
+ requestConfigs,
2794
+ _httpClient,
2795
+ _isHttpHandlerEnabled,
2796
+ _httpErrorCallback,
2797
+ _httpFinishCallback
2798
+ );
2799
+ const getHttpClient = () => _httpClient;
2800
+ const enableHttpHandler = () => {
2801
+ _authenticationHelper.enableHttpHandler(_httpClient);
2802
+ _isHttpHandlerEnabled = true;
2803
+ return true;
2804
+ };
2805
+ const disableHttpHandler = () => {
2806
+ _authenticationHelper.disableHttpHandler(_httpClient);
2807
+ _isHttpHandlerEnabled = false;
2808
+ return true;
2809
+ };
2810
+ const checkSession = async () => {
2811
+ const oidcEndpoints = await _authenticationClient.getOpenIDProviderEndpoints();
2812
+ const config2 = await _dataLayer.getConfigData();
2813
+ _authenticationHelper.initializeSessionManger(
2814
+ config2,
2815
+ oidcEndpoints,
2816
+ async () => (await _authenticationClient.getUserSession()).sessionState,
2817
+ async (params) => _authenticationClient.getSignInUrl(params),
2818
+ _sessionManagementHelper
2819
+ );
2820
+ };
2821
+ const shouldStopAuthn = async () => _sessionManagementHelper.receivePromptNoneResponse(async (sessionState) => {
2822
+ await _dataLayer.setSessionDataParameter(
2823
+ OIDCRequestConstants3.Params.SESSION_STATE,
2824
+ sessionState ?? ""
2825
+ );
2826
+ });
2827
+ const setSessionStatus = async (sessionStatus) => {
2828
+ await _dataLayer.setSessionStatus(sessionStatus);
2829
+ };
2830
+ const signIn = async (signInConfig, authorizationCode, sessionState, state, tokenRequestConfig) => {
2831
+ const basicUserInfo = await _authenticationHelper.handleSignIn(shouldStopAuthn, checkSession, void 0);
2832
+ if (basicUserInfo) {
2833
+ return basicUserInfo;
2834
+ }
2835
+ let resolvedAuthorizationCode;
2836
+ let resolvedSessionState;
2837
+ let resolvedState;
2838
+ let resolvedTokenRequestConfig = { params: {} };
2839
+ if (config?.responseMode === "form_post" && authorizationCode) {
2840
+ resolvedAuthorizationCode = authorizationCode;
2841
+ resolvedSessionState = sessionState ?? "";
2842
+ resolvedState = state ?? "";
2843
+ } else {
2844
+ resolvedAuthorizationCode = new URL(window.location.href).searchParams.get(OIDCRequestConstants3.Params.AUTHORIZATION_CODE) ?? "";
2845
+ resolvedSessionState = new URL(window.location.href).searchParams.get(OIDCRequestConstants3.Params.SESSION_STATE) ?? "";
2846
+ resolvedState = new URL(window.location.href).searchParams.get(OIDCRequestConstants3.Params.STATE) ?? "";
2847
+ SPAUtils.removeAuthorizationCode();
2848
+ }
2849
+ if (resolvedAuthorizationCode && resolvedState) {
2850
+ setSessionStatus("true");
2851
+ const storedTokenRequestConfig = await _dataLayer.getTemporaryDataParameter(TOKEN_REQUEST_CONFIG_KEY);
2852
+ if (storedTokenRequestConfig && typeof storedTokenRequestConfig === "string") {
2853
+ resolvedTokenRequestConfig = JSON.parse(storedTokenRequestConfig);
2854
+ }
2855
+ return requestAccessToken(
2856
+ resolvedAuthorizationCode,
2857
+ resolvedSessionState,
2858
+ resolvedState,
2859
+ resolvedTokenRequestConfig
2860
+ );
2861
+ }
2862
+ return _authenticationClient.getSignInUrl(signInConfig).then(async (url) => {
2863
+ if (config.storage === "browserMemory" /* BrowserMemory */ && config.enablePKCE) {
2864
+ const pkceKey = extractPkceStorageKeyFromState(resolvedState);
2865
+ SPAUtils.setPKCE(pkceKey, await _authenticationClient.getPKCECode(resolvedState));
2866
+ }
2867
+ if (tokenRequestConfig) {
2868
+ _dataLayer.setTemporaryDataParameter(TOKEN_REQUEST_CONFIG_KEY, JSON.stringify(tokenRequestConfig));
2869
+ }
2870
+ if (signInConfig && signInConfig["response_mode"] === "direct") {
2871
+ const authorizeUrl = new URL(url);
2872
+ return initializeEmbeddedSignInFlow({
2873
+ url: `${authorizeUrl.origin}${authorizeUrl.pathname}`,
2874
+ payload: Object.fromEntries(authorizeUrl.searchParams.entries())
2875
+ });
2876
+ }
2877
+ location.href = url;
2878
+ await SPAUtils.waitTillPageRedirect();
2879
+ return Promise.resolve({
2880
+ allowedScopes: "",
2881
+ displayName: "",
2882
+ email: "",
2883
+ sessionState: "",
2884
+ sub: "",
2885
+ tenantDomain: "",
2886
+ username: ""
2887
+ });
2888
+ });
2889
+ };
2890
+ const signOut = async () => {
2891
+ if (await _authenticationClient.isSignedIn() && !_getSignOutURLFromSessionStorage) {
2892
+ location.href = await _authenticationClient.getSignOutUrl();
2893
+ } else {
2894
+ location.href = SPAUtils.getSignOutUrl(config.clientId, instanceID);
2895
+ }
2896
+ _spaHelper.clearRefreshTokenTimeout();
2897
+ await _dataLayer.removeOIDCProviderMetaData();
2898
+ await _dataLayer.removeTemporaryData();
2899
+ await _dataLayer.removeSessionData();
2900
+ await _dataLayer.removeSessionStatus();
2901
+ await SPAUtils.waitTillPageRedirect();
2902
+ return true;
2903
+ };
2904
+ const enableRetrievingSignOutURLFromSession = (config2) => {
2905
+ if (config2.preventSignOutURLUpdate) {
2906
+ _getSignOutURLFromSessionStorage = true;
2907
+ }
2908
+ };
2909
+ const exchangeToken = async (config2) => _authenticationHelper.exchangeToken(config2, enableRetrievingSignOutURLFromSession);
2910
+ const refreshAccessToken = async () => {
2911
+ try {
2912
+ return await _authenticationHelper.refreshAccessToken(enableRetrievingSignOutURLFromSession);
2913
+ } catch (error) {
2914
+ return Promise.reject(error);
2915
+ }
2916
+ };
2917
+ const revokeAccessToken = async () => {
2918
+ const timer = await _spaHelper.getRefreshTimeoutTimer();
2919
+ return _authenticationClient.revokeAccessToken().then(() => {
2920
+ _sessionManagementHelper.reset();
2921
+ _spaHelper.clearRefreshTokenTimeout(timer);
2922
+ return Promise.resolve(true);
2923
+ }).catch((error) => Promise.reject(error));
2924
+ };
2925
+ const requestAccessToken = async (resolvedAuthorizationCode, resolvedSessionState, resolvedState, tokenRequestConfig) => _authenticationHelper.requestAccessToken(
2926
+ resolvedAuthorizationCode,
2927
+ resolvedSessionState,
2928
+ checkSession,
2929
+ void 0,
2930
+ resolvedState,
2931
+ tokenRequestConfig
2932
+ );
2933
+ const constructSilentSignInUrl = async (additionalParams = {}) => {
2934
+ const config2 = await _dataLayer.getConfigData();
2935
+ const urlString = await _authenticationClient.getSignInUrl({
2936
+ prompt: "none",
2937
+ state: SILENT_SIGN_IN_STATE,
2938
+ ...additionalParams
2939
+ });
2940
+ const urlObject = new URL(urlString);
2941
+ urlObject.searchParams.set("response_mode", "query");
2942
+ const url = urlObject.toString();
2943
+ if (config2.storage === "browserMemory" /* BrowserMemory */ && config2.enablePKCE) {
2944
+ const state = urlObject.searchParams.get(OIDCRequestConstants3.Params.STATE);
2945
+ SPAUtils.setPKCE(
2946
+ extractPkceStorageKeyFromState(state ?? ""),
2947
+ await _authenticationClient.getPKCECode(state ?? "")
2948
+ );
2949
+ }
2950
+ return url;
2951
+ };
2952
+ const trySignInSilently = async (additionalParams, tokenRequestConfig) => _authenticationHelper.trySignInSilently(
2953
+ constructSilentSignInUrl,
2954
+ requestAccessToken,
2955
+ _sessionManagementHelper,
2956
+ additionalParams,
2957
+ tokenRequestConfig
2958
+ );
2959
+ const getUser = async () => _authenticationHelper.getUser();
2960
+ const getDecodedIdToken = async () => _authenticationHelper.getDecodedIdToken();
2961
+ const getCrypto = async () => _authenticationHelper.getCrypto();
2962
+ const getIdToken = async () => _authenticationHelper.getIdToken();
2963
+ const getOpenIDProviderEndpoints = async () => _authenticationHelper.getOpenIDProviderEndpoints();
2964
+ const getAccessToken = async () => _authenticationHelper.getAccessToken();
2965
+ const getStorageManager = async () => _authenticationHelper.getStorageManager();
2966
+ const getConfigData = async () => _dataLayer.getConfigData();
2967
+ const isSignedIn = async () => _authenticationHelper.isSignedIn();
2968
+ const isSessionActive = async () => await _dataLayer.getSessionStatus() === "true";
2969
+ const reInitialize = async (newConfig) => {
2970
+ const existingConfig = await _dataLayer.getConfigData();
2971
+ const isCheckSessionIframeDifferent = !(existingConfig && existingConfig.endpoints && existingConfig.endpoints.checkSessionIframe && newConfig && newConfig.endpoints && newConfig.endpoints.checkSessionIframe && existingConfig.endpoints.checkSessionIframe === newConfig.endpoints.checkSessionIframe);
2972
+ const config2 = { ...existingConfig, ...newConfig };
2973
+ await _authenticationClient.reInitialize(config2);
2974
+ if (config2.enableOIDCSessionManagement && isCheckSessionIframeDifferent) {
2975
+ _sessionManagementHelper.reset();
2976
+ checkSession();
2977
+ }
2978
+ };
2979
+ return {
2980
+ disableHttpHandler,
2981
+ enableHttpHandler,
2982
+ getAccessToken,
2983
+ getUser,
2984
+ getConfigData,
2985
+ getCrypto,
2986
+ getStorageManager,
2987
+ getDecodedIdToken,
2988
+ getHttpClient,
2989
+ getIdToken,
2990
+ getOpenIDProviderEndpoints,
2991
+ httpRequest,
2992
+ httpRequestAll,
2993
+ isSignedIn,
2994
+ isSessionActive,
2995
+ refreshAccessToken,
2996
+ exchangeToken,
2997
+ revokeAccessToken,
2998
+ setHttpRequestErrorCallback,
2999
+ setHttpRequestFinishCallback,
3000
+ setHttpRequestStartCallback,
3001
+ setHttpRequestSuccessCallback,
3002
+ signIn,
3003
+ signOut,
3004
+ trySignInSilently,
3005
+ reInitialize
3006
+ };
3007
+ };
3113
3008
 
3114
- // src/__legacy__/stores/memory-store.ts
3115
- var MemoryStore = class {
3116
- constructor() {
3117
- __publicField(this, "_data");
3118
- this._data = /* @__PURE__ */ new Map();
3119
- }
3120
- async setData(key, value) {
3121
- this._data.set(key, value);
3122
- }
3123
- async getData(key) {
3124
- return this._data?.get(key) ?? "{}";
3125
- }
3126
- async removeData(key) {
3127
- this._data.delete(key);
3128
- }
3129
- };
3009
+ // src/__legacy__/clients/web-worker-client.ts
3010
+ import {
3011
+ AsgardeoAuthClient as AsgardeoAuthClient6,
3012
+ AsgardeoAuthException as AsgardeoAuthException3,
3013
+ OIDCRequestConstants as OIDCRequestConstants4,
3014
+ extractPkceStorageKeyFromState as extractPkceStorageKeyFromState3
3015
+ } from "@asgardeo/javascript";
3130
3016
 
3131
- // src/__legacy__/stores/session-store.ts
3132
- var SessionStore = class {
3133
- async setData(key, value) {
3134
- sessionStorage.setItem(key, value);
3017
+ // src/__legacy__/helpers/authentication-helper.ts
3018
+ import {
3019
+ AsgardeoAuthException as AsgardeoAuthException2,
3020
+ extractPkceStorageKeyFromState as extractPkceStorageKeyFromState2
3021
+ } from "@asgardeo/javascript";
3022
+ var AuthenticationHelper = class {
3023
+ constructor(authClient, spaHelper) {
3024
+ __publicField(this, "_authenticationClient");
3025
+ __publicField(this, "_storageManager");
3026
+ __publicField(this, "_spaHelper");
3027
+ __publicField(this, "_instanceID");
3028
+ __publicField(this, "_isTokenRefreshing");
3029
+ this._authenticationClient = authClient;
3030
+ this._storageManager = this._authenticationClient.getStorageManager();
3031
+ this._spaHelper = spaHelper;
3032
+ this._instanceID = this._authenticationClient.getInstanceId();
3033
+ this._isTokenRefreshing = false;
3135
3034
  }
3136
- async getData(key) {
3137
- return sessionStorage.getItem(key) ?? "{}";
3035
+ enableHttpHandler(httpClient) {
3036
+ httpClient?.enableHandler && httpClient.enableHandler();
3138
3037
  }
3139
- async removeData(key) {
3140
- sessionStorage.removeItem(key);
3038
+ disableHttpHandler(httpClient) {
3039
+ httpClient?.disableHandler && httpClient.disableHandler();
3141
3040
  }
3142
- };
3143
-
3144
- // src/__legacy__/utils/crypto-utils.ts
3145
- var import_buffer = __toESM(require_buffer(), 1);
3146
- var import_randombytes = __toESM(require_browser(), 1);
3147
- import { AsgardeoAuthException as AsgardeoAuthException2 } from "@asgardeo/javascript";
3148
- import base64url from "base64url";
3149
- import sha256 from "fast-sha256";
3150
- import { createLocalJWKSet, jwtVerify } from "jose";
3151
- var SPACryptoUtils = class {
3152
- /**
3153
- * Get URL encoded string.
3154
- *
3155
- * @returns {string} base 64 url encoded value.
3156
- */
3157
- base64URLEncode(value) {
3158
- return base64url.encode(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
3041
+ initializeSessionManger(config, oidcEndpoints, getSessionState, getAuthzURL, sessionManagementHelper) {
3042
+ sessionManagementHelper.initialize(
3043
+ config.clientId,
3044
+ oidcEndpoints.checkSessionIframe ?? "",
3045
+ getSessionState,
3046
+ config.checkSessionInterval ?? 3,
3047
+ config.sessionRefreshInterval ?? 300,
3048
+ config.afterSignInUrl,
3049
+ getAuthzURL
3050
+ );
3159
3051
  }
3160
- base64URLDecode(value) {
3161
- return base64url.decode(value).toString();
3052
+ async exchangeToken(config, enableRetrievingSignOutURLFromSession) {
3053
+ let useDefaultEndpoint = true;
3054
+ let matches = false;
3055
+ if (config?.tokenEndpoint) {
3056
+ useDefaultEndpoint = false;
3057
+ for (const baseUrl of [
3058
+ ...(await this._storageManager.getConfigData())?.resourceServerURLs ?? [],
3059
+ config.baseUrl
3060
+ ]) {
3061
+ if (baseUrl && config.tokenEndpoint?.startsWith(baseUrl)) {
3062
+ matches = true;
3063
+ break;
3064
+ }
3065
+ }
3066
+ }
3067
+ if (config.shouldReplayAfterRefresh) {
3068
+ this._storageManager.setTemporaryDataParameter(CUSTOM_GRANT_CONFIG, JSON.stringify(config));
3069
+ }
3070
+ if (useDefaultEndpoint || matches) {
3071
+ return this._authenticationClient.exchangeToken(config).then(async (response) => {
3072
+ if (enableRetrievingSignOutURLFromSession && typeof enableRetrievingSignOutURLFromSession === "function") {
3073
+ enableRetrievingSignOutURLFromSession(config);
3074
+ }
3075
+ if (config.returnsSession) {
3076
+ this._spaHelper.refreshAccessTokenAutomatically(this);
3077
+ return this._authenticationClient.getUser();
3078
+ } else {
3079
+ return response;
3080
+ }
3081
+ }).catch((error) => {
3082
+ return Promise.reject(error);
3083
+ });
3084
+ } else {
3085
+ return Promise.reject(
3086
+ new AsgardeoAuthException2(
3087
+ "SPA-MAIN_THREAD_CLIENT-RCG-IV01",
3088
+ "Request to the provided endpoint is prohibited.",
3089
+ "Requests can only be sent to resource servers specified by the `resourceServerURLs` attribute while initializing the SDK. The specified token endpoint in this request cannot be found among the `resourceServerURLs`"
3090
+ )
3091
+ );
3092
+ }
3162
3093
  }
3163
- hashSha256(data) {
3164
- return import_buffer.Buffer.from(sha256(new TextEncoder().encode(data)));
3094
+ async getCustomGrantConfigData() {
3095
+ const configString = await this._storageManager.getTemporaryDataParameter(CUSTOM_GRANT_CONFIG);
3096
+ if (configString) {
3097
+ return JSON.parse(configString);
3098
+ } else {
3099
+ return null;
3100
+ }
3165
3101
  }
3166
- generateRandomBytes(length) {
3167
- return (0, import_randombytes.default)(length);
3102
+ async refreshAccessToken(enableRetrievingSignOutURLFromSession) {
3103
+ try {
3104
+ await this._authenticationClient.refreshAccessToken();
3105
+ const customGrantConfig = await this.getCustomGrantConfigData();
3106
+ if (customGrantConfig) {
3107
+ await this.exchangeToken(customGrantConfig, enableRetrievingSignOutURLFromSession);
3108
+ }
3109
+ this._spaHelper.refreshAccessTokenAutomatically(this);
3110
+ return this._authenticationClient.getUser();
3111
+ } catch (error) {
3112
+ const refreshTokenError = {
3113
+ type: REFRESH_ACCESS_TOKEN_ERR0R
3114
+ };
3115
+ window.postMessage(refreshTokenError);
3116
+ return Promise.reject(error);
3117
+ }
3168
3118
  }
3169
- verifyJwt(idToken, jwk, algorithms, clientId, issuer, subject, clockTolerance, validateJwtIssuer) {
3170
- const jwtVerifyOptions = {
3171
- algorithms,
3172
- audience: clientId,
3173
- clockTolerance,
3174
- subject
3175
- };
3176
- if (validateJwtIssuer ?? true) {
3177
- jwtVerifyOptions["issuer"] = issuer;
3119
+ async retryFailedRequests(failedRequest) {
3120
+ const httpClient = failedRequest.httpClient;
3121
+ const requestConfig = failedRequest.requestConfig;
3122
+ const isHttpHandlerEnabled = failedRequest.isHttpHandlerEnabled;
3123
+ const httpErrorCallback = failedRequest.httpErrorCallback;
3124
+ const httpFinishCallback = failedRequest.httpFinishCallback;
3125
+ await SPAUtils.until(() => !this._isTokenRefreshing);
3126
+ try {
3127
+ const httpResponse = await httpClient.request(requestConfig);
3128
+ return Promise.resolve(httpResponse);
3129
+ } catch (error) {
3130
+ if (isHttpHandlerEnabled) {
3131
+ if (typeof httpErrorCallback === "function") {
3132
+ await httpErrorCallback(error);
3133
+ }
3134
+ if (typeof httpFinishCallback === "function") {
3135
+ httpFinishCallback();
3136
+ }
3137
+ }
3138
+ return Promise.reject(error);
3178
3139
  }
3179
- return jwtVerify(
3180
- idToken,
3181
- createLocalJWKSet({
3182
- keys: [jwk]
3183
- }),
3184
- jwtVerifyOptions
3185
- ).then(() => {
3186
- return Promise.resolve(true);
3187
- }).catch((error) => {
3140
+ }
3141
+ async httpRequest(httpClient, requestConfig, isHttpHandlerEnabled, httpErrorCallback, httpFinishCallback, enableRetrievingSignOutURLFromSession) {
3142
+ let matches = false;
3143
+ const config = await this._storageManager.getConfigData();
3144
+ for (const baseUrl of [...await config?.resourceServerURLs ?? [], config.baseUrl]) {
3145
+ if (baseUrl && requestConfig?.url?.startsWith(baseUrl)) {
3146
+ matches = true;
3147
+ break;
3148
+ }
3149
+ }
3150
+ if (matches) {
3151
+ return httpClient.request(requestConfig).then((response) => {
3152
+ return Promise.resolve(response);
3153
+ }).catch(async (error) => {
3154
+ if (error?.response?.status === 401 || !error?.response) {
3155
+ if (this._isTokenRefreshing) {
3156
+ return this.retryFailedRequests({
3157
+ enableRetrievingSignOutURLFromSession,
3158
+ httpClient,
3159
+ httpErrorCallback,
3160
+ httpFinishCallback,
3161
+ isHttpHandlerEnabled,
3162
+ requestConfig
3163
+ });
3164
+ }
3165
+ this._isTokenRefreshing = true;
3166
+ let refreshAccessTokenResponse;
3167
+ try {
3168
+ refreshAccessTokenResponse = await this.refreshAccessToken(enableRetrievingSignOutURLFromSession);
3169
+ this._isTokenRefreshing = false;
3170
+ } catch (refreshError) {
3171
+ this._isTokenRefreshing = false;
3172
+ if (isHttpHandlerEnabled) {
3173
+ if (typeof httpErrorCallback === "function") {
3174
+ await httpErrorCallback({
3175
+ ...error,
3176
+ code: ACCESS_TOKEN_INVALID
3177
+ });
3178
+ }
3179
+ if (typeof httpFinishCallback === "function") {
3180
+ httpFinishCallback();
3181
+ }
3182
+ }
3183
+ throw new AsgardeoAuthException2(
3184
+ "SPA-AUTH_HELPER-HR-SE01",
3185
+ refreshError?.name ?? "Refresh token request failed.",
3186
+ refreshError?.message ?? "An error occurred while trying to refresh the access token following a 401 response from the server."
3187
+ );
3188
+ }
3189
+ if (refreshAccessTokenResponse) {
3190
+ try {
3191
+ const httpResponse = await httpClient.request(requestConfig);
3192
+ return Promise.resolve(httpResponse);
3193
+ } catch (error2) {
3194
+ if (isHttpHandlerEnabled) {
3195
+ if (typeof httpErrorCallback === "function") {
3196
+ await httpErrorCallback(error2);
3197
+ }
3198
+ if (typeof httpFinishCallback === "function") {
3199
+ httpFinishCallback();
3200
+ }
3201
+ }
3202
+ return Promise.reject(error2);
3203
+ }
3204
+ }
3205
+ }
3206
+ if (isHttpHandlerEnabled) {
3207
+ if (typeof httpErrorCallback === "function") {
3208
+ await httpErrorCallback(error);
3209
+ }
3210
+ if (typeof httpFinishCallback === "function") {
3211
+ httpFinishCallback();
3212
+ }
3213
+ }
3214
+ return Promise.reject(error);
3215
+ });
3216
+ } else {
3188
3217
  return Promise.reject(
3189
3218
  new AsgardeoAuthException2(
3190
- "SPA-CRYPTO-UTILS-VJ-IV01",
3191
- error?.reason ?? JSON.stringify(error),
3192
- `${error?.code} ${error?.claim}`
3219
+ "SPA-AUTH_HELPER-HR-IV02",
3220
+ "Request to the provided endpoint is prohibited.",
3221
+ "Requests can only be sent to resource servers specified by the `resourceServerURLs` attribute while initializing the SDK. The specified endpoint in this request cannot be found among the `resourceServerURLs`"
3193
3222
  )
3194
3223
  );
3195
- });
3196
- }
3197
- };
3198
-
3199
- // src/__legacy__/clients/main-thread-client.ts
3200
- var initiateStore = (store) => {
3201
- switch (store) {
3202
- case "localStorage" /* LocalStorage */:
3203
- return new LocalStore();
3204
- case "sessionStorage" /* SessionStorage */:
3205
- return new SessionStore();
3206
- case "browserMemory" /* BrowserMemory */:
3207
- return new MemoryStore();
3208
- default:
3209
- return new SessionStore();
3210
- }
3211
- };
3212
- var MainThreadClient = async (instanceID, config, getAuthHelper) => {
3213
- const _store = initiateStore(config.storage);
3214
- const _cryptoUtils = new SPACryptoUtils();
3215
- const _authenticationClient = new AsgardeoAuthClient5();
3216
- await _authenticationClient.initialize(config, _store, _cryptoUtils, instanceID);
3217
- const _spaHelper = new SPAHelper(_authenticationClient);
3218
- const _dataLayer = _authenticationClient.getStorageManager();
3219
- const _sessionManagementHelper = await SessionManagementHelper(
3220
- async () => {
3221
- return _authenticationClient.getSignOutUrl();
3222
- },
3223
- config.storage ?? "sessionStorage" /* SessionStorage */,
3224
- (sessionState) => _dataLayer.setSessionDataParameter(
3225
- OIDCRequestConstants3.Params.SESSION_STATE,
3226
- sessionState ?? ""
3227
- )
3228
- );
3229
- const _authenticationHelper = getAuthHelper(_authenticationClient, _spaHelper);
3230
- let _getSignOutURLFromSessionStorage = false;
3231
- const _httpClient = HttpClient.getInstance();
3232
- let _isHttpHandlerEnabled = true;
3233
- let _httpErrorCallback;
3234
- let _httpFinishCallback;
3235
- const attachToken = async (request) => {
3236
- await _authenticationHelper.attachTokenToRequestConfig(request);
3237
- };
3238
- _httpClient?.init && await _httpClient.init(true, attachToken);
3239
- const setHttpRequestStartCallback = (callback) => {
3240
- _httpClient?.setHttpRequestStartCallback && _httpClient.setHttpRequestStartCallback(callback);
3241
- };
3242
- const setHttpRequestSuccessCallback = (callback) => {
3243
- _httpClient?.setHttpRequestSuccessCallback && _httpClient.setHttpRequestSuccessCallback(callback);
3244
- };
3245
- const setHttpRequestFinishCallback = (callback) => {
3246
- _httpClient?.setHttpRequestFinishCallback && _httpClient.setHttpRequestFinishCallback(callback);
3247
- };
3248
- const setHttpRequestErrorCallback = (callback) => {
3249
- _httpErrorCallback = callback;
3250
- };
3251
- const httpRequest = async (requestConfig) => {
3252
- return await _authenticationHelper.httpRequest(
3253
- _httpClient,
3254
- requestConfig,
3255
- _isHttpHandlerEnabled,
3256
- _httpErrorCallback,
3257
- _httpFinishCallback
3258
- );
3259
- };
3260
- const httpRequestAll = async (requestConfigs) => {
3261
- return await _authenticationHelper.httpRequestAll(
3262
- requestConfigs,
3263
- _httpClient,
3264
- _isHttpHandlerEnabled,
3265
- _httpErrorCallback,
3266
- _httpFinishCallback
3267
- );
3268
- };
3269
- const getHttpClient = () => {
3270
- return _httpClient;
3271
- };
3272
- const enableHttpHandler = () => {
3273
- _authenticationHelper.enableHttpHandler(_httpClient);
3274
- _isHttpHandlerEnabled = true;
3275
- return true;
3276
- };
3277
- const disableHttpHandler = () => {
3278
- _authenticationHelper.disableHttpHandler(_httpClient);
3279
- _isHttpHandlerEnabled = false;
3280
- return true;
3281
- };
3282
- const checkSession = async () => {
3283
- const oidcEndpoints = await _authenticationClient.getOpenIDProviderEndpoints();
3284
- const config2 = await _dataLayer.getConfigData();
3285
- _authenticationHelper.initializeSessionManger(
3286
- config2,
3287
- oidcEndpoints,
3288
- async () => (await _authenticationClient.getUserSession()).sessionState,
3289
- async (params) => _authenticationClient.getSignInUrl(params),
3290
- _sessionManagementHelper
3291
- );
3292
- };
3293
- const shouldStopAuthn = async () => {
3294
- return await _sessionManagementHelper.receivePromptNoneResponse(async (sessionState) => {
3295
- await _dataLayer.setSessionDataParameter(
3296
- OIDCRequestConstants3.Params.SESSION_STATE,
3297
- sessionState ?? ""
3298
- );
3299
- return;
3300
- });
3301
- };
3302
- const setSessionStatus = async (sessionStatus) => {
3303
- await _dataLayer.setSessionStatus(sessionStatus);
3304
- };
3305
- const signIn = async (signInConfig, authorizationCode, sessionState, state, tokenRequestConfig) => {
3306
- if (signInConfig["flow"]) {
3307
- return handleApplicationNativeAuthentication({
3308
- url: signInConfig["flow"]["requestConfig"]["url"],
3309
- payload: signInConfig["flow"]["payload"]
3310
- });
3311
3224
  }
3312
- const basicUserInfo = await _authenticationHelper.handleSignIn(shouldStopAuthn, checkSession, void 0);
3313
- if (basicUserInfo) {
3314
- return basicUserInfo;
3315
- } else {
3316
- let resolvedAuthorizationCode;
3317
- let resolvedSessionState;
3318
- let resolvedState;
3319
- let resolvedTokenRequestConfig = { params: {} };
3320
- if (config?.responseMode === "form_post" && authorizationCode) {
3321
- resolvedAuthorizationCode = authorizationCode;
3322
- resolvedSessionState = sessionState ?? "";
3323
- resolvedState = state ?? "";
3324
- } else {
3325
- resolvedAuthorizationCode = new URL(window.location.href).searchParams.get(OIDCRequestConstants3.Params.AUTHORIZATION_CODE) ?? "";
3326
- resolvedSessionState = new URL(window.location.href).searchParams.get(OIDCRequestConstants3.Params.SESSION_STATE) ?? "";
3327
- resolvedState = new URL(window.location.href).searchParams.get(OIDCRequestConstants3.Params.STATE) ?? "";
3328
- SPAUtils.removeAuthorizationCode();
3329
- }
3330
- if (resolvedAuthorizationCode && resolvedState) {
3331
- setSessionStatus("true");
3332
- const storedTokenRequestConfig = await _dataLayer.getTemporaryDataParameter(TOKEN_REQUEST_CONFIG_KEY);
3333
- if (storedTokenRequestConfig && typeof storedTokenRequestConfig === "string") {
3334
- resolvedTokenRequestConfig = JSON.parse(storedTokenRequestConfig);
3225
+ }
3226
+ async httpRequestAll(requestConfigs, httpClient, isHttpHandlerEnabled, httpErrorCallback, httpFinishCallback) {
3227
+ let matches = true;
3228
+ const config = await this._storageManager.getConfigData();
3229
+ for (const requestConfig of requestConfigs) {
3230
+ let urlMatches = false;
3231
+ for (const baseUrl of [...(await config)?.resourceServerURLs ?? [], config.baseUrl]) {
3232
+ if (baseUrl && requestConfig.url?.startsWith(baseUrl)) {
3233
+ urlMatches = true;
3234
+ break;
3335
3235
  }
3336
- return requestAccessToken(
3337
- resolvedAuthorizationCode,
3338
- resolvedSessionState,
3339
- resolvedState,
3340
- resolvedTokenRequestConfig
3341
- );
3342
3236
  }
3343
- return _authenticationClient.getSignInUrl(signInConfig).then(async (url) => {
3344
- if (config.storage === "browserMemory" /* BrowserMemory */ && config.enablePKCE) {
3345
- const pkceKey = extractPkceStorageKeyFromState2(resolvedState);
3346
- SPAUtils.setPKCE(pkceKey, await _authenticationClient.getPKCECode(resolvedState));
3237
+ if (!urlMatches) {
3238
+ matches = false;
3239
+ break;
3240
+ }
3241
+ }
3242
+ const requests = [];
3243
+ if (matches) {
3244
+ requestConfigs.forEach((request) => {
3245
+ requests.push(httpClient.request(request));
3246
+ });
3247
+ return httpClient?.all && httpClient.all(requests).then((responses) => {
3248
+ return Promise.resolve(responses);
3249
+ }).catch(async (error) => {
3250
+ if (error?.response?.status === 401 || !error?.response) {
3251
+ let refreshTokenResponse;
3252
+ try {
3253
+ refreshTokenResponse = await this._authenticationClient.refreshAccessToken();
3254
+ } catch (refreshError) {
3255
+ if (isHttpHandlerEnabled) {
3256
+ if (typeof httpErrorCallback === "function") {
3257
+ await httpErrorCallback({
3258
+ ...error,
3259
+ code: ACCESS_TOKEN_INVALID
3260
+ });
3261
+ }
3262
+ if (typeof httpFinishCallback === "function") {
3263
+ httpFinishCallback();
3264
+ }
3265
+ }
3266
+ throw new AsgardeoAuthException2(
3267
+ "SPA-AUTH_HELPER-HRA-SE01",
3268
+ refreshError?.name ?? "Refresh token request failed.",
3269
+ refreshError?.message ?? "An error occurred while trying to refresh the access token following a 401 response from the server."
3270
+ );
3271
+ }
3272
+ if (refreshTokenResponse) {
3273
+ return httpClient.all && httpClient.all(requests).then((response) => {
3274
+ return Promise.resolve(response);
3275
+ }).catch(async (error2) => {
3276
+ if (isHttpHandlerEnabled) {
3277
+ if (typeof httpErrorCallback === "function") {
3278
+ await httpErrorCallback(error2);
3279
+ }
3280
+ if (typeof httpFinishCallback === "function") {
3281
+ httpFinishCallback();
3282
+ }
3283
+ }
3284
+ return Promise.reject(error2);
3285
+ });
3286
+ }
3347
3287
  }
3348
- if (tokenRequestConfig) {
3349
- _dataLayer.setTemporaryDataParameter(TOKEN_REQUEST_CONFIG_KEY, JSON.stringify(tokenRequestConfig));
3288
+ if (isHttpHandlerEnabled) {
3289
+ if (typeof httpErrorCallback === "function") {
3290
+ await httpErrorCallback(error);
3291
+ }
3292
+ if (typeof httpFinishCallback === "function") {
3293
+ httpFinishCallback();
3294
+ }
3350
3295
  }
3351
- if (signInConfig["response_mode"] === "direct") {
3352
- const authorizeUrl = new URL(url);
3353
- return initializeApplicationNativeAuthentication({
3354
- url: `${authorizeUrl.origin}${authorizeUrl.pathname}`,
3355
- payload: Object.fromEntries(authorizeUrl.searchParams.entries())
3356
- });
3296
+ return Promise.reject(error);
3297
+ });
3298
+ } else {
3299
+ throw new AsgardeoAuthException2(
3300
+ "SPA-AUTH_HELPER-HRA-IV02",
3301
+ "Request to the provided endpoint is prohibited.",
3302
+ "Requests can only be sent to resource servers specified by the `resourceServerURLs` attribute while initializing the SDK. The specified endpoint in this request cannot be found among the `resourceServerURLs`"
3303
+ );
3304
+ }
3305
+ }
3306
+ async requestAccessToken(authorizationCode, sessionState, checkSession, pkce, state, tokenRequestConfig) {
3307
+ const config = await this._storageManager.getConfigData();
3308
+ if (config.storage === "browserMemory" /* BrowserMemory */ && config.enablePKCE && sessionState) {
3309
+ const pkce2 = SPAUtils.getPKCE(extractPkceStorageKeyFromState2(sessionState));
3310
+ await this._authenticationClient.setPKCECode(extractPkceStorageKeyFromState2(sessionState), pkce2);
3311
+ } else if (config.storage === "webWorker" /* WebWorker */ && pkce) {
3312
+ await this._authenticationClient.setPKCECode(pkce, state ?? "");
3313
+ }
3314
+ if (authorizationCode) {
3315
+ return this._authenticationClient.requestAccessToken(authorizationCode, sessionState ?? "", state ?? "", void 0, tokenRequestConfig).then(async () => {
3316
+ if (config.storage !== "webWorker" /* WebWorker */) {
3317
+ SPAUtils.setSignOutURL(await this._authenticationClient.getSignOutUrl(), config.clientId, this._instanceID);
3318
+ if (this._spaHelper) {
3319
+ this._spaHelper.clearRefreshTokenTimeout();
3320
+ this._spaHelper.refreshAccessTokenAutomatically(this);
3321
+ }
3322
+ if (checkSession && typeof checkSession === "function" && config.enableOIDCSessionManagement) {
3323
+ checkSession();
3324
+ }
3357
3325
  } else {
3358
- location.href = url;
3326
+ if (this._spaHelper) {
3327
+ this._spaHelper.refreshAccessTokenAutomatically(this);
3328
+ }
3359
3329
  }
3360
- await SPAUtils.waitTillPageRedirect();
3361
- return Promise.resolve({
3362
- allowedScopes: "",
3363
- displayName: "",
3364
- email: "",
3365
- sessionState: "",
3366
- sub: "",
3367
- tenantDomain: "",
3368
- username: ""
3369
- });
3330
+ return this._authenticationClient.getUser();
3331
+ }).catch((error) => {
3332
+ return Promise.reject(error);
3333
+ });
3334
+ }
3335
+ return Promise.reject(
3336
+ new AsgardeoAuthException2(
3337
+ "SPA-AUTH_HELPER-RAT1-NF01",
3338
+ "No authorization code.",
3339
+ "No authorization code was found."
3340
+ )
3341
+ );
3342
+ }
3343
+ async trySignInSilently(constructSilentSignInUrl, requestAccessToken, sessionManagementHelper, additionalParams, tokenRequestConfig) {
3344
+ if (SPAUtils.isInitializedSilentSignIn()) {
3345
+ await sessionManagementHelper.receivePromptNoneResponse();
3346
+ return Promise.resolve({
3347
+ allowedScopes: "",
3348
+ displayName: "",
3349
+ email: "",
3350
+ sessionState: "",
3351
+ sub: "",
3352
+ tenantDomain: "",
3353
+ username: ""
3370
3354
  });
3371
3355
  }
3372
- };
3373
- const signOut = async () => {
3374
- if (await _authenticationClient.isSignedIn() && !_getSignOutURLFromSessionStorage) {
3375
- location.href = await _authenticationClient.getSignOutUrl();
3376
- } else {
3377
- location.href = SPAUtils.getSignOutUrl(config.clientId, instanceID);
3378
- }
3379
- _spaHelper.clearRefreshTokenTimeout();
3380
- await _dataLayer.removeOIDCProviderMetaData();
3381
- await _dataLayer.removeTemporaryData();
3382
- await _dataLayer.removeSessionData();
3383
- await _dataLayer.removeSessionStatus();
3384
- await SPAUtils.waitTillPageRedirect();
3385
- return true;
3386
- };
3387
- const enableRetrievingSignOutURLFromSession = (config2) => {
3388
- if (config2.preventSignOutURLUpdate) {
3389
- _getSignOutURLFromSessionStorage = true;
3390
- }
3391
- };
3392
- const exchangeToken = async (config2) => {
3393
- return await _authenticationHelper.exchangeToken(config2, enableRetrievingSignOutURLFromSession);
3394
- };
3395
- const refreshAccessToken = async () => {
3356
+ const rpIFrame = document.getElementById(RP_IFRAME);
3357
+ const promptNoneIFrame = rpIFrame?.contentDocument?.getElementById(
3358
+ PROMPT_NONE_IFRAME
3359
+ );
3396
3360
  try {
3397
- return await _authenticationHelper.refreshAccessToken(enableRetrievingSignOutURLFromSession);
3361
+ const url = await constructSilentSignInUrl(additionalParams);
3362
+ promptNoneIFrame.src = url;
3398
3363
  } catch (error) {
3399
3364
  return Promise.reject(error);
3400
3365
  }
3401
- };
3402
- const revokeAccessToken = async () => {
3403
- const timer = await _spaHelper.getRefreshTimeoutTimer();
3404
- return _authenticationClient.revokeAccessToken().then(() => {
3405
- _sessionManagementHelper.reset();
3406
- _spaHelper.clearRefreshTokenTimeout(timer);
3407
- return Promise.resolve(true);
3408
- }).catch((error) => Promise.reject(error));
3409
- };
3410
- const requestAccessToken = async (resolvedAuthorizationCode, resolvedSessionState, resolvedState, tokenRequestConfig) => {
3411
- return await _authenticationHelper.requestAccessToken(
3412
- resolvedAuthorizationCode,
3413
- resolvedSessionState,
3414
- checkSession,
3415
- void 0,
3416
- resolvedState,
3417
- tokenRequestConfig
3418
- );
3419
- };
3420
- const constructSilentSignInUrl = async (additionalParams = {}) => {
3421
- const config2 = await _dataLayer.getConfigData();
3422
- const urlString = await _authenticationClient.getSignInUrl({
3423
- prompt: "none",
3424
- state: SILENT_SIGN_IN_STATE,
3425
- ...additionalParams
3366
+ return new Promise((resolve, reject) => {
3367
+ const timer = setTimeout(() => {
3368
+ resolve(false);
3369
+ }, 1e4);
3370
+ const listenToPromptNoneIFrame = async (e) => {
3371
+ const data = e.data;
3372
+ if (data?.type == CHECK_SESSION_SIGNED_OUT) {
3373
+ window.removeEventListener("message", listenToPromptNoneIFrame);
3374
+ clearTimeout(timer);
3375
+ resolve(false);
3376
+ }
3377
+ if (data?.type == CHECK_SESSION_SIGNED_IN && data?.data?.code) {
3378
+ requestAccessToken(data?.data?.code, data?.data?.sessionState, data?.data?.state, tokenRequestConfig).then((response) => {
3379
+ window.removeEventListener("message", listenToPromptNoneIFrame);
3380
+ resolve(response);
3381
+ }).catch((error) => {
3382
+ window.removeEventListener("message", listenToPromptNoneIFrame);
3383
+ reject(error);
3384
+ }).finally(() => {
3385
+ clearTimeout(timer);
3386
+ });
3387
+ }
3388
+ };
3389
+ window.addEventListener("message", listenToPromptNoneIFrame);
3426
3390
  });
3427
- const urlObject = new URL(urlString);
3428
- urlObject.searchParams.set("response_mode", "query");
3429
- const url = urlObject.toString();
3430
- if (config2.storage === "browserMemory" /* BrowserMemory */ && config2.enablePKCE) {
3431
- const state = urlObject.searchParams.get(OIDCRequestConstants3.Params.STATE);
3432
- SPAUtils.setPKCE(
3433
- extractPkceStorageKeyFromState2(state ?? ""),
3434
- await _authenticationClient.getPKCECode(state ?? "")
3435
- );
3391
+ }
3392
+ async handleSignIn(shouldStopAuthn, checkSession, tryRetrievingUserInfo) {
3393
+ const config = await this._storageManager.getConfigData();
3394
+ if (await shouldStopAuthn()) {
3395
+ return Promise.resolve({
3396
+ allowedScopes: "",
3397
+ displayName: "",
3398
+ email: "",
3399
+ sessionState: "",
3400
+ sub: "",
3401
+ tenantDomain: "",
3402
+ username: ""
3403
+ });
3436
3404
  }
3437
- return url;
3438
- };
3439
- const trySignInSilently = async (additionalParams, tokenRequestConfig) => {
3440
- return await _authenticationHelper.trySignInSilently(
3441
- constructSilentSignInUrl,
3442
- requestAccessToken,
3443
- _sessionManagementHelper,
3444
- additionalParams,
3445
- tokenRequestConfig
3446
- );
3447
- };
3448
- const getUser = async () => {
3449
- return _authenticationHelper.getUser();
3450
- };
3451
- const getDecodedIdToken = async () => {
3452
- return _authenticationHelper.getDecodedIdToken();
3453
- };
3454
- const getCrypto = async () => {
3455
- return _authenticationHelper.getCrypto();
3456
- };
3457
- const getIdToken = async () => {
3458
- return _authenticationHelper.getIdToken();
3459
- };
3460
- const getOpenIDProviderEndpoints = async () => {
3461
- return _authenticationHelper.getOpenIDProviderEndpoints();
3462
- };
3463
- const getAccessToken = async () => {
3464
- return _authenticationHelper.getAccessToken();
3465
- };
3466
- const getStorageManager = async () => {
3467
- return _authenticationHelper.getStorageManager();
3468
- };
3469
- const getConfigData = async () => {
3470
- return await _dataLayer.getConfigData();
3471
- };
3472
- const isSignedIn = async () => {
3473
- return _authenticationHelper.isSignedIn();
3474
- };
3475
- const isSessionActive = async () => {
3476
- return await _dataLayer.getSessionStatus() === "true";
3477
- };
3478
- const reInitialize = async (newConfig) => {
3479
- const existingConfig = await _dataLayer.getConfigData();
3480
- const isCheckSessionIframeDifferent = !(existingConfig && existingConfig.endpoints && existingConfig.endpoints.checkSessionIframe && newConfig && newConfig.endpoints && newConfig.endpoints.checkSessionIframe && existingConfig.endpoints.checkSessionIframe === newConfig.endpoints.checkSessionIframe);
3481
- const config2 = { ...existingConfig, ...newConfig };
3482
- await _authenticationClient.reInitialize(config2);
3483
- if (config2.enableOIDCSessionManagement && isCheckSessionIframeDifferent) {
3484
- _sessionManagementHelper.reset();
3485
- checkSession();
3405
+ if (config.storage !== "webWorker" /* WebWorker */) {
3406
+ if (await this._authenticationClient.isSignedIn()) {
3407
+ this._spaHelper.clearRefreshTokenTimeout();
3408
+ this._spaHelper.refreshAccessTokenAutomatically(this);
3409
+ if (config.enableOIDCSessionManagement) {
3410
+ checkSession();
3411
+ }
3412
+ return Promise.resolve(await this._authenticationClient.getUser());
3413
+ }
3486
3414
  }
3487
- };
3488
- return {
3489
- disableHttpHandler,
3490
- enableHttpHandler,
3491
- getAccessToken,
3492
- getUser,
3493
- getConfigData,
3494
- getCrypto,
3495
- getStorageManager,
3496
- getDecodedIdToken,
3497
- getHttpClient,
3498
- getIdToken,
3499
- getOpenIDProviderEndpoints,
3500
- httpRequest,
3501
- httpRequestAll,
3502
- isSignedIn,
3503
- isSessionActive,
3504
- refreshAccessToken,
3505
- exchangeToken,
3506
- revokeAccessToken,
3507
- setHttpRequestErrorCallback,
3508
- setHttpRequestFinishCallback,
3509
- setHttpRequestStartCallback,
3510
- setHttpRequestSuccessCallback,
3511
- signIn,
3512
- signOut,
3513
- trySignInSilently,
3514
- reInitialize
3515
- };
3415
+ const error = new URL(window.location.href).searchParams.get(ERROR);
3416
+ const errorDescription = new URL(window.location.href).searchParams.get(ERROR_DESCRIPTION);
3417
+ if (error) {
3418
+ const url = new URL(window.location.href);
3419
+ url.searchParams.delete(ERROR);
3420
+ url.searchParams.delete(ERROR_DESCRIPTION);
3421
+ history.pushState(null, document.title, url.toString());
3422
+ throw new AsgardeoAuthException2("SPA-AUTH_HELPER-SI-SE01", error, errorDescription ?? "");
3423
+ }
3424
+ if (config.storage === "webWorker" /* WebWorker */ && tryRetrievingUserInfo) {
3425
+ const basicUserInfo = await tryRetrievingUserInfo();
3426
+ if (basicUserInfo) {
3427
+ return basicUserInfo;
3428
+ }
3429
+ }
3430
+ return Promise.resolve(void 0);
3431
+ }
3432
+ async attachTokenToRequestConfig(request) {
3433
+ const requestConfig = { attachToken: true, ...request };
3434
+ if (requestConfig.attachToken) {
3435
+ if (requestConfig.shouldAttachIDPAccessToken) {
3436
+ request.headers = {
3437
+ ...request.headers,
3438
+ Authorization: `Bearer ${await this.getIDPAccessToken()}`
3439
+ };
3440
+ } else {
3441
+ request.headers = {
3442
+ ...request.headers,
3443
+ Authorization: `Bearer ${await this.getAccessToken()}`
3444
+ };
3445
+ }
3446
+ }
3447
+ }
3448
+ async getUser() {
3449
+ return this._authenticationClient.getUser();
3450
+ }
3451
+ async getDecodedIdToken() {
3452
+ return this._authenticationClient.getDecodedIdToken();
3453
+ }
3454
+ async getDecodedIDPIDToken() {
3455
+ return this._authenticationClient.getDecodedIdToken();
3456
+ }
3457
+ async getCrypto() {
3458
+ return this._authenticationClient.getCrypto();
3459
+ }
3460
+ async getIdToken() {
3461
+ return this._authenticationClient.getIdToken();
3462
+ }
3463
+ async getOpenIDProviderEndpoints() {
3464
+ return this._authenticationClient.getOpenIDProviderEndpoints();
3465
+ }
3466
+ async getAccessToken() {
3467
+ return this._authenticationClient.getAccessToken();
3468
+ }
3469
+ async getIDPAccessToken() {
3470
+ return (await this._storageManager.getSessionData())?.access_token;
3471
+ }
3472
+ getStorageManager() {
3473
+ return this._storageManager;
3474
+ }
3475
+ async isSignedIn() {
3476
+ return this._authenticationClient.isSignedIn();
3477
+ }
3516
3478
  };
3517
3479
 
3518
3480
  // src/__legacy__/clients/web-worker-client.ts
3519
- import {
3520
- AsgardeoAuthClient as AsgardeoAuthClient6,
3521
- AsgardeoAuthException as AsgardeoAuthException3,
3522
- OIDCRequestConstants as OIDCRequestConstants4,
3523
- extractPkceStorageKeyFromState as extractPkceStorageKeyFromState3
3524
- } from "@asgardeo/javascript";
3525
3481
  var initiateStore2 = (store) => {
3526
3482
  switch (store) {
3527
3483
  case "localStorage" /* LocalStorage */:
@@ -5379,17 +5335,6 @@ var workerReceiver = (getAuthHelper) => {
5379
5335
  };
5380
5336
  };
5381
5337
 
5382
- // src/constants/StyleConstants.ts
5383
- var StyleConstants = class {
5384
- constructor() {
5385
- }
5386
- };
5387
- /**
5388
- * CSS class prefix for out of the box components.
5389
- */
5390
- __publicField(StyleConstants, "VENDOR_CSS_CLASS_PREFIX", "asgardeo");
5391
- var StyleConstants_default = StyleConstants;
5392
-
5393
5338
  // src/utils/hasAuthParamsInUrl.ts
5394
5339
  var hasAuthParamsInUrl = (params = window.location.search) => {
5395
5340
  const MATCHER = /[?&]code=[^&]+/;
@@ -5397,12 +5342,6 @@ var hasAuthParamsInUrl = (params = window.location.search) => {
5397
5342
  };
5398
5343
  var hasAuthParamsInUrl_default = hasAuthParamsInUrl;
5399
5344
 
5400
- // src/utils/withVendorCSSClassPrefix.ts
5401
- var withVendorCSSClassPrefix = (className) => {
5402
- return `${StyleConstants_default.VENDOR_CSS_CLASS_PREFIX}-${className}`;
5403
- };
5404
- var withVendorCSSClassPrefix_default = withVendorCSSClassPrefix;
5405
-
5406
5345
  // src/AsgardeoBrowserClient.ts
5407
5346
  import { AsgardeoJavaScriptClient } from "@asgardeo/javascript";
5408
5347
  var AsgardeoBrowserClient = class extends AsgardeoJavaScriptClient {
@@ -5431,12 +5370,10 @@ export {
5431
5370
  ResponseType,
5432
5371
  SPAHelper,
5433
5372
  SPAUtils,
5434
- StyleConstants_default as StyleConstants,
5435
5373
  TOKEN_REQUEST_CONFIG_KEY,
5436
5374
  WebWorkerClass,
5437
5375
  WebWorkerClient,
5438
5376
  hasAuthParamsInUrl_default as hasAuthParamsInUrl,
5439
- withVendorCSSClassPrefix_default as withVendorCSSClassPrefix,
5440
5377
  workerReceiver
5441
5378
  };
5442
5379
  /*! Bundled license information: