@asgardeo/auth-spa 0.2.19 → 0.2.22

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 (116) hide show
  1. package/.eslintrc.js +1 -2
  2. package/README.md +53 -24
  3. package/babel.config.js +1 -2
  4. package/dist/asgardeo-spa.production.esm.js +105 -44
  5. package/dist/asgardeo-spa.production.esm.js.map +1 -1
  6. package/dist/asgardeo-spa.production.js +106 -45
  7. package/dist/asgardeo-spa.production.js.map +1 -1
  8. package/dist/asgardeo-spa.production.min.js +1 -1
  9. package/dist/asgardeo-spa.production.min.js.map +1 -1
  10. package/dist/polyfilled/asgardeo-spa.production.esm.js +103 -42
  11. package/dist/polyfilled/asgardeo-spa.production.esm.js.map +1 -1
  12. package/dist/polyfilled/asgardeo-spa.production.js +103 -42
  13. package/dist/polyfilled/asgardeo-spa.production.js.map +1 -1
  14. package/dist/polyfilled/asgardeo-spa.production.min.js +1 -1
  15. package/dist/polyfilled/asgardeo-spa.production.min.js.map +1 -1
  16. package/dist/src/client.d.ts +10 -6
  17. package/dist/src/client.d.ts.map +1 -1
  18. package/dist/src/client.js +26 -14
  19. package/dist/src/client.js.map +1 -1
  20. package/dist/src/clients/main-thread-client.d.ts.map +1 -1
  21. package/dist/src/clients/main-thread-client.js +61 -48
  22. package/dist/src/clients/main-thread-client.js.map +1 -1
  23. package/dist/src/clients/web-worker-client.d.ts +1 -1
  24. package/dist/src/clients/web-worker-client.d.ts.map +1 -1
  25. package/dist/src/clients/web-worker-client.js +51 -32
  26. package/dist/src/clients/web-worker-client.js.map +1 -1
  27. package/dist/src/{exception/exception.d.ts → constants/errors.d.ts} +3 -11
  28. package/dist/src/constants/errors.d.ts.map +1 -0
  29. package/dist/src/{exception/exception.js → constants/errors.js} +3 -14
  30. package/dist/src/constants/errors.js.map +1 -0
  31. package/dist/src/constants/hooks.d.ts +2 -1
  32. package/dist/src/constants/hooks.d.ts.map +1 -1
  33. package/dist/src/constants/hooks.js +1 -0
  34. package/dist/src/constants/hooks.js.map +1 -1
  35. package/dist/src/constants/index.d.ts +1 -0
  36. package/dist/src/constants/index.d.ts.map +1 -1
  37. package/dist/src/constants/index.js +1 -0
  38. package/dist/src/constants/index.js.map +1 -1
  39. package/dist/src/constants/parameters.d.ts +1 -0
  40. package/dist/src/constants/parameters.d.ts.map +1 -1
  41. package/dist/src/constants/parameters.js +1 -0
  42. package/dist/src/constants/parameters.js.map +1 -1
  43. package/dist/src/helpers/session-management-helper.d.ts +1 -1
  44. package/dist/src/helpers/session-management-helper.d.ts.map +1 -1
  45. package/dist/src/helpers/session-management-helper.js +33 -43
  46. package/dist/src/helpers/session-management-helper.js.map +1 -1
  47. package/dist/src/index-polyfill.d.ts +0 -1
  48. package/dist/src/index-polyfill.d.ts.map +1 -1
  49. package/dist/src/index-polyfill.js +0 -1
  50. package/dist/src/index-polyfill.js.map +1 -1
  51. package/dist/src/models/client.d.ts +4 -4
  52. package/dist/src/models/client.d.ts.map +1 -1
  53. package/dist/src/models/http-client.d.ts +1 -1
  54. package/dist/src/models/http-client.d.ts.map +1 -1
  55. package/dist/src/models/index.d.ts +1 -0
  56. package/dist/src/models/index.d.ts.map +1 -1
  57. package/dist/src/models/index.js +1 -0
  58. package/dist/src/models/index.js.map +1 -1
  59. package/dist/src/models/message.d.ts +1 -0
  60. package/dist/src/models/message.d.ts.map +1 -1
  61. package/dist/src/models/session-management-helper.d.ts +2 -1
  62. package/dist/src/models/session-management-helper.d.ts.map +1 -1
  63. package/dist/src/{exception/index.js → models/sign-out-error.d.ts} +6 -3
  64. package/dist/src/models/sign-out-error.d.ts.map +1 -0
  65. package/{src/exception/index.ts → dist/src/models/sign-out-error.js} +3 -3
  66. package/dist/src/models/sign-out-error.js.map +1 -0
  67. package/dist/src/models/web-worker.d.ts +3 -3
  68. package/dist/src/models/web-worker.d.ts.map +1 -1
  69. package/dist/src/models/web-worker.js.map +1 -1
  70. package/dist/src/public-api.d.ts +1 -1
  71. package/dist/src/public-api.d.ts.map +1 -1
  72. package/dist/src/public-api.js +1 -1
  73. package/dist/src/public-api.js.map +1 -1
  74. package/dist/src/utils/crypto-utils.d.ts +33 -0
  75. package/dist/src/utils/crypto-utils.d.ts.map +1 -0
  76. package/dist/src/utils/crypto-utils.js +55 -0
  77. package/dist/src/utils/crypto-utils.js.map +1 -0
  78. package/dist/src/utils/spa-utils.d.ts +5 -3
  79. package/dist/src/utils/spa-utils.d.ts.map +1 -1
  80. package/dist/src/utils/spa-utils.js +26 -10
  81. package/dist/src/utils/spa-utils.js.map +1 -1
  82. package/dist/src/worker/client.worker.d.ts.map +1 -1
  83. package/dist/src/worker/client.worker.js +5 -5
  84. package/dist/src/worker/client.worker.js.map +1 -1
  85. package/dist/src/worker/worker-core.d.ts.map +1 -1
  86. package/dist/src/worker/worker-core.js +57 -49
  87. package/dist/src/worker/worker-core.js.map +1 -1
  88. package/dist/tsconfig.tsbuildinfo +1 -1
  89. package/package.json +31 -30
  90. package/rollup.config.js +3 -5
  91. package/src/client.ts +45 -50
  92. package/src/clients/main-thread-client.ts +96 -89
  93. package/src/clients/web-worker-client.ts +73 -48
  94. package/src/constants/errors.ts +19 -0
  95. package/src/constants/hooks.ts +2 -1
  96. package/src/constants/index.ts +1 -0
  97. package/src/constants/parameters.ts +1 -0
  98. package/src/helpers/session-management-helper.ts +31 -40
  99. package/src/index-polyfill.ts +0 -1
  100. package/src/models/client.ts +5 -5
  101. package/src/models/http-client.ts +3 -2
  102. package/src/models/index.ts +1 -0
  103. package/src/models/message.ts +1 -0
  104. package/src/models/session-management-helper.ts +3 -2
  105. package/{dist/src/exception/index.d.ts → src/models/sign-out-error.ts} +6 -3
  106. package/src/models/web-worker.ts +8 -2
  107. package/src/public-api.ts +2 -1
  108. package/src/utils/crypto-utils.ts +74 -0
  109. package/src/utils/spa-utils.ts +33 -10
  110. package/src/worker/client.worker.ts +6 -11
  111. package/src/worker/worker-core.ts +98 -101
  112. package/dist/src/exception/exception.d.ts.map +0 -1
  113. package/dist/src/exception/exception.js.map +0 -1
  114. package/dist/src/exception/index.d.ts.map +0 -1
  115. package/dist/src/exception/index.js.map +0 -1
  116. package/src/exception/exception.ts +0 -44
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
3
+ *
4
+ * WSO2 Inc. licenses this file to you under the Apache License,
5
+ * Version 2.0 (the "License"); you may not use this file except
6
+ * in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing,
12
+ * software distributed under the License is distributed on an
13
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ * KIND, either express or implied. See the License for the
15
+ * specific language governing permissions and limitations
16
+ * under the License.
17
+ */
18
+
19
+ import { Buffer } from "buffer";
20
+ import { CryptoUtils, JWKInterface } from "@asgardeo/auth-js";
21
+ import base64url from "base64url";
22
+ import sha256 from "fast-sha256";
23
+ import { createLocalJWKSet, jwtVerify } from "jose";
24
+ import randombytes from "randombytes";
25
+
26
+ export class SPACryptoUtils implements CryptoUtils<Buffer | string>
27
+ {
28
+ /**
29
+ * Get URL encoded string.
30
+ *
31
+ * @returns {string} base 64 url encoded value.
32
+ */
33
+ public base64URLEncode(value: Buffer | string): string {
34
+ return base64url.encode(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
35
+ }
36
+
37
+ public base64URLDecode(value: string): string {
38
+ return base64url.decode(value).toString();
39
+ }
40
+
41
+ public hashSha256(data: string): string | Buffer {
42
+ return Buffer.from(sha256(new TextEncoder().encode(data)));
43
+ }
44
+
45
+ public generateRandomBytes(length: number): string | Buffer {
46
+ return randombytes(length);
47
+ }
48
+
49
+ public verifyJwt(
50
+ idToken: string,
51
+ jwk: Partial<JWKInterface>,
52
+ algorithms: string[],
53
+ clientID: string,
54
+ issuer: string,
55
+ subject: string,
56
+ clockTolerance?: number
57
+ ): Promise<boolean> {
58
+ return jwtVerify(
59
+ idToken,
60
+ createLocalJWKSet({
61
+ keys: [jwk]
62
+ }),
63
+ {
64
+ algorithms: algorithms,
65
+ audience: clientID,
66
+ clockTolerance: clockTolerance,
67
+ issuer: issuer,
68
+ subject: subject
69
+ }
70
+ ).then(() => {
71
+ return Promise.resolve(true);
72
+ });
73
+ }
74
+ }
@@ -16,12 +16,15 @@
16
16
  * under the License.
17
17
  */
18
18
 
19
- import { AsgardeoAuthClient, PKCE_CODE_VERIFIER, SIGN_OUT_URL } from "@asgardeo/auth-js";
19
+ import { AsgardeoAuthClient, SIGN_OUT_SUCCESS_PARAM, SIGN_OUT_URL } from "@asgardeo/auth-js";
20
+ import { SignOutError } from "..";
20
21
  import {
21
22
  ERROR,
23
+ ERROR_DESCRIPTION,
22
24
  INITIALIZED_SILENT_SIGN_IN,
23
25
  PROMPT_NONE_REQUEST_SENT,
24
- SILENT_SIGN_IN_STATE
26
+ SILENT_SIGN_IN_STATE,
27
+ STATE_QUERY
25
28
  } from "../constants";
26
29
 
27
30
  export class SPAUtils {
@@ -34,12 +37,12 @@ export class SPAUtils {
34
37
  history.pushState({}, document.title, url.replace(/\?code=.*$/, ""));
35
38
  }
36
39
 
37
- public static getPKCE(): string {
38
- return sessionStorage.getItem(PKCE_CODE_VERIFIER) ?? "";
40
+ public static getPKCE(pkceKey: string): string {
41
+ return sessionStorage.getItem(pkceKey) ?? "";
39
42
  }
40
43
 
41
- public static setPKCE(pkce: string): void {
42
- sessionStorage.setItem(PKCE_CODE_VERIFIER, pkce);
44
+ public static setPKCE(pkceKey: string, pkce: string): void {
45
+ sessionStorage.setItem(pkceKey, pkce);
43
46
  }
44
47
 
45
48
  public static setSignOutURL(url: string): void {
@@ -50,8 +53,8 @@ export class SPAUtils {
50
53
  return sessionStorage.getItem(SIGN_OUT_URL) ?? "";
51
54
  }
52
55
 
53
- public static removePKCE(): void {
54
- sessionStorage.removeItem(PKCE_CODE_VERIFIER);
56
+ public static removePKCE(pkceKey: string): void {
57
+ sessionStorage.removeItem(pkceKey);
55
58
  }
56
59
 
57
60
  /**
@@ -121,6 +124,23 @@ export class SPAUtils {
121
124
  return false;
122
125
  }
123
126
 
127
+ public static didSignOutFail(): boolean | SignOutError {
128
+ if (AsgardeoAuthClient.didSignOutFail(window.location.href)) {
129
+ const url: URL = new URL(window.location.href);
130
+ const error: string | null = url.searchParams.get(ERROR);
131
+ const description: string | null = url.searchParams.get(ERROR_DESCRIPTION);
132
+ const newUrl = window.location.href.split("?")[0];
133
+ history.pushState({}, document.title, newUrl);
134
+
135
+ return {
136
+ description: description ?? "",
137
+ error: error ?? ""
138
+ };
139
+ }
140
+
141
+ return false;
142
+ }
143
+
124
144
  /**
125
145
  * Checks if the URL the user agent is redirected to after an authorization request has the state parameter.
126
146
  *
@@ -129,7 +149,7 @@ export class SPAUtils {
129
149
  public static isSilentStatePresentInURL(): boolean {
130
150
  const state = new URL(window.location.href).searchParams.get("state");
131
151
 
132
- return state === SILENT_SIGN_IN_STATE;
152
+ return state?.includes(SILENT_SIGN_IN_STATE) ?? false;
133
153
  }
134
154
 
135
155
  /**
@@ -153,7 +173,10 @@ export class SPAUtils {
153
173
  * @returns {boolean} - True if the URL contains an error.
154
174
  */
155
175
  public static hasErrorInURL(url: string = window.location.href): boolean {
156
- return !!new URL(url).searchParams.get(ERROR);
176
+ const urlObject: URL = new URL(url);
177
+ return (
178
+ !!urlObject.searchParams.get(ERROR) && urlObject.searchParams.get(STATE_QUERY) !== SIGN_OUT_SUCCESS_PARAM
179
+ );
157
180
  }
158
181
 
159
182
  /**
@@ -16,7 +16,7 @@
16
16
  * under the License.
17
17
  */
18
18
 
19
- import { AuthClientConfig, BasicUserInfo } from "@asgardeo/auth-js";
19
+ import { AsgardeoAuthException, AuthClientConfig, BasicUserInfo } from "@asgardeo/auth-js";
20
20
  import { WebWorkerCore } from "./worker-core";
21
21
  import {
22
22
  DISABLE_HTTP_HANDLER,
@@ -44,7 +44,6 @@ import {
44
44
  START_AUTO_REFRESH_TOKEN,
45
45
  UPDATE_CONFIG
46
46
  } from "../constants";
47
- import { AsgardeoSPAException } from "../exception";
48
47
  import {
49
48
  AuthorizationResponse,
50
49
  HttpResponse,
@@ -63,10 +62,8 @@ ctx.onmessage = async ({ data, ports }) => {
63
62
  if (data.type !== INIT && !webWorker) {
64
63
  port.postMessage(
65
64
  MessageUtils.generateFailureMessage(
66
- new AsgardeoSPAException(
67
- "CLIENT_WORKER-ONMSG-NF01",
68
- "client.worker",
69
- data.type,
65
+ new AsgardeoAuthException(
66
+ "SPA-CLIENT_WORKER-ONMSG-NF01",
70
67
  "The web worker has not been initialized yet.",
71
68
  "The initialize method needs to be called before the specified operation can be carried out."
72
69
  )
@@ -103,7 +100,7 @@ ctx.onmessage = async ({ data, ports }) => {
103
100
  break;
104
101
  case REQUEST_ACCESS_TOKEN:
105
102
  webWorker
106
- .requestAccessToken(data?.data?.code, data?.data?.sessionState, data?.data?.pkce)
103
+ .requestAccessToken(data?.data?.code, data?.data?.sessionState, data?.data?.pkce, data?.data?.state)
107
104
  .then((response: BasicUserInfo) => {
108
105
  port.postMessage(MessageUtils.generateSuccessMessage(response));
109
106
  })
@@ -264,10 +261,8 @@ ctx.onmessage = async ({ data, ports }) => {
264
261
  default:
265
262
  port?.postMessage(
266
263
  MessageUtils.generateFailureMessage(
267
- new AsgardeoSPAException(
268
- "CLIENT_WORKER-ONMSG-IV02",
269
- "client.worker",
270
- "onmessage",
264
+ new AsgardeoAuthException(
265
+ "SPA-CLIENT_WORKER-ONMSG-IV02",
271
266
  "The message type is invalid.",
272
267
  `The message type provided, ${data.type}, is invalid.`
273
268
  )
@@ -18,18 +18,20 @@
18
18
 
19
19
  import {
20
20
  AsgardeoAuthClient,
21
+ AsgardeoAuthException,
21
22
  AuthClientConfig,
22
23
  AuthorizationURLParams,
23
24
  BasicUserInfo,
24
25
  CustomGrantConfig,
25
26
  DecodedIDTokenPayload,
27
+ FetchResponse,
26
28
  OIDCEndpoints,
27
29
  SESSION_STATE,
30
+ STATE,
28
31
  Store,
29
32
  TokenResponse
30
33
  } from "@asgardeo/auth-js";
31
34
  import { CUSTOM_GRANT_CONFIG } from "../constants";
32
- import { AsgardeoSPAException } from "../exception";
33
35
  import { SPAHelper } from "../helpers";
34
36
  import { HttpClient, HttpClientInstance } from "../http-client";
35
37
  import {
@@ -41,21 +43,19 @@ import {
41
43
  WebWorkerCoreInterface
42
44
  } from "../models";
43
45
  import { MemoryStore } from "../stores";
46
+ import { SPACryptoUtils } from "../utils/crypto-utils";
44
47
 
45
48
  export const WebWorkerCore = async (
46
49
  config: AuthClientConfig<WebWorkerClientConfig>
47
50
  ): Promise<WebWorkerCoreInterface> => {
48
51
  const _store: Store = new MemoryStore();
49
- const _authenticationClient = new AsgardeoAuthClient<WebWorkerClientConfig>(_store);
52
+ const _cryptoUtils: SPACryptoUtils = new SPACryptoUtils();
53
+ const _authenticationClient = new AsgardeoAuthClient<WebWorkerClientConfig>(_store, _cryptoUtils);
50
54
  await _authenticationClient.initialize(config);
51
55
 
52
56
  const _spaHelper = new SPAHelper<WebWorkerClientConfig>(_authenticationClient);
53
57
  const _dataLayer = _authenticationClient.getDataLayer();
54
58
 
55
- let _onHttpRequestStart: () => void;
56
- let _onHttpRequestSuccess: (response: HttpResponse) => void;
57
- let _onHttpRequestFinish: () => void;
58
- let _onHttpRequestError: (error: HttpError) => void;
59
59
  const _httpClient: HttpClientInstance = HttpClient.getInstance();
60
60
 
61
61
  const attachToken = async (request: HttpRequestConfig): Promise<void> => {
@@ -63,7 +63,7 @@ export const WebWorkerCore = async (
63
63
  if (requestConfig.attachToken) {
64
64
  request.headers = {
65
65
  ...request.headers,
66
- Authorization: `Bearer ${await _authenticationClient.getAccessToken()}`
66
+ Authorization: `Bearer ${ await _authenticationClient.getAccessToken() }`
67
67
  };
68
68
  }
69
69
  };
@@ -84,13 +84,13 @@ export const WebWorkerCore = async (
84
84
 
85
85
  const httpRequest = async (requestConfig: HttpRequestConfig): Promise<HttpResponse> => {
86
86
  let matches = false;
87
- const config = await _dataLayer.getConfigData();
87
+ const serverOrigin = (config as any).baseUrl || (config as any).serverOrigin;
88
88
 
89
89
  for (const baseUrl of [
90
90
  ...((await _dataLayer.getConfigData())?.resourceServerURLs ?? []),
91
- config?.serverOrigin
91
+ serverOrigin
92
92
  ]) {
93
- if (requestConfig?.url?.startsWith(baseUrl)) {
93
+ if (baseUrl && requestConfig?.url?.startsWith(baseUrl)) {
94
94
  matches = true;
95
95
 
96
96
  break;
@@ -103,45 +103,43 @@ export const WebWorkerCore = async (
103
103
  .then((response: HttpResponse) => {
104
104
  return Promise.resolve(response);
105
105
  })
106
- .catch((error: HttpError) => {
106
+ .catch(async (error: HttpError) => {
107
107
  if (error?.response?.status === 401 || !error?.response) {
108
- return refreshAccessToken()
109
- .then(() => {
110
- return _httpClient
111
- .request(requestConfig)
112
- .then((response) => {
113
- return Promise.resolve(response);
114
- })
115
- .catch((error) => {
116
- return Promise.reject(error);
117
- });
118
- })
119
- .catch((refreshError) => {
120
- return Promise.reject(
121
- new AsgardeoSPAException(
122
- "WORKER_CORE-HR-ES01",
123
- "worker-core",
124
- "httpRequest",
125
- "",
126
- "",
127
- refreshError
128
- )
129
- );
130
- });
108
+ let refreshAccessTokenResponse: BasicUserInfo;
109
+ try {
110
+ refreshAccessTokenResponse = await refreshAccessToken();
111
+ } catch (refreshError: any) {
112
+ throw new AsgardeoAuthException(
113
+ "SPA-WORKER_CORE-HR-SE01",
114
+ refreshError?.name ?? "Refresh token request failed.",
115
+ refreshError?.message ??
116
+ "An error occurred while trying to refresh the " +
117
+ "access token following a 401 response from the server."
118
+ );
119
+ }
120
+
121
+ if (refreshAccessTokenResponse) {
122
+ return _httpClient
123
+ .request(requestConfig)
124
+ .then((response) => {
125
+ return Promise.resolve(response);
126
+ })
127
+ .catch((error) => {
128
+ return Promise.reject(error);
129
+ });
130
+ }
131
131
  }
132
132
 
133
133
  return Promise.reject(error);
134
134
  });
135
135
  } else {
136
136
  return Promise.reject(
137
- new AsgardeoSPAException(
138
- "WORKER_CORE-HR-IV02",
139
- "worker-core",
140
- "httpRequest",
137
+ new AsgardeoAuthException(
138
+ "SPA-WORKER_CORE-HR-IV02",
141
139
  "Request to the provided endpoint is prohibited.",
142
140
  "Requests can only be sent to resource servers specified by the `resourceServerURLs`" +
143
- " attribute while initializing the SDK. The specified endpoint in this request " +
144
- "cannot be found among the `resourceServerURLs`"
141
+ " attribute while initializing the SDK. The specified endpoint in this request " +
142
+ "cannot be found among the `resourceServerURLs`"
145
143
  )
146
144
  );
147
145
  }
@@ -149,16 +147,17 @@ export const WebWorkerCore = async (
149
147
 
150
148
  const httpRequestAll = async (requestConfigs: HttpRequestConfig[]): Promise<HttpResponse[] | undefined> => {
151
149
  let matches = true;
152
- const config = await _dataLayer.getConfigData();
150
+
151
+ const serverOrigin = (config as any).baseUrl || (config as any).serverOrigin;
153
152
 
154
153
  for (const requestConfig of requestConfigs) {
155
154
  let urlMatches = false;
156
155
 
157
156
  for (const baseUrl of [
158
157
  ...((await _dataLayer.getConfigData())?.resourceServerURLs ?? []),
159
- config?.serverOrigin
158
+ serverOrigin
160
159
  ]) {
161
- if (requestConfig.url?.startsWith(baseUrl)) {
160
+ if (baseUrl && requestConfig.url?.startsWith(baseUrl)) {
162
161
  urlMatches = true;
163
162
 
164
163
  break;
@@ -186,35 +185,34 @@ export const WebWorkerCore = async (
186
185
  .then((responses: HttpResponse[]) => {
187
186
  return Promise.resolve(responses);
188
187
  })
189
- .catch((error: HttpError) => {
188
+ .catch(async (error: HttpError) => {
190
189
  if (error?.response?.status === 401) {
191
- return _authenticationClient
192
- .refreshAccessToken()
193
- .then(() => {
194
- return (
195
- _httpClient.all &&
196
- _httpClient
197
- .all(requests)
198
- .then((response) => {
199
- return Promise.resolve(response);
200
- })
201
- .catch((error) => {
202
- return Promise.reject(error);
203
- })
204
- );
205
- })
206
- .catch((refreshError) => {
207
- return Promise.reject(
208
- new AsgardeoSPAException(
209
- "WORKER_CORE-HRA-ES01",
210
- "worker-core",
211
- "httpRequestAll",
212
- "",
213
- "",
214
- refreshError
215
- )
216
- );
217
- });
190
+ let refreshAccessTokenResponse: BasicUserInfo;
191
+ try {
192
+ refreshAccessTokenResponse = await refreshAccessToken();
193
+ } catch (refreshError: any) {
194
+ throw new AsgardeoAuthException(
195
+ "SPA-WORKER_CORE-HRA-SE01",
196
+ refreshError?.name ?? "Refresh token request failed.",
197
+ refreshError?.message ??
198
+ "An error occurred while trying to refresh the " +
199
+ "access token following a 401 response from the server."
200
+ );
201
+ }
202
+
203
+ if (refreshAccessTokenResponse) {
204
+ return (
205
+ _httpClient.all &&
206
+ _httpClient
207
+ .all(requests)
208
+ .then((response) => {
209
+ return Promise.resolve(response);
210
+ })
211
+ .catch((error) => {
212
+ return Promise.reject(error);
213
+ })
214
+ );
215
+ }
218
216
  }
219
217
 
220
218
  return Promise.reject(error);
@@ -222,14 +220,12 @@ export const WebWorkerCore = async (
222
220
  );
223
221
  } else {
224
222
  return Promise.reject(
225
- new AsgardeoSPAException(
226
- "WORKER_CORE-HRA-IV02",
227
- "worker-core",
228
- "httpRequest",
223
+ new AsgardeoAuthException(
224
+ "SPA-WORKER_CORE-HRA-IV02",
229
225
  "Request to the provided endpoint is prohibited.",
230
226
  "Requests can only be sent to resource servers specified by the `resourceServerURLs`" +
231
- " attribute while initializing the SDK. The specified endpoint in this request " +
232
- "cannot be found among the `resourceServerURLs`"
227
+ " attribute while initializing the SDK. The specified endpoint in this request " +
228
+ "cannot be found among the `resourceServerURLs`"
233
229
  )
234
230
  );
235
231
  }
@@ -247,7 +243,11 @@ export const WebWorkerCore = async (
247
243
  return _authenticationClient
248
244
  .getAuthorizationURL(params)
249
245
  .then(async (url: string) => {
250
- return { authorizationURL: url, pkce: (await _authenticationClient.getPKCECode()) as string };
246
+ const urlObject: URL = new URL(url);
247
+ const state: string = urlObject.searchParams.get(STATE) ?? "";
248
+ const pkce: string = await _authenticationClient.getPKCECode(state);
249
+
250
+ return { authorizationURL: url, pkce: pkce };
251
251
  })
252
252
  .catch((error) => Promise.reject(error));
253
253
  };
@@ -262,17 +262,18 @@ export const WebWorkerCore = async (
262
262
  const requestAccessToken = async (
263
263
  authorizationCode?: string,
264
264
  sessionState?: string,
265
- pkce?: string
265
+ pkce?: string,
266
+ state?: string
266
267
  ): Promise<BasicUserInfo> => {
267
268
  const config = await _dataLayer.getConfigData();
268
269
 
269
270
  if (pkce && config.enablePKCE) {
270
- await _authenticationClient.setPKCECode(pkce);
271
+ await _authenticationClient.setPKCECode(pkce, state ?? "");
271
272
  }
272
273
 
273
274
  if (authorizationCode) {
274
275
  return _authenticationClient
275
- .requestAccessToken(authorizationCode, sessionState ?? "")
276
+ .requestAccessToken(authorizationCode, sessionState ?? "", state ?? "'")
276
277
  .then(() => {
277
278
  _spaHelper.refreshAccessTokenAutomatically();
278
279
 
@@ -284,10 +285,8 @@ export const WebWorkerCore = async (
284
285
  }
285
286
 
286
287
  return Promise.reject(
287
- new AsgardeoSPAException(
288
- "WORKER_CORE-RAT1-NF01",
289
- "worker-core",
290
- "requestAccessToken",
288
+ new AsgardeoAuthException(
289
+ "SPA-WORKER_CORE-RAT1-NF01",
291
290
  "No authorization code.",
292
291
  "No authorization code was found."
293
292
  )
@@ -304,38 +303,38 @@ export const WebWorkerCore = async (
304
303
  return await _authenticationClient.getSignOutURL();
305
304
  };
306
305
 
307
- const requestCustomGrant = async (config: CustomGrantConfig): Promise<BasicUserInfo | HttpResponse> => {
306
+ const requestCustomGrant = async (config: CustomGrantConfig): Promise<BasicUserInfo | FetchResponse> => {
308
307
  let useDefaultEndpoint = true;
309
308
  let matches = false;
310
- const clientConfig = await _dataLayer.getConfigData();
309
+ const serverOrigin = (config as any).baseUrl || (config as any).serverOrigin;
311
310
 
312
311
  // If the config does not contains a token endpoint, default token endpoint will be used.
313
312
  if (config?.tokenEndpoint) {
314
313
  useDefaultEndpoint = false;
315
314
  for (const baseUrl of [
316
315
  ...((await _dataLayer.getConfigData())?.resourceServerURLs ?? []),
317
- clientConfig?.serverOrigin
316
+ serverOrigin
318
317
  ]) {
319
- if (config.tokenEndpoint?.startsWith(baseUrl)) {
318
+ if (baseUrl && config.tokenEndpoint?.startsWith(baseUrl)) {
320
319
  matches = true;
321
320
  break;
322
321
  }
323
322
  }
324
323
  }
325
324
 
326
- if(config.shouldReplayAfterRefresh) {
325
+ if (config.shouldReplayAfterRefresh) {
327
326
  _dataLayer.setTemporaryDataParameter(CUSTOM_GRANT_CONFIG, JSON.stringify(config));
328
327
  }
329
328
  if (useDefaultEndpoint || matches) {
330
329
  return _authenticationClient
331
330
  .requestCustomGrant(config)
332
- .then(async (response: HttpResponse | TokenResponse) => {
331
+ .then(async (response: FetchResponse | TokenResponse) => {
333
332
  if (config.returnsSession) {
334
333
  _spaHelper.refreshAccessTokenAutomatically();
335
334
 
336
335
  return _authenticationClient.getBasicUserInfo();
337
336
  } else {
338
- return response as HttpResponse;
337
+ return response as FetchResponse;
339
338
  }
340
339
  })
341
340
  .catch((error) => {
@@ -343,14 +342,12 @@ export const WebWorkerCore = async (
343
342
  });
344
343
  } else {
345
344
  return Promise.reject(
346
- new AsgardeoSPAException(
347
- "WORKER_CORE-RCG-IV01",
348
- "worker-core",
349
- "requestCustomGrant",
345
+ new AsgardeoAuthException(
346
+ "SPA-WORKER_CORE-RCG-IV01",
350
347
  "Request to the provided endpoint is prohibited.",
351
348
  "Requests can only be sent to resource servers specified by the `resourceServerURLs`" +
352
- " attribute while initializing the SDK. The specified token endpoint in this request " +
353
- "cannot be found among the `resourceServerURLs`"
349
+ " attribute while initializing the SDK. The specified token endpoint in this request " +
350
+ "cannot be found among the `resourceServerURLs`"
354
351
  )
355
352
  );
356
353
  }
@@ -422,11 +419,11 @@ export const WebWorkerCore = async (
422
419
  };
423
420
 
424
421
  const getCustomGrantConfigData = async (): Promise<AuthClientConfig<CustomGrantConfig> | null> => {
425
- const configString = await _dataLayer.getTemporaryDataParameter(CUSTOM_GRANT_CONFIG);
426
- if(configString) {
422
+ const configString = await _dataLayer.getTemporaryDataParameter(CUSTOM_GRANT_CONFIG);
423
+ if (configString) {
427
424
  return JSON.parse(configString as string);
428
425
  } else {
429
- return null
426
+ return null;
430
427
  }
431
428
  };
432
429
 
@@ -1 +0,0 @@
1
- {"version":3,"file":"exception.d.ts","sourceRoot":"","sources":["../../../src/exception/exception.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,qBAAa,oBAAqB,SAAQ,KAAK;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,oBAAoB,GAAG,SAAS,CAAC;gBAG3C,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,WAAW,EAAE,MAAM,EACnB,KAAK,CAAC,EAAE,oBAAoB,GAAG,SAAS;CAW/C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"exception.js","sourceRoot":"","sources":["../../../src/exception/exception.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAQ3C,YACI,IAAY,EACZ,IAAY,EACZ,MAAc,EACd,OAAe,EACf,WAAmB,EACnB,KAAwC;QAExC,KAAK,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,OAAO,CAAC,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;QAClC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACtD,CAAC;CACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/exception/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;EAgBE;AAEF,cAAc,aAAa,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/exception/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;EAgBE;AAEF,cAAc,aAAa,CAAC"}
@@ -1,44 +0,0 @@
1
- /**
2
- * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
3
- *
4
- * WSO2 Inc. licenses this file to you under the Apache License,
5
- * Version 2.0 (the "License"); you may not use this file except
6
- * in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing,
12
- * software distributed under the License is distributed on an
13
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
- * KIND, either express or implied. See the License for the
15
- * specific language governing permissions and limitations
16
- * under the License.
17
- */
18
-
19
- export class AsgardeoSPAException extends Error {
20
- public name: string;
21
- public code: string;
22
- public file: string;
23
- public method: string;
24
- public description: string;
25
- public error: AsgardeoSPAException | undefined;
26
-
27
- public constructor(
28
- code: string,
29
- file: string,
30
- method: string,
31
- message: string,
32
- description: string,
33
- error?: AsgardeoSPAException | undefined
34
- ) {
35
- super(message ?? error?.message);
36
- this.name = this.constructor.name;
37
- this.code = code;
38
- this.file = file;
39
- this.method = method;
40
- this.error = error;
41
- this.description = description;
42
- Object.setPrototypeOf(this, new.target.prototype);
43
- }
44
- }