@asgardeo/auth-spa 0.3.8 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/asgardeo-spa.production.esm.js +13 -13
  2. package/dist/asgardeo-spa.production.esm.js.map +1 -1
  3. package/dist/asgardeo-spa.production.js +13 -13
  4. package/dist/asgardeo-spa.production.js.map +1 -1
  5. package/dist/asgardeo-spa.production.min.js +1 -1
  6. package/dist/asgardeo-spa.production.min.js.map +1 -1
  7. package/dist/polyfilled/asgardeo-spa.production.esm.js +42 -40
  8. package/dist/polyfilled/asgardeo-spa.production.esm.js.map +1 -1
  9. package/dist/polyfilled/asgardeo-spa.production.js +42 -40
  10. package/dist/polyfilled/asgardeo-spa.production.js.map +1 -1
  11. package/dist/polyfilled/asgardeo-spa.production.min.js +1 -1
  12. package/dist/polyfilled/asgardeo-spa.production.min.js.map +1 -1
  13. package/dist/src/client.d.ts +21 -16
  14. package/dist/src/client.d.ts.map +1 -1
  15. package/dist/src/client.js +29 -3
  16. package/dist/src/client.js.map +1 -1
  17. package/dist/src/clients/main-thread-client.d.ts +3 -2
  18. package/dist/src/clients/main-thread-client.d.ts.map +1 -1
  19. package/dist/src/clients/main-thread-client.js +83 -385
  20. package/dist/src/clients/main-thread-client.js.map +1 -1
  21. package/dist/src/clients/web-worker-client.d.ts +3 -2
  22. package/dist/src/clients/web-worker-client.d.ts.map +1 -1
  23. package/dist/src/clients/web-worker-client.js +98 -138
  24. package/dist/src/clients/web-worker-client.js.map +1 -1
  25. package/dist/src/helpers/authentication-helper.d.ts +50 -0
  26. package/dist/src/helpers/authentication-helper.d.ts.map +1 -0
  27. package/dist/src/helpers/authentication-helper.js +482 -0
  28. package/dist/src/helpers/authentication-helper.js.map +1 -0
  29. package/dist/src/helpers/index.d.ts +1 -0
  30. package/dist/src/helpers/index.d.ts.map +1 -1
  31. package/dist/src/helpers/index.js +1 -0
  32. package/dist/src/helpers/index.js.map +1 -1
  33. package/dist/src/public-api.d.ts +3 -0
  34. package/dist/src/public-api.d.ts.map +1 -1
  35. package/dist/src/public-api.js +5 -0
  36. package/dist/src/public-api.js.map +1 -1
  37. package/dist/src/worker/index.d.ts +1 -1
  38. package/dist/src/worker/index.d.ts.map +1 -1
  39. package/dist/src/worker/index.js +1 -1
  40. package/dist/src/worker/index.js.map +1 -1
  41. package/dist/src/worker/worker-core.d.ts +3 -2
  42. package/dist/src/worker/worker-core.d.ts.map +1 -1
  43. package/dist/src/worker/worker-core.js +23 -202
  44. package/dist/src/worker/worker-core.js.map +1 -1
  45. package/dist/src/worker/worker-receiver.d.ts +22 -0
  46. package/dist/src/worker/worker-receiver.d.ts.map +1 -0
  47. package/dist/src/worker/worker-receiver.js +233 -0
  48. package/dist/src/worker/worker-receiver.js.map +1 -0
  49. package/dist/src/{worker/client.worker.d.ts → worker.d.ts} +2 -2
  50. package/dist/src/worker.d.ts.map +1 -0
  51. package/dist/src/worker.js +24 -0
  52. package/dist/src/worker.js.map +1 -0
  53. package/dist/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +1 -1
  55. package/src/client.ts +65 -19
  56. package/src/clients/main-thread-client.ts +137 -486
  57. package/src/clients/web-worker-client.ts +128 -169
  58. package/src/helpers/authentication-helper.ts +661 -0
  59. package/src/helpers/index.ts +1 -0
  60. package/src/public-api.ts +7 -0
  61. package/src/worker/index.ts +1 -1
  62. package/src/worker/worker-core.ts +48 -261
  63. package/src/worker/worker-receiver.ts +297 -0
  64. package/src/worker.ts +30 -0
  65. package/dist/src/worker/client.worker.d.ts.map +0 -1
  66. package/dist/src/worker/client.worker.js +0 -232
  67. package/dist/src/worker/client.worker.js.map +0 -1
  68. package/src/worker/client.worker.ts +0 -286
@@ -19,11 +19,9 @@
19
19
  import {
20
20
  AUTHORIZATION_CODE,
21
21
  AsgardeoAuthClient,
22
- AsgardeoAuthException,
23
22
  AuthClientConfig,
24
23
  AuthenticationUtils,
25
24
  BasicUserInfo,
26
- CustomGrantConfig,
27
25
  DecodedIDTokenPayload,
28
26
  FetchResponse,
29
27
  GetAuthURLConfig,
@@ -31,31 +29,20 @@ import {
31
29
  ResponseMode,
32
30
  SESSION_STATE,
33
31
  STATE,
34
- Store,
35
- TokenResponse
32
+ Store
36
33
  } from "@asgardeo/auth-js";
37
34
  import {
38
- ACCESS_TOKEN_INVALID,
39
- CHECK_SESSION_SIGNED_IN,
40
- CHECK_SESSION_SIGNED_OUT,
41
- CUSTOM_GRANT_CONFIG,
42
- ERROR,
43
- ERROR_DESCRIPTION,
44
- PROMPT_NONE_IFRAME,
45
- RP_IFRAME,
46
35
  SILENT_SIGN_IN_STATE,
47
36
  Storage
48
37
  } from "../constants";
49
- import { SPAHelper, SessionManagementHelper } from "../helpers";
38
+ import { AuthenticationHelper, SPAHelper, SessionManagementHelper } from "../helpers";
50
39
  import { HttpClient, HttpClientInstance } from "../http-client";
51
40
  import {
52
- AuthorizationInfo,
53
41
  HttpError,
54
42
  HttpRequestConfig,
55
43
  HttpResponse,
56
44
  MainThreadClientConfig,
57
- MainThreadClientInterface,
58
- Message
45
+ MainThreadClientInterface
59
46
  } from "../models";
60
47
  import { SPACustomGrantConfig } from "../models/request-custom-grant";
61
48
  import { LocalStore, MemoryStore, SessionStore } from "../stores";
@@ -76,7 +63,11 @@ const initiateStore = (store: Storage | undefined): Store => {
76
63
  };
77
64
 
78
65
  export const MainThreadClient = async (
79
- config: AuthClientConfig<MainThreadClientConfig>
66
+ config: AuthClientConfig<MainThreadClientConfig>,
67
+ getAuthHelper: (
68
+ authClient: AsgardeoAuthClient<MainThreadClientConfig>,
69
+ spaHelper: SPAHelper<MainThreadClientConfig>
70
+ ) => AuthenticationHelper<MainThreadClientConfig>
80
71
  ): Promise<MainThreadClientInterface> => {
81
72
  const _store: Store = initiateStore(config.storage);
82
73
  const _cryptoUtils: SPACryptoUtils = new SPACryptoUtils();
@@ -92,6 +83,8 @@ export const MainThreadClient = async (
92
83
  config.storage ?? Storage.SessionStorage,
93
84
  (sessionState: string) => _dataLayer.setSessionDataParameter(SESSION_STATE, sessionState ?? "")
94
85
  );
86
+
87
+ const _authenticationHelper = getAuthHelper(_authenticationClient, _spaHelper);
95
88
 
96
89
  let _getSignOutURLFromSessionStorage: boolean = false;
97
90
 
@@ -100,28 +93,18 @@ export const MainThreadClient = async (
100
93
  let _httpErrorCallback: (error: HttpError) => void | Promise<void>;
101
94
  let _httpFinishCallback: () => void;
102
95
 
103
- const attachToken = async (request: HttpRequestConfig): Promise<void> => {
104
- const requestConfig = { attachToken: true, ...request };
105
- if (requestConfig.attachToken) {
106
- request.headers = {
107
- ...request.headers,
108
- Authorization: `Bearer ${ await _authenticationClient.getAccessToken() }`
109
- };
110
- }
111
- };
112
-
113
- _httpClient?.init && (await _httpClient.init(true, attachToken));
96
+ _httpClient?.init && (await _httpClient.init(true, _authenticationHelper.attachToken));
114
97
 
115
98
  const setHttpRequestStartCallback = (callback: () => void): void => {
116
- _httpClient?.setHttpRequestStartCallback && _httpClient.setHttpRequestStartCallback(callback);
99
+ _authenticationHelper.setHttpRequestStartCallback(_httpClient, callback);
117
100
  };
118
101
 
119
102
  const setHttpRequestSuccessCallback = (callback: (response: HttpResponse) => void): void => {
120
- _httpClient?.setHttpRequestSuccessCallback && _httpClient.setHttpRequestSuccessCallback(callback);
103
+ _authenticationHelper.setHttpRequestSuccessCallback(_httpClient, callback);
121
104
  };
122
105
 
123
106
  const setHttpRequestFinishCallback = (callback: () => void): void => {
124
- _httpClient?.setHttpRequestFinishCallback && _httpClient.setHttpRequestFinishCallback(callback);
107
+ _authenticationHelper.setHttpRequestFinishCallback(_httpClient, callback);
125
108
  _httpFinishCallback = callback;
126
109
  };
127
110
 
@@ -130,198 +113,23 @@ export const MainThreadClient = async (
130
113
  };
131
114
 
132
115
  const httpRequest = async (requestConfig: HttpRequestConfig): Promise<HttpResponse> => {
133
- let matches = false;
134
- const config = await _dataLayer.getConfigData();
135
-
136
- for (const baseUrl of [ ...((await config?.resourceServerURLs) ?? []), (config as any).baseUrl ]) {
137
- if (baseUrl && requestConfig?.url?.startsWith(baseUrl)) {
138
- matches = true;
139
-
140
- break;
141
- }
142
- }
143
-
144
- if (matches) {
145
- return _httpClient
146
- .request(requestConfig)
147
- .then((response: HttpResponse) => {
148
- return Promise.resolve(response);
149
- })
150
- .catch(async (error: HttpError) => {
151
- if (error?.response?.status === 401 || !error?.response) {
152
- // Try to refresh the token
153
- let refreshTokenResponse;
154
- try {
155
- refreshTokenResponse = await refreshAccessToken();
156
- } catch (refreshError: any) {
157
- if (_isHttpHandlerEnabled) {
158
- if (typeof _httpErrorCallback === "function") {
159
- await _httpErrorCallback({ ...error, code: ACCESS_TOKEN_INVALID });
160
- }
161
- if (typeof _httpFinishCallback === "function") {
162
- _httpFinishCallback();
163
- }
164
- }
165
-
166
- throw new AsgardeoAuthException(
167
- "SPA-MAIN_THREAD_CLIENT-HR-SE01",
168
- refreshError?.name ?? "Refresh token request failed.",
169
- refreshError?.message ??
170
- "An error occurred while trying to refresh the " +
171
- "access token following a 401 response from the server."
172
- );
173
- }
174
-
175
- // Retry the request after refreshing the token
176
- if (refreshTokenResponse) {
177
- try {
178
- const httpResponse = await _httpClient.request(requestConfig);
179
- return Promise.resolve(httpResponse);
180
- } catch (error: any) {
181
- if (_isHttpHandlerEnabled) {
182
- if (typeof _httpErrorCallback === "function") {
183
- await _httpErrorCallback(error);
184
- }
185
- if (typeof _httpFinishCallback === "function") {
186
- _httpFinishCallback();
187
- }
188
- }
189
-
190
- return Promise.reject(error);
191
- }
192
- }
193
- }
194
-
195
- if (_isHttpHandlerEnabled) {
196
- if (typeof _httpErrorCallback === "function") {
197
- await _httpErrorCallback(error);
198
- }
199
- if (typeof _httpFinishCallback === "function") {
200
- _httpFinishCallback();
201
- }
202
- }
203
-
204
- return Promise.reject(error);
205
- });
206
- } else {
207
- throw new AsgardeoAuthException(
208
- "SPA-MAIN_THREAD_CLIENT-HR-IV02",
209
- "Request to the provided endpoint is prohibited.",
210
- "Requests can only be sent to resource servers specified by the `resourceServerURLs`" +
211
- " attribute while initializing the SDK. The specified endpoint in this request " +
212
- "cannot be found among the `resourceServerURLs`"
213
- );
214
- }
116
+ return await _authenticationHelper.httpRequest(
117
+ _httpClient,
118
+ requestConfig,
119
+ _isHttpHandlerEnabled,
120
+ _httpErrorCallback,
121
+ _httpFinishCallback
122
+ );
215
123
  };
216
124
 
217
125
  const httpRequestAll = async (requestConfigs: HttpRequestConfig[]): Promise<HttpResponse[] | undefined> => {
218
- let matches = true;
219
- const config = await _dataLayer.getConfigData();
220
-
221
- for (const requestConfig of requestConfigs) {
222
- let urlMatches = false;
223
-
224
- for (const baseUrl of [
225
- ...((await config)?.resourceServerURLs ?? []),
226
- (config as any).baseUrl
227
- ]) {
228
- if (baseUrl && requestConfig.url?.startsWith(baseUrl)) {
229
- urlMatches = true;
230
-
231
- break;
232
- }
233
- }
234
-
235
- if (!urlMatches) {
236
- matches = false;
237
-
238
- break;
239
- }
240
- }
241
-
242
- const requests: Promise<HttpResponse<any>>[] = [];
243
-
244
- if (matches) {
245
- requestConfigs.forEach((request) => {
246
- requests.push(_httpClient.request(request));
247
- });
248
-
249
- return (
250
- _httpClient?.all &&
251
- _httpClient
252
- .all(requests)
253
- .then((responses: HttpResponse[]) => {
254
- return Promise.resolve(responses);
255
- })
256
- .catch(async (error: HttpError) => {
257
- if (error?.response?.status === 401 || !error?.response) {
258
- let refreshTokenResponse: TokenResponse;
259
- try {
260
- refreshTokenResponse = await _authenticationClient.refreshAccessToken();
261
- } catch (refreshError: any) {
262
- if (_isHttpHandlerEnabled) {
263
- if (typeof _httpErrorCallback === "function") {
264
- await _httpErrorCallback({ ...error, code: ACCESS_TOKEN_INVALID });
265
- }
266
- if (typeof _httpFinishCallback === "function") {
267
- _httpFinishCallback();
268
- }
269
- }
270
-
271
- throw new AsgardeoAuthException(
272
- "SPA-MAIN_THREAD_CLIENT-HRA-SE01",
273
- refreshError?.name ?? "Refresh token request failed.",
274
- refreshError?.message ??
275
- "An error occurred while trying to refresh the " +
276
- "access token following a 401 response from the server."
277
- );
278
- }
279
-
280
- if (refreshTokenResponse) {
281
- return (
282
- _httpClient.all &&
283
- _httpClient
284
- .all(requests)
285
- .then((response) => {
286
- return Promise.resolve(response);
287
- })
288
- .catch(async (error) => {
289
- if (_isHttpHandlerEnabled) {
290
- if (typeof _httpErrorCallback === "function") {
291
- await _httpErrorCallback(error);
292
- }
293
- if (typeof _httpFinishCallback === "function") {
294
- _httpFinishCallback();
295
- }
296
- }
297
-
298
- return Promise.reject(error);
299
- })
300
- );
301
- }
302
- }
303
-
304
- if (_isHttpHandlerEnabled) {
305
- if (typeof _httpErrorCallback === "function") {
306
- await _httpErrorCallback(error);
307
- }
308
- if (typeof _httpFinishCallback === "function") {
309
- _httpFinishCallback();
310
- }
311
- }
312
-
313
- return Promise.reject(error);
314
- })
315
- );
316
- } else {
317
- throw new AsgardeoAuthException(
318
- "SPA-MAIN_THREAD_CLIENT-HRA-IV02",
319
- "Request to the provided endpoint is prohibited.",
320
- "Requests can only be sent to resource servers specified by the `resourceServerURLs`" +
321
- " attribute while initializing the SDK. The specified endpoint in this request " +
322
- "cannot be found among the `resourceServerURLs`"
323
- );
324
- }
126
+ return await _authenticationHelper.httpRequestAll(
127
+ requestConfigs,
128
+ _httpClient,
129
+ _isHttpHandlerEnabled,
130
+ _httpErrorCallback,
131
+ _httpFinishCallback
132
+ );
325
133
  };
326
134
 
327
135
  const getHttpClient = (): HttpClientInstance => {
@@ -329,14 +137,14 @@ export const MainThreadClient = async (
329
137
  };
330
138
 
331
139
  const enableHttpHandler = (): boolean => {
332
- _httpClient?.enableHandler && _httpClient.enableHandler();
140
+ _authenticationHelper.enableHttpHandler(_httpClient);
333
141
  _isHttpHandlerEnabled = true;
334
142
 
335
143
  return true;
336
144
  };
337
145
 
338
146
  const disableHttpHandler = (): boolean => {
339
- _httpClient?.disableHandler && _httpClient.disableHandler();
147
+ _authenticationHelper.disableHttpHandler(_httpClient);
340
148
  _isHttpHandlerEnabled = false;
341
149
 
342
150
  return true;
@@ -346,110 +154,81 @@ export const MainThreadClient = async (
346
154
  const oidcEndpoints: OIDCEndpoints = await _authenticationClient.getOIDCServiceEndpoints();
347
155
  const config = await _dataLayer.getConfigData();
348
156
 
349
- _sessionManagementHelper.initialize(
350
- config.clientID,
351
- oidcEndpoints.checkSessionIframe ?? "",
157
+ _authenticationHelper.initializeSessionManger(
158
+ config,
159
+ oidcEndpoints,
352
160
  async () => (await _authenticationClient.getBasicUserInfo()).sessionState,
353
- config.checkSessionInterval ?? 3,
354
- config.sessionRefreshInterval ?? 300,
355
- config.signInRedirectURL,
356
- async (params?: GetAuthURLConfig): Promise<string> => _authenticationClient.getAuthorizationURL(params)
161
+ async (params?: GetAuthURLConfig): Promise<string> => _authenticationClient.getAuthorizationURL(params),
162
+ _sessionManagementHelper
357
163
  );
358
164
  };
359
165
 
166
+ const shouldStopAuthn = async (): Promise<boolean> => {
167
+ return await _sessionManagementHelper.receivePromptNoneResponse(
168
+ async (sessionState: string | null) => {
169
+ await _dataLayer.setSessionDataParameter(SESSION_STATE, sessionState ?? "");
170
+ return;
171
+ }
172
+ );
173
+ }
174
+
360
175
  const signIn = async (
361
176
  signInConfig?: GetAuthURLConfig,
362
177
  authorizationCode?: string,
363
178
  sessionState?: string,
364
179
  state?: string
365
180
  ): Promise<BasicUserInfo> => {
366
- const config = await _dataLayer.getConfigData();
367
181
 
368
- const shouldStopContinue: boolean = await _sessionManagementHelper.receivePromptNoneResponse(
369
- async (sessionState: string | null) => {
370
- await _dataLayer.setSessionDataParameter(SESSION_STATE, sessionState ?? "");
371
- return;
372
- }
182
+ const basicUserInfo = await _authenticationHelper.handleSignIn(
183
+ shouldStopAuthn,
184
+ checkSession
373
185
  );
374
186
 
375
- if (shouldStopContinue) {
376
- return Promise.resolve({
377
- allowedScopes: "",
378
- displayName: "",
379
- email: "",
380
- sessionState: "",
381
- sub: "",
382
- tenantDomain: "",
383
- username: ""
384
- });
385
- }
386
-
387
- if (await _authenticationClient.isAuthenticated()) {
388
- _spaHelper.clearRefreshTokenTimeout();
389
- _spaHelper.refreshAccessTokenAutomatically();
390
-
391
- // Enable OIDC Sessions Management only if it is set to true in the config.
392
- if (config.enableOIDCSessionManagement) {
393
- checkSession();
394
- }
395
-
396
- return Promise.resolve(await _authenticationClient.getBasicUserInfo());
397
- }
398
-
399
- let resolvedAuthorizationCode: string;
400
- let resolvedSessionState: string;
401
- let resolvedState: string;
402
-
403
- if (config?.responseMode === ResponseMode.formPost && authorizationCode) {
404
- resolvedAuthorizationCode = authorizationCode;
405
- resolvedSessionState = sessionState ?? "";
406
- resolvedState = state ?? "";
187
+ if(basicUserInfo) {
188
+ return basicUserInfo;
407
189
  } else {
408
- resolvedAuthorizationCode = new URL(window.location.href).searchParams.get(AUTHORIZATION_CODE) ?? "";
409
- resolvedSessionState = new URL(window.location.href).searchParams.get(SESSION_STATE) ?? "";
410
- resolvedState = new URL(window.location.href).searchParams.get(STATE) ?? "";
411
-
412
- SPAUtils.removeAuthorizationCode();
413
- }
414
-
415
- if (resolvedAuthorizationCode && resolvedState) {
416
- return requestAccessToken(resolvedAuthorizationCode, resolvedSessionState, resolvedState);
417
- }
418
-
419
- const error = new URL(window.location.href).searchParams.get(ERROR);
420
- const errorDescription = new URL(window.location.href).searchParams.get(ERROR_DESCRIPTION);
421
-
422
- if (error) {
423
- const url = new URL(window.location.href);
424
- url.searchParams.delete(ERROR);
425
- url.searchParams.delete(ERROR_DESCRIPTION);
426
-
427
- history.pushState(null, document.title, url.toString());
428
-
429
- throw new AsgardeoAuthException("SPA-MAIN_THREAD_CLIENT-SI-SE01", error, errorDescription ?? "");
430
- }
431
-
432
- return _authenticationClient.getAuthorizationURL(signInConfig).then(async (url: string) => {
433
- if (config.storage === Storage.BrowserMemory && config.enablePKCE) {
434
- const pkceKey: string = AuthenticationUtils.extractPKCEKeyFromStateParam(resolvedState);
435
-
436
- SPAUtils.setPKCE(pkceKey, (await _authenticationClient.getPKCECode(resolvedState)) as string);
190
+ let resolvedAuthorizationCode: string;
191
+ let resolvedSessionState: string;
192
+ let resolvedState: string;
193
+
194
+ if (config?.responseMode === ResponseMode.formPost && authorizationCode) {
195
+ resolvedAuthorizationCode = authorizationCode;
196
+ resolvedSessionState = sessionState ?? "";
197
+ resolvedState = state ?? "";
198
+ } else {
199
+ resolvedAuthorizationCode = new URL(window.location.href).searchParams.get(AUTHORIZATION_CODE) ?? "";
200
+ resolvedSessionState = new URL(window.location.href).searchParams.get(SESSION_STATE) ?? "";
201
+ resolvedState = new URL(window.location.href).searchParams.get(STATE) ?? "";
202
+
203
+ SPAUtils.removeAuthorizationCode();
437
204
  }
438
205
 
439
- location.href = url;
440
-
441
- await SPAUtils.waitTillPageRedirect();
206
+ if (resolvedAuthorizationCode && resolvedState) {
207
+ return requestAccessToken(resolvedAuthorizationCode, resolvedSessionState, resolvedState);
208
+ }
442
209
 
443
- return Promise.resolve({
444
- allowedScopes: "",
445
- displayName: "",
446
- email: "",
447
- sessionState: "",
448
- sub: "",
449
- tenantDomain: "",
450
- username: ""
210
+ return _authenticationClient.getAuthorizationURL(signInConfig).then(async (url: string) => {
211
+ if (config.storage === Storage.BrowserMemory && config.enablePKCE) {
212
+ const pkceKey: string = AuthenticationUtils.extractPKCEKeyFromStateParam(resolvedState);
213
+
214
+ SPAUtils.setPKCE(pkceKey, (await _authenticationClient.getPKCECode(resolvedState)) as string);
215
+ }
216
+
217
+ location.href = url;
218
+
219
+ await SPAUtils.waitTillPageRedirect();
220
+
221
+ return Promise.resolve({
222
+ allowedScopes: "",
223
+ displayName: "",
224
+ email: "",
225
+ sessionState: "",
226
+ sub: "",
227
+ tenantDomain: "",
228
+ username: ""
229
+ });
451
230
  });
452
- });
231
+ }
453
232
  };
454
233
 
455
234
  const signOut = async (): Promise<boolean> => {
@@ -469,69 +248,25 @@ export const MainThreadClient = async (
469
248
  return true;
470
249
  };
471
250
 
472
- const requestCustomGrant = async (config: SPACustomGrantConfig): Promise<BasicUserInfo | FetchResponse> => {
473
- let useDefaultEndpoint = true;
474
- let matches = false;
475
-
476
- // If the config does not contains a token endpoint, default token endpoint will be used.
477
- if (config?.tokenEndpoint) {
478
- useDefaultEndpoint = false;
479
-
480
- for (const baseUrl of [
481
- ...((await _dataLayer.getConfigData())?.resourceServerURLs ?? []),
482
- (config as any).baseUrl
483
- ]) {
484
- if (baseUrl && config.tokenEndpoint?.startsWith(baseUrl)) {
485
- matches = true;
486
- break;
487
- }
488
- }
489
- }
490
- if (config.shouldReplayAfterRefresh) {
491
- _dataLayer.setTemporaryDataParameter(CUSTOM_GRANT_CONFIG, JSON.stringify(config));
492
- }
493
- if (useDefaultEndpoint || matches) {
494
- return _authenticationClient
495
- .requestCustomGrant(config)
496
- .then(async (response: FetchResponse | TokenResponse) => {
497
- if (config.preventSignOutURLUpdate) {
498
- _getSignOutURLFromSessionStorage = true;
499
- }
500
-
501
- if (config.returnsSession) {
502
- _spaHelper.refreshAccessTokenAutomatically();
503
-
504
- return _authenticationClient.getBasicUserInfo();
505
- } else {
506
- return response as FetchResponse;
507
- }
508
- })
509
- .catch((error) => {
510
- return Promise.reject(error);
511
- });
512
- } else {
513
- return Promise.reject(
514
- new AsgardeoAuthException(
515
- "SPA-MAIN_THREAD_CLIENT-RCG-IV01",
516
- "Request to the provided endpoint is prohibited.",
517
- "Requests can only be sent to resource servers specified by the `resourceServerURLs`" +
518
- " attribute while initializing the SDK. The specified token endpoint in this request " +
519
- "cannot be found among the `resourceServerURLs`"
520
- )
521
- );
251
+ const enableRetrievingSignOutURLFromSession = (config: SPACustomGrantConfig) => {
252
+ if (config.preventSignOutURLUpdate) {
253
+ _getSignOutURLFromSessionStorage = true;
522
254
  }
255
+ }
256
+
257
+ const requestCustomGrant = async (config: SPACustomGrantConfig):
258
+ Promise<BasicUserInfo | FetchResponse> => {
259
+ return await _authenticationHelper.requestCustomGrant(
260
+ config,
261
+ enableRetrievingSignOutURLFromSession
262
+ );
523
263
  };
524
264
 
525
265
  const refreshAccessToken = async (): Promise<BasicUserInfo> => {
526
266
  try {
527
- await _authenticationClient.refreshAccessToken();
528
- const customGrantConfig = await getCustomGrantConfigData();
529
- if (customGrantConfig) {
530
- await requestCustomGrant(customGrantConfig);
531
- }
532
- _spaHelper.refreshAccessTokenAutomatically();
533
-
534
- return _authenticationClient.getBasicUserInfo();
267
+ return await _authenticationHelper.refreshAccessToken(
268
+ enableRetrievingSignOutURLFromSession
269
+ );
535
270
  } catch (error) {
536
271
  return Promise.reject(error);
537
272
  }
@@ -554,40 +289,38 @@ export const MainThreadClient = async (
554
289
  resolvedSessionState: string,
555
290
  resolvedState: string
556
291
  ): Promise<BasicUserInfo> => {
292
+ return await _authenticationHelper.requestAccessToken(
293
+ resolvedAuthorizationCode,
294
+ resolvedSessionState,
295
+ checkSession,
296
+ undefined,
297
+ resolvedState
298
+ );
299
+ };
300
+
301
+ const constructSilentSignInUrl = async (): Promise<string> => {
557
302
  const config = await _dataLayer.getConfigData();
303
+ const urlString: string = await _authenticationClient.getAuthorizationURL({
304
+ prompt: "none",
305
+ state: SILENT_SIGN_IN_STATE
306
+ });
307
+
308
+ // Replace form_post with query
309
+ const urlObject = new URL(urlString);
310
+ urlObject.searchParams.set("response_mode", "query");
311
+ const url: string = urlObject.toString();
558
312
 
559
313
  if (config.storage === Storage.BrowserMemory && config.enablePKCE) {
560
- const pkce = SPAUtils.getPKCE(AuthenticationUtils.extractPKCEKeyFromStateParam(resolvedState));
314
+ const state = urlObject.searchParams.get(STATE);
561
315
 
562
- await _authenticationClient.setPKCECode(
563
- AuthenticationUtils.extractPKCEKeyFromStateParam(resolvedState),
564
- pkce
316
+ SPAUtils.setPKCE(
317
+ AuthenticationUtils.extractPKCEKeyFromStateParam(state ?? ""),
318
+ (await _authenticationClient.getPKCECode(state ?? "")) as string
565
319
  );
566
320
  }
567
321
 
568
- return _authenticationClient
569
- .requestAccessToken(resolvedAuthorizationCode, resolvedSessionState, resolvedState)
570
- .then(async () => {
571
- // Disable this temporarily
572
- /* if (config.storage === Storage.BrowserMemory) {
573
- SPAUtils.setSignOutURL(await _authenticationClient.getSignOutURL());
574
- } */
575
- SPAUtils.setSignOutURL(await _authenticationClient.getSignOutURL());
576
-
577
- _spaHelper.clearRefreshTokenTimeout();
578
- _spaHelper.refreshAccessTokenAutomatically();
579
-
580
- // Enable OIDC Sessions Management only if it is set to true in the config.
581
- if (config.enableOIDCSessionManagement) {
582
- checkSession();
583
- }
584
-
585
- return _authenticationClient.getBasicUserInfo();
586
- })
587
- .catch((error) => {
588
- return Promise.reject(error);
589
- });
590
- };
322
+ return url;
323
+ }
591
324
 
592
325
  /**
593
326
  * This method checks if there is an active user session in the server by sending a prompt none request.
@@ -597,109 +330,36 @@ export const MainThreadClient = async (
597
330
  * if the user is signed in or with `false` if there is no active user session in the server.
598
331
  */
599
332
  const trySignInSilently = async (): Promise<BasicUserInfo | boolean> => {
600
- const config = await _dataLayer.getConfigData();
601
-
602
- if (SPAUtils.isInitializedSilentSignIn()) {
603
- await _sessionManagementHelper.receivePromptNoneResponse();
604
-
605
- return Promise.resolve({
606
- allowedScopes: "",
607
- displayName: "",
608
- email: "",
609
- sessionState: "",
610
- sub: "",
611
- tenantDomain: "",
612
- username: ""
613
- });
614
- }
615
-
616
- const rpIFrame = document.getElementById(RP_IFRAME) as HTMLIFrameElement;
617
-
618
- const promptNoneIFrame: HTMLIFrameElement = rpIFrame?.contentDocument?.getElementById(
619
- PROMPT_NONE_IFRAME
620
- ) as HTMLIFrameElement;
621
-
622
- try {
623
- const urlString: string = await _authenticationClient.getAuthorizationURL({
624
- prompt: "none",
625
- state: SILENT_SIGN_IN_STATE
626
- });
627
-
628
- // Replace form_post with query
629
- const urlObject = new URL(urlString);
630
- urlObject.searchParams.set("response_mode", "query");
631
- const url: string = urlObject.toString();
632
-
633
- if (config.storage === Storage.BrowserMemory && config.enablePKCE) {
634
- const state = urlObject.searchParams.get(STATE);
635
-
636
- SPAUtils.setPKCE(
637
- AuthenticationUtils.extractPKCEKeyFromStateParam(state ?? ""),
638
- (await _authenticationClient.getPKCECode(state ?? "")) as string
639
- );
640
- }
641
333
 
642
- promptNoneIFrame.src = url;
643
- } catch (error) {
644
- return Promise.reject(error);
645
- }
646
-
647
- return new Promise((resolve, reject) => {
648
- const timer = setTimeout(() => {
649
- resolve(false);
650
- }, 10000);
651
-
652
- const listenToPromptNoneIFrame = async (e: MessageEvent) => {
653
- const data: Message<AuthorizationInfo | null> = e.data;
654
-
655
- if (data?.type == CHECK_SESSION_SIGNED_OUT) {
656
- window.removeEventListener("message", listenToPromptNoneIFrame);
657
- clearTimeout(timer);
658
- resolve(false);
659
- }
660
-
661
- if (data?.type == CHECK_SESSION_SIGNED_IN && data?.data?.code) {
662
- requestAccessToken(data.data.code, data?.data?.sessionState, data?.data?.state)
663
- .then((response: BasicUserInfo) => {
664
- window.removeEventListener("message", listenToPromptNoneIFrame);
665
- resolve(response);
666
- })
667
- .catch((error) => {
668
- window.removeEventListener("message", listenToPromptNoneIFrame);
669
- reject(error);
670
- })
671
- .finally(() => {
672
- clearTimeout(timer);
673
- });
674
- }
675
- };
676
-
677
- window.addEventListener("message", listenToPromptNoneIFrame);
678
- });
334
+ return await _authenticationHelper.trySignInSilently(
335
+ constructSilentSignInUrl,
336
+ requestAccessToken,
337
+ _sessionManagementHelper
338
+ );
679
339
  };
680
340
 
681
341
  const getBasicUserInfo = async (): Promise<BasicUserInfo> => {
682
- return _authenticationClient.getBasicUserInfo();
342
+ return _authenticationHelper.getBasicUserInfo();
683
343
  };
684
344
 
685
345
  const getDecodedIDToken = async (): Promise<DecodedIDTokenPayload> => {
686
- return _authenticationClient.getDecodedIDToken();
346
+ return _authenticationHelper.getDecodedIDToken();
687
347
  };
688
348
 
689
349
  const getIDToken = async (): Promise<string> => {
690
- return _authenticationClient.getIDToken();
350
+ return _authenticationHelper.getIDToken();
691
351
  };
692
352
 
693
353
  const getOIDCServiceEndpoints = async (): Promise<OIDCEndpoints> => {
694
- return _authenticationClient.getOIDCServiceEndpoints();
354
+ return _authenticationHelper.getOIDCServiceEndpoints();
695
355
  };
696
356
 
697
357
  const getAccessToken = async (): Promise<string> => {
698
- return _authenticationClient.getAccessToken();
358
+ return _authenticationHelper.getAccessToken();
699
359
  };
700
360
 
701
361
  const isAuthenticated = async (): Promise<boolean> => {
702
- return _authenticationClient.isAuthenticated();
362
+ return _authenticationHelper.isAuthenticated();
703
363
  };
704
364
 
705
365
  const updateConfig = async (newConfig: Partial<AuthClientConfig<MainThreadClientConfig>>): Promise<void> => {
@@ -724,15 +384,6 @@ export const MainThreadClient = async (
724
384
  }
725
385
  };
726
386
 
727
- const getCustomGrantConfigData = async (): Promise<AuthClientConfig<CustomGrantConfig> | null> => {
728
- const configString = await _dataLayer.getTemporaryDataParameter(CUSTOM_GRANT_CONFIG);
729
- if (configString) {
730
- return JSON.parse(configString as string);
731
- } else {
732
- return null;
733
- }
734
- };
735
-
736
387
  return {
737
388
  disableHttpHandler,
738
389
  enableHttpHandler,