@asgardeo/browser 0.0.1 → 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
@@ -1914,13 +1914,15 @@ var require_browser = __commonJS({
1914
1914
 
1915
1915
  // src/__legacy__/client.ts
1916
1916
  import {
1917
- AsgardeoAuthException as AsgardeoAuthException5
1917
+ AsgardeoAuthException as AsgardeoAuthException4
1918
1918
  } from "@asgardeo/javascript";
1919
1919
 
1920
- // src/__legacy__/helpers/authentication-helper.ts
1920
+ // src/__legacy__/clients/main-thread-client.ts
1921
1921
  import {
1922
- AsgardeoAuthException,
1923
- extractPkceStorageKeyFromState
1922
+ AsgardeoAuthClient as AsgardeoAuthClient4,
1923
+ OIDCRequestConstants as OIDCRequestConstants3,
1924
+ extractPkceStorageKeyFromState,
1925
+ initializeEmbeddedSignInFlow
1924
1926
  } from "@asgardeo/javascript";
1925
1927
 
1926
1928
  // src/__legacy__/constants/messages-types.ts
@@ -1991,6 +1993,9 @@ var STATE_QUERY = "state";
1991
1993
  // src/__legacy__/constants/errors.ts
1992
1994
  var ACCESS_TOKEN_INVALID = "Access token is invalid";
1993
1995
 
1996
+ // src/__legacy__/helpers/session-management-helper.ts
1997
+ import { AsgardeoAuthClient as AsgardeoAuthClient2, OIDCRequestConstants as OIDCRequestConstants2 } from "@asgardeo/javascript";
1998
+
1994
1999
  // src/__legacy__/utils/message-utils.ts
1995
2000
  var MessageUtils = class {
1996
2001
  // eslint-disable-next-line @typescript-eslint/no-empty-function
@@ -2046,15 +2051,15 @@ var _SPAUtils = class _SPAUtils {
2046
2051
  static setPKCE(pkceKey, pkce) {
2047
2052
  sessionStorage.setItem(pkceKey, pkce);
2048
2053
  }
2049
- static setSignOutURL(url, clientID, instanceID) {
2054
+ static setSignOutURL(url, clientId, instanceID) {
2050
2055
  sessionStorage.setItem(
2051
- `${OIDCRequestConstants.SignOut.Storage.StorageKeys.SIGN_OUT_URL}-instance_${instanceID}-${clientID}`,
2056
+ `${OIDCRequestConstants.SignOut.Storage.StorageKeys.SIGN_OUT_URL}-instance_${instanceID}-${clientId}`,
2052
2057
  url
2053
2058
  );
2054
2059
  }
2055
- static getSignOutURL(clientID, instanceID) {
2060
+ static getSignOutUrl(clientId, instanceID) {
2056
2061
  return sessionStorage.getItem(
2057
- `${OIDCRequestConstants.SignOut.Storage.StorageKeys.SIGN_OUT_URL}-instance_${instanceID}-${clientID}`
2062
+ `${OIDCRequestConstants.SignOut.Storage.StorageKeys.SIGN_OUT_URL}-instance_${instanceID}-${clientId}`
2058
2063
  ) ?? "";
2059
2064
  }
2060
2065
  static removePKCE(pkceKey) {
@@ -2108,7 +2113,7 @@ var _SPAUtils = class _SPAUtils {
2108
2113
  if (AsgardeoAuthClient.isSignOutSuccessful(window.location.href)) {
2109
2114
  const newUrl = window.location.href.split("?")[0];
2110
2115
  history.pushState({}, document.title, newUrl);
2111
- await AsgardeoAuthClient.clearUserSessionData();
2116
+ await AsgardeoAuthClient.clearSession();
2112
2117
  return true;
2113
2118
  }
2114
2119
  return false;
@@ -2203,1678 +2208,1276 @@ __publicField(_SPAUtils, "until", (condition, timeout = 500) => {
2203
2208
  });
2204
2209
  var SPAUtils = _SPAUtils;
2205
2210
 
2206
- // src/__legacy__/helpers/authentication-helper.ts
2207
- var AuthenticationHelper = class {
2208
- constructor(authClient, spaHelper) {
2209
- __publicField(this, "_authenticationClient");
2210
- __publicField(this, "_dataLayer");
2211
- __publicField(this, "_spaHelper");
2212
- __publicField(this, "_instanceID");
2213
- __publicField(this, "_isTokenRefreshing");
2214
- this._authenticationClient = authClient;
2215
- this._dataLayer = this._authenticationClient.getDataLayer();
2216
- this._spaHelper = spaHelper;
2217
- this._instanceID = this._authenticationClient.getInstanceID();
2218
- this._isTokenRefreshing = false;
2219
- }
2220
- enableHttpHandler(httpClient) {
2221
- httpClient?.enableHandler && httpClient.enableHandler();
2222
- }
2223
- disableHttpHandler(httpClient) {
2224
- httpClient?.disableHandler && httpClient.disableHandler();
2225
- }
2226
- initializeSessionManger(config, oidcEndpoints, getSessionState, getAuthzURL, sessionManagementHelper) {
2227
- sessionManagementHelper.initialize(
2228
- config.clientID,
2229
- oidcEndpoints.checkSessionIframe ?? "",
2230
- getSessionState,
2231
- config.checkSessionInterval ?? 3,
2232
- config.sessionRefreshInterval ?? 300,
2233
- config.signInRedirectURL,
2234
- getAuthzURL
2235
- );
2236
- }
2237
- async requestCustomGrant(config, enableRetrievingSignOutURLFromSession) {
2238
- let useDefaultEndpoint = true;
2239
- let matches = false;
2240
- if (config?.tokenEndpoint) {
2241
- useDefaultEndpoint = false;
2242
- for (const baseUrl of [
2243
- ...(await this._dataLayer.getConfigData())?.resourceServerURLs ?? [],
2244
- config.baseUrl
2245
- ]) {
2246
- if (baseUrl && config.tokenEndpoint?.startsWith(baseUrl)) {
2247
- matches = true;
2248
- break;
2249
- }
2250
- }
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();
2251
2235
  }
2252
- if (config.shouldReplayAfterRefresh) {
2253
- this._dataLayer.setTemporaryDataParameter(CUSTOM_GRANT_CONFIG, JSON.stringify(config));
2236
+ if (_sessionRefreshInterval > -1) {
2237
+ sessionRefreshInterval = setInterval(() => {
2238
+ sendPromptNoneRequest();
2239
+ }, _sessionRefreshInterval * 1e3);
2254
2240
  }
2255
- if (useDefaultEndpoint || matches) {
2256
- return this._authenticationClient.requestCustomGrant(config).then(async (response) => {
2257
- if (enableRetrievingSignOutURLFromSession && typeof enableRetrievingSignOutURLFromSession === "function") {
2258
- enableRetrievingSignOutURLFromSession(config);
2259
- }
2260
- if (config.returnsSession) {
2261
- this._spaHelper.refreshAccessTokenAutomatically(this);
2262
- return this._authenticationClient.getBasicUserInfo();
2263
- } else {
2264
- return response;
2265
- }
2266
- }).catch((error) => {
2267
- return Promise.reject(error);
2268
- });
2269
- } else {
2270
- return Promise.reject(
2271
- new AsgardeoAuthException(
2272
- "SPA-MAIN_THREAD_CLIENT-RCG-IV01",
2273
- "Request to the provided endpoint is prohibited.",
2274
- "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`"
2275
- )
2276
- );
2241
+ };
2242
+ const initiateCheckSession = async () => {
2243
+ if (!_checkSessionEndpoint || !_clientID || !_redirectURL) {
2244
+ return;
2277
2245
  }
2278
- }
2279
- async getCustomGrantConfigData() {
2280
- const configString = await this._dataLayer.getTemporaryDataParameter(CUSTOM_GRANT_CONFIG);
2281
- if (configString) {
2282
- return JSON.parse(configString);
2283
- } else {
2284
- 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
+ }
2285
2256
  }
2286
- }
2287
- async refreshAccessToken(enableRetrievingSignOutURLFromSession) {
2288
- try {
2289
- await this._authenticationClient.refreshAccessToken();
2290
- const customGrantConfig = await this.getCustomGrantConfigData();
2291
- if (customGrantConfig) {
2292
- await this.requestCustomGrant(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;
2293
2272
  }
2294
- this._spaHelper.refreshAccessTokenAutomatically(this);
2295
- return this._authenticationClient.getBasicUserInfo();
2296
- } catch (error) {
2297
- const refreshTokenError = {
2298
- 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
+ }
2299
2294
  };
2300
- window.postMessage(refreshTokenError);
2301
- 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;
2302
2304
  }
2303
- }
2304
- async retryFailedRequests(failedRequest) {
2305
- const httpClient = failedRequest.httpClient;
2306
- const requestConfig = failedRequest.requestConfig;
2307
- const isHttpHandlerEnabled = failedRequest.isHttpHandlerEnabled;
2308
- const httpErrorCallback = failedRequest.httpErrorCallback;
2309
- const httpFinishCallback = failedRequest.httpFinishCallback;
2310
- await SPAUtils.until(() => !this._isTokenRefreshing);
2311
- try {
2312
- const httpResponse = await httpClient.request(requestConfig);
2313
- return Promise.resolve(httpResponse);
2314
- } catch (error) {
2315
- if (isHttpHandlerEnabled) {
2316
- if (typeof httpErrorCallback === "function") {
2317
- 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;
2318
2328
  }
2319
- if (typeof httpFinishCallback === "function") {
2320
- 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;
2321
2353
  }
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;
2322
2361
  }
2323
- return Promise.reject(error);
2324
2362
  }
2325
- }
2326
- async httpRequest(httpClient, requestConfig, isHttpHandlerEnabled, httpErrorCallback, httpFinishCallback, enableRetrievingSignOutURLFromSession) {
2327
- let matches = false;
2328
- const config = await this._dataLayer.getConfigData();
2329
- for (const baseUrl of [...await config?.resourceServerURLs ?? [], config.baseUrl]) {
2330
- if (baseUrl && requestConfig?.url?.startsWith(baseUrl)) {
2331
- matches = true;
2332
- break;
2363
+ return false;
2364
+ };
2365
+ return async (signOut, storage, setSessionState) => {
2366
+ let rpIFrame = document.createElement("iframe");
2367
+ rpIFrame.setAttribute("id", RP_IFRAME);
2368
+ rpIFrame.style.display = "none";
2369
+ let rpIframeLoaded = false;
2370
+ rpIFrame.onload = () => {
2371
+ rpIFrame = document.getElementById(RP_IFRAME);
2372
+ const rpDoc = rpIFrame?.contentDocument;
2373
+ const opIFrame = rpDoc?.createElement("iframe");
2374
+ if (opIFrame) {
2375
+ opIFrame.setAttribute("id", OP_IFRAME);
2376
+ opIFrame.style.display = "none";
2333
2377
  }
2378
+ const promptNoneIFrame = rpDoc?.createElement("iframe");
2379
+ if (promptNoneIFrame) {
2380
+ promptNoneIFrame.setAttribute("id", PROMPT_NONE_IFRAME);
2381
+ promptNoneIFrame.style.display = "none";
2382
+ }
2383
+ opIFrame && rpIFrame?.contentDocument?.body?.appendChild(opIFrame);
2384
+ promptNoneIFrame && rpIFrame?.contentDocument?.body?.appendChild(promptNoneIFrame);
2385
+ rpIframeLoaded = true;
2386
+ };
2387
+ document?.body?.appendChild(rpIFrame);
2388
+ _signOut = signOut;
2389
+ _storage = storage;
2390
+ _setSessionState = setSessionState;
2391
+ const sleep = () => {
2392
+ return new Promise((resolve) => setTimeout(resolve, 1));
2393
+ };
2394
+ while (rpIframeLoaded === false) {
2395
+ await sleep();
2334
2396
  }
2335
- if (matches) {
2336
- return httpClient.request(requestConfig).then((response) => {
2337
- return Promise.resolve(response);
2338
- }).catch(async (error) => {
2339
- if (error?.response?.status === 401 || !error?.response) {
2340
- if (this._isTokenRefreshing) {
2341
- return this.retryFailedRequests({
2342
- enableRetrievingSignOutURLFromSession,
2343
- httpClient,
2344
- httpErrorCallback,
2345
- httpFinishCallback,
2346
- isHttpHandlerEnabled,
2347
- requestConfig
2348
- });
2349
- }
2350
- this._isTokenRefreshing = true;
2351
- let refreshAccessTokenResponse;
2352
- try {
2353
- refreshAccessTokenResponse = await this.refreshAccessToken(enableRetrievingSignOutURLFromSession);
2354
- this._isTokenRefreshing = false;
2355
- } catch (refreshError) {
2356
- this._isTokenRefreshing = false;
2357
- if (isHttpHandlerEnabled) {
2358
- if (typeof httpErrorCallback === "function") {
2359
- await httpErrorCallback({
2360
- ...error,
2361
- code: ACCESS_TOKEN_INVALID
2362
- });
2363
- }
2364
- if (typeof httpFinishCallback === "function") {
2365
- httpFinishCallback();
2366
- }
2367
- }
2368
- throw new AsgardeoAuthException(
2369
- "SPA-AUTH_HELPER-HR-SE01",
2370
- refreshError?.name ?? "Refresh token request failed.",
2371
- refreshError?.message ?? "An error occurred while trying to refresh the access token following a 401 response from the server."
2372
- );
2373
- }
2374
- if (refreshAccessTokenResponse) {
2375
- try {
2376
- const httpResponse = await httpClient.request(requestConfig);
2377
- return Promise.resolve(httpResponse);
2378
- } catch (error2) {
2379
- if (isHttpHandlerEnabled) {
2380
- if (typeof httpErrorCallback === "function") {
2381
- await httpErrorCallback(error2);
2382
- }
2383
- if (typeof httpFinishCallback === "function") {
2384
- httpFinishCallback();
2385
- }
2386
- }
2387
- return Promise.reject(error2);
2388
- }
2389
- }
2390
- }
2391
- if (isHttpHandlerEnabled) {
2392
- if (typeof httpErrorCallback === "function") {
2393
- await httpErrorCallback(error);
2394
- }
2395
- if (typeof httpFinishCallback === "function") {
2396
- httpFinishCallback();
2397
- }
2398
- }
2399
- return Promise.reject(error);
2400
- });
2401
- } else {
2402
- return Promise.reject(
2403
- new AsgardeoAuthException(
2404
- "SPA-AUTH_HELPER-HR-IV02",
2405
- "Request to the provided endpoint is prohibited.",
2406
- "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`"
2407
- )
2408
- );
2409
- }
2397
+ return {
2398
+ initialize,
2399
+ receivePromptNoneResponse,
2400
+ reset
2401
+ };
2402
+ };
2403
+ })();
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();
2410
2413
  }
2411
- async httpRequestAll(requestConfigs, httpClient, isHttpHandlerEnabled, httpErrorCallback, httpFinishCallback) {
2412
- let matches = true;
2413
- const config = await this._dataLayer.getConfigData();
2414
- for (const requestConfig of requestConfigs) {
2415
- let urlMatches = false;
2416
- for (const baseUrl of [...(await config)?.resourceServerURLs ?? [], config.baseUrl]) {
2417
- if (baseUrl && requestConfig.url?.startsWith(baseUrl)) {
2418
- urlMatches = true;
2419
- break;
2420
- }
2421
- }
2422
- if (!urlMatches) {
2423
- matches = false;
2424
- break;
2425
- }
2414
+ async refreshAccessTokenAutomatically(authenticationHelper) {
2415
+ const shouldRefreshAutomatically = (await this._storageManager.getConfigData())?.periodicTokenRefresh ?? false;
2416
+ if (!shouldRefreshAutomatically) {
2417
+ return;
2426
2418
  }
2427
- const requests = [];
2428
- if (matches) {
2429
- requestConfigs.forEach((request) => {
2430
- requests.push(httpClient.request(request));
2431
- });
2432
- return httpClient?.all && httpClient.all(requests).then((responses) => {
2433
- return Promise.resolve(responses);
2434
- }).catch(async (error) => {
2435
- if (error?.response?.status === 401 || !error?.response) {
2436
- let refreshTokenResponse;
2437
- try {
2438
- refreshTokenResponse = await this._authenticationClient.refreshAccessToken();
2439
- } catch (refreshError) {
2440
- if (isHttpHandlerEnabled) {
2441
- if (typeof httpErrorCallback === "function") {
2442
- await httpErrorCallback({
2443
- ...error,
2444
- code: ACCESS_TOKEN_INVALID
2445
- });
2446
- }
2447
- if (typeof httpFinishCallback === "function") {
2448
- httpFinishCallback();
2449
- }
2450
- }
2451
- throw new AsgardeoAuthException(
2452
- "SPA-AUTH_HELPER-HRA-SE01",
2453
- refreshError?.name ?? "Refresh token request failed.",
2454
- refreshError?.message ?? "An error occurred while trying to refresh the access token following a 401 response from the server."
2455
- );
2456
- }
2457
- if (refreshTokenResponse) {
2458
- return httpClient.all && httpClient.all(requests).then((response) => {
2459
- return Promise.resolve(response);
2460
- }).catch(async (error2) => {
2461
- if (isHttpHandlerEnabled) {
2462
- if (typeof httpErrorCallback === "function") {
2463
- await httpErrorCallback(error2);
2464
- }
2465
- if (typeof httpFinishCallback === "function") {
2466
- httpFinishCallback();
2467
- }
2468
- }
2469
- return Promise.reject(error2);
2470
- });
2471
- }
2472
- }
2473
- if (isHttpHandlerEnabled) {
2474
- if (typeof httpErrorCallback === "function") {
2475
- await httpErrorCallback(error);
2476
- }
2477
- if (typeof httpFinishCallback === "function") {
2478
- httpFinishCallback();
2479
- }
2480
- }
2481
- return Promise.reject(error);
2482
- });
2483
- } else {
2484
- throw new AsgardeoAuthException(
2485
- "SPA-AUTH_HELPER-HRA-IV02",
2486
- "Request to the provided endpoint is prohibited.",
2487
- "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`"
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)
2488
2429
  );
2489
2430
  }
2490
2431
  }
2491
- async requestAccessToken(authorizationCode, sessionState, checkSession, pkce, state, tokenRequestConfig) {
2492
- const config = await this._dataLayer.getConfigData();
2493
- if (config.storage === "browserMemory" /* BrowserMemory */ && config.enablePKCE && sessionState) {
2494
- const pkce2 = SPAUtils.getPKCE(extractPkceStorageKeyFromState(sessionState));
2495
- await this._authenticationClient.setPKCECode(extractPkceStorageKeyFromState(sessionState), pkce2);
2496
- } else if (config.storage === "webWorker" /* WebWorker */ && pkce) {
2497
- await this._authenticationClient.setPKCECode(pkce, state ?? "");
2498
- }
2499
- if (authorizationCode) {
2500
- return this._authenticationClient.requestAccessToken(authorizationCode, sessionState ?? "", state ?? "", void 0, tokenRequestConfig).then(async () => {
2501
- if (config.storage !== "webWorker" /* WebWorker */) {
2502
- SPAUtils.setSignOutURL(await this._authenticationClient.getSignOutURL(), config.clientID, this._instanceID);
2503
- if (this._spaHelper) {
2504
- this._spaHelper.clearRefreshTokenTimeout();
2505
- this._spaHelper.refreshAccessTokenAutomatically(this);
2506
- }
2507
- if (checkSession && typeof checkSession === "function" && config.enableOIDCSessionManagement) {
2508
- checkSession();
2509
- }
2510
- } else {
2511
- if (this._spaHelper) {
2512
- this._spaHelper.refreshAccessTokenAutomatically(this);
2513
- }
2514
- }
2515
- return this._authenticationClient.getBasicUserInfo();
2516
- }).catch((error) => {
2517
- return Promise.reject(error);
2518
- });
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
+ );
2519
2439
  }
2520
- return Promise.reject(
2521
- new AsgardeoAuthException(
2522
- "SPA-AUTH_HELPER-RAT1-NF01",
2523
- "No authorization code.",
2524
- "No authorization code was found."
2525
- )
2526
- );
2440
+ return -1;
2527
2441
  }
2528
- async trySignInSilently(constructSilentSignInUrl, requestAccessToken, sessionManagementHelper, additionalParams, tokenRequestConfig) {
2529
- if (SPAUtils.isInitializedSilentSignIn()) {
2530
- await sessionManagementHelper.receivePromptNoneResponse();
2531
- return Promise.resolve({
2532
- allowedScopes: "",
2533
- displayName: "",
2534
- email: "",
2535
- sessionState: "",
2536
- sub: "",
2537
- tenantDomain: "",
2538
- username: ""
2539
- });
2442
+ async clearRefreshTokenTimeout(timer) {
2443
+ if (timer) {
2444
+ clearTimeout(timer);
2445
+ return;
2540
2446
  }
2541
- const rpIFrame = document.getElementById(RP_IFRAME);
2542
- const promptNoneIFrame = rpIFrame?.contentDocument?.getElementById(
2543
- PROMPT_NONE_IFRAME
2544
- );
2545
- try {
2546
- const url = await constructSilentSignInUrl(additionalParams);
2547
- promptNoneIFrame.src = url;
2548
- } catch (error) {
2549
- return Promise.reject(error);
2447
+ const refreshTimer = await this.getRefreshTimeoutTimer();
2448
+ if (refreshTimer !== -1) {
2449
+ clearTimeout(refreshTimer);
2550
2450
  }
2551
- return new Promise((resolve, reject) => {
2552
- const timer = setTimeout(() => {
2553
- resolve(false);
2554
- }, 1e4);
2555
- const listenToPromptNoneIFrame = async (e) => {
2556
- const data = e.data;
2557
- if (data?.type == CHECK_SESSION_SIGNED_OUT) {
2558
- window.removeEventListener("message", listenToPromptNoneIFrame);
2559
- clearTimeout(timer);
2560
- resolve(false);
2561
- }
2562
- if (data?.type == CHECK_SESSION_SIGNED_IN && data?.data?.code) {
2563
- requestAccessToken(data?.data?.code, data?.data?.sessionState, data?.data?.state, tokenRequestConfig).then((response) => {
2564
- window.removeEventListener("message", listenToPromptNoneIFrame);
2565
- resolve(response);
2566
- }).catch((error) => {
2567
- window.removeEventListener("message", listenToPromptNoneIFrame);
2568
- reject(error);
2569
- }).finally(() => {
2570
- clearTimeout(timer);
2571
- });
2572
- }
2573
- };
2574
- window.addEventListener("message", listenToPromptNoneIFrame);
2451
+ }
2452
+ };
2453
+
2454
+ // src/__legacy__/http-client/clients/axios-http-client.ts
2455
+ import axios from "axios";
2456
+
2457
+ // src/__legacy__/http-client/helpers/decorators.ts
2458
+ function staticDecorator() {
2459
+ return (_constructor) => {
2460
+ };
2461
+ }
2462
+
2463
+ // src/__legacy__/http-client/clients/axios-http-client.ts
2464
+ var HttpClient = class {
2465
+ /**
2466
+ * Private constructor to avoid object instantiation from outside
2467
+ * the class.
2468
+ *
2469
+ * @hideconstructor
2470
+ */
2471
+ constructor() {
2472
+ __publicField(this, "attachToken", () => Promise.resolve());
2473
+ __publicField(this, "requestStartCallback", () => null);
2474
+ __publicField(this, "requestSuccessCallback", () => null);
2475
+ __publicField(this, "requestErrorCallback", () => null);
2476
+ __publicField(this, "requestFinishCallback", () => null);
2477
+ this.init = this.init.bind(this);
2478
+ this.setHttpRequestErrorCallback = this.setHttpRequestErrorCallback.bind(this);
2479
+ this.setHttpRequestFinishCallback = this.setHttpRequestFinishCallback.bind(this);
2480
+ this.setHttpRequestStartCallback = this.setHttpRequestStartCallback.bind(this);
2481
+ this.setHttpRequestSuccessCallback = this.setHttpRequestSuccessCallback.bind(this);
2482
+ }
2483
+ /**
2484
+ * Returns an aggregated instance of type `HttpInstance` of `HttpClient`.
2485
+ *
2486
+ * @return {any}
2487
+ */
2488
+ static getInstance() {
2489
+ if (this.axiosInstance) {
2490
+ return this.axiosInstance;
2491
+ }
2492
+ this.axiosInstance = axios.create({
2493
+ withCredentials: true
2575
2494
  });
2495
+ if (!this.clientInstance) {
2496
+ this.clientInstance = new HttpClient();
2497
+ }
2498
+ this.axiosInstance.interceptors.request.use(async (request) => await this.clientInstance.requestHandler(request));
2499
+ this.axiosInstance.interceptors.response.use(
2500
+ (response) => this.clientInstance.successHandler(response),
2501
+ (error) => this.clientInstance.errorHandler(error)
2502
+ );
2503
+ this.axiosInstance.all = axios.all;
2504
+ this.axiosInstance.spread = axios.spread;
2505
+ this.axiosInstance.init = this.clientInstance.init;
2506
+ this.axiosInstance.enableHandler = this.clientInstance.enableHandler;
2507
+ this.axiosInstance.disableHandler = this.clientInstance.disableHandler;
2508
+ this.axiosInstance.disableHandlerWithTimeout = this.clientInstance.disableHandlerWithTimeout;
2509
+ this.axiosInstance.setHttpRequestStartCallback = this.clientInstance.setHttpRequestStartCallback;
2510
+ this.axiosInstance.setHttpRequestSuccessCallback = this.clientInstance.setHttpRequestSuccessCallback;
2511
+ this.axiosInstance.setHttpRequestErrorCallback = this.clientInstance.setHttpRequestErrorCallback;
2512
+ this.axiosInstance.setHttpRequestFinishCallback = this.clientInstance.setHttpRequestFinishCallback;
2513
+ return this.axiosInstance;
2576
2514
  }
2577
- async handleSignIn(shouldStopAuthn, checkSession, tryRetrievingUserInfo) {
2578
- const config = await this._dataLayer.getConfigData();
2579
- if (await shouldStopAuthn()) {
2580
- return Promise.resolve({
2581
- allowedScopes: "",
2582
- displayName: "",
2583
- email: "",
2584
- sessionState: "",
2585
- sub: "",
2586
- tenantDomain: "",
2587
- username: ""
2515
+ /**
2516
+ * Intercepts all the requests.
2517
+ * If the `isHandlerEnabled` flag is set to true, fires the `requestStartCallback`
2518
+ * and retrieves the access token from the server and attaches it to the request.
2519
+ * Else, just returns the original request.
2520
+ *
2521
+ * @param {HttpRequestConfig} request - Original request.
2522
+ * @return {HttpRequestConfig}
2523
+ */
2524
+ async requestHandler(request) {
2525
+ await this.attachToken(request);
2526
+ if (request?.shouldEncodeToFormData) {
2527
+ const data = request?.data;
2528
+ const formData = new FormData();
2529
+ Object.keys(data).forEach((key) => {
2530
+ formData.append(key, data[key]);
2588
2531
  });
2532
+ request.data = formData;
2589
2533
  }
2590
- if (config.storage !== "webWorker" /* WebWorker */) {
2591
- if (await this._authenticationClient.isAuthenticated()) {
2592
- this._spaHelper.clearRefreshTokenTimeout();
2593
- this._spaHelper.refreshAccessTokenAutomatically(this);
2594
- if (config.enableOIDCSessionManagement) {
2595
- checkSession();
2596
- }
2597
- return Promise.resolve(await this._authenticationClient.getBasicUserInfo());
2534
+ request.startTimeInMs = (/* @__PURE__ */ new Date()).getTime();
2535
+ if (HttpClient.isHandlerEnabled) {
2536
+ if (this.requestStartCallback && typeof this.requestStartCallback === "function") {
2537
+ this.requestStartCallback(request);
2598
2538
  }
2599
2539
  }
2600
- const error = new URL(window.location.href).searchParams.get(ERROR);
2601
- const errorDescription = new URL(window.location.href).searchParams.get(ERROR_DESCRIPTION);
2602
- if (error) {
2603
- const url = new URL(window.location.href);
2604
- url.searchParams.delete(ERROR);
2605
- url.searchParams.delete(ERROR_DESCRIPTION);
2606
- history.pushState(null, document.title, url.toString());
2607
- throw new AsgardeoAuthException("SPA-AUTH_HELPER-SI-SE01", error, errorDescription ?? "");
2608
- }
2609
- if (config.storage === "webWorker" /* WebWorker */ && tryRetrievingUserInfo) {
2610
- const basicUserInfo = await tryRetrievingUserInfo();
2611
- if (basicUserInfo) {
2612
- return basicUserInfo;
2540
+ return request;
2541
+ }
2542
+ /**
2543
+ * Handles response errors.
2544
+ * If the `isHandlerEnabled` flag is set to true, fires the `requestErrorCallback`
2545
+ * and the `requestFinishCallback` functions. Else, just returns the original error.
2546
+ *
2547
+ * @param {HttpError} error - Original error.
2548
+ * @return {HttpError}
2549
+ */
2550
+ errorHandler(error) {
2551
+ if (HttpClient.isHandlerEnabled) {
2552
+ if (this.requestErrorCallback && typeof this.requestErrorCallback === "function") {
2553
+ this.requestErrorCallback(error);
2554
+ }
2555
+ if (this.requestFinishCallback && typeof this.requestFinishCallback === "function") {
2556
+ this.requestFinishCallback();
2613
2557
  }
2614
2558
  }
2615
- return Promise.resolve(void 0);
2559
+ throw error;
2616
2560
  }
2617
- async attachTokenToRequestConfig(request) {
2618
- const requestConfig = { attachToken: true, ...request };
2619
- if (requestConfig.attachToken) {
2620
- if (requestConfig.shouldAttachIDPAccessToken) {
2621
- request.headers = {
2622
- ...request.headers,
2623
- Authorization: `Bearer ${await this.getIDPAccessToken()}`
2624
- };
2625
- } else {
2626
- request.headers = {
2627
- ...request.headers,
2628
- Authorization: `Bearer ${await this.getAccessToken()}`
2629
- };
2561
+ /**
2562
+ * Handles response success.
2563
+ * If the `isHandlerEnabled` flag is set to true, fires the `requestSuccessCallback`
2564
+ * and the `requestFinishCallback` functions. Else, just returns the original response.
2565
+ *
2566
+ * @param {HttpResponse} response - Original response.
2567
+ * @return {HttpResponse}
2568
+ */
2569
+ successHandler(response) {
2570
+ if (HttpClient.isHandlerEnabled) {
2571
+ if (this.requestSuccessCallback && typeof this.requestSuccessCallback === "function") {
2572
+ this.requestSuccessCallback(response);
2573
+ }
2574
+ if (this.requestFinishCallback && typeof this.requestFinishCallback === "function") {
2575
+ this.requestFinishCallback();
2630
2576
  }
2631
2577
  }
2578
+ return response;
2579
+ }
2580
+ /**
2581
+ * Initializes the Http client.
2582
+ *
2583
+ * @param isHandlerEnabled - Flag to toggle handler enablement.
2584
+ * @param requestStartCallback - Callback function to be triggered on request start.
2585
+ * @param requestSuccessCallback - Callback function to be triggered on request success.
2586
+ * @param requestErrorCallback - Callback function to be triggered on request error.
2587
+ * @param requestFinishCallback - Callback function to be triggered on request error.
2588
+ */
2589
+ async init(isHandlerEnabled = true, attachToken) {
2590
+ HttpClient.isHandlerEnabled = isHandlerEnabled;
2591
+ this.attachToken = attachToken;
2632
2592
  }
2633
- async getBasicUserInfo() {
2634
- return this._authenticationClient.getBasicUserInfo();
2593
+ /**
2594
+ * Enables the handler.
2595
+ */
2596
+ enableHandler() {
2597
+ HttpClient.isHandlerEnabled = true;
2635
2598
  }
2636
- async getDecodedIDToken() {
2637
- return this._authenticationClient.getDecodedIDToken();
2599
+ /**
2600
+ * Disables the handler.
2601
+ */
2602
+ disableHandler() {
2603
+ HttpClient.isHandlerEnabled = false;
2638
2604
  }
2639
- async getDecodedIDPIDToken() {
2640
- return this._authenticationClient.getDecodedIDToken();
2605
+ /**
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);
2641
2615
  }
2642
- async getCryptoHelper() {
2643
- return this._authenticationClient.getCryptoHelper();
2616
+ setHttpRequestStartCallback(callback) {
2617
+ this.requestStartCallback = callback;
2644
2618
  }
2645
- async getIDToken() {
2646
- return this._authenticationClient.getIDToken();
2619
+ setHttpRequestSuccessCallback(callback) {
2620
+ this.requestSuccessCallback = callback;
2647
2621
  }
2648
- async getOIDCServiceEndpoints() {
2649
- return this._authenticationClient.getOIDCServiceEndpoints();
2622
+ setHttpRequestErrorCallback(callback) {
2623
+ this.requestErrorCallback = callback;
2650
2624
  }
2651
- async getAccessToken() {
2652
- return this._authenticationClient.getAccessToken();
2625
+ setHttpRequestFinishCallback(callback) {
2626
+ this.requestFinishCallback = callback;
2653
2627
  }
2654
- async getIDPAccessToken() {
2655
- return (await this._dataLayer.getSessionData())?.access_token;
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);
2656
2641
  }
2657
- getDataLayer() {
2658
- return this._dataLayer;
2642
+ async getData(key) {
2643
+ return localStorage.getItem(key) ?? "{}";
2659
2644
  }
2660
- async isAuthenticated() {
2661
- return this._authenticationClient.isAuthenticated();
2645
+ async removeData(key) {
2646
+ localStorage.removeItem(key);
2662
2647
  }
2663
2648
  };
2664
2649
 
2665
- // src/__legacy__/helpers/spa-helper.ts
2666
- import { TokenConstants } from "@asgardeo/javascript";
2667
- var SPAHelper = class {
2668
- constructor(authClient) {
2669
- __publicField(this, "_authenticationClient");
2670
- __publicField(this, "_dataLayer");
2671
- this._authenticationClient = authClient;
2672
- this._dataLayer = this._authenticationClient.getDataLayer();
2650
+ // src/__legacy__/stores/memory-store.ts
2651
+ var MemoryStore = class {
2652
+ constructor() {
2653
+ __publicField(this, "_data");
2654
+ this._data = /* @__PURE__ */ new Map();
2673
2655
  }
2674
- async refreshAccessTokenAutomatically(authenticationHelper) {
2675
- const shouldRefreshAutomatically = (await this._dataLayer.getConfigData())?.periodicTokenRefresh ?? false;
2676
- if (!shouldRefreshAutomatically) {
2677
- return;
2678
- }
2679
- const sessionData = await this._dataLayer.getSessionData();
2680
- if (sessionData.refresh_token) {
2681
- const expiryTime = parseInt(sessionData.expires_in);
2682
- const time = expiryTime <= 10 ? expiryTime : expiryTime - 10;
2683
- const timer = setTimeout(async () => {
2684
- await authenticationHelper.refreshAccessToken();
2685
- }, time * 1e3);
2686
- await this._dataLayer.setTemporaryDataParameter(
2687
- TokenConstants.Storage.StorageKeys.REFRESH_TOKEN_TIMER,
2688
- JSON.stringify(timer)
2689
- );
2690
- }
2656
+ async setData(key, value) {
2657
+ this._data.set(key, value);
2691
2658
  }
2692
- async getRefreshTimeoutTimer() {
2693
- if (await this._dataLayer.getTemporaryDataParameter(TokenConstants.Storage.StorageKeys.REFRESH_TOKEN_TIMER)) {
2694
- return JSON.parse(
2695
- await this._dataLayer.getTemporaryDataParameter(
2696
- TokenConstants.Storage.StorageKeys.REFRESH_TOKEN_TIMER
2697
- )
2698
- );
2699
- }
2700
- return -1;
2659
+ async getData(key) {
2660
+ return this._data?.get(key) ?? "{}";
2701
2661
  }
2702
- async clearRefreshTokenTimeout(timer) {
2703
- if (timer) {
2704
- clearTimeout(timer);
2705
- return;
2706
- }
2707
- const refreshTimer = await this.getRefreshTimeoutTimer();
2708
- if (refreshTimer !== -1) {
2709
- clearTimeout(refreshTimer);
2710
- }
2662
+ async removeData(key) {
2663
+ this._data.delete(key);
2711
2664
  }
2712
2665
  };
2713
2666
 
2714
- // src/__legacy__/helpers/session-management-helper.ts
2715
- import { AsgardeoAuthClient as AsgardeoAuthClient4, OIDCRequestConstants as OIDCRequestConstants2 } from "@asgardeo/javascript";
2716
- var SessionManagementHelper = /* @__PURE__ */ (() => {
2717
- let _clientID;
2718
- let _checkSessionEndpoint;
2719
- let _sessionState;
2720
- let _interval;
2721
- let _redirectURL;
2722
- let _sessionRefreshInterval;
2723
- let _signOut;
2724
- let _sessionRefreshIntervalTimeout;
2725
- let _checkSessionIntervalTimeout;
2726
- let _storage;
2727
- let _setSessionState;
2728
- let _getAuthorizationURL;
2729
- const initialize = (clientID, checkSessionEndpoint, getSessionState, interval, sessionRefreshInterval, redirectURL, getAuthorizationURL) => {
2730
- _clientID = clientID;
2731
- _checkSessionEndpoint = checkSessionEndpoint;
2732
- _sessionState = getSessionState;
2733
- _interval = interval;
2734
- _redirectURL = redirectURL;
2735
- _sessionRefreshInterval = sessionRefreshInterval;
2736
- _getAuthorizationURL = getAuthorizationURL;
2737
- if (_interval > -1) {
2738
- initiateCheckSession();
2739
- }
2740
- if (_sessionRefreshInterval > -1) {
2741
- sessionRefreshInterval = setInterval(() => {
2742
- sendPromptNoneRequest();
2743
- }, _sessionRefreshInterval * 1e3);
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.
2690
+ *
2691
+ * @returns {string} base 64 url encoded value.
2692
+ */
2693
+ base64URLEncode(value) {
2694
+ return base64url.encode(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
2695
+ }
2696
+ base64URLDecode(value) {
2697
+ return base64url.decode(value).toString();
2698
+ }
2699
+ hashSha256(data) {
2700
+ return import_buffer.Buffer.from(sha256(new TextEncoder().encode(data)));
2701
+ }
2702
+ generateRandomBytes(length) {
2703
+ return (0, import_randombytes.default)(length);
2704
+ }
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;
2744
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
+ });
2732
+ }
2733
+ };
2734
+
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();
2746
+ }
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);
2745
2771
  };
2746
- const initiateCheckSession = async () => {
2747
- if (!_checkSessionEndpoint || !_clientID || !_redirectURL) {
2748
- return;
2749
- }
2750
- const OP_IFRAME2 = "opIFrame";
2751
- async function checkSession() {
2752
- const sessionState = await _sessionState();
2753
- if (Boolean(_clientID) && Boolean(sessionState)) {
2754
- const message = `${_clientID} ${sessionState}`;
2755
- const rpIFrame2 = document.getElementById(RP_IFRAME);
2756
- const opIframe2 = rpIFrame2?.contentDocument?.getElementById(OP_IFRAME2);
2757
- const win = opIframe2.contentWindow;
2758
- win?.postMessage(message, _checkSessionEndpoint);
2759
- }
2760
- }
2761
- const rpIFrame = document.getElementById(RP_IFRAME);
2762
- const opIframe = rpIFrame?.contentDocument?.getElementById(OP_IFRAME2);
2763
- opIframe.src = _checkSessionEndpoint + "?client_id=" + _clientID + "&redirect_uri=" + _redirectURL;
2764
- _checkSessionIntervalTimeout = setInterval(checkSession, _interval * 1e3);
2765
- listenToResponseFromOPIFrame();
2772
+ _httpClient?.init && await _httpClient.init(true, attachToken);
2773
+ const setHttpRequestStartCallback = (callback) => {
2774
+ _httpClient?.setHttpRequestStartCallback && _httpClient.setHttpRequestStartCallback(callback);
2766
2775
  };
2767
- const reset = () => {
2768
- clearInterval(_checkSessionIntervalTimeout);
2769
- clearInterval(_sessionRefreshIntervalTimeout);
2776
+ const setHttpRequestSuccessCallback = (callback) => {
2777
+ _httpClient?.setHttpRequestSuccessCallback && _httpClient.setHttpRequestSuccessCallback(callback);
2770
2778
  };
2771
- const listenToResponseFromOPIFrame = () => {
2772
- async function receiveMessage(e) {
2773
- const targetOrigin = _checkSessionEndpoint;
2774
- if (!targetOrigin || targetOrigin?.indexOf(e.origin) < 0 || e?.data?.type === SET_SESSION_STATE_FROM_IFRAME) {
2775
- return;
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));
2776
2866
  }
2777
- if (e.data === "unchanged") {
2778
- } else if (e.data === "error") {
2779
- window.location.href = await _signOut();
2780
- } else if (e.data === "changed") {
2781
- sendPromptNoneRequest();
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
+ });
2782
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);
2783
2895
  }
2784
- window?.addEventListener("message", receiveMessage, false);
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;
2785
2903
  };
2786
- const sendPromptNoneRequest = async () => {
2787
- const rpIFrame = document.getElementById(RP_IFRAME);
2788
- const promptNoneIFrame = rpIFrame?.contentDocument?.getElementById(
2789
- PROMPT_NONE_IFRAME
2790
- );
2791
- if (SPAUtils.canSendPromptNoneRequest()) {
2792
- SPAUtils.setPromptNoneRequestSent(true);
2793
- const receiveMessageListener = (e) => {
2794
- if (e?.data?.type === SET_SESSION_STATE_FROM_IFRAME) {
2795
- _setSessionState(e?.data?.data ?? "");
2796
- window?.removeEventListener("message", receiveMessageListener);
2797
- }
2798
- };
2799
- if (_storage === "browserMemory" /* BrowserMemory */ || _storage === "webWorker" /* WebWorker */) {
2800
- window?.addEventListener("message", receiveMessageListener);
2801
- }
2802
- const promptNoneURL = await _getAuthorizationURL({
2803
- prompt: "none",
2804
- response_mode: "query",
2805
- state: STATE
2806
- });
2807
- promptNoneIFrame.src = promptNoneURL;
2904
+ const enableRetrievingSignOutURLFromSession = (config2) => {
2905
+ if (config2.preventSignOutURLUpdate) {
2906
+ _getSignOutURLFromSessionStorage = true;
2808
2907
  }
2809
2908
  };
2810
- const receivePromptNoneResponse = async (setSessionState) => {
2811
- const state = new URL(window.location.href).searchParams.get(STATE_QUERY);
2812
- const sessionState = new URL(window.location.href).searchParams.get(OIDCRequestConstants2.Params.SESSION_STATE);
2813
- const parent = window.parent.parent;
2814
- if (state !== null && (state.includes(STATE) || state.includes(SILENT_SIGN_IN_STATE))) {
2815
- const code = new URL(window.location.href).searchParams.get("code");
2816
- if (code !== null && code.length !== 0) {
2817
- if (state.includes(SILENT_SIGN_IN_STATE)) {
2818
- const message = {
2819
- data: {
2820
- code,
2821
- sessionState: sessionState ?? "",
2822
- state
2823
- },
2824
- type: CHECK_SESSION_SIGNED_IN
2825
- };
2826
- sessionStorage.setItem(INITIALIZED_SILENT_SIGN_IN, "false");
2827
- parent.postMessage(message, parent.origin);
2828
- SPAUtils.setPromptNoneRequestSent(false);
2829
- window.location.href = "about:blank";
2830
- await SPAUtils.waitTillPageRedirect();
2831
- return true;
2832
- }
2833
- const newSessionState = new URL(window.location.href).searchParams.get("session_state");
2834
- if (_storage === "localStorage" /* LocalStorage */ || _storage === "sessionStorage" /* SessionStorage */) {
2835
- setSessionState && await setSessionState(newSessionState);
2836
- } else {
2837
- const message = {
2838
- data: newSessionState ?? "",
2839
- type: SET_SESSION_STATE_FROM_IFRAME
2840
- };
2841
- window?.parent?.parent?.postMessage(message);
2842
- }
2843
- SPAUtils.setPromptNoneRequestSent(false);
2844
- window.location.href = "about:blank";
2845
- await SPAUtils.waitTillPageRedirect();
2846
- return true;
2847
- } else {
2848
- if (state.includes(SILENT_SIGN_IN_STATE)) {
2849
- const message = {
2850
- type: CHECK_SESSION_SIGNED_OUT
2851
- };
2852
- window.parent.parent.postMessage(message, parent.origin);
2853
- SPAUtils.setPromptNoneRequestSent(false);
2854
- window.location.href = "about:blank";
2855
- await SPAUtils.waitTillPageRedirect();
2856
- return true;
2857
- }
2858
- SPAUtils.setPromptNoneRequestSent(false);
2859
- const signOutURL = await _signOut();
2860
- await AsgardeoAuthClient4.clearUserSessionData();
2861
- parent.location.href = signOutURL;
2862
- window.location.href = "about:blank";
2863
- await SPAUtils.waitTillPageRedirect();
2864
- return true;
2865
- }
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);
2866
2915
  }
2867
- return false;
2868
2916
  };
2869
- return async (signOut, storage, setSessionState) => {
2870
- let rpIFrame = document.createElement("iframe");
2871
- rpIFrame.setAttribute("id", RP_IFRAME);
2872
- rpIFrame.style.display = "none";
2873
- let rpIframeLoaded = false;
2874
- rpIFrame.onload = () => {
2875
- rpIFrame = document.getElementById(RP_IFRAME);
2876
- const rpDoc = rpIFrame?.contentDocument;
2877
- const opIFrame = rpDoc?.createElement("iframe");
2878
- if (opIFrame) {
2879
- opIFrame.setAttribute("id", OP_IFRAME);
2880
- opIFrame.style.display = "none";
2881
- }
2882
- const promptNoneIFrame = rpDoc?.createElement("iframe");
2883
- if (promptNoneIFrame) {
2884
- promptNoneIFrame.setAttribute("id", PROMPT_NONE_IFRAME);
2885
- promptNoneIFrame.style.display = "none";
2886
- }
2887
- opIFrame && rpIFrame?.contentDocument?.body?.appendChild(opIFrame);
2888
- promptNoneIFrame && rpIFrame?.contentDocument?.body?.appendChild(promptNoneIFrame);
2889
- rpIframeLoaded = true;
2890
- };
2891
- document?.body?.appendChild(rpIFrame);
2892
- _signOut = signOut;
2893
- _storage = storage;
2894
- _setSessionState = setSessionState;
2895
- const sleep = () => {
2896
- return new Promise((resolve) => setTimeout(resolve, 1));
2897
- };
2898
- while (rpIframeLoaded === false) {
2899
- await sleep();
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
+ );
2900
2949
  }
2901
- return {
2902
- initialize,
2903
- receivePromptNoneResponse,
2904
- reset
2905
- };
2950
+ return url;
2906
2951
  };
2907
- })();
2908
-
2909
- // src/__legacy__/worker/worker-receiver.ts
2910
- import { AsgardeoAuthException as AsgardeoAuthException3 } from "@asgardeo/javascript";
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
+ };
2911
3008
 
2912
- // src/__legacy__/worker/worker-core.ts
3009
+ // src/__legacy__/clients/web-worker-client.ts
2913
3010
  import {
2914
- AsgardeoAuthClient as AsgardeoAuthClient5,
2915
- OIDCRequestConstants as OIDCRequestConstants3
3011
+ AsgardeoAuthClient as AsgardeoAuthClient6,
3012
+ AsgardeoAuthException as AsgardeoAuthException3,
3013
+ OIDCRequestConstants as OIDCRequestConstants4,
3014
+ extractPkceStorageKeyFromState as extractPkceStorageKeyFromState3
2916
3015
  } from "@asgardeo/javascript";
2917
3016
 
2918
- // src/__legacy__/http-client/clients/axios-http-client.ts
2919
- import axios from "axios";
2920
-
2921
- // src/__legacy__/http-client/helpers/decorators.ts
2922
- function staticDecorator() {
2923
- return (_constructor) => {
2924
- };
2925
- }
2926
-
2927
- // src/__legacy__/http-client/clients/axios-http-client.ts
2928
- var HttpClient = class {
2929
- /**
2930
- * Private constructor to avoid object instantiation from outside
2931
- * the class.
2932
- *
2933
- * @hideconstructor
2934
- */
2935
- constructor() {
2936
- __publicField(this, "attachToken", () => Promise.resolve());
2937
- __publicField(this, "requestStartCallback", () => null);
2938
- __publicField(this, "requestSuccessCallback", () => null);
2939
- __publicField(this, "requestErrorCallback", () => null);
2940
- __publicField(this, "requestFinishCallback", () => null);
2941
- this.init = this.init.bind(this);
2942
- this.setHttpRequestErrorCallback = this.setHttpRequestErrorCallback.bind(this);
2943
- this.setHttpRequestFinishCallback = this.setHttpRequestFinishCallback.bind(this);
2944
- this.setHttpRequestStartCallback = this.setHttpRequestStartCallback.bind(this);
2945
- this.setHttpRequestSuccessCallback = this.setHttpRequestSuccessCallback.bind(this);
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;
2946
3034
  }
2947
- /**
2948
- * Returns an aggregated instance of type `HttpInstance` of `HttpClient`.
2949
- *
2950
- * @return {any}
2951
- */
2952
- static getInstance() {
2953
- if (this.axiosInstance) {
2954
- return this.axiosInstance;
2955
- }
2956
- this.axiosInstance = axios.create({
2957
- withCredentials: true
2958
- });
2959
- if (!this.clientInstance) {
2960
- this.clientInstance = new HttpClient();
2961
- }
2962
- this.axiosInstance.interceptors.request.use(async (request) => await this.clientInstance.requestHandler(request));
2963
- this.axiosInstance.interceptors.response.use(
2964
- (response) => this.clientInstance.successHandler(response),
2965
- (error) => this.clientInstance.errorHandler(error)
2966
- );
2967
- this.axiosInstance.all = axios.all;
2968
- this.axiosInstance.spread = axios.spread;
2969
- this.axiosInstance.init = this.clientInstance.init;
2970
- this.axiosInstance.enableHandler = this.clientInstance.enableHandler;
2971
- this.axiosInstance.disableHandler = this.clientInstance.disableHandler;
2972
- this.axiosInstance.disableHandlerWithTimeout = this.clientInstance.disableHandlerWithTimeout;
2973
- this.axiosInstance.setHttpRequestStartCallback = this.clientInstance.setHttpRequestStartCallback;
2974
- this.axiosInstance.setHttpRequestSuccessCallback = this.clientInstance.setHttpRequestSuccessCallback;
2975
- this.axiosInstance.setHttpRequestErrorCallback = this.clientInstance.setHttpRequestErrorCallback;
2976
- this.axiosInstance.setHttpRequestFinishCallback = this.clientInstance.setHttpRequestFinishCallback;
2977
- return this.axiosInstance;
3035
+ enableHttpHandler(httpClient) {
3036
+ httpClient?.enableHandler && httpClient.enableHandler();
2978
3037
  }
2979
- /**
2980
- * Intercepts all the requests.
2981
- * If the `isHandlerEnabled` flag is set to true, fires the `requestStartCallback`
2982
- * and retrieves the access token from the server and attaches it to the request.
2983
- * Else, just returns the original request.
2984
- *
2985
- * @param {HttpRequestConfig} request - Original request.
2986
- * @return {HttpRequestConfig}
2987
- */
2988
- async requestHandler(request) {
2989
- await this.attachToken(request);
2990
- if (request?.shouldEncodeToFormData) {
2991
- const data = request?.data;
2992
- const formData = new FormData();
2993
- Object.keys(data).forEach((key) => {
2994
- formData.append(key, data[key]);
3038
+ disableHttpHandler(httpClient) {
3039
+ httpClient?.disableHandler && httpClient.disableHandler();
3040
+ }
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
+ );
3051
+ }
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);
2995
3083
  });
2996
- request.data = formData;
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
+ );
2997
3092
  }
2998
- request.startTimeInMs = (/* @__PURE__ */ new Date()).getTime();
2999
- if (HttpClient.isHandlerEnabled) {
3000
- if (this.requestStartCallback && typeof this.requestStartCallback === "function") {
3001
- this.requestStartCallback(request);
3093
+ }
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
+ }
3101
+ }
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);
3002
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);
3003
3117
  }
3004
- return request;
3005
3118
  }
3006
- /**
3007
- * Handles response errors.
3008
- * If the `isHandlerEnabled` flag is set to true, fires the `requestErrorCallback`
3009
- * and the `requestFinishCallback` functions. Else, just returns the original error.
3010
- *
3011
- * @param {HttpError} error - Original error.
3012
- * @return {HttpError}
3013
- */
3014
- errorHandler(error) {
3015
- if (HttpClient.isHandlerEnabled) {
3016
- if (this.requestErrorCallback && typeof this.requestErrorCallback === "function") {
3017
- this.requestErrorCallback(error);
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
+ }
3018
3137
  }
3019
- if (this.requestFinishCallback && typeof this.requestFinishCallback === "function") {
3020
- this.requestFinishCallback();
3138
+ return Promise.reject(error);
3139
+ }
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;
3021
3148
  }
3022
3149
  }
3023
- throw error;
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 {
3217
+ return Promise.reject(
3218
+ new AsgardeoAuthException2(
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`"
3222
+ )
3223
+ );
3224
+ }
3024
3225
  }
3025
- /**
3026
- * Handles response success.
3027
- * If the `isHandlerEnabled` flag is set to true, fires the `requestSuccessCallback`
3028
- * and the `requestFinishCallback` functions. Else, just returns the original response.
3029
- *
3030
- * @param {HttpResponse} response - Original response.
3031
- * @return {HttpResponse}
3032
- */
3033
- successHandler(response) {
3034
- if (HttpClient.isHandlerEnabled) {
3035
- if (this.requestSuccessCallback && typeof this.requestSuccessCallback === "function") {
3036
- this.requestSuccessCallback(response);
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;
3235
+ }
3037
3236
  }
3038
- if (this.requestFinishCallback && typeof this.requestFinishCallback === "function") {
3039
- this.requestFinishCallback();
3237
+ if (!urlMatches) {
3238
+ matches = false;
3239
+ break;
3040
3240
  }
3041
3241
  }
3042
- return response;
3043
- }
3044
- /**
3045
- * Initializes the Http client.
3046
- *
3047
- * @param isHandlerEnabled - Flag to toggle handler enablement.
3048
- * @param requestStartCallback - Callback function to be triggered on request start.
3049
- * @param requestSuccessCallback - Callback function to be triggered on request success.
3050
- * @param requestErrorCallback - Callback function to be triggered on request error.
3051
- * @param requestFinishCallback - Callback function to be triggered on request error.
3052
- */
3053
- async init(isHandlerEnabled = true, attachToken) {
3054
- HttpClient.isHandlerEnabled = isHandlerEnabled;
3055
- this.attachToken = attachToken;
3056
- }
3057
- /**
3058
- * Enables the handler.
3059
- */
3060
- enableHandler() {
3061
- HttpClient.isHandlerEnabled = true;
3062
- }
3063
- /**
3064
- * Disables the handler.
3065
- */
3066
- disableHandler() {
3067
- HttpClient.isHandlerEnabled = false;
3068
- }
3069
- /**
3070
- * Disables the handler for a given period of time.
3071
- *
3072
- * @param {number} timeout - Timeout in milliseconds.
3073
- */
3074
- disableHandlerWithTimeout(timeout = HttpClient.DEFAULT_HANDLER_DISABLE_TIMEOUT) {
3075
- HttpClient.isHandlerEnabled = false;
3076
- setTimeout(() => {
3077
- HttpClient.isHandlerEnabled = true;
3078
- }, timeout);
3079
- }
3080
- setHttpRequestStartCallback(callback) {
3081
- this.requestStartCallback = callback;
3082
- }
3083
- setHttpRequestSuccessCallback(callback) {
3084
- this.requestSuccessCallback = callback;
3085
- }
3086
- setHttpRequestErrorCallback(callback) {
3087
- this.requestErrorCallback = callback;
3088
- }
3089
- setHttpRequestFinishCallback(callback) {
3090
- this.requestFinishCallback = callback;
3091
- }
3092
- };
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
-
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);
3111
- }
3112
- };
3113
-
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
- };
3130
-
3131
- // src/__legacy__/stores/session-store.ts
3132
- var SessionStore = class {
3133
- async setData(key, value) {
3134
- sessionStorage.setItem(key, value);
3135
- }
3136
- async getData(key) {
3137
- return sessionStorage.getItem(key) ?? "{}";
3138
- }
3139
- async removeData(key) {
3140
- sessionStorage.removeItem(key);
3141
- }
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, "");
3159
- }
3160
- base64URLDecode(value) {
3161
- return base64url.decode(value).toString();
3162
- }
3163
- hashSha256(data) {
3164
- return import_buffer.Buffer.from(sha256(new TextEncoder().encode(data)));
3165
- }
3166
- generateRandomBytes(length) {
3167
- return (0, import_randombytes.default)(length);
3168
- }
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;
3178
- }
3179
- return jwtVerify(
3180
- idToken,
3181
- createLocalJWKSet({
3182
- keys: [jwk]
3183
- }),
3184
- jwtVerifyOptions
3185
- ).then(() => {
3186
- return Promise.resolve(true);
3187
- }).catch((error) => {
3188
- return Promise.reject(
3189
- new AsgardeoAuthException2(
3190
- "SPA-CRYPTO-UTILS-VJ-IV01",
3191
- error?.reason ?? JSON.stringify(error),
3192
- `${error?.code} ${error?.claim}`
3193
- )
3194
- );
3195
- });
3196
- }
3197
- };
3198
-
3199
- // src/__legacy__/worker/worker-core.ts
3200
- var WebWorkerCore = async (config, getAuthHelper) => {
3201
- const _store = new MemoryStore();
3202
- const _cryptoUtils = new SPACryptoUtils();
3203
- const _authenticationClient = new AsgardeoAuthClient5();
3204
- await _authenticationClient.initialize(config, _store, _cryptoUtils);
3205
- const _spaHelper = new SPAHelper(_authenticationClient);
3206
- const _authenticationHelper = getAuthHelper(
3207
- _authenticationClient,
3208
- _spaHelper
3209
- );
3210
- const _dataLayer = _authenticationClient.getDataLayer();
3211
- const _httpClient = HttpClient.getInstance();
3212
- const attachToken = async (request) => {
3213
- await _authenticationHelper.attachTokenToRequestConfig(request);
3214
- };
3215
- _httpClient?.init && await _httpClient.init(true, attachToken);
3216
- const setHttpRequestStartCallback = (callback) => {
3217
- _httpClient?.setHttpRequestStartCallback && _httpClient.setHttpRequestStartCallback(callback);
3218
- };
3219
- const setHttpRequestSuccessCallback = (callback) => {
3220
- _httpClient?.setHttpRequestSuccessCallback && _httpClient.setHttpRequestSuccessCallback(callback);
3221
- };
3222
- const setHttpRequestFinishCallback = (callback) => {
3223
- _httpClient?.setHttpRequestFinishCallback && _httpClient.setHttpRequestFinishCallback(callback);
3224
- };
3225
- const httpRequest = async (requestConfig) => {
3226
- return await _authenticationHelper.httpRequest(_httpClient, requestConfig);
3227
- };
3228
- const httpRequestAll = async (requestConfigs) => {
3229
- return await _authenticationHelper.httpRequestAll(requestConfigs, _httpClient);
3230
- };
3231
- const enableHttpHandler = () => {
3232
- _authenticationHelper.enableHttpHandler(_httpClient);
3233
- };
3234
- const disableHttpHandler = () => {
3235
- _authenticationHelper.disableHttpHandler(_httpClient);
3236
- };
3237
- const getAuthorizationURL = async (params) => {
3238
- return _authenticationClient.getAuthorizationURL(params).then(async (url) => {
3239
- const urlObject = new URL(url);
3240
- const state = urlObject.searchParams.get(OIDCRequestConstants3.Params.STATE) ?? "";
3241
- const pkce = await _authenticationClient.getPKCECode(state);
3242
- return { authorizationURL: url, pkce };
3243
- }).catch((error) => Promise.reject(error));
3244
- };
3245
- const startAutoRefreshToken = async () => {
3246
- _spaHelper.clearRefreshTokenTimeout();
3247
- _spaHelper.refreshAccessTokenAutomatically(_authenticationHelper);
3248
- return;
3249
- };
3250
- const requestAccessToken = async (authorizationCode, sessionState, pkce, state) => {
3251
- return await _authenticationHelper.requestAccessToken(authorizationCode, sessionState, void 0, pkce, state);
3252
- };
3253
- const signOut = async () => {
3254
- _spaHelper.clearRefreshTokenTimeout();
3255
- return await _authenticationClient.getSignOutURL();
3256
- };
3257
- const getSignOutURL = async () => {
3258
- return await _authenticationClient.getSignOutURL();
3259
- };
3260
- const requestCustomGrant = async (config2) => {
3261
- return await _authenticationHelper.requestCustomGrant(config2);
3262
- };
3263
- const refreshAccessToken = async () => {
3264
- try {
3265
- return await _authenticationHelper.refreshAccessToken();
3266
- } catch (error) {
3267
- return Promise.reject(error);
3268
- }
3269
- };
3270
- const revokeAccessToken = async () => {
3271
- const timer = await _spaHelper.getRefreshTimeoutTimer();
3272
- return _authenticationClient.revokeAccessToken().then(() => {
3273
- _spaHelper.clearRefreshTokenTimeout(timer);
3274
- return Promise.resolve(true);
3275
- }).catch((error) => Promise.reject(error));
3276
- };
3277
- const getBasicUserInfo = async () => {
3278
- return _authenticationHelper.getBasicUserInfo();
3279
- };
3280
- const getDecodedIDToken = async () => {
3281
- return _authenticationHelper.getDecodedIDToken();
3282
- };
3283
- const getCryptoHelper = async () => {
3284
- return _authenticationHelper.getCryptoHelper();
3285
- };
3286
- const getDecodedIDPIDToken = async () => {
3287
- return _authenticationHelper.getDecodedIDPIDToken();
3288
- };
3289
- const getIDToken = async () => {
3290
- return _authenticationHelper.getIDToken();
3291
- };
3292
- const getOIDCServiceEndpoints = async () => {
3293
- return _authenticationHelper.getOIDCServiceEndpoints();
3294
- };
3295
- const getAccessToken = () => {
3296
- return _authenticationHelper.getAccessToken();
3297
- };
3298
- const isAuthenticated = () => {
3299
- return _authenticationHelper.isAuthenticated();
3300
- };
3301
- const setSessionState = async (sessionState) => {
3302
- await _dataLayer.setSessionDataParameter(
3303
- OIDCRequestConstants3.Params.SESSION_STATE,
3304
- sessionState
3305
- );
3306
- return;
3307
- };
3308
- const updateConfig = async (config2) => {
3309
- await _authenticationClient.updateConfig(config2);
3310
- return;
3311
- };
3312
- const getConfigData = async () => {
3313
- return _dataLayer.getConfigData();
3314
- };
3315
- return {
3316
- disableHttpHandler,
3317
- enableHttpHandler,
3318
- getAccessToken,
3319
- getAuthorizationURL,
3320
- getBasicUserInfo,
3321
- getConfigData,
3322
- getCryptoHelper,
3323
- getDecodedIDPIDToken,
3324
- getDecodedIDToken,
3325
- getIDToken,
3326
- getOIDCServiceEndpoints,
3327
- getSignOutURL,
3328
- httpRequest,
3329
- httpRequestAll,
3330
- isAuthenticated,
3331
- refreshAccessToken,
3332
- requestAccessToken,
3333
- requestCustomGrant,
3334
- revokeAccessToken,
3335
- setHttpRequestFinishCallback,
3336
- setHttpRequestStartCallback,
3337
- setHttpRequestSuccessCallback,
3338
- setSessionState,
3339
- signOut,
3340
- startAutoRefreshToken,
3341
- updateConfig
3342
- };
3343
- };
3344
-
3345
- // src/__legacy__/worker/worker-receiver.ts
3346
- var workerReceiver = (getAuthHelper) => {
3347
- const ctx = self;
3348
- let webWorker;
3349
- ctx.onmessage = async ({ data, ports }) => {
3350
- const port = ports[0];
3351
- if (data.type !== INIT && !webWorker) {
3352
- port.postMessage(
3353
- MessageUtils.generateFailureMessage(
3354
- new AsgardeoAuthException3(
3355
- "SPA-CLIENT_WORKER-ONMSG-NF01",
3356
- "The web worker has not been initialized yet.",
3357
- "The initialize method needs to be called before the specified operation can be carried out."
3358
- )
3359
- )
3360
- );
3361
- return;
3362
- }
3363
- switch (data.type) {
3364
- case INIT:
3365
- try {
3366
- const config = { ...data.data };
3367
- webWorker = await WebWorkerCore(config, getAuthHelper);
3368
- webWorker.setHttpRequestFinishCallback(onRequestFinishCallback);
3369
- webWorker.setHttpRequestStartCallback(onRequestStartCallback);
3370
- webWorker.setHttpRequestSuccessCallback(onRequestSuccessCallback);
3371
- port.postMessage(MessageUtils.generateSuccessMessage());
3372
- } catch (error) {
3373
- port.postMessage(MessageUtils.generateFailureMessage(error));
3374
- }
3375
- break;
3376
- case GET_AUTH_URL:
3377
- webWorker.getAuthorizationURL(data?.data).then((response) => {
3378
- port.postMessage(MessageUtils.generateSuccessMessage(response));
3379
- }).catch((error) => {
3380
- port.postMessage(MessageUtils.generateFailureMessage(error));
3381
- });
3382
- break;
3383
- case REQUEST_ACCESS_TOKEN:
3384
- webWorker.requestAccessToken(data?.data?.code, data?.data?.sessionState, data?.data?.pkce, data?.data?.state).then((response) => {
3385
- port.postMessage(MessageUtils.generateSuccessMessage(response));
3386
- }).catch((error) => {
3387
- port.postMessage(MessageUtils.generateFailureMessage(error));
3388
- });
3389
- break;
3390
- case HTTP_REQUEST: {
3391
- const request = data.data;
3392
- const requestData = request?.data;
3393
- if (data.data?.data?.formData === true) {
3394
- const formData = new FormData();
3395
- for (const key in requestData) {
3396
- if (key === "formData") {
3397
- continue;
3398
- }
3399
- formData.append(key, requestData[key]);
3400
- }
3401
- request.data = formData;
3402
- }
3403
- webWorker.httpRequest(request).then((response) => {
3404
- port.postMessage(MessageUtils.generateSuccessMessage(response));
3405
- }).catch((error) => {
3406
- port.postMessage(MessageUtils.generateFailureMessage(error));
3407
- });
3408
- break;
3409
- }
3410
- case HTTP_REQUEST_ALL:
3411
- webWorker.httpRequestAll(data.data).then((response) => {
3412
- port.postMessage(MessageUtils.generateSuccessMessage(response));
3413
- }).catch((error) => {
3414
- port.postMessage(MessageUtils.generateFailureMessage(error));
3415
- });
3416
- break;
3417
- case SIGN_OUT:
3418
- try {
3419
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.signOut()));
3420
- } catch (error) {
3421
- port.postMessage(MessageUtils.generateFailureMessage(error));
3422
- }
3423
- break;
3424
- case REQUEST_CUSTOM_GRANT:
3425
- webWorker.requestCustomGrant(data.data).then((response) => {
3426
- port.postMessage(MessageUtils.generateSuccessMessage(response));
3427
- }).catch((error) => {
3428
- port.postMessage(MessageUtils.generateFailureMessage(error));
3429
- });
3430
- break;
3431
- case REVOKE_ACCESS_TOKEN:
3432
- webWorker.revokeAccessToken().then((response) => {
3433
- port.postMessage(MessageUtils.generateSuccessMessage(response));
3434
- }).catch((error) => {
3435
- port.postMessage(MessageUtils.generateFailureMessage(error));
3436
- });
3437
- break;
3438
- case GET_OIDC_SERVICE_ENDPOINTS:
3439
- try {
3440
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getOIDCServiceEndpoints()));
3441
- } catch (error) {
3442
- port.postMessage(MessageUtils.generateFailureMessage(error));
3443
- }
3444
- break;
3445
- case GET_BASIC_USER_INFO:
3446
- try {
3447
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getBasicUserInfo()));
3448
- } catch (error) {
3449
- port.postMessage(MessageUtils.generateFailureMessage(error));
3450
- }
3451
- break;
3452
- case GET_DECODED_ID_TOKEN:
3453
- try {
3454
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getDecodedIDToken()));
3455
- } catch (error) {
3456
- port.postMessage(MessageUtils.generateFailureMessage(error));
3457
- }
3458
- break;
3459
- case GET_CRYPTO_HELPER:
3460
- try {
3461
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getCryptoHelper()));
3462
- } catch (error) {
3463
- port.postMessage(MessageUtils.generateFailureMessage(error));
3464
- }
3465
- break;
3466
- case GET_ID_TOKEN:
3467
- try {
3468
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getIDToken()));
3469
- } catch (error) {
3470
- port.postMessage(MessageUtils.generateFailureMessage(error));
3471
- }
3472
- break;
3473
- case ENABLE_HTTP_HANDLER:
3474
- webWorker.enableHttpHandler();
3475
- port.postMessage(MessageUtils.generateSuccessMessage());
3476
- break;
3477
- case DISABLE_HTTP_HANDLER:
3478
- webWorker.disableHttpHandler();
3479
- port.postMessage(MessageUtils.generateSuccessMessage());
3480
- break;
3481
- case IS_AUTHENTICATED:
3482
- try {
3483
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.isAuthenticated()));
3484
- } catch (error) {
3485
- port.postMessage(MessageUtils.generateFailureMessage(error));
3486
- }
3487
- break;
3488
- case GET_SIGN_OUT_URL:
3489
- try {
3490
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getSignOutURL()));
3491
- } catch (error) {
3492
- port.postMessage(MessageUtils.generateFailureMessage(error));
3493
- }
3494
- break;
3495
- case REFRESH_ACCESS_TOKEN:
3496
- try {
3497
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.refreshAccessToken()));
3498
- } catch (error) {
3499
- port.postMessage(MessageUtils.generateFailureMessage(error));
3500
- }
3501
- break;
3502
- case START_AUTO_REFRESH_TOKEN:
3503
- try {
3504
- port.postMessage(MessageUtils.generateSuccessMessage(webWorker.startAutoRefreshToken()));
3505
- } catch (error) {
3506
- port.postMessage(MessageUtils.generateFailureMessage(error));
3507
- }
3508
- break;
3509
- case SET_SESSION_STATE:
3510
- try {
3511
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.setSessionState(data?.data)));
3512
- } catch (error) {
3513
- port.postMessage(MessageUtils.generateFailureMessage(error));
3514
- }
3515
- break;
3516
- case UPDATE_CONFIG:
3517
- try {
3518
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.updateConfig(data?.data)));
3519
- } catch (error) {
3520
- port.postMessage(MessageUtils.generateFailureMessage(error));
3521
- }
3522
- break;
3523
- case GET_CONFIG_DATA:
3524
- try {
3525
- port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getConfigData()));
3526
- } catch (error) {
3527
- port.postMessage(MessageUtils.generateFailureMessage(error));
3528
- }
3529
- break;
3530
- default:
3531
- port?.postMessage(
3532
- MessageUtils.generateFailureMessage(
3533
- new AsgardeoAuthException3(
3534
- "SPA-CLIENT_WORKER-ONMSG-IV02",
3535
- "The message type is invalid.",
3536
- `The message type provided, ${data.type}, is invalid.`
3537
- )
3538
- )
3539
- );
3540
- }
3541
- };
3542
- const onRequestStartCallback = () => {
3543
- ctx.postMessage({ type: REQUEST_START });
3544
- };
3545
- const onRequestSuccessCallback = (response) => {
3546
- ctx.postMessage({ data: JSON.stringify(response ?? ""), type: REQUEST_SUCCESS });
3547
- };
3548
- const onRequestFinishCallback = () => {
3549
- ctx.postMessage({ type: REQUEST_FINISH });
3550
- };
3551
- };
3552
-
3553
- // src/worker.ts
3554
- workerReceiver((authClient, spaHelper) => {
3555
- return new AuthenticationHelper(authClient, spaHelper);
3556
- });
3557
- var worker_default = {};
3558
-
3559
- // src/__legacy__/clients/main-thread-client.ts
3560
- import {
3561
- AsgardeoAuthClient as AsgardeoAuthClient7,
3562
- ResponseMode,
3563
- OIDCRequestConstants as OIDCRequestConstants4,
3564
- extractPkceStorageKeyFromState as extractPkceStorageKeyFromState2
3565
- } from "@asgardeo/javascript";
3566
- var initiateStore = (store) => {
3567
- switch (store) {
3568
- case "localStorage" /* LocalStorage */:
3569
- return new LocalStore();
3570
- case "sessionStorage" /* SessionStorage */:
3571
- return new SessionStore();
3572
- case "browserMemory" /* BrowserMemory */:
3573
- return new MemoryStore();
3574
- default:
3575
- return new SessionStore();
3576
- }
3577
- };
3578
- var MainThreadClient = async (instanceID, config, getAuthHelper) => {
3579
- const _store = initiateStore(config.storage);
3580
- const _cryptoUtils = new SPACryptoUtils();
3581
- const _authenticationClient = new AsgardeoAuthClient7();
3582
- await _authenticationClient.initialize(config, _store, _cryptoUtils, instanceID);
3583
- const _spaHelper = new SPAHelper(_authenticationClient);
3584
- const _dataLayer = _authenticationClient.getDataLayer();
3585
- const _sessionManagementHelper = await SessionManagementHelper(
3586
- async () => {
3587
- return _authenticationClient.getSignOutURL();
3588
- },
3589
- config.storage ?? "sessionStorage" /* SessionStorage */,
3590
- (sessionState) => _dataLayer.setSessionDataParameter(
3591
- OIDCRequestConstants4.Params.SESSION_STATE,
3592
- sessionState ?? ""
3593
- )
3594
- );
3595
- const _authenticationHelper = getAuthHelper(_authenticationClient, _spaHelper);
3596
- let _getSignOutURLFromSessionStorage = false;
3597
- const _httpClient = HttpClient.getInstance();
3598
- let _isHttpHandlerEnabled = true;
3599
- let _httpErrorCallback;
3600
- let _httpFinishCallback;
3601
- const attachToken = async (request) => {
3602
- await _authenticationHelper.attachTokenToRequestConfig(request);
3603
- };
3604
- _httpClient?.init && await _httpClient.init(true, attachToken);
3605
- const setHttpRequestStartCallback = (callback) => {
3606
- _httpClient?.setHttpRequestStartCallback && _httpClient.setHttpRequestStartCallback(callback);
3607
- };
3608
- const setHttpRequestSuccessCallback = (callback) => {
3609
- _httpClient?.setHttpRequestSuccessCallback && _httpClient.setHttpRequestSuccessCallback(callback);
3610
- };
3611
- const setHttpRequestFinishCallback = (callback) => {
3612
- _httpClient?.setHttpRequestFinishCallback && _httpClient.setHttpRequestFinishCallback(callback);
3613
- };
3614
- const setHttpRequestErrorCallback = (callback) => {
3615
- _httpErrorCallback = callback;
3616
- };
3617
- const httpRequest = async (requestConfig) => {
3618
- return await _authenticationHelper.httpRequest(
3619
- _httpClient,
3620
- requestConfig,
3621
- _isHttpHandlerEnabled,
3622
- _httpErrorCallback,
3623
- _httpFinishCallback
3624
- );
3625
- };
3626
- const httpRequestAll = async (requestConfigs) => {
3627
- return await _authenticationHelper.httpRequestAll(
3628
- requestConfigs,
3629
- _httpClient,
3630
- _isHttpHandlerEnabled,
3631
- _httpErrorCallback,
3632
- _httpFinishCallback
3633
- );
3634
- };
3635
- const getHttpClient = () => {
3636
- return _httpClient;
3637
- };
3638
- const enableHttpHandler = () => {
3639
- _authenticationHelper.enableHttpHandler(_httpClient);
3640
- _isHttpHandlerEnabled = true;
3641
- return true;
3642
- };
3643
- const disableHttpHandler = () => {
3644
- _authenticationHelper.disableHttpHandler(_httpClient);
3645
- _isHttpHandlerEnabled = false;
3646
- return true;
3647
- };
3648
- const checkSession = async () => {
3649
- const oidcEndpoints = await _authenticationClient.getOIDCServiceEndpoints();
3650
- const config2 = await _dataLayer.getConfigData();
3651
- _authenticationHelper.initializeSessionManger(
3652
- config2,
3653
- oidcEndpoints,
3654
- async () => (await _authenticationClient.getBasicUserInfo()).sessionState,
3655
- async (params) => _authenticationClient.getAuthorizationURL(params),
3656
- _sessionManagementHelper
3657
- );
3658
- };
3659
- const shouldStopAuthn = async () => {
3660
- return await _sessionManagementHelper.receivePromptNoneResponse(async (sessionState) => {
3661
- await _dataLayer.setSessionDataParameter(
3662
- OIDCRequestConstants4.Params.SESSION_STATE,
3663
- sessionState ?? ""
3664
- );
3665
- return;
3666
- });
3667
- };
3668
- const setSessionStatus = async (sessionStatus) => {
3669
- await _dataLayer.setSessionStatus(sessionStatus);
3670
- };
3671
- const signIn = async (signInConfig, authorizationCode, sessionState, state, tokenRequestConfig) => {
3672
- const basicUserInfo = await _authenticationHelper.handleSignIn(shouldStopAuthn, checkSession, void 0);
3673
- if (basicUserInfo) {
3674
- return basicUserInfo;
3675
- } else {
3676
- let resolvedAuthorizationCode;
3677
- let resolvedSessionState;
3678
- let resolvedState;
3679
- let resolvedTokenRequestConfig = { params: {} };
3680
- if (config?.responseMode === ResponseMode.FormPost && authorizationCode) {
3681
- resolvedAuthorizationCode = authorizationCode;
3682
- resolvedSessionState = sessionState ?? "";
3683
- resolvedState = state ?? "";
3684
- } else {
3685
- resolvedAuthorizationCode = new URL(window.location.href).searchParams.get(OIDCRequestConstants4.Params.AUTHORIZATION_CODE) ?? "";
3686
- resolvedSessionState = new URL(window.location.href).searchParams.get(OIDCRequestConstants4.Params.SESSION_STATE) ?? "";
3687
- resolvedState = new URL(window.location.href).searchParams.get(OIDCRequestConstants4.Params.STATE) ?? "";
3688
- SPAUtils.removeAuthorizationCode();
3689
- }
3690
- if (resolvedAuthorizationCode && resolvedState) {
3691
- setSessionStatus("true");
3692
- const storedTokenRequestConfig = await _dataLayer.getTemporaryDataParameter(TOKEN_REQUEST_CONFIG_KEY);
3693
- if (storedTokenRequestConfig && typeof storedTokenRequestConfig === "string") {
3694
- resolvedTokenRequestConfig = JSON.parse(storedTokenRequestConfig);
3695
- }
3696
- return requestAccessToken(
3697
- resolvedAuthorizationCode,
3698
- resolvedSessionState,
3699
- resolvedState,
3700
- resolvedTokenRequestConfig
3701
- );
3702
- }
3703
- return _authenticationClient.getAuthorizationURL(signInConfig).then(async (url) => {
3704
- if (config.storage === "browserMemory" /* BrowserMemory */ && config.enablePKCE) {
3705
- const pkceKey = extractPkceStorageKeyFromState2(resolvedState);
3706
- SPAUtils.setPKCE(pkceKey, await _authenticationClient.getPKCECode(resolvedState));
3707
- }
3708
- if (tokenRequestConfig) {
3709
- _dataLayer.setTemporaryDataParameter(TOKEN_REQUEST_CONFIG_KEY, JSON.stringify(tokenRequestConfig));
3710
- }
3711
- location.href = url;
3712
- await SPAUtils.waitTillPageRedirect();
3713
- return Promise.resolve({
3714
- allowedScopes: "",
3715
- displayName: "",
3716
- email: "",
3717
- sessionState: "",
3718
- sub: "",
3719
- tenantDomain: "",
3720
- username: ""
3721
- });
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
+ }
3287
+ }
3288
+ if (isHttpHandlerEnabled) {
3289
+ if (typeof httpErrorCallback === "function") {
3290
+ await httpErrorCallback(error);
3291
+ }
3292
+ if (typeof httpFinishCallback === "function") {
3293
+ httpFinishCallback();
3294
+ }
3295
+ }
3296
+ return Promise.reject(error);
3722
3297
  });
3723
- }
3724
- };
3725
- const signOut = async () => {
3726
- if (await _authenticationClient.isAuthenticated() && !_getSignOutURLFromSessionStorage) {
3727
- location.href = await _authenticationClient.getSignOutURL();
3728
3298
  } else {
3729
- location.href = SPAUtils.getSignOutURL(config.clientID, instanceID);
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
+ );
3730
3304
  }
3731
- _spaHelper.clearRefreshTokenTimeout();
3732
- await _dataLayer.removeOIDCProviderMetaData();
3733
- await _dataLayer.removeTemporaryData();
3734
- await _dataLayer.removeSessionData();
3735
- await _dataLayer.removeSessionStatus();
3736
- await SPAUtils.waitTillPageRedirect();
3737
- return true;
3738
- };
3739
- const enableRetrievingSignOutURLFromSession = (config2) => {
3740
- if (config2.preventSignOutURLUpdate) {
3741
- _getSignOutURLFromSessionStorage = true;
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 ?? "");
3742
3313
  }
3743
- };
3744
- const requestCustomGrant = async (config2) => {
3745
- return await _authenticationHelper.requestCustomGrant(config2, enableRetrievingSignOutURLFromSession);
3746
- };
3747
- const refreshAccessToken = async () => {
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
+ }
3325
+ } else {
3326
+ if (this._spaHelper) {
3327
+ this._spaHelper.refreshAccessTokenAutomatically(this);
3328
+ }
3329
+ }
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: ""
3354
+ });
3355
+ }
3356
+ const rpIFrame = document.getElementById(RP_IFRAME);
3357
+ const promptNoneIFrame = rpIFrame?.contentDocument?.getElementById(
3358
+ PROMPT_NONE_IFRAME
3359
+ );
3748
3360
  try {
3749
- return await _authenticationHelper.refreshAccessToken(enableRetrievingSignOutURLFromSession);
3361
+ const url = await constructSilentSignInUrl(additionalParams);
3362
+ promptNoneIFrame.src = url;
3750
3363
  } catch (error) {
3751
3364
  return Promise.reject(error);
3752
3365
  }
3753
- };
3754
- const revokeAccessToken = async () => {
3755
- const timer = await _spaHelper.getRefreshTimeoutTimer();
3756
- return _authenticationClient.revokeAccessToken().then(() => {
3757
- _sessionManagementHelper.reset();
3758
- _spaHelper.clearRefreshTokenTimeout(timer);
3759
- return Promise.resolve(true);
3760
- }).catch((error) => Promise.reject(error));
3761
- };
3762
- const requestAccessToken = async (resolvedAuthorizationCode, resolvedSessionState, resolvedState, tokenRequestConfig) => {
3763
- return await _authenticationHelper.requestAccessToken(
3764
- resolvedAuthorizationCode,
3765
- resolvedSessionState,
3766
- checkSession,
3767
- void 0,
3768
- resolvedState,
3769
- tokenRequestConfig
3770
- );
3771
- };
3772
- const constructSilentSignInUrl = async (additionalParams = {}) => {
3773
- const config2 = await _dataLayer.getConfigData();
3774
- const urlString = await _authenticationClient.getAuthorizationURL({
3775
- prompt: "none",
3776
- state: SILENT_SIGN_IN_STATE,
3777
- ...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);
3778
3390
  });
3779
- const urlObject = new URL(urlString);
3780
- urlObject.searchParams.set("response_mode", "query");
3781
- const url = urlObject.toString();
3782
- if (config2.storage === "browserMemory" /* BrowserMemory */ && config2.enablePKCE) {
3783
- const state = urlObject.searchParams.get(OIDCRequestConstants4.Params.STATE);
3784
- SPAUtils.setPKCE(
3785
- extractPkceStorageKeyFromState2(state ?? ""),
3786
- await _authenticationClient.getPKCECode(state ?? "")
3787
- );
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
+ });
3788
3404
  }
3789
- return url;
3790
- };
3791
- const trySignInSilently = async (additionalParams, tokenRequestConfig) => {
3792
- return await _authenticationHelper.trySignInSilently(
3793
- constructSilentSignInUrl,
3794
- requestAccessToken,
3795
- _sessionManagementHelper,
3796
- additionalParams,
3797
- tokenRequestConfig
3798
- );
3799
- };
3800
- const getBasicUserInfo = async () => {
3801
- return _authenticationHelper.getBasicUserInfo();
3802
- };
3803
- const getDecodedIDToken = async () => {
3804
- return _authenticationHelper.getDecodedIDToken();
3805
- };
3806
- const getCryptoHelper = async () => {
3807
- return _authenticationHelper.getCryptoHelper();
3808
- };
3809
- const getIDToken = async () => {
3810
- return _authenticationHelper.getIDToken();
3811
- };
3812
- const getOIDCServiceEndpoints = async () => {
3813
- return _authenticationHelper.getOIDCServiceEndpoints();
3814
- };
3815
- const getAccessToken = async () => {
3816
- return _authenticationHelper.getAccessToken();
3817
- };
3818
- const getDataLayer = async () => {
3819
- return _authenticationHelper.getDataLayer();
3820
- };
3821
- const getConfigData = async () => {
3822
- return await _dataLayer.getConfigData();
3823
- };
3824
- const isAuthenticated = async () => {
3825
- return _authenticationHelper.isAuthenticated();
3826
- };
3827
- const isSessionActive = async () => {
3828
- return await _dataLayer.getSessionStatus() === "true";
3829
- };
3830
- const updateConfig = async (newConfig) => {
3831
- const existingConfig = await _dataLayer.getConfigData();
3832
- const isCheckSessionIframeDifferent = !(existingConfig && existingConfig.endpoints && existingConfig.endpoints.checkSessionIframe && newConfig && newConfig.endpoints && newConfig.endpoints.checkSessionIframe && existingConfig.endpoints.checkSessionIframe === newConfig.endpoints.checkSessionIframe);
3833
- const config2 = { ...existingConfig, ...newConfig };
3834
- await _authenticationClient.updateConfig(config2);
3835
- if (config2.enableOIDCSessionManagement && isCheckSessionIframeDifferent) {
3836
- _sessionManagementHelper.reset();
3837
- 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
+ }
3838
3414
  }
3839
- };
3840
- return {
3841
- disableHttpHandler,
3842
- enableHttpHandler,
3843
- getAccessToken,
3844
- getBasicUserInfo,
3845
- getConfigData,
3846
- getCryptoHelper,
3847
- getDataLayer,
3848
- getDecodedIDToken,
3849
- getHttpClient,
3850
- getIDToken,
3851
- getOIDCServiceEndpoints,
3852
- httpRequest,
3853
- httpRequestAll,
3854
- isAuthenticated,
3855
- isSessionActive,
3856
- refreshAccessToken,
3857
- requestCustomGrant,
3858
- revokeAccessToken,
3859
- setHttpRequestErrorCallback,
3860
- setHttpRequestFinishCallback,
3861
- setHttpRequestStartCallback,
3862
- setHttpRequestSuccessCallback,
3863
- signIn,
3864
- signOut,
3865
- trySignInSilently,
3866
- updateConfig
3867
- };
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
+ }
3868
3478
  };
3869
3479
 
3870
3480
  // src/__legacy__/clients/web-worker-client.ts
3871
- import {
3872
- AsgardeoAuthClient as AsgardeoAuthClient8,
3873
- AsgardeoAuthException as AsgardeoAuthException4,
3874
- ResponseMode as ResponseMode2,
3875
- OIDCRequestConstants as OIDCRequestConstants5,
3876
- extractPkceStorageKeyFromState as extractPkceStorageKeyFromState3
3877
- } from "@asgardeo/javascript";
3878
3481
  var initiateStore2 = (store) => {
3879
3482
  switch (store) {
3880
3483
  case "localStorage" /* LocalStorage */:
@@ -3894,7 +3497,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
3894
3497
  let _getSignOutURLFromSessionStorage = false;
3895
3498
  const _store = initiateStore2(config.storage);
3896
3499
  const _cryptoUtils = new SPACryptoUtils();
3897
- const _authenticationClient = new AsgardeoAuthClient8();
3500
+ const _authenticationClient = new AsgardeoAuthClient6();
3898
3501
  await _authenticationClient.initialize(config, _store, _cryptoUtils, instanceID);
3899
3502
  const _spaHelper = new SPAHelper(_authenticationClient);
3900
3503
  const _sessionManagementHelper = await SessionManagementHelper(
@@ -3906,7 +3509,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
3906
3509
  const signOutURL = await communicate(message);
3907
3510
  return signOutURL;
3908
3511
  } catch {
3909
- return SPAUtils.getSignOutURL(config.clientID, instanceID);
3512
+ return SPAUtils.getSignOutUrl(config.clientId, instanceID);
3910
3513
  }
3911
3514
  },
3912
3515
  config.storage,
@@ -3923,7 +3526,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
3923
3526
  return new Promise((resolve, reject) => {
3924
3527
  const timer = setTimeout(() => {
3925
3528
  reject(
3926
- new AsgardeoAuthException4(
3529
+ new AsgardeoAuthException3(
3927
3530
  "SPA-WEB_WORKER_CLIENT-COM-TO01",
3928
3531
  "Operation timed out.",
3929
3532
  "No response was received from the web worker for " + _requestTimeout / 1e3 + " since dispatching the request"
@@ -3946,7 +3549,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
3946
3549
  };
3947
3550
  });
3948
3551
  };
3949
- const requestCustomGrant = (requestParams) => {
3552
+ const exchangeToken = (requestParams) => {
3950
3553
  const message = {
3951
3554
  data: requestParams,
3952
3555
  type: REQUEST_CUSTOM_GRANT
@@ -4069,13 +3672,13 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4069
3672
  return communicate(message);
4070
3673
  };
4071
3674
  const checkSession = async () => {
4072
- const oidcEndpoints = await getOIDCServiceEndpoints();
3675
+ const oidcEndpoints = await getOpenIDProviderEndpoints();
4073
3676
  const config2 = await getConfigData();
4074
3677
  _authenticationHelper.initializeSessionManger(
4075
3678
  config2,
4076
3679
  oidcEndpoints,
4077
- async () => (await getBasicUserInfo()).sessionState,
4078
- async (params) => (await getAuthorizationURL(params)).authorizationURL,
3680
+ async () => (await _authenticationClient.getUserSession()).sessionState,
3681
+ async (params) => (await getSignInUrl(params)).authorizationURL,
4079
3682
  _sessionManagementHelper
4080
3683
  );
4081
3684
  };
@@ -4089,9 +3692,11 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4089
3692
  },
4090
3693
  type: GET_AUTH_URL
4091
3694
  };
4092
- const response = await communicate(message);
3695
+ const response = await communicate(
3696
+ message
3697
+ );
4093
3698
  const pkceKey = extractPkceStorageKeyFromState3(
4094
- new URL(response.authorizationURL).searchParams.get(OIDCRequestConstants5.Params.STATE) ?? ""
3699
+ new URL(response.authorizationURL).searchParams.get(OIDCRequestConstants4.Params.STATE) ?? ""
4095
3700
  );
4096
3701
  response.pkce && config2.enablePKCE && SPAUtils.setPKCE(pkceKey, response.pkce);
4097
3702
  const urlString = response.authorizationURL;
@@ -4109,7 +3714,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4109
3714
  tokenRequestConfig
4110
3715
  );
4111
3716
  };
4112
- const getAuthorizationURL = async (params) => {
3717
+ const getSignInUrl = async (params) => {
4113
3718
  const config2 = await getConfigData();
4114
3719
  const message = {
4115
3720
  data: params,
@@ -4119,7 +3724,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4119
3724
  async (response) => {
4120
3725
  if (response.pkce && config2.enablePKCE) {
4121
3726
  const pkceKey = extractPkceStorageKeyFromState3(
4122
- new URL(response.authorizationURL).searchParams.get(OIDCRequestConstants5.Params.STATE) ?? ""
3727
+ new URL(response.authorizationURL).searchParams.get(OIDCRequestConstants4.Params.STATE) ?? ""
4123
3728
  );
4124
3729
  SPAUtils.setPKCE(pkceKey, response.pkce);
4125
3730
  }
@@ -4146,7 +3751,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4146
3751
  type: GET_SIGN_OUT_URL
4147
3752
  };
4148
3753
  return communicate(message2).then((url) => {
4149
- SPAUtils.setSignOutURL(url, config2.clientID, instanceID);
3754
+ SPAUtils.setSignOutURL(url, config2.clientId, instanceID);
4150
3755
  if (config2.enableOIDCSessionManagement) {
4151
3756
  checkSession();
4152
3757
  }
@@ -4165,12 +3770,12 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4165
3770
  });
4166
3771
  };
4167
3772
  const tryRetrievingUserInfo = async () => {
4168
- if (await isAuthenticated()) {
3773
+ if (await isSignedIn()) {
4169
3774
  await startAutoRefreshToken();
4170
3775
  if (config.enableOIDCSessionManagement) {
4171
3776
  checkSession();
4172
3777
  }
4173
- return getBasicUserInfo();
3778
+ return getUser();
4174
3779
  }
4175
3780
  return Promise.resolve(void 0);
4176
3781
  };
@@ -4186,20 +3791,20 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4186
3791
  let resolvedAuthorizationCode;
4187
3792
  let resolvedSessionState;
4188
3793
  let resolvedState;
4189
- if (config?.responseMode === ResponseMode2.FormPost && authorizationCode) {
3794
+ if (config?.responseMode === "form_post" && authorizationCode) {
4190
3795
  resolvedAuthorizationCode = authorizationCode;
4191
3796
  resolvedSessionState = sessionState ?? "";
4192
3797
  resolvedState = state ?? "";
4193
3798
  } else {
4194
- resolvedAuthorizationCode = new URL(window.location.href).searchParams.get(OIDCRequestConstants5.Params.AUTHORIZATION_CODE) ?? "";
4195
- resolvedSessionState = new URL(window.location.href).searchParams.get(OIDCRequestConstants5.Params.SESSION_STATE) ?? "";
4196
- resolvedState = new URL(window.location.href).searchParams.get(OIDCRequestConstants5.Params.STATE) ?? "";
3799
+ resolvedAuthorizationCode = new URL(window.location.href).searchParams.get(OIDCRequestConstants4.Params.AUTHORIZATION_CODE) ?? "";
3800
+ resolvedSessionState = new URL(window.location.href).searchParams.get(OIDCRequestConstants4.Params.SESSION_STATE) ?? "";
3801
+ resolvedState = new URL(window.location.href).searchParams.get(OIDCRequestConstants4.Params.STATE) ?? "";
4197
3802
  SPAUtils.removeAuthorizationCode();
4198
3803
  }
4199
3804
  if (resolvedAuthorizationCode && resolvedState) {
4200
3805
  return requestAccessToken(resolvedAuthorizationCode, resolvedSessionState, resolvedState, tokenRequestConfig);
4201
3806
  }
4202
- return getAuthorizationURL(params).then(async (response) => {
3807
+ return getSignInUrl(params).then(async (response) => {
4203
3808
  location.href = response.authorizationURL;
4204
3809
  await SPAUtils.waitTillPageRedirect();
4205
3810
  return Promise.resolve({
@@ -4230,7 +3835,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4230
3835
  return reject(error);
4231
3836
  });
4232
3837
  } else {
4233
- window.location.href = SPAUtils.getSignOutURL(config.clientID, instanceID);
3838
+ window.location.href = SPAUtils.getSignOutUrl(config.clientId, instanceID);
4234
3839
  return SPAUtils.waitTillPageRedirect().then(() => {
4235
3840
  return Promise.resolve(true);
4236
3841
  });
@@ -4248,7 +3853,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4248
3853
  return Promise.reject(error);
4249
3854
  });
4250
3855
  };
4251
- const getOIDCServiceEndpoints = () => {
3856
+ const getOpenIDProviderEndpoints = () => {
4252
3857
  const message = {
4253
3858
  type: GET_OIDC_SERVICE_ENDPOINTS
4254
3859
  };
@@ -4268,7 +3873,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4268
3873
  return Promise.reject(error);
4269
3874
  });
4270
3875
  };
4271
- const getBasicUserInfo = () => {
3876
+ const getUser = () => {
4272
3877
  const message = {
4273
3878
  type: GET_BASIC_USER_INFO
4274
3879
  };
@@ -4278,7 +3883,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4278
3883
  return Promise.reject(error);
4279
3884
  });
4280
3885
  };
4281
- const getDecodedIDToken = () => {
3886
+ const getDecodedIdToken = () => {
4282
3887
  const message = {
4283
3888
  type: GET_DECODED_ID_TOKEN
4284
3889
  };
@@ -4298,7 +3903,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4298
3903
  return Promise.reject(error);
4299
3904
  });
4300
3905
  };
4301
- const getCryptoHelper = () => {
3906
+ const getCrypto = () => {
4302
3907
  const message = {
4303
3908
  type: GET_CRYPTO_HELPER
4304
3909
  };
@@ -4308,7 +3913,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4308
3913
  return Promise.reject(error);
4309
3914
  });
4310
3915
  };
4311
- const getIDToken = () => {
3916
+ const getIdToken = () => {
4312
3917
  const message = {
4313
3918
  type: GET_ID_TOKEN
4314
3919
  };
@@ -4318,7 +3923,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4318
3923
  return Promise.reject(error);
4319
3924
  });
4320
3925
  };
4321
- const isAuthenticated = () => {
3926
+ const isSignedIn = () => {
4322
3927
  const message = {
4323
3928
  type: IS_AUTHENTICATED
4324
3929
  };
@@ -4354,7 +3959,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4354
3959
  httpClientHandlers.requestFinishCallback = callback;
4355
3960
  }
4356
3961
  };
4357
- const updateConfig = async (newConfig) => {
3962
+ const reInitialize = async (newConfig) => {
4358
3963
  const existingConfig = await getConfigData();
4359
3964
  const isCheckSessionIframeDifferent = !(existingConfig && existingConfig.endpoints && existingConfig.endpoints.checkSessionIframe && newConfig && newConfig.endpoints && newConfig.endpoints.checkSessionIframe && existingConfig.endpoints.checkSessionIframe === newConfig.endpoints.checkSessionIframe);
4360
3965
  const config2 = { ...existingConfig, ...newConfig };
@@ -4371,19 +3976,19 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4371
3976
  return {
4372
3977
  disableHttpHandler,
4373
3978
  enableHttpHandler,
4374
- getBasicUserInfo,
3979
+ getUser,
4375
3980
  getConfigData,
4376
- getCryptoHelper,
3981
+ getCrypto,
4377
3982
  getDecodedIDPIDToken,
4378
- getDecodedIDToken,
4379
- getIDToken,
4380
- getOIDCServiceEndpoints,
3983
+ getDecodedIdToken,
3984
+ getIdToken,
3985
+ getOpenIDProviderEndpoints,
4381
3986
  httpRequest,
4382
3987
  httpRequestAll,
4383
3988
  initialize,
4384
- isAuthenticated,
3989
+ isSignedIn,
4385
3990
  refreshAccessToken,
4386
- requestCustomGrant,
3991
+ exchangeToken,
4387
3992
  revokeAccessToken,
4388
3993
  setHttpRequestErrorCallback,
4389
3994
  setHttpRequestFinishCallback,
@@ -4392,7 +3997,7 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4392
3997
  signIn,
4393
3998
  signOut,
4394
3999
  trySignInSilently,
4395
- updateConfig
4000
+ reInitialize
4396
4001
  };
4397
4002
  };
4398
4003
 
@@ -4400,7 +4005,6 @@ var WebWorkerClient = async (instanceID, config, webWorker, getAuthHelper) => {
4400
4005
  var DefaultConfig = {
4401
4006
  autoLogoutOnTokenRefreshError: true,
4402
4007
  checkSessionInterval: 3,
4403
- clientHost: origin,
4404
4008
  enableOIDCSessionManagement: false,
4405
4009
  periodicTokenRefresh: false,
4406
4010
  sessionRefreshInterval: 300,
@@ -4411,7 +4015,8 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4411
4015
  __publicField(this, "_client");
4412
4016
  __publicField(this, "_storage");
4413
4017
  __publicField(this, "_authHelper", AuthenticationHelper);
4414
- __publicField(this, "_worker", worker_default);
4018
+ // protected _worker: new () => Worker = WorkerFile;
4019
+ __publicField(this, "_worker", null);
4415
4020
  __publicField(this, "_initialized", false);
4416
4021
  __publicField(this, "_startedInitialize", false);
4417
4022
  __publicField(this, "_onSignInCallback", () => null);
@@ -4430,13 +4035,13 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4430
4035
  this._authHelper = AuthenticationHelper;
4431
4036
  }
4432
4037
  }
4433
- instantiateWorker(worker) {
4434
- if (worker) {
4435
- this._worker = worker;
4436
- } else {
4437
- this._worker = worker_default;
4438
- }
4439
- }
4038
+ // public instantiateWorker(worker: new () => Worker) {
4039
+ // if (worker) {
4040
+ // this._worker = worker;
4041
+ // } else {
4042
+ // this._worker = WorkerFile;
4043
+ // }
4044
+ // }
4440
4045
  /**
4441
4046
  * This method specifies if the `AsgardeoSPAClient` has been initialized or not.
4442
4047
  *
@@ -4446,7 +4051,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4446
4051
  *
4447
4052
  * @private
4448
4053
  */
4449
- async _isInitialized() {
4054
+ async isInitialized() {
4450
4055
  if (!this._startedInitialize) {
4451
4056
  return false;
4452
4057
  }
@@ -4476,18 +4081,18 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4476
4081
  * @private
4477
4082
  */
4478
4083
  async _validateMethod(validateAuthentication = true) {
4479
- if (!await this._isInitialized()) {
4084
+ if (!await this.isInitialized()) {
4480
4085
  return Promise.reject(
4481
- new AsgardeoAuthException5(
4086
+ new AsgardeoAuthException4(
4482
4087
  "SPA-AUTH_CLIENT-VM-NF01",
4483
4088
  "The SDK is not initialized.",
4484
4089
  "The SDK must be initialized first."
4485
4090
  )
4486
4091
  );
4487
4092
  }
4488
- if (validateAuthentication && !await this.isAuthenticated()) {
4093
+ if (validateAuthentication && !await this.isSignedIn()) {
4489
4094
  return Promise.reject(
4490
- new AsgardeoAuthException5(
4095
+ new AsgardeoAuthException4(
4491
4096
  "SPA-AUTH_CLIENT-VM-IV02",
4492
4097
  "The user is not authenticated.",
4493
4098
  "The user must be authenticated first."
@@ -4537,8 +4142,8 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4537
4142
  * @example
4538
4143
  * ```
4539
4144
  * auth.initialize({
4540
- * signInRedirectURL: "http://localhost:3000/sign-in",
4541
- * clientID: "client ID",
4145
+ * afterSignInUrl: "http://localhost:3000/sign-in",
4146
+ * clientId: "client ID",
4542
4147
  * baseUrl: "https://api.asgardeo.io"
4543
4148
  * });
4544
4149
  * ```
@@ -4554,7 +4159,6 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4554
4159
  this._initialized = false;
4555
4160
  this._startedInitialize = true;
4556
4161
  authHelper && this.instantiateAuthHelper(authHelper);
4557
- workerFile && this.instantiateWorker(workerFile);
4558
4162
  const _config = await this._client?.getConfigData();
4559
4163
  if (!(this._storage === "webWorker" /* WebWorker */)) {
4560
4164
  const mainThreadClientConfig = config;
@@ -4615,11 +4219,11 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4615
4219
  /**
4616
4220
  * This method returns a Promise that resolves with the basic user information obtained from the ID token.
4617
4221
  *
4618
- * @return {Promise<BasicUserInfo>} - A promise that resolves with the user information.
4222
+ * @return {Promise<User>} - A promise that resolves with the user information.
4619
4223
  *
4620
4224
  * @example
4621
4225
  * ```
4622
- * auth.getBasicUserInfo().then((response) => {
4226
+ * auth.getUser().then((response) => {
4623
4227
  * // console.log(response);
4624
4228
  * }).catch((error) => {
4625
4229
  * // console.error(error);
@@ -4632,9 +4236,9 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4632
4236
  *
4633
4237
  * @preserve
4634
4238
  */
4635
- async getBasicUserInfo() {
4239
+ async getUser() {
4636
4240
  await this._validateMethod();
4637
- return this._client?.getBasicUserInfo();
4241
+ return this._client?.getUser();
4638
4242
  }
4639
4243
  /**
4640
4244
  * This method initiates the authentication flow. This should be called twice.
@@ -4659,7 +4263,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4659
4263
  * @param {string} sessionState - The session state. (Optional)
4660
4264
  * @param {string} state - The state. (Optional)
4661
4265
  *
4662
- * @return {Promise<BasicUserInfo>} - A promise that resolves with the user information.
4266
+ * @return {Promise<User>} - A promise that resolves with the user information.
4663
4267
  *
4664
4268
  * @example
4665
4269
  * ```
@@ -4673,16 +4277,14 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4673
4277
  * @preserve
4674
4278
  */
4675
4279
  async signIn(config, authorizationCode, sessionState, state, tokenRequestConfig) {
4676
- await this._isInitialized();
4280
+ await this.isInitialized();
4677
4281
  if (!SPAUtils.canContinueSignIn(Boolean(config?.callOnlyOnRedirect), authorizationCode)) {
4678
4282
  return void 0;
4679
4283
  }
4680
4284
  delete config?.callOnlyOnRedirect;
4681
4285
  return this._client?.signIn(config, authorizationCode, sessionState, state, tokenRequestConfig).then((response) => {
4682
4286
  if (this._onSignInCallback) {
4683
- if (response.allowedScopes || response.displayName || response.email || response.username) {
4684
- this._onSignInCallback(response);
4685
- }
4287
+ this._onSignInCallback(response);
4686
4288
  }
4687
4289
  return response;
4688
4290
  });
@@ -4695,7 +4297,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4695
4297
  * If this method is to be called on page load and the `signIn` method is also to be called on page load,
4696
4298
  * then it is advisable to call this method after the `signIn` call.
4697
4299
  *
4698
- * @return {Promise<BasicUserInfo | boolean>} - A Promise that resolves with the user information after signing in
4300
+ * @return {Promise<User | boolean>} - A Promise that resolves with the user information after signing in
4699
4301
  * or with `false` if the user is not signed in.
4700
4302
  *
4701
4303
  * @example
@@ -4704,16 +4306,13 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4704
4306
  *```
4705
4307
  */
4706
4308
  async trySignInSilently(additionalParams, tokenRequestConfig) {
4707
- await this._isInitialized();
4309
+ await this.isInitialized();
4708
4310
  if (SPAUtils.wasSignInCalled()) {
4709
4311
  return void 0;
4710
4312
  }
4711
4313
  return this._client?.trySignInSilently(additionalParams, tokenRequestConfig).then((response) => {
4712
4314
  if (this._onSignInCallback && response) {
4713
- const basicUserInfo = response;
4714
- if (basicUserInfo.allowedScopes || basicUserInfo.displayName || basicUserInfo.email || basicUserInfo.username) {
4715
- this._onSignInCallback(basicUserInfo);
4716
- }
4315
+ this._onSignInCallback(response);
4717
4316
  }
4718
4317
  return response;
4719
4318
  });
@@ -4866,7 +4465,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4866
4465
  *
4867
4466
  * @preserve
4868
4467
  */
4869
- async requestCustomGrant(config) {
4468
+ async exchangeToken(config) {
4870
4469
  if (config.signInRequired) {
4871
4470
  await this._validateMethod();
4872
4471
  } else {
@@ -4874,14 +4473,14 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4874
4473
  }
4875
4474
  if (!config.id) {
4876
4475
  return Promise.reject(
4877
- new AsgardeoAuthException5(
4476
+ new AsgardeoAuthException4(
4878
4477
  "SPA-AUTH_CLIENT-RCG-NF01",
4879
4478
  "The custom grant request id not found.",
4880
4479
  "The id attribute of the custom grant config object passed as an argument should have a value."
4881
4480
  )
4882
4481
  );
4883
4482
  }
4884
- const customGrantResponse = await this._client?.requestCustomGrant(config);
4483
+ const customGrantResponse = await this._client?.exchangeToken(config);
4885
4484
  const customGrantCallback = this._onCustomGrant.get(config.id);
4886
4485
  customGrantCallback && customGrantCallback(this._onCustomGrant?.get(config.id));
4887
4486
  return customGrantResponse;
@@ -4932,9 +4531,9 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4932
4531
  *
4933
4532
  * @preserve
4934
4533
  */
4935
- async getOIDCServiceEndpoints() {
4936
- await this._isInitialized();
4937
- return this._client?.getOIDCServiceEndpoints();
4534
+ async getOpenIDProviderEndpoints() {
4535
+ await this.isInitialized();
4536
+ return this._client?.getOpenIDProviderEndpoints();
4938
4537
  }
4939
4538
  /**
4940
4539
  * This methods returns the Axios http client.
@@ -4951,13 +4550,13 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4951
4550
  const mainThreadClient = this._client;
4952
4551
  return mainThreadClient.getHttpClient();
4953
4552
  }
4954
- throw new AsgardeoAuthException5(
4553
+ throw new AsgardeoAuthException4(
4955
4554
  "SPA-AUTH_CLIENT-GHC-IV01",
4956
4555
  "Http client cannot be returned.",
4957
4556
  "The http client cannot be returned when the storage type is set to webWorker."
4958
4557
  );
4959
4558
  }
4960
- throw new AsgardeoAuthException5(
4559
+ throw new AsgardeoAuthException4(
4961
4560
  "SPA-AUTH_CLIENT-GHC-NF02",
4962
4561
  "The SDK is not initialized.",
4963
4562
  "The SDK has not been initialized yet. Initialize the SDK using the initialize method before calling this method."
@@ -4971,7 +4570,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4971
4570
  *
4972
4571
  * @example
4973
4572
  * ```
4974
- * auth.getDecodedIDToken().then((response)=>{
4573
+ * auth.getDecodedIdToken().then((response)=>{
4975
4574
  * // console.log(response);
4976
4575
  * }).catch((error)=>{
4977
4576
  * // console.error(error);
@@ -4983,9 +4582,9 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4983
4582
  *
4984
4583
  * @preserve
4985
4584
  */
4986
- async getDecodedIDToken() {
4585
+ async getDecodedIdToken() {
4987
4586
  await this._validateMethod();
4988
- return this._client?.getDecodedIDToken();
4587
+ return this._client?.getDecodedIdToken();
4989
4588
  }
4990
4589
  /**
4991
4590
  * This method returns the IsomorphicCrypto instance.
@@ -4995,21 +4594,21 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
4995
4594
  *
4996
4595
  * @example
4997
4596
  * ```
4998
- * auth.getCryptoHelper().then((response)=>{
4597
+ * auth.getCrypto().then((response)=>{
4999
4598
  * // console.log(response);
5000
4599
  * }).catch((error)=>{
5001
4600
  * // console.error(error);
5002
4601
  * });
5003
4602
  * ```
5004
- * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getCryptoHelper
4603
+ * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getCrypto
5005
4604
  *
5006
4605
  * @memberof AsgardeoSPAClient
5007
4606
  *
5008
4607
  * @preserve
5009
4608
  */
5010
- async getCryptoHelper() {
4609
+ async getCrypto() {
5011
4610
  await this._validateMethod();
5012
- return this._client?.getCryptoHelper();
4611
+ return this._client?.getCrypto();
5013
4612
  }
5014
4613
  /**
5015
4614
  * This method return the ID token.
@@ -5018,18 +4617,18 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5018
4617
  *
5019
4618
  * @example
5020
4619
  * ```
5021
- * const idToken = await auth.getIDToken();
4620
+ * const idToken = await auth.getIdToken();
5022
4621
  * ```
5023
4622
  *
5024
- * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getIDToken
4623
+ * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getIdToken
5025
4624
  *
5026
4625
  * @memberof AsgardeoAuthClient
5027
4626
  *
5028
4627
  * @preserve
5029
4628
  */
5030
- async getIDToken() {
4629
+ async getIdToken() {
5031
4630
  await this._validateMethod();
5032
- return this._client?.getIDToken();
4631
+ return this._client?.getIdToken();
5033
4632
  }
5034
4633
  /**
5035
4634
  * This method return a Promise that resolves with the access token.
@@ -5057,7 +4656,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5057
4656
  await this._validateMethod();
5058
4657
  if (this._storage && [("webWorker" /* WebWorker */, "browserMemory" /* BrowserMemory */)].includes(this._storage)) {
5059
4658
  return Promise.reject(
5060
- new AsgardeoAuthException5(
4659
+ new AsgardeoAuthException4(
5061
4660
  "SPA-AUTH_CLIENT-GAT-IV01",
5062
4661
  "The access token cannot be returned.",
5063
4662
  "The access token cannot be returned when the storage type is set to webWorker or browserMemory."
@@ -5093,7 +4692,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5093
4692
  await this._validateMethod();
5094
4693
  if (this._storage && [("webWorker" /* WebWorker */, "browserMemory" /* BrowserMemory */)].includes(this._storage)) {
5095
4694
  return Promise.reject(
5096
- new AsgardeoAuthException5(
4695
+ new AsgardeoAuthException4(
5097
4696
  "SPA-AUTH_CLIENT-GIAT-IV01",
5098
4697
  "The access token cannot be returned.",
5099
4698
  "The access token cannot be returned when the storage type is set to webWorker or browserMemory."
@@ -5112,7 +4711,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5112
4711
  *
5113
4712
  * @example
5114
4713
  * ```
5115
- * auth.getDataLayer().then((dataLayer) => {
4714
+ * auth.getStorageManager().then((dataLayer) => {
5116
4715
  * // console.log(dataLayer);
5117
4716
  * }).catch((error) => {
5118
4717
  * // console.error(error);
@@ -5125,11 +4724,11 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5125
4724
  *
5126
4725
  * @preserve
5127
4726
  */
5128
- async getDataLayer() {
4727
+ async getStorageManager() {
5129
4728
  await this._validateMethod();
5130
4729
  if (this._storage && [("webWorker" /* WebWorker */, "browserMemory" /* BrowserMemory */)].includes(this._storage)) {
5131
4730
  return Promise.reject(
5132
- new AsgardeoAuthException5(
4731
+ new AsgardeoAuthException4(
5133
4732
  "SPA-AUTH_CLIENT-GDL-IV01",
5134
4733
  "The data layer cannot be returned.",
5135
4734
  "The data layer cannot be returned when the storage type is set to webWorker or browserMemory."
@@ -5137,7 +4736,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5137
4736
  );
5138
4737
  }
5139
4738
  const mainThreadClient = this._client;
5140
- return mainThreadClient.getDataLayer();
4739
+ return mainThreadClient.getStorageManager();
5141
4740
  }
5142
4741
  /**
5143
4742
  * This method return a Promise that resolves with the config data stored in the storage.
@@ -5196,9 +4795,9 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5196
4795
  *
5197
4796
  * @preserve
5198
4797
  */
5199
- async isAuthenticated() {
5200
- await this._isInitialized();
5201
- return this._client?.isAuthenticated();
4798
+ async isSignedIn() {
4799
+ await this.isInitialized();
4800
+ return this._client?.isSignedIn();
5202
4801
  }
5203
4802
  /**
5204
4803
  * This method specifies if there is an active session in the browser or not.
@@ -5210,10 +4809,10 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5210
4809
  * @preserve
5211
4810
  */
5212
4811
  async isSessionActive() {
5213
- await this._isInitialized();
4812
+ await this.isInitialized();
5214
4813
  if (this._storage && [("webWorker" /* WebWorker */, "browserMemory" /* BrowserMemory */)].includes(this._storage)) {
5215
4814
  return Promise.reject(
5216
- new AsgardeoAuthException5(
4815
+ new AsgardeoAuthException4(
5217
4816
  "SPA-AUTH_CLIENT-ISA-IV01",
5218
4817
  "The active session cannot be returned.",
5219
4818
  "The active session cannot be returned when the storage type is set to webWorker or browserMemory."
@@ -5224,7 +4823,7 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5224
4823
  return mainThreadClient?.isSessionActive();
5225
4824
  }
5226
4825
  async on(hook, callback, id) {
5227
- await this._isInitialized();
4826
+ await this.isInitialized();
5228
4827
  if (callback && typeof callback === "function") {
5229
4828
  switch (hook) {
5230
4829
  case "sign-in" /* SignIn */:
@@ -5263,128 +4862,478 @@ var _AsgardeoSPAClient = class _AsgardeoSPAClient {
5263
4862
  if (signOutFail) {
5264
4863
  this._onSignOutFailedCallback(signOutFail);
5265
4864
  }
5266
- break;
4865
+ break;
4866
+ }
4867
+ default:
4868
+ throw new AsgardeoAuthException4("SPA-AUTH_CLIENT-ON-IV01", "Invalid hook.", "The provided hook is invalid.");
4869
+ }
4870
+ } else {
4871
+ throw new AsgardeoAuthException4(
4872
+ "SPA-AUTH_CLIENT-ON-IV02",
4873
+ "Invalid callback function.",
4874
+ "The provided callback function is invalid."
4875
+ );
4876
+ }
4877
+ }
4878
+ /**
4879
+ * This method enables callback functions attached to the http client.
4880
+ *
4881
+ * @return {Promise<boolean>} - A promise that resolves with True.
4882
+ *
4883
+ * @example
4884
+ * ```
4885
+ * auth.enableHttpHandler();
4886
+ * ```
4887
+ *
4888
+ * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#enableHttpHandler
4889
+ *
4890
+ * @memberof AsgardeoSPAClient
4891
+ *
4892
+ * @preserve
4893
+ */
4894
+ async enableHttpHandler() {
4895
+ await this.isInitialized();
4896
+ return this._client?.enableHttpHandler();
4897
+ }
4898
+ /**
4899
+ * This method disables callback functions attached to the http client.
4900
+ *
4901
+ * @return {Promise<boolean>} - A promise that resolves with True.
4902
+ *
4903
+ * @example
4904
+ * ```
4905
+ * auth.disableHttpHandler();
4906
+ * ```
4907
+ *
4908
+ * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#disableHttpHandler
4909
+ *
4910
+ * @memberof AsgardeoSPAClient
4911
+ *
4912
+ * @preserve
4913
+ */
4914
+ async disableHttpHandler() {
4915
+ await this.isInitialized();
4916
+ return this._client?.disableHttpHandler();
4917
+ }
4918
+ /**
4919
+ * This method updates the configuration that was passed into the constructor when instantiating this class.
4920
+ *
4921
+ * @param {Partial<AuthClientConfig<T>>} config - A config object to update the SDK configurations with.
4922
+ *
4923
+ * @example
4924
+ * ```
4925
+ * const config = {
4926
+ * afterSignInUrl: "http://localhost:3000/sign-in",
4927
+ * clientId: "client ID",
4928
+ * baseUrl: "https://api.asgardeo.io"
4929
+ * }
4930
+ * const auth.reInitialize(config);
4931
+ * ```
4932
+ * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master/lib#reInitialize
4933
+ *
4934
+ * @memberof AsgardeoAuthClient
4935
+ *
4936
+ * @preserve
4937
+ */
4938
+ async reInitialize(config) {
4939
+ await this.isInitialized();
4940
+ if (this._storage === "webWorker" /* WebWorker */) {
4941
+ const client = this._client;
4942
+ await client.reInitialize(config);
4943
+ } else {
4944
+ const client = this._client;
4945
+ await client.reInitialize(config);
4946
+ }
4947
+ return;
4948
+ }
4949
+ };
4950
+ __publicField(_AsgardeoSPAClient, "_instances", /* @__PURE__ */ new Map());
4951
+ var AsgardeoSPAClient = _AsgardeoSPAClient;
4952
+
4953
+ // src/__legacy__/models/http-client.ts
4954
+ import {
4955
+ AxiosResponse,
4956
+ Method,
4957
+ AxiosRequestTransformer,
4958
+ AxiosResponseTransformer,
4959
+ AxiosAdapter,
4960
+ AxiosBasicCredentials,
4961
+ ResponseType,
4962
+ AxiosProxyConfig,
4963
+ CancelToken,
4964
+ AxiosError,
4965
+ AxiosPromise,
4966
+ AxiosInstance
4967
+ } from "axios";
4968
+
4969
+ // src/__legacy__/models/web-worker.ts
4970
+ var WebWorkerClass = class {
4971
+ constructor() {
4972
+ __publicField(this, "onmessage", () => null);
4973
+ __publicField(this, "postMessage", () => null);
4974
+ }
4975
+ };
4976
+
4977
+ // src/__legacy__/worker/worker-receiver.ts
4978
+ import { AsgardeoAuthException as AsgardeoAuthException5 } from "@asgardeo/javascript";
4979
+
4980
+ // src/__legacy__/worker/worker-core.ts
4981
+ import {
4982
+ AsgardeoAuthClient as AsgardeoAuthClient8,
4983
+ OIDCRequestConstants as OIDCRequestConstants5
4984
+ } from "@asgardeo/javascript";
4985
+ var WebWorkerCore = async (config, getAuthHelper) => {
4986
+ const _store = new MemoryStore();
4987
+ const _cryptoUtils = new SPACryptoUtils();
4988
+ const _authenticationClient = new AsgardeoAuthClient8();
4989
+ await _authenticationClient.initialize(config, _store, _cryptoUtils);
4990
+ const _spaHelper = new SPAHelper(_authenticationClient);
4991
+ const _authenticationHelper = getAuthHelper(
4992
+ _authenticationClient,
4993
+ _spaHelper
4994
+ );
4995
+ const _dataLayer = _authenticationClient.getStorageManager();
4996
+ const _httpClient = HttpClient.getInstance();
4997
+ const attachToken = async (request) => {
4998
+ await _authenticationHelper.attachTokenToRequestConfig(request);
4999
+ };
5000
+ _httpClient?.init && await _httpClient.init(true, attachToken);
5001
+ const setHttpRequestStartCallback = (callback) => {
5002
+ _httpClient?.setHttpRequestStartCallback && _httpClient.setHttpRequestStartCallback(callback);
5003
+ };
5004
+ const setHttpRequestSuccessCallback = (callback) => {
5005
+ _httpClient?.setHttpRequestSuccessCallback && _httpClient.setHttpRequestSuccessCallback(callback);
5006
+ };
5007
+ const setHttpRequestFinishCallback = (callback) => {
5008
+ _httpClient?.setHttpRequestFinishCallback && _httpClient.setHttpRequestFinishCallback(callback);
5009
+ };
5010
+ const httpRequest = async (requestConfig) => {
5011
+ return await _authenticationHelper.httpRequest(_httpClient, requestConfig);
5012
+ };
5013
+ const httpRequestAll = async (requestConfigs) => {
5014
+ return await _authenticationHelper.httpRequestAll(requestConfigs, _httpClient);
5015
+ };
5016
+ const enableHttpHandler = () => {
5017
+ _authenticationHelper.enableHttpHandler(_httpClient);
5018
+ };
5019
+ const disableHttpHandler = () => {
5020
+ _authenticationHelper.disableHttpHandler(_httpClient);
5021
+ };
5022
+ const getSignInUrl = async (params) => {
5023
+ return _authenticationClient.getSignInUrl(params).then(async (url) => {
5024
+ const urlObject = new URL(url);
5025
+ const state = urlObject.searchParams.get(OIDCRequestConstants5.Params.STATE) ?? "";
5026
+ const pkce = await _authenticationClient.getPKCECode(state);
5027
+ return { authorizationURL: url, pkce };
5028
+ }).catch((error) => Promise.reject(error));
5029
+ };
5030
+ const startAutoRefreshToken = async () => {
5031
+ _spaHelper.clearRefreshTokenTimeout();
5032
+ _spaHelper.refreshAccessTokenAutomatically(_authenticationHelper);
5033
+ return;
5034
+ };
5035
+ const requestAccessToken = async (authorizationCode, sessionState, pkce, state) => {
5036
+ return await _authenticationHelper.requestAccessToken(authorizationCode, sessionState, void 0, pkce, state);
5037
+ };
5038
+ const signOut = async () => {
5039
+ _spaHelper.clearRefreshTokenTimeout();
5040
+ return await _authenticationClient.getSignOutUrl();
5041
+ };
5042
+ const getSignOutUrl = async () => {
5043
+ return await _authenticationClient.getSignOutUrl();
5044
+ };
5045
+ const exchangeToken = async (config2) => {
5046
+ return await _authenticationHelper.exchangeToken(config2);
5047
+ };
5048
+ const refreshAccessToken = async () => {
5049
+ try {
5050
+ return await _authenticationHelper.refreshAccessToken();
5051
+ } catch (error) {
5052
+ return Promise.reject(error);
5053
+ }
5054
+ };
5055
+ const revokeAccessToken = async () => {
5056
+ const timer = await _spaHelper.getRefreshTimeoutTimer();
5057
+ return _authenticationClient.revokeAccessToken().then(() => {
5058
+ _spaHelper.clearRefreshTokenTimeout(timer);
5059
+ return Promise.resolve(true);
5060
+ }).catch((error) => Promise.reject(error));
5061
+ };
5062
+ const getUser = async () => {
5063
+ return _authenticationHelper.getUser();
5064
+ };
5065
+ const getDecodedIdToken = async () => {
5066
+ return _authenticationHelper.getDecodedIdToken();
5067
+ };
5068
+ const getCrypto = async () => {
5069
+ return _authenticationHelper.getCrypto();
5070
+ };
5071
+ const getDecodedIDPIDToken = async () => {
5072
+ return _authenticationHelper.getDecodedIDPIDToken();
5073
+ };
5074
+ const getIdToken = async () => {
5075
+ return _authenticationHelper.getIdToken();
5076
+ };
5077
+ const getOpenIDProviderEndpoints = async () => {
5078
+ return _authenticationHelper.getOpenIDProviderEndpoints();
5079
+ };
5080
+ const getAccessToken = () => {
5081
+ return _authenticationHelper.getAccessToken();
5082
+ };
5083
+ const isSignedIn = () => {
5084
+ return _authenticationHelper.isSignedIn();
5085
+ };
5086
+ const setSessionState = async (sessionState) => {
5087
+ await _dataLayer.setSessionDataParameter(
5088
+ OIDCRequestConstants5.Params.SESSION_STATE,
5089
+ sessionState
5090
+ );
5091
+ return;
5092
+ };
5093
+ const reInitialize = async (config2) => {
5094
+ await _authenticationClient.reInitialize(config2);
5095
+ return;
5096
+ };
5097
+ const getConfigData = async () => {
5098
+ return _dataLayer.getConfigData();
5099
+ };
5100
+ return {
5101
+ disableHttpHandler,
5102
+ enableHttpHandler,
5103
+ getAccessToken,
5104
+ getSignInUrl,
5105
+ getUser,
5106
+ getConfigData,
5107
+ getCrypto,
5108
+ getDecodedIDPIDToken,
5109
+ getDecodedIdToken,
5110
+ getIdToken,
5111
+ getOpenIDProviderEndpoints,
5112
+ getSignOutUrl,
5113
+ httpRequest,
5114
+ httpRequestAll,
5115
+ isSignedIn,
5116
+ refreshAccessToken,
5117
+ requestAccessToken,
5118
+ exchangeToken,
5119
+ revokeAccessToken,
5120
+ setHttpRequestFinishCallback,
5121
+ setHttpRequestStartCallback,
5122
+ setHttpRequestSuccessCallback,
5123
+ setSessionState,
5124
+ signOut,
5125
+ startAutoRefreshToken,
5126
+ reInitialize
5127
+ };
5128
+ };
5129
+
5130
+ // src/__legacy__/worker/worker-receiver.ts
5131
+ var workerReceiver = (getAuthHelper) => {
5132
+ const ctx = self;
5133
+ let webWorker;
5134
+ ctx.onmessage = async ({ data, ports }) => {
5135
+ const port = ports[0];
5136
+ if (data.type !== INIT && !webWorker) {
5137
+ port.postMessage(
5138
+ MessageUtils.generateFailureMessage(
5139
+ new AsgardeoAuthException5(
5140
+ "SPA-CLIENT_WORKER-ONMSG-NF01",
5141
+ "The web worker has not been initialized yet.",
5142
+ "The initialize method needs to be called before the specified operation can be carried out."
5143
+ )
5144
+ )
5145
+ );
5146
+ return;
5147
+ }
5148
+ switch (data.type) {
5149
+ case INIT:
5150
+ try {
5151
+ const config = { ...data.data };
5152
+ webWorker = await WebWorkerCore(config, getAuthHelper);
5153
+ webWorker.setHttpRequestFinishCallback(onRequestFinishCallback);
5154
+ webWorker.setHttpRequestStartCallback(onRequestStartCallback);
5155
+ webWorker.setHttpRequestSuccessCallback(onRequestSuccessCallback);
5156
+ port.postMessage(MessageUtils.generateSuccessMessage());
5157
+ } catch (error) {
5158
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5159
+ }
5160
+ break;
5161
+ case GET_AUTH_URL:
5162
+ webWorker.getSignInUrl(data?.data).then((response) => {
5163
+ port.postMessage(MessageUtils.generateSuccessMessage(response));
5164
+ }).catch((error) => {
5165
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5166
+ });
5167
+ break;
5168
+ case REQUEST_ACCESS_TOKEN:
5169
+ webWorker.requestAccessToken(data?.data?.code, data?.data?.sessionState, data?.data?.pkce, data?.data?.state).then((response) => {
5170
+ port.postMessage(MessageUtils.generateSuccessMessage(response));
5171
+ }).catch((error) => {
5172
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5173
+ });
5174
+ break;
5175
+ case HTTP_REQUEST: {
5176
+ const request = data.data;
5177
+ const requestData = request?.data;
5178
+ if (data.data?.data?.formData === true) {
5179
+ const formData = new FormData();
5180
+ for (const key in requestData) {
5181
+ if (key === "formData") {
5182
+ continue;
5183
+ }
5184
+ formData.append(key, requestData[key]);
5185
+ }
5186
+ request.data = formData;
5267
5187
  }
5268
- default:
5269
- throw new AsgardeoAuthException5("SPA-AUTH_CLIENT-ON-IV01", "Invalid hook.", "The provided hook is invalid.");
5188
+ webWorker.httpRequest(request).then((response) => {
5189
+ port.postMessage(MessageUtils.generateSuccessMessage(response));
5190
+ }).catch((error) => {
5191
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5192
+ });
5193
+ break;
5270
5194
  }
5271
- } else {
5272
- throw new AsgardeoAuthException5(
5273
- "SPA-AUTH_CLIENT-ON-IV02",
5274
- "Invalid callback function.",
5275
- "The provided callback function is invalid."
5276
- );
5277
- }
5278
- }
5279
- /**
5280
- * This method enables callback functions attached to the http client.
5281
- *
5282
- * @return {Promise<boolean>} - A promise that resolves with True.
5283
- *
5284
- * @example
5285
- * ```
5286
- * auth.enableHttpHandler();
5287
- * ```
5288
- *
5289
- * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#enableHttpHandler
5290
- *
5291
- * @memberof AsgardeoSPAClient
5292
- *
5293
- * @preserve
5294
- */
5295
- async enableHttpHandler() {
5296
- await this._isInitialized();
5297
- return this._client?.enableHttpHandler();
5298
- }
5299
- /**
5300
- * This method disables callback functions attached to the http client.
5301
- *
5302
- * @return {Promise<boolean>} - A promise that resolves with True.
5303
- *
5304
- * @example
5305
- * ```
5306
- * auth.disableHttpHandler();
5307
- * ```
5308
- *
5309
- * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#disableHttpHandler
5310
- *
5311
- * @memberof AsgardeoSPAClient
5312
- *
5313
- * @preserve
5314
- */
5315
- async disableHttpHandler() {
5316
- await this._isInitialized();
5317
- return this._client?.disableHttpHandler();
5318
- }
5319
- /**
5320
- * This method updates the configuration that was passed into the constructor when instantiating this class.
5321
- *
5322
- * @param {Partial<AuthClientConfig<T>>} config - A config object to update the SDK configurations with.
5323
- *
5324
- * @example
5325
- * ```
5326
- * const config = {
5327
- * signInRedirectURL: "http://localhost:3000/sign-in",
5328
- * clientID: "client ID",
5329
- * baseUrl: "https://api.asgardeo.io"
5330
- * }
5331
- * const auth.updateConfig(config);
5332
- * ```
5333
- * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master/lib#updateConfig
5334
- *
5335
- * @memberof AsgardeoAuthClient
5336
- *
5337
- * @preserve
5338
- */
5339
- async updateConfig(config) {
5340
- await this._isInitialized();
5341
- if (this._storage === "webWorker" /* WebWorker */) {
5342
- const client = this._client;
5343
- await client.updateConfig(config);
5344
- } else {
5345
- const client = this._client;
5346
- await client.updateConfig(config);
5195
+ case HTTP_REQUEST_ALL:
5196
+ webWorker.httpRequestAll(data.data).then((response) => {
5197
+ port.postMessage(MessageUtils.generateSuccessMessage(response));
5198
+ }).catch((error) => {
5199
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5200
+ });
5201
+ break;
5202
+ case SIGN_OUT:
5203
+ try {
5204
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.signOut()));
5205
+ } catch (error) {
5206
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5207
+ }
5208
+ break;
5209
+ case REQUEST_CUSTOM_GRANT:
5210
+ webWorker.exchangeToken(data.data).then((response) => {
5211
+ port.postMessage(MessageUtils.generateSuccessMessage(response));
5212
+ }).catch((error) => {
5213
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5214
+ });
5215
+ break;
5216
+ case REVOKE_ACCESS_TOKEN:
5217
+ webWorker.revokeAccessToken().then((response) => {
5218
+ port.postMessage(MessageUtils.generateSuccessMessage(response));
5219
+ }).catch((error) => {
5220
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5221
+ });
5222
+ break;
5223
+ case GET_OIDC_SERVICE_ENDPOINTS:
5224
+ try {
5225
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getOpenIDProviderEndpoints()));
5226
+ } catch (error) {
5227
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5228
+ }
5229
+ break;
5230
+ case GET_BASIC_USER_INFO:
5231
+ try {
5232
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getUser()));
5233
+ } catch (error) {
5234
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5235
+ }
5236
+ break;
5237
+ case GET_DECODED_ID_TOKEN:
5238
+ try {
5239
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getDecodedIdToken()));
5240
+ } catch (error) {
5241
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5242
+ }
5243
+ break;
5244
+ case GET_CRYPTO_HELPER:
5245
+ try {
5246
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getCrypto()));
5247
+ } catch (error) {
5248
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5249
+ }
5250
+ break;
5251
+ case GET_ID_TOKEN:
5252
+ try {
5253
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getIdToken()));
5254
+ } catch (error) {
5255
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5256
+ }
5257
+ break;
5258
+ case ENABLE_HTTP_HANDLER:
5259
+ webWorker.enableHttpHandler();
5260
+ port.postMessage(MessageUtils.generateSuccessMessage());
5261
+ break;
5262
+ case DISABLE_HTTP_HANDLER:
5263
+ webWorker.disableHttpHandler();
5264
+ port.postMessage(MessageUtils.generateSuccessMessage());
5265
+ break;
5266
+ case IS_AUTHENTICATED:
5267
+ try {
5268
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.isSignedIn()));
5269
+ } catch (error) {
5270
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5271
+ }
5272
+ break;
5273
+ case GET_SIGN_OUT_URL:
5274
+ try {
5275
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getSignOutUrl()));
5276
+ } catch (error) {
5277
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5278
+ }
5279
+ break;
5280
+ case REFRESH_ACCESS_TOKEN:
5281
+ try {
5282
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.refreshAccessToken()));
5283
+ } catch (error) {
5284
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5285
+ }
5286
+ break;
5287
+ case START_AUTO_REFRESH_TOKEN:
5288
+ try {
5289
+ port.postMessage(MessageUtils.generateSuccessMessage(webWorker.startAutoRefreshToken()));
5290
+ } catch (error) {
5291
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5292
+ }
5293
+ break;
5294
+ case SET_SESSION_STATE:
5295
+ try {
5296
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.setSessionState(data?.data)));
5297
+ } catch (error) {
5298
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5299
+ }
5300
+ break;
5301
+ case UPDATE_CONFIG:
5302
+ try {
5303
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.reInitialize(data?.data)));
5304
+ } catch (error) {
5305
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5306
+ }
5307
+ break;
5308
+ case GET_CONFIG_DATA:
5309
+ try {
5310
+ port.postMessage(MessageUtils.generateSuccessMessage(await webWorker.getConfigData()));
5311
+ } catch (error) {
5312
+ port.postMessage(MessageUtils.generateFailureMessage(error));
5313
+ }
5314
+ break;
5315
+ default:
5316
+ port?.postMessage(
5317
+ MessageUtils.generateFailureMessage(
5318
+ new AsgardeoAuthException5(
5319
+ "SPA-CLIENT_WORKER-ONMSG-IV02",
5320
+ "The message type is invalid.",
5321
+ `The message type provided, ${data.type}, is invalid.`
5322
+ )
5323
+ )
5324
+ );
5347
5325
  }
5348
- return;
5349
- }
5350
- };
5351
- __publicField(_AsgardeoSPAClient, "_instances", /* @__PURE__ */ new Map());
5352
- var AsgardeoSPAClient = _AsgardeoSPAClient;
5353
-
5354
- // src/__legacy__/models/http-client.ts
5355
- import {
5356
- AxiosResponse,
5357
- Method,
5358
- AxiosRequestTransformer,
5359
- AxiosResponseTransformer,
5360
- AxiosAdapter,
5361
- AxiosBasicCredentials,
5362
- ResponseType,
5363
- AxiosProxyConfig,
5364
- CancelToken,
5365
- AxiosError,
5366
- AxiosPromise,
5367
- AxiosInstance
5368
- } from "axios";
5369
-
5370
- // src/__legacy__/models/web-worker.ts
5371
- var WebWorkerClass = class extends Worker {
5372
- constructor() {
5373
- super(...arguments);
5374
- __publicField(this, "onmessage", () => null);
5375
- }
5376
- };
5377
-
5378
- // src/constants/StyleConstants.ts
5379
- var StyleConstants = class {
5380
- constructor() {
5381
- }
5326
+ };
5327
+ const onRequestStartCallback = () => {
5328
+ ctx.postMessage({ type: REQUEST_START });
5329
+ };
5330
+ const onRequestSuccessCallback = (response) => {
5331
+ ctx.postMessage({ data: JSON.stringify(response ?? ""), type: REQUEST_SUCCESS });
5332
+ };
5333
+ const onRequestFinishCallback = () => {
5334
+ ctx.postMessage({ type: REQUEST_FINISH });
5335
+ };
5382
5336
  };
5383
- /**
5384
- * CSS class prefix for out of the box components.
5385
- */
5386
- __publicField(StyleConstants, "VENDOR_CSS_CLASS_PREFIX", "asgardeo");
5387
- var StyleConstants_default = StyleConstants;
5388
5337
 
5389
5338
  // src/utils/hasAuthParamsInUrl.ts
5390
5339
  var hasAuthParamsInUrl = (params = window.location.search) => {
@@ -5393,12 +5342,6 @@ var hasAuthParamsInUrl = (params = window.location.search) => {
5393
5342
  };
5394
5343
  var hasAuthParamsInUrl_default = hasAuthParamsInUrl;
5395
5344
 
5396
- // src/utils/withVendorCSSClassPrefix.ts
5397
- var withVendorCSSClassPrefix = (className) => {
5398
- return `${StyleConstants_default.VENDOR_CSS_CLASS_PREFIX}-${className}`;
5399
- };
5400
- var withVendorCSSClassPrefix_default = withVendorCSSClassPrefix;
5401
-
5402
5345
  // src/AsgardeoBrowserClient.ts
5403
5346
  import { AsgardeoJavaScriptClient } from "@asgardeo/javascript";
5404
5347
  var AsgardeoBrowserClient = class extends AsgardeoJavaScriptClient {
@@ -5427,12 +5370,10 @@ export {
5427
5370
  ResponseType,
5428
5371
  SPAHelper,
5429
5372
  SPAUtils,
5430
- StyleConstants_default as StyleConstants,
5431
5373
  TOKEN_REQUEST_CONFIG_KEY,
5432
5374
  WebWorkerClass,
5433
5375
  WebWorkerClient,
5434
5376
  hasAuthParamsInUrl_default as hasAuthParamsInUrl,
5435
- withVendorCSSClassPrefix_default as withVendorCSSClassPrefix,
5436
5377
  workerReceiver
5437
5378
  };
5438
5379
  /*! Bundled license information: