@auth0/auth0-spa-js 2.1.3 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
- import { Auth0ClientOptions, RedirectLoginOptions, PopupLoginOptions, PopupConfigOptions, RedirectLoginResult, GetTokenSilentlyOptions, GetTokenWithPopupOptions, LogoutOptions, User, IdToken, GetTokenSilentlyVerboseResponse } from './global';
1
+ import { Auth0ClientOptions, RedirectLoginOptions, PopupLoginOptions, PopupConfigOptions, RedirectLoginResult, GetTokenSilentlyOptions, GetTokenWithPopupOptions, LogoutOptions, User, IdToken, GetTokenSilentlyVerboseResponse, TokenEndpointResponse } from './global';
2
+ import { CustomTokenExchangeOptions } from './TokenExchange';
2
3
  /**
3
4
  * Auth0 SDK for Single Page Applications using [Authorization Code Grant Flow with PKCE](https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce).
4
5
  */
@@ -186,4 +187,43 @@ export declare class Auth0Client {
186
187
  */
187
188
  private _releaseLockOnPageHide;
188
189
  private _requestToken;
190
+ /**
191
+ * Exchanges an external subject token for an Auth0 token via a token exchange request.
192
+ *
193
+ * @param {CustomTokenExchangeOptions} options - The options required to perform the token exchange.
194
+ *
195
+ * @returns {Promise<TokenEndpointResponse>} A promise that resolves to the token endpoint response,
196
+ * which contains the issued Auth0 tokens.
197
+ *
198
+ * This method implements the token exchange grant as specified in RFC 8693 by first validating
199
+ * the provided subject token type and then constructing a token request to the /oauth/token endpoint.
200
+ * The request includes the following parameters:
201
+ *
202
+ * - `grant_type`: Hard-coded to "urn:ietf:params:oauth:grant-type:token-exchange".
203
+ * - `subject_token`: The external token provided via the options.
204
+ * - `subject_token_type`: The type of the external token (validated by this function).
205
+ * - `scope`: A unique set of scopes, generated by merging the scopes supplied in the options
206
+ * with the SDK’s default scopes.
207
+ * - `audience`: The target audience from the options, with fallback to the SDK's authorization configuration.
208
+ *
209
+ * **Example Usage:**
210
+ *
211
+ * ```
212
+ * // Define the token exchange options
213
+ * const options: CustomTokenExchangeOptions = {
214
+ * subject_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...',
215
+ * subject_token_type: 'urn:acme:legacy-system-token',
216
+ * scope: "openid profile"
217
+ * };
218
+ *
219
+ * // Exchange the external token for Auth0 tokens
220
+ * try {
221
+ * const tokenResponse = await instance.exchangeToken(options);
222
+ * // Use tokenResponse.access_token, tokenResponse.id_token, etc.
223
+ * } catch (error) {
224
+ * // Handle token exchange error
225
+ * }
226
+ * ```
227
+ */
228
+ exchangeToken(options: CustomTokenExchangeOptions): Promise<TokenEndpointResponse>;
189
229
  }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Represents the configuration options required for initiating a Custom Token Exchange request
3
+ * following RFC 8693 specifications.
4
+ *
5
+ * @see {@link https://www.rfc-editor.org/rfc/rfc8693 | RFC 8693: OAuth 2.0 Token Exchange}
6
+ */
7
+ export type CustomTokenExchangeOptions = {
8
+ /**
9
+ * The type identifier for the subject token being exchanged
10
+ *
11
+ * @pattern
12
+ * - Must be a namespaced URI under your organization's control
13
+ * - Forbidden patterns:
14
+ * - `^urn:ietf:params:oauth:*` (IETF reserved)
15
+ * - `^https:\/\/auth0\.com/*` (Auth0 reserved)
16
+ * - `^urn:auth0:*` (Auth0 reserved)
17
+ *
18
+ * @example
19
+ * "urn:acme:legacy-system-token"
20
+ * "https://api.yourcompany.com/token-type/v1"
21
+ */
22
+ subject_token_type: string;
23
+ /**
24
+ * The opaque token value being exchanged for Auth0 tokens
25
+ *
26
+ * @security
27
+ * - Must be validated in Auth0 Actions using strong cryptographic verification
28
+ * - Implement replay attack protection
29
+ * - Recommended validation libraries: `jose`, `jsonwebtoken`
30
+ *
31
+ * @example
32
+ * "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
33
+ */
34
+ subject_token: string;
35
+ /**
36
+ * The target audience for the requested Auth0 token
37
+ *
38
+ * @remarks
39
+ * Must match exactly with an API identifier configured in your Auth0 tenant.
40
+ * If not provided, falls back to the client's default audience.
41
+ *
42
+ * @example
43
+ * "https://api.your-service.com/v1"
44
+ */
45
+ audience?: string;
46
+ /**
47
+ * Space-separated list of OAuth 2.0 scopes being requested
48
+ *
49
+ * @remarks
50
+ * Subject to API authorization policies configured in Auth0
51
+ *
52
+ * @example
53
+ * "openid profile email read:data write:data"
54
+ */
55
+ scope?: string;
56
+ /**
57
+ * Additional custom parameters for Auth0 Action processing
58
+ *
59
+ * @remarks
60
+ * Accessible in Action code via `event.request.body`
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * {
65
+ * custom_parameter: "session_context",
66
+ * device_fingerprint: "a3d8f7...",
67
+ * }
68
+ * ```
69
+ */
70
+ [key: string]: unknown;
71
+ };
@@ -72,6 +72,8 @@ export interface AuthorizationParams {
72
72
  *
73
73
  * - If you provide an Organization ID (a string with the prefix `org_`), it will be validated against the `org_id` claim of your user's ID Token. The validation is case-sensitive.
74
74
  * - If you provide an Organization Name (a string *without* the prefix `org_`), it will be validated against the `org_name` claim of your user's ID Token. The validation is case-insensitive.
75
+ * To use an Organization Name you must have "Allow Organization Names in Authentication API" switched on in your Auth0 settings dashboard.
76
+ * More information is available on the [Auth0 documentation portal](https://auth0.com/docs/manage-users/organizations/configure-organizations/use-org-name-authentication-api)
75
77
  *
76
78
  */
77
79
  organization?: string;
@@ -1,4 +1,10 @@
1
1
  /**
2
2
  * @ignore
3
3
  */
4
+ /**
5
+ * Returns a string of unique scopes by removing duplicates and unnecessary whitespace.
6
+ *
7
+ * @param {...(string | undefined)[]} scopes - A list of scope strings or undefined values.
8
+ * @returns {string} A string containing unique scopes separated by a single space.
9
+ */
4
10
  export declare const getUniqueScopes: (...scopes: (string | undefined)[]) => string;
@@ -1,2 +1,2 @@
1
- declare const _default: "2.1.3";
1
+ declare const _default: "2.3.0";
2
2
  export default _default;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "@auth0/auth0-spa-js",
4
4
  "description": "Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE",
5
5
  "license": "MIT",
6
- "version": "2.1.3",
6
+ "version": "2.3.0",
7
7
  "main": "dist/lib/auth0-spa-js.cjs.js",
8
8
  "types": "dist/typings/index.d.ts",
9
9
  "module": "dist/auth0-spa-js.production.esm.js",
@@ -39,7 +39,7 @@
39
39
  "@typescript-eslint/eslint-plugin-tslint": "^5.33.1",
40
40
  "@typescript-eslint/parser": "^5.33.1",
41
41
  "browser-tabs-lock": "^1.2.15",
42
- "browserstack-cypress-cli": "1.27.0",
42
+ "browserstack-cypress-cli": "1.28.0",
43
43
  "cli-table": "^0.3.6",
44
44
  "concurrently": "^7.3.0",
45
45
  "cypress": "13.6.1",
@@ -92,6 +92,7 @@ import {
92
92
  OLD_IS_AUTHENTICATED_COOKIE_NAME,
93
93
  patchOpenUrlWithOnRedirect
94
94
  } from './Auth0Client.utils';
95
+ import { CustomTokenExchangeOptions } from './TokenExchange';
95
96
 
96
97
  /**
97
98
  * @ignore
@@ -900,7 +901,15 @@ export class Auth0Client {
900
901
  const authorizeTimeout =
901
902
  options.timeoutInSeconds || this.options.authorizeTimeoutInSeconds;
902
903
 
903
- const codeResult = await runIframe(url, this.domainUrl, authorizeTimeout);
904
+ // Extract origin from domainUrl, fallback to domainUrl if URL parsing fails
905
+ let eventOrigin: string;
906
+ try {
907
+ eventOrigin = new URL(this.domainUrl).origin;
908
+ } catch {
909
+ eventOrigin = this.domainUrl;
910
+ }
911
+
912
+ const codeResult = await runIframe(url, eventOrigin, authorizeTimeout);
904
913
 
905
914
  if (stateIn !== codeResult.state) {
906
915
  throw new GenericError('state_mismatch', 'Invalid state');
@@ -1097,7 +1106,10 @@ export class Auth0Client {
1097
1106
  };
1098
1107
 
1099
1108
  private async _requestToken(
1100
- options: PKCERequestTokenOptions | RefreshTokenRequestTokenOptions,
1109
+ options:
1110
+ | PKCERequestTokenOptions
1111
+ | RefreshTokenRequestTokenOptions
1112
+ | TokenExchangeRequestOptions,
1101
1113
  additionalParameters?: RequestTokenAdditionalParameters
1102
1114
  ) {
1103
1115
  const { nonceIn, organization } = additionalParameters || {};
@@ -1137,6 +1149,68 @@ export class Auth0Client {
1137
1149
 
1138
1150
  return { ...authResult, decodedToken };
1139
1151
  }
1152
+
1153
+ /*
1154
+ Custom Token Exchange
1155
+ * **Implementation Notes:**
1156
+ * - Ensure that the `subject_token` provided has been securely obtained and is valid according
1157
+ * to your external identity provider's policies before invoking this function.
1158
+ * - The function leverages internal helper methods:
1159
+ * - `validateTokenType` confirms that the `subject_token_type` is supported.
1160
+ * - `getUniqueScopes` merges and de-duplicates scopes between the provided options and
1161
+ * the instance's default scopes.
1162
+ * - `_requestToken` performs the actual HTTP request to the token endpoint.
1163
+ */
1164
+
1165
+ /**
1166
+ * Exchanges an external subject token for an Auth0 token via a token exchange request.
1167
+ *
1168
+ * @param {CustomTokenExchangeOptions} options - The options required to perform the token exchange.
1169
+ *
1170
+ * @returns {Promise<TokenEndpointResponse>} A promise that resolves to the token endpoint response,
1171
+ * which contains the issued Auth0 tokens.
1172
+ *
1173
+ * This method implements the token exchange grant as specified in RFC 8693 by first validating
1174
+ * the provided subject token type and then constructing a token request to the /oauth/token endpoint.
1175
+ * The request includes the following parameters:
1176
+ *
1177
+ * - `grant_type`: Hard-coded to "urn:ietf:params:oauth:grant-type:token-exchange".
1178
+ * - `subject_token`: The external token provided via the options.
1179
+ * - `subject_token_type`: The type of the external token (validated by this function).
1180
+ * - `scope`: A unique set of scopes, generated by merging the scopes supplied in the options
1181
+ * with the SDK’s default scopes.
1182
+ * - `audience`: The target audience from the options, with fallback to the SDK's authorization configuration.
1183
+ *
1184
+ * **Example Usage:**
1185
+ *
1186
+ * ```
1187
+ * // Define the token exchange options
1188
+ * const options: CustomTokenExchangeOptions = {
1189
+ * subject_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...',
1190
+ * subject_token_type: 'urn:acme:legacy-system-token',
1191
+ * scope: "openid profile"
1192
+ * };
1193
+ *
1194
+ * // Exchange the external token for Auth0 tokens
1195
+ * try {
1196
+ * const tokenResponse = await instance.exchangeToken(options);
1197
+ * // Use tokenResponse.access_token, tokenResponse.id_token, etc.
1198
+ * } catch (error) {
1199
+ * // Handle token exchange error
1200
+ * }
1201
+ * ```
1202
+ */
1203
+ async exchangeToken(
1204
+ options: CustomTokenExchangeOptions
1205
+ ): Promise<TokenEndpointResponse> {
1206
+ return this._requestToken({
1207
+ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
1208
+ subject_token: options.subject_token,
1209
+ subject_token_type: options.subject_token_type,
1210
+ scope: getUniqueScopes(options.scope, this.scope),
1211
+ audience: options.audience || this.options.authorizationParams.audience
1212
+ });
1213
+ }
1140
1214
  }
1141
1215
 
1142
1216
  interface BaseRequestTokenOptions {
@@ -1157,6 +1231,14 @@ interface RefreshTokenRequestTokenOptions extends BaseRequestTokenOptions {
1157
1231
  refresh_token?: string;
1158
1232
  }
1159
1233
 
1234
+ interface TokenExchangeRequestOptions extends BaseRequestTokenOptions {
1235
+ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange';
1236
+ subject_token: string;
1237
+ subject_token_type: string;
1238
+ actor_token?: string;
1239
+ actor_token_type?: string;
1240
+ }
1241
+
1160
1242
  interface RequestTokenAdditionalParameters {
1161
1243
  nonceIn?: string;
1162
1244
  organization?: string;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Represents the configuration options required for initiating a Custom Token Exchange request
3
+ * following RFC 8693 specifications.
4
+ *
5
+ * @see {@link https://www.rfc-editor.org/rfc/rfc8693 | RFC 8693: OAuth 2.0 Token Exchange}
6
+ */
7
+ export type CustomTokenExchangeOptions = {
8
+ /**
9
+ * The type identifier for the subject token being exchanged
10
+ *
11
+ * @pattern
12
+ * - Must be a namespaced URI under your organization's control
13
+ * - Forbidden patterns:
14
+ * - `^urn:ietf:params:oauth:*` (IETF reserved)
15
+ * - `^https:\/\/auth0\.com/*` (Auth0 reserved)
16
+ * - `^urn:auth0:*` (Auth0 reserved)
17
+ *
18
+ * @example
19
+ * "urn:acme:legacy-system-token"
20
+ * "https://api.yourcompany.com/token-type/v1"
21
+ */
22
+ subject_token_type: string;
23
+
24
+ /**
25
+ * The opaque token value being exchanged for Auth0 tokens
26
+ *
27
+ * @security
28
+ * - Must be validated in Auth0 Actions using strong cryptographic verification
29
+ * - Implement replay attack protection
30
+ * - Recommended validation libraries: `jose`, `jsonwebtoken`
31
+ *
32
+ * @example
33
+ * "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
34
+ */
35
+ subject_token: string;
36
+
37
+ /**
38
+ * The target audience for the requested Auth0 token
39
+ *
40
+ * @remarks
41
+ * Must match exactly with an API identifier configured in your Auth0 tenant.
42
+ * If not provided, falls back to the client's default audience.
43
+ *
44
+ * @example
45
+ * "https://api.your-service.com/v1"
46
+ */
47
+ audience?: string;
48
+
49
+ /**
50
+ * Space-separated list of OAuth 2.0 scopes being requested
51
+ *
52
+ * @remarks
53
+ * Subject to API authorization policies configured in Auth0
54
+ *
55
+ * @example
56
+ * "openid profile email read:data write:data"
57
+ */
58
+ scope?: string;
59
+
60
+ /**
61
+ * Additional custom parameters for Auth0 Action processing
62
+ *
63
+ * @remarks
64
+ * Accessible in Action code via `event.request.body`
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * {
69
+ * custom_parameter: "session_context",
70
+ * device_fingerprint: "a3d8f7...",
71
+ * }
72
+ * ```
73
+ */
74
+ [key: string]: unknown;
75
+ };
package/src/api.ts CHANGED
@@ -15,9 +15,18 @@ export async function oauthToken(
15
15
  }: TokenEndpointOptions,
16
16
  worker?: Worker
17
17
  ) {
18
+ const isTokenExchange =
19
+ options.grant_type === 'urn:ietf:params:oauth:grant-type:token-exchange';
20
+
21
+ const allParams = {
22
+ ...options,
23
+ ...(isTokenExchange && audience && { audience }),
24
+ ...(isTokenExchange && scope && { scope })
25
+ };
26
+
18
27
  const body = useFormData
19
- ? createQueryParams(options)
20
- : JSON.stringify(options);
28
+ ? createQueryParams(allParams)
29
+ : JSON.stringify(allParams);
21
30
 
22
31
  return await getJSON<TokenEndpointResponse>(
23
32
  `${baseUrl}/oauth/token`,
package/src/global.ts CHANGED
@@ -84,6 +84,8 @@ export interface AuthorizationParams {
84
84
  *
85
85
  * - If you provide an Organization ID (a string with the prefix `org_`), it will be validated against the `org_id` claim of your user's ID Token. The validation is case-sensitive.
86
86
  * - If you provide an Organization Name (a string *without* the prefix `org_`), it will be validated against the `org_name` claim of your user's ID Token. The validation is case-insensitive.
87
+ * To use an Organization Name you must have "Allow Organization Names in Authentication API" switched on in your Auth0 settings dashboard.
88
+ * More information is available on the [Auth0 documentation portal](https://auth0.com/docs/manage-users/organizations/configure-organizations/use-org-name-authentication-api)
87
89
  *
88
90
  */
89
91
  organization?: string;
package/src/scope.ts CHANGED
@@ -6,6 +6,12 @@ const dedupe = (arr: string[]) => Array.from(new Set(arr));
6
6
  /**
7
7
  * @ignore
8
8
  */
9
+ /**
10
+ * Returns a string of unique scopes by removing duplicates and unnecessary whitespace.
11
+ *
12
+ * @param {...(string | undefined)[]} scopes - A list of scope strings or undefined values.
13
+ * @returns {string} A string containing unique scopes separated by a single space.
14
+ */
9
15
  export const getUniqueScopes = (...scopes: (string | undefined)[]) => {
10
16
  return dedupe(scopes.filter(Boolean).join(' ').trim().split(/\s+/)).join(' ');
11
17
  };
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export default '2.1.3';
1
+ export default '2.3.0';