Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@auth0/auth0-api-js

Package Overview
Dependencies
Maintainers
44
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@auth0/auth0-api-js - npm Package Compare versions

Comparing version
1.1.0
to
1.2.0
+84
-3
dist/index.cjs

@@ -37,2 +37,3 @@ "use strict";

InvalidRequestError: () => InvalidRequestError,
MissingClientAuthError: () => import_auth0_auth_js2.MissingClientAuthError,
MissingRequiredArgumentError: () => MissingRequiredArgumentError,

@@ -42,2 +43,3 @@ MissingTransactionError: () => MissingTransactionError,

SigningAlgorithm: () => SigningAlgorithm,
TokenExchangeError: () => import_auth0_auth_js2.TokenExchangeError,
VerifyAccessTokenError: () => VerifyAccessTokenError,

@@ -127,5 +129,26 @@ getToken: () => getToken

/**
* Verifies the provided access token.
* @param options Options used to verify the logout token.
* @returns
* Verifies the provided access token against the ApiClient's configured audience.
*
* This method validates the JWT signature using the Auth0 tenant's JWKS and verifies
* standard claims including issuer, expiration, and issued-at time. The audience claim
* is verified against the audience configured when constructing the ApiClient.
*
* @param options Options containing the access token and optional required claims.
* @returns Promise resolving to the verified token payload containing all JWT claims.
* @throws {VerifyAccessTokenError} When verification fails due to invalid signature,
* expired token, mismatched audience, or missing required claims.
*
* @example
* ```typescript
* const apiClient = new ApiClient({
* domain: 'example.auth0.com',
* audience: 'https://api.example.com', // This audience is used for verification
* clientId: 'client123',
* clientSecret: 'secret'
* });
*
* const payload = await apiClient.verifyAccessToken({
* accessToken: 'eyJhbGc...'
* });
* ```
*/

@@ -177,2 +200,55 @@ async verifyAccessToken(options) {

}
/**
* Exchanges a token via a Custom Token Exchange Profile for a different API audience while preserving user identity (RFC 8693).
*
* This method supports **Custom Token Exchange** for custom token types via a configured Token Exchange Profile.
*
* For **Access Token Exchange with Token Vault** (external provider's access tokens), use {@link getAccessTokenForConnection} instead.
*
* **Note**: This method requires a confidential client (client credentials must be configured).
* While Custom Token Exchange Early Access technically permits public clients, this implementation
* currently requires client authentication. Public client support may be added in a future release.
*
* @param subjectToken - The raw token to be exchanged (without "Bearer " prefix)
* @param options - Configuration for the token exchange
*
* @returns A promise that resolves with the {@link TokenExchangeProfileResult}
*
* @throws {TokenExchangeError} When client credentials are not configured or exchange fails
*
* @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Documentation}
*
* @example
* ```typescript
* const result = await apiClient.getTokenByExchangeProfile(
* userToken,
* {
* subjectTokenType: 'urn:example:custom-token',
* audience: 'https://api.backend.com',
* scope: 'read:data write:data',
* }
* );
* ```
*/
async getTokenByExchangeProfile(subjectToken, options) {
if (!this.#authClient) {
throw new import_auth0_auth_js.MissingClientAuthError();
}
const response = await this.#authClient.exchangeToken({
subjectTokenType: options.subjectTokenType,
subjectToken,
audience: options.audience,
scope: options.scope,
requestedTokenType: options.requestedTokenType
});
return {
accessToken: response.accessToken,
expiresAt: response.expiresAt,
...response.scope && { scope: response.scope },
...response.idToken && { idToken: response.idToken },
...response.refreshToken && { refreshToken: response.refreshToken },
...response.tokenType && { tokenType: response.tokenType },
...response.issuedTokenType && { issuedTokenType: response.issuedTokenType }
};
}
};

@@ -444,2 +520,5 @@

}
// src/index.ts
var import_auth0_auth_js2 = require("@auth0/auth0-auth-js");
// Annotate the CommonJS export names for ESM import in node:

@@ -451,2 +530,3 @@ 0 && (module.exports = {

InvalidRequestError,
MissingClientAuthError,
MissingRequiredArgumentError,

@@ -456,2 +536,3 @@ MissingTransactionError,

SigningAlgorithm,
TokenExchangeError,
VerifyAccessTokenError,

@@ -458,0 +539,0 @@ getToken

+1
-1

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/index.ts","../src/api-client.ts","../src/errors.ts","../src/protected-resource-metadata.ts","../src/token.ts"],"sourcesContent":["export { ApiClient } from './api-client.js';\nexport * from './protected-resource-metadata.js';\nexport * from './errors.js';\nexport * from './types.js';\nexport { getToken } from './token.js';\n","import * as oauth from 'oauth4webapi';\nimport { createRemoteJWKSet, jwtVerify, customFetch } from 'jose';\nimport { AuthClient, TokenForConnectionError } from '@auth0/auth0-auth-js';\nimport { AccessTokenForConnectionOptions, ApiClientOptions, ConnectionTokenSet, VerifyAccessTokenOptions } from './types.js';\nimport {\n MissingRequiredArgumentError,\n VerifyAccessTokenError,\n} from './errors.js';\n\nexport class ApiClient {\n #serverMetadata: oauth.AuthorizationServer | undefined;\n readonly #options: ApiClientOptions;\n #jwks?: ReturnType<typeof createRemoteJWKSet>;\n readonly #authClient: AuthClient | undefined;\n\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n if (options.clientId) {\n this.#authClient = new AuthClient({\n domain: options.domain,\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n clientAssertionSigningKey: options.clientAssertionSigningKey,\n clientAssertionSigningAlg: options.clientAssertionSigningAlg,\n customFetch: options.customFetch,\n });\n }\n\n if (!this.#options.audience) {\n throw new MissingRequiredArgumentError('audience');\n }\n }\n\n /**\n * Initialized the SDK by performing Metadata Discovery.\n */\n async #discover() {\n if (this.#serverMetadata) {\n return {\n serverMetadata: this.#serverMetadata,\n };\n }\n\n const issuer = new URL(`https://${this.#options.domain}`);\n const response = await oauth.discoveryRequest(issuer, {\n [oauth.customFetch]: this.#options.customFetch,\n });\n\n this.#serverMetadata = await oauth.processDiscoveryResponse(\n issuer,\n response\n );\n\n return {\n serverMetadata: this.#serverMetadata,\n };\n }\n\n /**\n * Verifies the provided access token.\n * @param options Options used to verify the logout token.\n * @returns\n */\n async verifyAccessToken(options: VerifyAccessTokenOptions) {\n const { serverMetadata } = await this.#discover();\n\n this.#jwks ||= createRemoteJWKSet(new URL(serverMetadata!.jwks_uri!), {\n [customFetch]: this.#options.customFetch,\n });\n\n try {\n const { payload } = await jwtVerify(options.accessToken, this.#jwks, {\n issuer: this.#serverMetadata!.issuer,\n audience: this.#options.audience,\n algorithms: ['RS256'],\n requiredClaims: ['iat', 'exp', ...(options.requiredClaims || [])],\n });\n return payload;\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n throw new VerifyAccessTokenError((e as any).message);\n }\n }\n\n /**\n * Retrieves an access token for a connection.\n *\n * @param options - Options for retrieving an access token for a connection.\n *\n * @throws {TokenForConnectionError} If there was an issue requesting the access token.\n *\n * @returns The Connection Token Set, containing the access token for the connection, as well as additional information.\n */\n public async getAccessTokenForConnection(options: AccessTokenForConnectionOptions): Promise<ConnectionTokenSet> {\n if (!this.#authClient) {\n throw new TokenForConnectionError(\n 'Client credentials are required to use getAccessTokenForConnection'\n );\n }\n\n const tokenEndpointResponse = await this.#authClient.getTokenForConnection({\n connection: options.connection,\n loginHint: options.loginHint,\n accessToken: options.accessToken,\n });\n\n return {\n accessToken: tokenEndpointResponse.accessToken,\n scope: tokenEndpointResponse.scope,\n expiresAt: tokenEndpointResponse.expiresAt,\n connection: options.connection,\n loginHint: options.loginHint,\n };\n }\n}\n","/**\n * Error thrown when the transaction is missing.\n */\nexport class MissingTransactionError extends Error {\n public code: string = 'missing_transaction_error';\n\n constructor(message?: string) {\n super(message ?? 'The transaction is missing.');\n this.name = 'MissingTransactionError';\n }\n}\n\n/**\n * Error thrown when verifying the access token.\n */\nexport class VerifyAccessTokenError extends Error {\n public code: string = 'verify_access_token_error';\n\n constructor(message: string) {\n super(message);\n this.name = 'VerifyAccessTokenError';\n }\n}\n\n/**\n * Error thrown when request is missing a valid token or\n * multiple auth methods used\n */\nexport class InvalidRequestError extends Error {\n public code: string = 'invalid_request';\n\n constructor(message: string) {\n super(message);\n this.name = 'InvalidRequestError';\n }\n}\n\n/**\n * Error thrown when a required argument is missing.\n */\nexport class MissingRequiredArgumentError extends Error {\n public code: string = 'missing_required_argument_error';\n\n constructor(argument: string) {\n super(`The argument '${argument}' is required but was not provided.`);\n this.name = 'MissingRequiredArgumentError';\n }\n}\n","/**\n * RFC 9728 - OAuth 2.0 Protected Resource Metadata\n * https://datatracker.ietf.org/doc/html/rfc9728\n */\n\nimport { MissingRequiredArgumentError } from \"./errors.js\";\n\n/**\n * Supported methods of sending an OAuth 2.0 bearer token\n */\nexport enum BearerMethod {\n HEADER = \"header\",\n BODY = \"body\",\n QUERY = \"query\",\n}\n\n/**\n * Supported signing algorithms\n */\nexport enum SigningAlgorithm {\n RS256 = \"RS256\",\n RS384 = \"RS384\",\n RS512 = \"RS512\",\n ES256 = \"ES256\",\n ES384 = \"ES384\",\n ES512 = \"ES512\",\n PS256 = \"PS256\",\n PS384 = \"PS384\",\n PS512 = \"PS512\",\n HS256 = \"HS256\",\n HS384 = \"HS384\",\n HS512 = \"HS512\",\n}\n\n/**\n * Grant types supported\n */\nexport enum GrantType {\n AUTHORIZATION_CODE = \"authorization_code\",\n IMPLICIT = \"implicit\",\n PASSWORD = \"password\",\n CLIENT_CREDENTIALS = \"client_credentials\",\n REFRESH_TOKEN = \"refresh_token\",\n JWT_BEARER = \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n SAML2_BEARER = \"urn:ietf:params:oauth:grant-type:saml2-bearer\",\n DEVICE_CODE = \"urn:ietf:params:oauth:grant-type:device_code\",\n}\n\n/**\n * Interface for Protected Resource Metadata\n */\nexport interface IProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n jwks_uri?: string;\n scopes_supported?: string[];\n bearer_methods_supported?: BearerMethod[];\n resource_signing_alg_values_supported?: SigningAlgorithm[];\n resource_name?: string;\n resource_documentation?: string;\n resource_policy_uri?: string;\n resource_tos_uri?: string;\n tls_client_certificate_bound_access_tokens?: boolean;\n authorization_details_types_supported?: string[];\n dpop_signing_alg_values_supported?: string[];\n dpop_bound_access_tokens_required?: boolean;\n}\n\n/**\n * Builder for creating a ProtectedResourceMetadata instance\n *\n * @example\n * ```typescript\n * const metadata = new ProtectedResourceMetadataBuilder('https://api.example.com', ['https://auth.example.com'])\n * .withJwksUri('https://api.example.com/.well-known/jwks.json')\n * .withScopesSupported(['read', 'write'])\n * .build();\n * // serialize to json\n * const json = metadata.toJSON();\n * ```\n */\nexport class ProtectedResourceMetadataBuilder {\n private readonly props: Partial<IProtectedResourceMetadata> &\n Pick<IProtectedResourceMetadata, \"resource\" | \"authorization_servers\">;\n\n /**\n * Constructor for the builder\n * @param resource - The protected resource identifier (REQUIRED)\n * @param authorization_servers - Array of authorization server URLs (REQUIRED)\n */\n constructor(resource: string, authorization_servers: string[]) {\n if (!resource?.trim()) {\n throw new MissingRequiredArgumentError(\"resource\");\n }\n if (\n !Array.isArray(authorization_servers) ||\n authorization_servers.length === 0\n ) {\n throw new MissingRequiredArgumentError(\"authorization_servers\");\n }\n this.props = { resource, authorization_servers };\n }\n\n get properties(): IProtectedResourceMetadata {\n return this.props;\n }\n\n /**\n * Builds the ProtectedResourceMetadata\n */\n public build() {\n return new ProtectedResourceMetadata(this);\n }\n\n /**\n * Builder method to add JWKS URI\n */\n withJwksUri(jwks_uri: string): this {\n this.props.jwks_uri = jwks_uri;\n return this;\n }\n\n /**\n * Builder method to add supported scopes\n */\n withScopesSupported(scopes_supported: string[]): this {\n this.props.scopes_supported = [...scopes_supported];\n return this;\n }\n\n /**\n * Builder method to add supported bearer methods\n */\n withBearerMethodsSupported(\n bearer_methods_supported: BearerMethod[]\n ): this {\n this.props.bearer_methods_supported = [...bearer_methods_supported];\n return this;\n }\n\n /**\n * Builder method to add supported resource signing algorithms\n */\n withResourceSigningAlgValuesSupported(\n resource_signing_alg_values_supported: SigningAlgorithm[]\n ): this {\n this.props.resource_signing_alg_values_supported = [...resource_signing_alg_values_supported];\n return this;\n }\n\n /**\n * Builder method to add resource_name\n */\n withResourceName(resource_name: string): this {\n this.props.resource_name = resource_name;\n return this;\n }\n\n /**\n * Builder method to add resource documentation URL\n */\n withResourceDocumentation(resource_documentation: string): this {\n this.props.resource_documentation = resource_documentation;\n return this;\n }\n\n /**\n * Builder method to add resource policy URI\n */\n withResourcePolicyUri(resource_policy_uri: string): this {\n this.props.resource_policy_uri = resource_policy_uri;\n return this;\n }\n\n /**\n * Builder method to add resource terms of service URI\n */\n withResourceTosUri(resource_tos_uri: string): this {\n this.props.resource_tos_uri = resource_tos_uri;\n return this;\n }\n\n /**\n * Builder method to enable TLS client certificate bound access tokens\n */\n withTlsClientCertificateBoundAccessTokens(tls_client_certificate_bound_access_tokens: boolean): this {\n this.props.tls_client_certificate_bound_access_tokens = tls_client_certificate_bound_access_tokens;\n return this;\n }\n\n /**\n * Builder method to add supported authorization details types\n */\n withAuthorizationDetailsTypesSupported(authorization_details_types_supported: string[]): this {\n this.props.authorization_details_types_supported = [...authorization_details_types_supported];\n return this;\n }\n\n /**\n * Builder method to add supported DPoP signing algorithms\n */\n withDpopSigningAlgValuesSupported(dpop_signing_alg_values_supported: string[]): this {\n this.props.dpop_signing_alg_values_supported = [...dpop_signing_alg_values_supported];\n return this;\n }\n\n /**\n * Builder method to require DPoP bound access tokens\n */\n withDpopBoundAccessTokensRequired(dpop_bound_access_tokens_required: boolean): this {\n this.props.dpop_bound_access_tokens_required = dpop_bound_access_tokens_required;\n return this;\n }\n\n\n}\n\nclass ProtectedResourceMetadata {\n readonly #resource: string;\n readonly #authorization_servers: string[];\n readonly #jwks_uri?: string;\n readonly #scopes_supported?: string[];\n readonly #bearer_methods_supported?: BearerMethod[];\n readonly #resource_signing_alg_values_supported?: SigningAlgorithm[];\n readonly #resource_documentation?: string;\n readonly #resource_policy_uri?: string;\n readonly #resource_tos_uri?: string;\n readonly #resource_name?: string;\n readonly #tls_client_certificate_bound_access_tokens?: boolean;\n readonly #authorization_details_types_supported?: string[];\n readonly #dpop_signing_alg_values_supported?: string[];\n readonly #dpop_bound_access_tokens_required?: boolean;\n\n constructor(builder: ProtectedResourceMetadataBuilder) {\n const props = builder.properties;\n this.#resource = props.resource;\n this.#authorization_servers = [...props.authorization_servers];\n this.#jwks_uri = props.jwks_uri;\n this.#scopes_supported = props.scopes_supported\n ? [...props.scopes_supported]\n : undefined;\n this.#bearer_methods_supported = props.bearer_methods_supported\n ? [...props.bearer_methods_supported]\n : undefined;\n this.#resource_signing_alg_values_supported = props.resource_signing_alg_values_supported\n ? [...props.resource_signing_alg_values_supported]\n : undefined;\n this.#resource_documentation = props.resource_documentation;\n this.#resource_policy_uri = props.resource_policy_uri;\n this.#resource_tos_uri = props.resource_tos_uri;\n this.#resource_name = props.resource_name;\n this.#tls_client_certificate_bound_access_tokens = props.tls_client_certificate_bound_access_tokens;\n this.#authorization_details_types_supported = props.authorization_details_types_supported\n ? [...props.authorization_details_types_supported]\n : undefined;\n this.#dpop_signing_alg_values_supported = props.dpop_signing_alg_values_supported\n ? [...props.dpop_signing_alg_values_supported]\n : undefined;\n this.#dpop_bound_access_tokens_required = props.dpop_bound_access_tokens_required;\n }\n\n /**\n * Convert to JSON representation\n */\n public toJSON(): IProtectedResourceMetadata {\n return {\n resource: this.#resource,\n authorization_servers: [...this.#authorization_servers],\n\n ...(this.#jwks_uri !== undefined && { jwks_uri: this.#jwks_uri }),\n ...(this.#scopes_supported !== undefined && {\n scopes_supported: [...this.#scopes_supported],\n }),\n ...(this.#bearer_methods_supported !== undefined && {\n bearer_methods_supported: [...this.#bearer_methods_supported],\n }),\n ...(this.#resource_signing_alg_values_supported !== undefined && {\n resource_signing_alg_values_supported: [...this.#resource_signing_alg_values_supported],\n }),\n ...(this.#resource_documentation !== undefined && {\n resource_documentation: this.#resource_documentation,\n }),\n ...(this.#resource_policy_uri !== undefined && {\n resource_policy_uri: this.#resource_policy_uri,\n }),\n ...(this.#resource_tos_uri !== undefined && {\n resource_tos_uri: this.#resource_tos_uri,\n }),\n ...(this.#resource_name !== undefined && {\n resource_name: this.#resource_name,\n }),\n ...(this.#tls_client_certificate_bound_access_tokens !== undefined && {\n tls_client_certificate_bound_access_tokens: this.#tls_client_certificate_bound_access_tokens,\n }),\n ...(this.#authorization_details_types_supported !== undefined && {\n authorization_details_types_supported: [...this.#authorization_details_types_supported],\n }),\n ...(this.#dpop_signing_alg_values_supported !== undefined && {\n dpop_signing_alg_values_supported: [...this.#dpop_signing_alg_values_supported],\n }),\n ...(this.#dpop_bound_access_tokens_required !== undefined && {\n dpop_bound_access_tokens_required: this.#dpop_bound_access_tokens_required,\n }),\n };\n }\n}\n","import { InvalidRequestError } from './errors.js';\n/**\n * Header-like object that can represent headers from different HTTP frameworks\n */\ntype HeadersLike = Record<string, unknown> & {\n authorization?: string;\n 'content-type'?: string;\n};\n\n/**\n * Query-like object for URL query parameters\n */\ntype QueryLike = Record<string, unknown> & { access_token?: string };\n\n/**\n * Body-like object for form-encoded request body\n */\ntype BodyLike = QueryLike;\n\n/**\n * Regular expression to match Bearer token in Authorization header\n */\nconst TOKEN_RE = /^Bearer (.+)$/i;\n\n/**\n * Extracts a Bearer token from HTTP request according to RFC 6750.\n * Supports all three methods defined in the RFC:\n * - Authorization header (Section 2.1)\n * - Form-encoded body parameter (Section 2.2)\n * - URI query parameter (Section 2.3)\n *\n * @param headers - HTTP headers object\n * @param query - Query parameters object (optional)\n * @param body - Request body object (optional)\n * @returns The extracted token string\n * @throws {InvalidRequestError} When no token is found or multiple methods are used\n *\n * @example\n * ```typescript\n * // Authorization header method (recommended)\n * const token1 = getToken({ authorization: 'Bearer mF_9.B5f-4.1JqM' });\n *\n * // Query parameter method\n * const token2 = getToken({}, { access_token: 'mF_9.B5f-4.1JqM' });\n *\n * // Form body method\n * const token3 = getToken(\n * { 'content-type': 'application/x-www-form-urlencoded' },\n * {},\n * { access_token: 'mF_9.B5f-4.1JqM' }\n * );\n *\n * // Express.js usage\n * const token4 = getToken(req.headers, req.query, req.body);\n * ```\n *\n * @see https://datatracker.ietf.org/doc/html/rfc6750#section-2 - RFC 6750 Section 2\n */\nexport function getToken(\n headers: HeadersLike,\n query?: QueryLike,\n body?: BodyLike\n): string {\n const fromHeader = getTokenFromHeader(headers);\n const fromQuery = getTokenFromQuery(query);\n const fromBody = getTokenFromBody(headers, body);\n\n if (!fromQuery && !fromHeader && !fromBody) {\n throw new InvalidRequestError('No Bearer token found in request');\n }\n\n // If multiple methods are used, throw an error\n if (+!!fromQuery + +!!fromBody + +!!fromHeader > 1) {\n throw new InvalidRequestError(\n 'More than one method used for authentication'\n );\n }\n\n return (fromQuery || fromBody || fromHeader) as string;\n}\n\n/**\n * Extract token from Authorization header\n */\nfunction getTokenFromHeader(headers: HeadersLike) {\n const authHeader = headers.authorization;\n if (typeof authHeader !== 'string') {\n return undefined;\n }\n\n const match = authHeader.match(TOKEN_RE);\n return match?.[1];\n}\n\n/**\n * Extract token from query parameters\n */\nfunction getTokenFromQuery(query?: QueryLike): string | undefined {\n const accessToken = query?.access_token;\n if (typeof accessToken === 'string') {\n return accessToken;\n }\n}\n\n/**\n * Extract token from form-encoded body\n */\nfunction getTokenFromBody(\n headers: HeadersLike,\n body?: BodyLike\n): string | undefined {\n if (!body || typeof body.access_token !== 'string') {\n return undefined;\n }\n\n const contentType = headers['content-type'];\n if (!contentType) {\n return undefined;\n }\n\n // Handle content-type with charset, e.g., \"application/x-www-form-urlencoded; charset=utf-8\"\n const isFormEncoded = contentType\n .toLowerCase()\n .includes('application/x-www-form-urlencoded');\n if (!isFormEncoded) {\n return undefined;\n }\n\n return body.access_token;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,YAAuB;AACvB,kBAA2D;AAC3D,2BAAoD;;;ACC7C,IAAM,0BAAN,cAAsC,MAAM;AAAA,EAC1C,OAAe;AAAA,EAEtB,YAAY,SAAkB;AAC5B,UAAM,WAAW,6BAA6B;AAC9C,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EACzC,OAAe;AAAA,EAEtB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACtC,OAAe;AAAA,EAEtB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK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AO,KAAK,iBAAiB,UAAU;AAClD,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,QAAQ,cAAc;AAC1C,MAAI,CAAC,aAAa;AAChB,WAAO;AAAA,EACT;AAGA,QAAM,gBAAgB,YACnB,YAAY,EACZ,SAAS,mCAAmC;AAC/C,MAAI,CAAC,eAAe;AAClB,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AACd;","names":["BearerMethod","SigningAlgorithm","GrantType"]}
{"version":3,"sources":["../src/index.ts","../src/api-client.ts","../src/errors.ts","../src/protected-resource-metadata.ts","../src/token.ts"],"sourcesContent":["export { ApiClient } from './api-client.js';\nexport * from './protected-resource-metadata.js';\nexport * from './errors.js';\nexport * from './types.js';\nexport { getToken } from './token.js';\n\n// Re-export shared errors from auth0-auth-js for convenience\nexport {\n MissingClientAuthError,\n TokenExchangeError,\n} from '@auth0/auth0-auth-js';\n","import * as oauth from 'oauth4webapi';\nimport { createRemoteJWKSet, jwtVerify, customFetch } from 'jose';\nimport { AuthClient, TokenForConnectionError, MissingClientAuthError } from '@auth0/auth0-auth-js';\nimport { AccessTokenForConnectionOptions, ApiClientOptions, ConnectionTokenSet, ExchangeProfileOptions, TokenExchangeProfileResult, VerifyAccessTokenOptions } from './types.js';\nimport {\n MissingRequiredArgumentError,\n VerifyAccessTokenError,\n} from './errors.js';\n\nexport class ApiClient {\n #serverMetadata: oauth.AuthorizationServer | undefined;\n readonly #options: ApiClientOptions;\n #jwks?: ReturnType<typeof createRemoteJWKSet>;\n readonly #authClient: AuthClient | undefined;\n\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n if (options.clientId) {\n this.#authClient = new AuthClient({\n domain: options.domain,\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n clientAssertionSigningKey: options.clientAssertionSigningKey,\n clientAssertionSigningAlg: options.clientAssertionSigningAlg,\n customFetch: options.customFetch,\n });\n }\n\n if (!this.#options.audience) {\n throw new MissingRequiredArgumentError('audience');\n }\n }\n\n /**\n * Initialized the SDK by performing Metadata Discovery.\n */\n async #discover() {\n if (this.#serverMetadata) {\n return {\n serverMetadata: this.#serverMetadata,\n };\n }\n\n const issuer = new URL(`https://${this.#options.domain}`);\n const response = await oauth.discoveryRequest(issuer, {\n [oauth.customFetch]: this.#options.customFetch,\n });\n\n this.#serverMetadata = await oauth.processDiscoveryResponse(\n issuer,\n response\n );\n\n return {\n serverMetadata: this.#serverMetadata,\n };\n }\n\n /**\n * Verifies the provided access token against the ApiClient's configured audience.\n *\n * This method validates the JWT signature using the Auth0 tenant's JWKS and verifies\n * standard claims including issuer, expiration, and issued-at time. The audience claim\n * is verified against the audience configured when constructing the ApiClient.\n *\n * @param options Options containing the access token and optional required claims.\n * @returns Promise resolving to the verified token payload containing all JWT claims.\n * @throws {VerifyAccessTokenError} When verification fails due to invalid signature,\n * expired token, mismatched audience, or missing required claims.\n *\n * @example\n * ```typescript\n * const apiClient = new ApiClient({\n * domain: 'example.auth0.com',\n * audience: 'https://api.example.com', // This audience is used for verification\n * clientId: 'client123',\n * clientSecret: 'secret'\n * });\n *\n * const payload = await apiClient.verifyAccessToken({\n * accessToken: 'eyJhbGc...'\n * });\n * ```\n */\n async verifyAccessToken(options: VerifyAccessTokenOptions) {\n const { serverMetadata } = await this.#discover();\n\n this.#jwks ||= createRemoteJWKSet(new URL(serverMetadata!.jwks_uri!), {\n [customFetch]: this.#options.customFetch,\n });\n\n try {\n const { payload } = await jwtVerify(options.accessToken, this.#jwks, {\n issuer: this.#serverMetadata!.issuer,\n audience: this.#options.audience,\n algorithms: ['RS256'],\n requiredClaims: ['iat', 'exp', ...(options.requiredClaims || [])],\n });\n return payload;\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n throw new VerifyAccessTokenError((e as any).message);\n }\n }\n\n /**\n * Retrieves an access token for a connection.\n *\n * @param options - Options for retrieving an access token for a connection.\n *\n * @throws {TokenForConnectionError} If there was an issue requesting the access token.\n *\n * @returns The Connection Token Set, containing the access token for the connection, as well as additional information.\n */\n public async getAccessTokenForConnection(options: AccessTokenForConnectionOptions): Promise<ConnectionTokenSet> {\n if (!this.#authClient) {\n throw new TokenForConnectionError(\n 'Client credentials are required to use getAccessTokenForConnection'\n );\n }\n\n const tokenEndpointResponse = await this.#authClient.getTokenForConnection({\n connection: options.connection,\n loginHint: options.loginHint,\n accessToken: options.accessToken,\n });\n\n return {\n accessToken: tokenEndpointResponse.accessToken,\n scope: tokenEndpointResponse.scope,\n expiresAt: tokenEndpointResponse.expiresAt,\n connection: options.connection,\n loginHint: options.loginHint,\n };\n }\n\n /**\n * Exchanges a token via a Custom Token Exchange Profile for a different API audience while preserving user identity (RFC 8693).\n *\n * This method supports **Custom Token Exchange** for custom token types via a configured Token Exchange Profile.\n *\n * For **Access Token Exchange with Token Vault** (external provider's access tokens), use {@link getAccessTokenForConnection} instead.\n *\n * **Note**: This method requires a confidential client (client credentials must be configured).\n * While Custom Token Exchange Early Access technically permits public clients, this implementation\n * currently requires client authentication. Public client support may be added in a future release.\n *\n * @param subjectToken - The raw token to be exchanged (without \"Bearer \" prefix)\n * @param options - Configuration for the token exchange\n *\n * @returns A promise that resolves with the {@link TokenExchangeProfileResult}\n *\n * @throws {TokenExchangeError} When client credentials are not configured or exchange fails\n *\n * @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Documentation}\n *\n * @example\n * ```typescript\n * const result = await apiClient.getTokenByExchangeProfile(\n * userToken,\n * {\n * subjectTokenType: 'urn:example:custom-token',\n * audience: 'https://api.backend.com',\n * scope: 'read:data write:data',\n * }\n * );\n * ```\n */\n public async getTokenByExchangeProfile(\n subjectToken: string,\n options: ExchangeProfileOptions\n ): Promise<TokenExchangeProfileResult> {\n if (!this.#authClient) {\n throw new MissingClientAuthError();\n }\n\n const response = await this.#authClient.exchangeToken({\n subjectTokenType: options.subjectTokenType,\n subjectToken,\n audience: options.audience,\n scope: options.scope,\n requestedTokenType: options.requestedTokenType,\n });\n\n return {\n accessToken: response.accessToken,\n expiresAt: response.expiresAt,\n ...(response.scope && { scope: response.scope }),\n ...(response.idToken && { idToken: response.idToken }),\n ...(response.refreshToken && { refreshToken: response.refreshToken }),\n ...(response.tokenType && { tokenType: response.tokenType }),\n ...(response.issuedTokenType && { issuedTokenType: response.issuedTokenType }),\n };\n }\n}\n","/**\n * Error thrown when the transaction is missing.\n */\nexport class MissingTransactionError extends Error {\n public code: string = 'missing_transaction_error';\n\n constructor(message?: string) {\n super(message ?? 'The transaction is missing.');\n this.name = 'MissingTransactionError';\n }\n}\n\n/**\n * Error thrown when verifying the access token.\n */\nexport class VerifyAccessTokenError extends Error {\n public code: string = 'verify_access_token_error';\n\n constructor(message: string) {\n super(message);\n this.name = 'VerifyAccessTokenError';\n }\n}\n\n/**\n * Error thrown when request is missing a valid token or\n * multiple auth methods used\n */\nexport class InvalidRequestError extends Error {\n public code: string = 'invalid_request';\n\n constructor(message: string) {\n super(message);\n this.name = 'InvalidRequestError';\n }\n}\n\n/**\n * Error thrown when a required argument is missing.\n */\nexport class MissingRequiredArgumentError extends Error {\n public code: string = 'missing_required_argument_error';\n\n constructor(argument: string) {\n super(`The argument '${argument}' is required but was not provided.`);\n this.name = 'MissingRequiredArgumentError';\n }\n}\n","/**\n * RFC 9728 - OAuth 2.0 Protected Resource Metadata\n * https://datatracker.ietf.org/doc/html/rfc9728\n */\n\nimport { MissingRequiredArgumentError } from \"./errors.js\";\n\n/**\n * Supported methods of sending an OAuth 2.0 bearer token\n */\nexport enum BearerMethod {\n HEADER = \"header\",\n BODY = \"body\",\n QUERY = \"query\",\n}\n\n/**\n * Supported signing algorithms\n */\nexport enum SigningAlgorithm {\n RS256 = \"RS256\",\n RS384 = \"RS384\",\n RS512 = \"RS512\",\n ES256 = \"ES256\",\n ES384 = \"ES384\",\n ES512 = \"ES512\",\n PS256 = \"PS256\",\n PS384 = \"PS384\",\n PS512 = \"PS512\",\n HS256 = \"HS256\",\n HS384 = \"HS384\",\n HS512 = \"HS512\",\n}\n\n/**\n * Grant types supported\n */\nexport enum GrantType {\n AUTHORIZATION_CODE = \"authorization_code\",\n IMPLICIT = \"implicit\",\n PASSWORD = \"password\",\n CLIENT_CREDENTIALS = \"client_credentials\",\n REFRESH_TOKEN = \"refresh_token\",\n JWT_BEARER = \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n SAML2_BEARER = \"urn:ietf:params:oauth:grant-type:saml2-bearer\",\n DEVICE_CODE = \"urn:ietf:params:oauth:grant-type:device_code\",\n}\n\n/**\n * Interface for Protected Resource Metadata\n */\nexport interface IProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n jwks_uri?: string;\n scopes_supported?: string[];\n bearer_methods_supported?: BearerMethod[];\n resource_signing_alg_values_supported?: SigningAlgorithm[];\n resource_name?: string;\n resource_documentation?: string;\n resource_policy_uri?: string;\n resource_tos_uri?: string;\n tls_client_certificate_bound_access_tokens?: boolean;\n authorization_details_types_supported?: string[];\n dpop_signing_alg_values_supported?: string[];\n dpop_bound_access_tokens_required?: boolean;\n}\n\n/**\n * Builder for creating a ProtectedResourceMetadata instance\n *\n * @example\n * ```typescript\n * const metadata = new ProtectedResourceMetadataBuilder('https://api.example.com', ['https://auth.example.com'])\n * .withJwksUri('https://api.example.com/.well-known/jwks.json')\n * .withScopesSupported(['read', 'write'])\n * .build();\n * // serialize to json\n * const json = metadata.toJSON();\n * ```\n */\nexport class ProtectedResourceMetadataBuilder {\n private readonly props: Partial<IProtectedResourceMetadata> &\n Pick<IProtectedResourceMetadata, \"resource\" | \"authorization_servers\">;\n\n /**\n * Constructor for the builder\n * @param resource - The protected resource identifier (REQUIRED)\n * @param authorization_servers - Array of authorization server URLs (REQUIRED)\n */\n constructor(resource: string, authorization_servers: string[]) {\n if (!resource?.trim()) {\n throw new MissingRequiredArgumentError(\"resource\");\n }\n if (\n !Array.isArray(authorization_servers) ||\n authorization_servers.length === 0\n ) {\n throw new MissingRequiredArgumentError(\"authorization_servers\");\n }\n this.props = { resource, authorization_servers };\n }\n\n get properties(): IProtectedResourceMetadata {\n return this.props;\n }\n\n /**\n * Builds the ProtectedResourceMetadata\n */\n public build() {\n return new ProtectedResourceMetadata(this);\n }\n\n /**\n * Builder method to add JWKS URI\n */\n withJwksUri(jwks_uri: string): this {\n this.props.jwks_uri = jwks_uri;\n return this;\n }\n\n /**\n * Builder method to add supported scopes\n */\n withScopesSupported(scopes_supported: string[]): this {\n this.props.scopes_supported = [...scopes_supported];\n return this;\n }\n\n /**\n * Builder method to add supported bearer methods\n */\n withBearerMethodsSupported(\n bearer_methods_supported: BearerMethod[]\n ): this {\n this.props.bearer_methods_supported = [...bearer_methods_supported];\n return this;\n }\n\n /**\n * Builder method to add supported resource signing algorithms\n */\n withResourceSigningAlgValuesSupported(\n resource_signing_alg_values_supported: SigningAlgorithm[]\n ): this {\n this.props.resource_signing_alg_values_supported = [...resource_signing_alg_values_supported];\n return this;\n }\n\n /**\n * Builder method to add resource_name\n */\n withResourceName(resource_name: string): this {\n this.props.resource_name = resource_name;\n return this;\n }\n\n /**\n * Builder method to add resource documentation URL\n */\n withResourceDocumentation(resource_documentation: string): this {\n this.props.resource_documentation = resource_documentation;\n return this;\n }\n\n /**\n * Builder method to add resource policy URI\n */\n withResourcePolicyUri(resource_policy_uri: string): this {\n this.props.resource_policy_uri = resource_policy_uri;\n return this;\n }\n\n /**\n * Builder method to add resource terms of service URI\n */\n withResourceTosUri(resource_tos_uri: string): this {\n this.props.resource_tos_uri = resource_tos_uri;\n return this;\n }\n\n /**\n * Builder method to enable TLS client certificate bound access tokens\n */\n withTlsClientCertificateBoundAccessTokens(tls_client_certificate_bound_access_tokens: boolean): this {\n this.props.tls_client_certificate_bound_access_tokens = tls_client_certificate_bound_access_tokens;\n return this;\n }\n\n /**\n * Builder method to add supported authorization details types\n */\n withAuthorizationDetailsTypesSupported(authorization_details_types_supported: string[]): this {\n this.props.authorization_details_types_supported = [...authorization_details_types_supported];\n return this;\n }\n\n /**\n * Builder method to add supported DPoP signing algorithms\n */\n withDpopSigningAlgValuesSupported(dpop_signing_alg_values_supported: string[]): this {\n this.props.dpop_signing_alg_values_supported = [...dpop_signing_alg_values_supported];\n return this;\n }\n\n /**\n * Builder method to require DPoP bound access tokens\n */\n withDpopBoundAccessTokensRequired(dpop_bound_access_tokens_required: boolean): this {\n this.props.dpop_bound_access_tokens_required = dpop_bound_access_tokens_required;\n return this;\n }\n\n\n}\n\nclass ProtectedResourceMetadata {\n readonly #resource: string;\n readonly #authorization_servers: string[];\n readonly #jwks_uri?: string;\n readonly #scopes_supported?: string[];\n readonly #bearer_methods_supported?: BearerMethod[];\n readonly #resource_signing_alg_values_supported?: SigningAlgorithm[];\n readonly #resource_documentation?: string;\n readonly #resource_policy_uri?: string;\n readonly #resource_tos_uri?: string;\n readonly #resource_name?: string;\n readonly #tls_client_certificate_bound_access_tokens?: boolean;\n readonly #authorization_details_types_supported?: string[];\n readonly #dpop_signing_alg_values_supported?: string[];\n readonly #dpop_bound_access_tokens_required?: boolean;\n\n constructor(builder: ProtectedResourceMetadataBuilder) {\n const props = builder.properties;\n this.#resource = props.resource;\n this.#authorization_servers = [...props.authorization_servers];\n this.#jwks_uri = props.jwks_uri;\n this.#scopes_supported = props.scopes_supported\n ? [...props.scopes_supported]\n : undefined;\n this.#bearer_methods_supported = props.bearer_methods_supported\n ? [...props.bearer_methods_supported]\n : undefined;\n this.#resource_signing_alg_values_supported = props.resource_signing_alg_values_supported\n ? [...props.resource_signing_alg_values_supported]\n : undefined;\n this.#resource_documentation = props.resource_documentation;\n this.#resource_policy_uri = props.resource_policy_uri;\n this.#resource_tos_uri = props.resource_tos_uri;\n this.#resource_name = props.resource_name;\n this.#tls_client_certificate_bound_access_tokens = props.tls_client_certificate_bound_access_tokens;\n this.#authorization_details_types_supported = props.authorization_details_types_supported\n ? [...props.authorization_details_types_supported]\n : undefined;\n this.#dpop_signing_alg_values_supported = props.dpop_signing_alg_values_supported\n ? [...props.dpop_signing_alg_values_supported]\n : undefined;\n this.#dpop_bound_access_tokens_required = props.dpop_bound_access_tokens_required;\n }\n\n /**\n * Convert to JSON representation\n */\n public toJSON(): IProtectedResourceMetadata {\n return {\n resource: this.#resource,\n authorization_servers: [...this.#authorization_servers],\n\n ...(this.#jwks_uri !== undefined && { jwks_uri: this.#jwks_uri }),\n ...(this.#scopes_supported !== undefined && {\n scopes_supported: [...this.#scopes_supported],\n }),\n ...(this.#bearer_methods_supported !== undefined && {\n bearer_methods_supported: [...this.#bearer_methods_supported],\n }),\n ...(this.#resource_signing_alg_values_supported !== undefined && {\n resource_signing_alg_values_supported: [...this.#resource_signing_alg_values_supported],\n }),\n ...(this.#resource_documentation !== undefined && {\n resource_documentation: this.#resource_documentation,\n }),\n ...(this.#resource_policy_uri !== undefined && {\n resource_policy_uri: this.#resource_policy_uri,\n }),\n ...(this.#resource_tos_uri !== undefined && {\n resource_tos_uri: this.#resource_tos_uri,\n }),\n ...(this.#resource_name !== undefined && {\n resource_name: this.#resource_name,\n }),\n ...(this.#tls_client_certificate_bound_access_tokens !== undefined && {\n tls_client_certificate_bound_access_tokens: this.#tls_client_certificate_bound_access_tokens,\n }),\n ...(this.#authorization_details_types_supported !== undefined && {\n authorization_details_types_supported: [...this.#authorization_details_types_supported],\n }),\n ...(this.#dpop_signing_alg_values_supported !== undefined && {\n dpop_signing_alg_values_supported: [...this.#dpop_signing_alg_values_supported],\n }),\n ...(this.#dpop_bound_access_tokens_required !== undefined && {\n dpop_bound_access_tokens_required: this.#dpop_bound_access_tokens_required,\n }),\n };\n }\n}\n","import { InvalidRequestError } from './errors.js';\n/**\n * Header-like object that can represent headers from different HTTP frameworks\n */\ntype HeadersLike = Record<string, unknown> & {\n authorization?: string;\n 'content-type'?: string;\n};\n\n/**\n * Query-like object for URL query parameters\n */\ntype QueryLike = Record<string, unknown> & { access_token?: string };\n\n/**\n * Body-like object for form-encoded request body\n */\ntype BodyLike = QueryLike;\n\n/**\n * Regular expression to match Bearer token in Authorization header\n */\nconst TOKEN_RE = /^Bearer (.+)$/i;\n\n/**\n * Extracts a Bearer token from HTTP request according to RFC 6750.\n * Supports all three methods defined in the RFC:\n * - Authorization header (Section 2.1)\n * - Form-encoded body parameter (Section 2.2)\n * - URI query parameter (Section 2.3)\n *\n * @param headers - HTTP headers object\n * @param query - Query parameters object (optional)\n * @param body - Request body object (optional)\n * @returns The extracted token string\n * @throws {InvalidRequestError} When no token is found or multiple methods are used\n *\n * @example\n * ```typescript\n * // Authorization header method (recommended)\n * const token1 = getToken({ authorization: 'Bearer mF_9.B5f-4.1JqM' });\n *\n * // Query parameter method\n * const token2 = getToken({}, { access_token: 'mF_9.B5f-4.1JqM' });\n *\n * // Form body method\n * const token3 = getToken(\n * { 'content-type': 'application/x-www-form-urlencoded' },\n * {},\n * { access_token: 'mF_9.B5f-4.1JqM' }\n * );\n *\n * // Express.js usage\n * const token4 = getToken(req.headers, req.query, req.body);\n * ```\n *\n * @see https://datatracker.ietf.org/doc/html/rfc6750#section-2 - RFC 6750 Section 2\n */\nexport function getToken(\n headers: HeadersLike,\n query?: QueryLike,\n body?: BodyLike\n): string {\n const fromHeader = getTokenFromHeader(headers);\n const fromQuery = getTokenFromQuery(query);\n const fromBody = getTokenFromBody(headers, body);\n\n if (!fromQuery && !fromHeader && !fromBody) {\n throw new InvalidRequestError('No Bearer token found in request');\n }\n\n // If multiple methods are used, throw an error\n if (+!!fromQuery + +!!fromBody + +!!fromHeader > 1) {\n throw new InvalidRequestError(\n 'More than one method used for authentication'\n );\n }\n\n return (fromQuery || fromBody || fromHeader) as string;\n}\n\n/**\n * Extract token from Authorization header\n */\nfunction getTokenFromHeader(headers: HeadersLike) {\n const authHeader = headers.authorization;\n if (typeof authHeader !== 'string') {\n return undefined;\n }\n\n const match = authHeader.match(TOKEN_RE);\n return match?.[1];\n}\n\n/**\n * Extract token from query parameters\n */\nfunction getTokenFromQuery(query?: QueryLike): string | undefined {\n const accessToken = query?.access_token;\n if (typeof accessToken === 'string') {\n return accessToken;\n }\n}\n\n/**\n * Extract token from form-encoded body\n */\nfunction getTokenFromBody(\n headers: HeadersLike,\n body?: BodyLike\n): string | undefined {\n if (!body || typeof body.access_token !== 'string') {\n return undefined;\n }\n\n const contentType = headers['content-type'];\n if (!contentType) {\n return undefined;\n }\n\n // Handle content-type with charset, e.g., \"application/x-www-form-urlencoded; charset=utf-8\"\n const isFormEncoded = contentType\n .toLowerCase()\n .includes('application/x-www-form-urlencoded');\n if (!isFormEncoded) {\n return undefined;\n }\n\n return body.access_token;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,YAAuB;AACvB,kBAA2D;AAC3D,2BAA4E;;;ACCrE,IAAM,0BAAN,cAAsC,MAAM;AAAA,EAC1C,OAAe;AAAA,EAEtB,YAAY,SAAkB;AAC5B,UAAM,WAAW,6BAA6B;AAC9C,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EACzC,OAAe;AAAA,EAEtB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACtC,OAAe;AAAA,EAEtB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,+BAAN,cAA2C,MAAM;AAAA,EAC/C,OAAe;AAAA,EAEtB,YAAY,UAAkB;AAC5B,UAAM,iBAAiB,QAAQ,qCAAqC;AACpE,SAAK,OAAO;AAAA,EACd;AACF;;;ADtCO,IAAM,YAAN,MAAgB;AAAA,EACrB;AAAA,EACS;AAAA,EACT;AAAA,EACS;AAAA,EAET,YAAY,SAA2B;AACrC,SAAK,WAAW;AAEhB,QAAI,QAAQ,UAAU;AACpB,WAAK,cAAc,IAAI,gCAAW;AAAA,QAChC,QAAQ,QAAQ;AAAA,QAChB,U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AAc,CAAC,UAAU;AAC1C,UAAM,IAAI,oBAAoB,kCAAkC;AAAA,EAClE;AAGA,MAAI,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,aAAa,GAAG;AAClD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAQ,aAAa,YAAY;AACnC;AAKA,SAAS,mBAAmB,SAAsB;AAChD,QAAM,aAAa,QAAQ;AAC3B,MAAI,OAAO,eAAe,UAAU;AAClC,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,WAAW,MAAM,QAAQ;AACvC,SAAO,QAAQ,CAAC;AAClB;AAKA,SAAS,kBAAkB,OAAuC;AAChE,QAAM,cAAc,OAAO;AAC3B,MAAI,OAAO,gBAAgB,UAAU;AACnC,WAAO;AAAA,EACT;AACF;AAKA,SAAS,iBACP,SACA,MACoB;AACpB,MAAI,CAAC,QAAQ,OAAO,KAAK,iBAAiB,UAAU;AAClD,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,QAAQ,cAAc;AAC1C,MAAI,CAAC,aAAa;AAChB,WAAO;AAAA,EACT;AAGA,QAAM,gBAAgB,YACnB,YAAY,EACZ,SAAS,mCAAmC;AAC/C,MAAI,CAAC,eAAe;AAClB,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AACd;;;AJ1HA,IAAAC,wBAGO;","names":["BearerMethod","SigningAlgorithm","GrantType","import_auth0_auth_js"]}
import * as jose from 'jose';
export { MissingClientAuthError, TokenExchangeError } from '@auth0/auth0-auth-js';

@@ -15,3 +16,3 @@ interface ApiClientOptions {

* The optional client ID of the application.
* Required when using the `getAccessTokenForConnection` method.
* Required when using the `getAccessTokenForConnection` or `getTokenByExchangeProfile` methods.
*/

@@ -21,3 +22,3 @@ clientId?: string;

* The optional client secret of the application.
* At least one of `clientSecret` or `clientAssertionSigningKey` is required when using the `getAccessTokenForConnection` method.
* At least one of `clientSecret` or `clientAssertionSigningKey` is required when using the `getAccessTokenForConnection` or `getTokenByExchangeProfile` methods.
*/

@@ -27,3 +28,3 @@ clientSecret?: string;

* The optional client assertion signing key to use.
* At least one of `clientSecret` or `clientAssertionSigningKey` is required when using the `getAccessTokenForConnection` method.
* At least one of `clientSecret` or `clientAssertionSigningKey` is required when using the `getAccessTokenForConnection` or `getTokenByExchangeProfile` methods.
*/

@@ -77,2 +78,93 @@ clientAssertionSigningKey?: string | CryptoKey;

}
/**
* Configuration options for exchanging a token via a Custom Token Exchange Profile (RFC 8693).
*
* This interface supports **Custom Token Exchange** for custom token types.
* Auth0 also supports **Access Token Exchange with Token Vault** for external provider's access tokens.
*
* @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Documentation}
* @see {@link https://auth0.com/docs/secure/tokens/token-vault/access-token-exchange-with-token-vault Token Vault Documentation}
*
* @example
* ```typescript
* const options: ExchangeProfileOptions = {
* subjectTokenType: 'urn:example:custom-token',
* audience: 'https://api.backend.com',
* scope: 'read:data write:data'
* };
* ```
*/
interface ExchangeProfileOptions {
/**
* URI identifying the type of the subject token being exchanged.
* Must match a `subject_token_type` configured in a Token Exchange Profile.
*
* For custom token types, this must be a URI scoped under your own ownership,
* such as http://acme.com/legacy-token or urn:acme:legacy-token.
*
* Reserved namespaces (cannot be used): http://auth0.com, https://auth0.com,
* http://okta.com, https://okta.com, urn:ietf, urn:auth0, urn:okta
*
* @example "urn:acme:legacy-token"
* @example "http://acme.com/mcp-token"
*/
subjectTokenType: string;
/**
* The audience (API identifier) for which tokens will be issued.
* Must match an API identifier configured in your Auth0 tenant.
*
* @example "https://api.backend.com"
*/
audience: string;
/**
* Space-separated list of OAuth 2.0 scopes to request for the exchanged token.
*
* @example "read:data write:data"
*/
scope?: string;
/**
* Type of token being requested (RFC 8693).
* Defaults to access_token if not specified.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc8693#section-2.1 RFC 8693 Section 2.1}
*
* @example "urn:ietf:params:oauth:token-type:access_token"
* @example "urn:ietf:params:oauth:token-type:refresh_token"
*/
requestedTokenType?: string;
}
/**
* Result returned from a token exchange via a Custom Token Exchange Profile (RFC 8693).
* Contains the exchanged tokens and metadata.
*/
interface TokenExchangeProfileResult {
/**
* The access token issued for the target backend API.
*/
accessToken: string;
/**
* The access token expiration time, represented in seconds since the Unix epoch.
*/
expiresAt: number;
/**
* The scope granted by Auth0 for the exchanged token.
*/
scope?: string;
/**
* ID token containing user identity claims (if requested via openid scope).
*/
idToken?: string;
/**
* Refresh token for obtaining new access tokens (if requested via offline_access scope).
*/
refreshToken?: string;
/**
* Token type (typically "Bearer").
*/
tokenType?: string;
/**
* RFC 8693 issued token type indicator (e.g., "urn:ietf:params:oauth:token-type:access_token").
*/
issuedTokenType?: string;
}
interface VerifyAccessTokenOptions {

@@ -95,5 +187,26 @@ /**

/**
* Verifies the provided access token.
* @param options Options used to verify the logout token.
* @returns
* Verifies the provided access token against the ApiClient's configured audience.
*
* This method validates the JWT signature using the Auth0 tenant's JWKS and verifies
* standard claims including issuer, expiration, and issued-at time. The audience claim
* is verified against the audience configured when constructing the ApiClient.
*
* @param options Options containing the access token and optional required claims.
* @returns Promise resolving to the verified token payload containing all JWT claims.
* @throws {VerifyAccessTokenError} When verification fails due to invalid signature,
* expired token, mismatched audience, or missing required claims.
*
* @example
* ```typescript
* const apiClient = new ApiClient({
* domain: 'example.auth0.com',
* audience: 'https://api.example.com', // This audience is used for verification
* clientId: 'client123',
* clientSecret: 'secret'
* });
*
* const payload = await apiClient.verifyAccessToken({
* accessToken: 'eyJhbGc...'
* });
* ```
*/

@@ -111,2 +224,35 @@ verifyAccessToken(options: VerifyAccessTokenOptions): Promise<jose.JWTPayload>;

getAccessTokenForConnection(options: AccessTokenForConnectionOptions): Promise<ConnectionTokenSet>;
/**
* Exchanges a token via a Custom Token Exchange Profile for a different API audience while preserving user identity (RFC 8693).
*
* This method supports **Custom Token Exchange** for custom token types via a configured Token Exchange Profile.
*
* For **Access Token Exchange with Token Vault** (external provider's access tokens), use {@link getAccessTokenForConnection} instead.
*
* **Note**: This method requires a confidential client (client credentials must be configured).
* While Custom Token Exchange Early Access technically permits public clients, this implementation
* currently requires client authentication. Public client support may be added in a future release.
*
* @param subjectToken - The raw token to be exchanged (without "Bearer " prefix)
* @param options - Configuration for the token exchange
*
* @returns A promise that resolves with the {@link TokenExchangeProfileResult}
*
* @throws {TokenExchangeError} When client credentials are not configured or exchange fails
*
* @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Documentation}
*
* @example
* ```typescript
* const result = await apiClient.getTokenByExchangeProfile(
* userToken,
* {
* subjectTokenType: 'urn:example:custom-token',
* audience: 'https://api.backend.com',
* scope: 'read:data write:data',
* }
* );
* ```
*/
getTokenByExchangeProfile(subjectToken: string, options: ExchangeProfileOptions): Promise<TokenExchangeProfileResult>;
}

@@ -342,2 +488,2 @@

export { type AccessTokenForConnectionOptions, ApiClient, type ApiClientOptions, BearerMethod, type ConnectionTokenSet, GrantType, type IProtectedResourceMetadata, InvalidRequestError, MissingRequiredArgumentError, MissingTransactionError, ProtectedResourceMetadataBuilder, SigningAlgorithm, VerifyAccessTokenError, type VerifyAccessTokenOptions, getToken };
export { type AccessTokenForConnectionOptions, ApiClient, type ApiClientOptions, BearerMethod, type ConnectionTokenSet, type ExchangeProfileOptions, GrantType, type IProtectedResourceMetadata, InvalidRequestError, MissingRequiredArgumentError, MissingTransactionError, ProtectedResourceMetadataBuilder, SigningAlgorithm, type TokenExchangeProfileResult, VerifyAccessTokenError, type VerifyAccessTokenOptions, getToken };
import * as jose from 'jose';
export { MissingClientAuthError, TokenExchangeError } from '@auth0/auth0-auth-js';

@@ -15,3 +16,3 @@ interface ApiClientOptions {

* The optional client ID of the application.
* Required when using the `getAccessTokenForConnection` method.
* Required when using the `getAccessTokenForConnection` or `getTokenByExchangeProfile` methods.
*/

@@ -21,3 +22,3 @@ clientId?: string;

* The optional client secret of the application.
* At least one of `clientSecret` or `clientAssertionSigningKey` is required when using the `getAccessTokenForConnection` method.
* At least one of `clientSecret` or `clientAssertionSigningKey` is required when using the `getAccessTokenForConnection` or `getTokenByExchangeProfile` methods.
*/

@@ -27,3 +28,3 @@ clientSecret?: string;

* The optional client assertion signing key to use.
* At least one of `clientSecret` or `clientAssertionSigningKey` is required when using the `getAccessTokenForConnection` method.
* At least one of `clientSecret` or `clientAssertionSigningKey` is required when using the `getAccessTokenForConnection` or `getTokenByExchangeProfile` methods.
*/

@@ -77,2 +78,93 @@ clientAssertionSigningKey?: string | CryptoKey;

}
/**
* Configuration options for exchanging a token via a Custom Token Exchange Profile (RFC 8693).
*
* This interface supports **Custom Token Exchange** for custom token types.
* Auth0 also supports **Access Token Exchange with Token Vault** for external provider's access tokens.
*
* @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Documentation}
* @see {@link https://auth0.com/docs/secure/tokens/token-vault/access-token-exchange-with-token-vault Token Vault Documentation}
*
* @example
* ```typescript
* const options: ExchangeProfileOptions = {
* subjectTokenType: 'urn:example:custom-token',
* audience: 'https://api.backend.com',
* scope: 'read:data write:data'
* };
* ```
*/
interface ExchangeProfileOptions {
/**
* URI identifying the type of the subject token being exchanged.
* Must match a `subject_token_type` configured in a Token Exchange Profile.
*
* For custom token types, this must be a URI scoped under your own ownership,
* such as http://acme.com/legacy-token or urn:acme:legacy-token.
*
* Reserved namespaces (cannot be used): http://auth0.com, https://auth0.com,
* http://okta.com, https://okta.com, urn:ietf, urn:auth0, urn:okta
*
* @example "urn:acme:legacy-token"
* @example "http://acme.com/mcp-token"
*/
subjectTokenType: string;
/**
* The audience (API identifier) for which tokens will be issued.
* Must match an API identifier configured in your Auth0 tenant.
*
* @example "https://api.backend.com"
*/
audience: string;
/**
* Space-separated list of OAuth 2.0 scopes to request for the exchanged token.
*
* @example "read:data write:data"
*/
scope?: string;
/**
* Type of token being requested (RFC 8693).
* Defaults to access_token if not specified.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc8693#section-2.1 RFC 8693 Section 2.1}
*
* @example "urn:ietf:params:oauth:token-type:access_token"
* @example "urn:ietf:params:oauth:token-type:refresh_token"
*/
requestedTokenType?: string;
}
/**
* Result returned from a token exchange via a Custom Token Exchange Profile (RFC 8693).
* Contains the exchanged tokens and metadata.
*/
interface TokenExchangeProfileResult {
/**
* The access token issued for the target backend API.
*/
accessToken: string;
/**
* The access token expiration time, represented in seconds since the Unix epoch.
*/
expiresAt: number;
/**
* The scope granted by Auth0 for the exchanged token.
*/
scope?: string;
/**
* ID token containing user identity claims (if requested via openid scope).
*/
idToken?: string;
/**
* Refresh token for obtaining new access tokens (if requested via offline_access scope).
*/
refreshToken?: string;
/**
* Token type (typically "Bearer").
*/
tokenType?: string;
/**
* RFC 8693 issued token type indicator (e.g., "urn:ietf:params:oauth:token-type:access_token").
*/
issuedTokenType?: string;
}
interface VerifyAccessTokenOptions {

@@ -95,5 +187,26 @@ /**

/**
* Verifies the provided access token.
* @param options Options used to verify the logout token.
* @returns
* Verifies the provided access token against the ApiClient's configured audience.
*
* This method validates the JWT signature using the Auth0 tenant's JWKS and verifies
* standard claims including issuer, expiration, and issued-at time. The audience claim
* is verified against the audience configured when constructing the ApiClient.
*
* @param options Options containing the access token and optional required claims.
* @returns Promise resolving to the verified token payload containing all JWT claims.
* @throws {VerifyAccessTokenError} When verification fails due to invalid signature,
* expired token, mismatched audience, or missing required claims.
*
* @example
* ```typescript
* const apiClient = new ApiClient({
* domain: 'example.auth0.com',
* audience: 'https://api.example.com', // This audience is used for verification
* clientId: 'client123',
* clientSecret: 'secret'
* });
*
* const payload = await apiClient.verifyAccessToken({
* accessToken: 'eyJhbGc...'
* });
* ```
*/

@@ -111,2 +224,35 @@ verifyAccessToken(options: VerifyAccessTokenOptions): Promise<jose.JWTPayload>;

getAccessTokenForConnection(options: AccessTokenForConnectionOptions): Promise<ConnectionTokenSet>;
/**
* Exchanges a token via a Custom Token Exchange Profile for a different API audience while preserving user identity (RFC 8693).
*
* This method supports **Custom Token Exchange** for custom token types via a configured Token Exchange Profile.
*
* For **Access Token Exchange with Token Vault** (external provider's access tokens), use {@link getAccessTokenForConnection} instead.
*
* **Note**: This method requires a confidential client (client credentials must be configured).
* While Custom Token Exchange Early Access technically permits public clients, this implementation
* currently requires client authentication. Public client support may be added in a future release.
*
* @param subjectToken - The raw token to be exchanged (without "Bearer " prefix)
* @param options - Configuration for the token exchange
*
* @returns A promise that resolves with the {@link TokenExchangeProfileResult}
*
* @throws {TokenExchangeError} When client credentials are not configured or exchange fails
*
* @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Documentation}
*
* @example
* ```typescript
* const result = await apiClient.getTokenByExchangeProfile(
* userToken,
* {
* subjectTokenType: 'urn:example:custom-token',
* audience: 'https://api.backend.com',
* scope: 'read:data write:data',
* }
* );
* ```
*/
getTokenByExchangeProfile(subjectToken: string, options: ExchangeProfileOptions): Promise<TokenExchangeProfileResult>;
}

@@ -342,2 +488,2 @@

export { type AccessTokenForConnectionOptions, ApiClient, type ApiClientOptions, BearerMethod, type ConnectionTokenSet, GrantType, type IProtectedResourceMetadata, InvalidRequestError, MissingRequiredArgumentError, MissingTransactionError, ProtectedResourceMetadataBuilder, SigningAlgorithm, VerifyAccessTokenError, type VerifyAccessTokenOptions, getToken };
export { type AccessTokenForConnectionOptions, ApiClient, type ApiClientOptions, BearerMethod, type ConnectionTokenSet, type ExchangeProfileOptions, GrantType, type IProtectedResourceMetadata, InvalidRequestError, MissingRequiredArgumentError, MissingTransactionError, ProtectedResourceMetadataBuilder, SigningAlgorithm, type TokenExchangeProfileResult, VerifyAccessTokenError, type VerifyAccessTokenOptions, getToken };
// src/api-client.ts
import * as oauth from "oauth4webapi";
import { createRemoteJWKSet, jwtVerify, customFetch as customFetch2 } from "jose";
import { AuthClient, TokenForConnectionError } from "@auth0/auth0-auth-js";
import { AuthClient, TokenForConnectionError, MissingClientAuthError } from "@auth0/auth0-auth-js";

@@ -80,5 +80,26 @@ // src/errors.ts

/**
* Verifies the provided access token.
* @param options Options used to verify the logout token.
* @returns
* Verifies the provided access token against the ApiClient's configured audience.
*
* This method validates the JWT signature using the Auth0 tenant's JWKS and verifies
* standard claims including issuer, expiration, and issued-at time. The audience claim
* is verified against the audience configured when constructing the ApiClient.
*
* @param options Options containing the access token and optional required claims.
* @returns Promise resolving to the verified token payload containing all JWT claims.
* @throws {VerifyAccessTokenError} When verification fails due to invalid signature,
* expired token, mismatched audience, or missing required claims.
*
* @example
* ```typescript
* const apiClient = new ApiClient({
* domain: 'example.auth0.com',
* audience: 'https://api.example.com', // This audience is used for verification
* clientId: 'client123',
* clientSecret: 'secret'
* });
*
* const payload = await apiClient.verifyAccessToken({
* accessToken: 'eyJhbGc...'
* });
* ```
*/

@@ -130,2 +151,55 @@ async verifyAccessToken(options) {

}
/**
* Exchanges a token via a Custom Token Exchange Profile for a different API audience while preserving user identity (RFC 8693).
*
* This method supports **Custom Token Exchange** for custom token types via a configured Token Exchange Profile.
*
* For **Access Token Exchange with Token Vault** (external provider's access tokens), use {@link getAccessTokenForConnection} instead.
*
* **Note**: This method requires a confidential client (client credentials must be configured).
* While Custom Token Exchange Early Access technically permits public clients, this implementation
* currently requires client authentication. Public client support may be added in a future release.
*
* @param subjectToken - The raw token to be exchanged (without "Bearer " prefix)
* @param options - Configuration for the token exchange
*
* @returns A promise that resolves with the {@link TokenExchangeProfileResult}
*
* @throws {TokenExchangeError} When client credentials are not configured or exchange fails
*
* @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Documentation}
*
* @example
* ```typescript
* const result = await apiClient.getTokenByExchangeProfile(
* userToken,
* {
* subjectTokenType: 'urn:example:custom-token',
* audience: 'https://api.backend.com',
* scope: 'read:data write:data',
* }
* );
* ```
*/
async getTokenByExchangeProfile(subjectToken, options) {
if (!this.#authClient) {
throw new MissingClientAuthError();
}
const response = await this.#authClient.exchangeToken({
subjectTokenType: options.subjectTokenType,
subjectToken,
audience: options.audience,
scope: options.scope,
requestedTokenType: options.requestedTokenType
});
return {
accessToken: response.accessToken,
expiresAt: response.expiresAt,
...response.scope && { scope: response.scope },
...response.idToken && { idToken: response.idToken },
...response.refreshToken && { refreshToken: response.refreshToken },
...response.tokenType && { tokenType: response.tokenType },
...response.issuedTokenType && { issuedTokenType: response.issuedTokenType }
};
}
};

@@ -397,2 +471,8 @@

}
// src/index.ts
import {
MissingClientAuthError as MissingClientAuthError2,
TokenExchangeError
} from "@auth0/auth0-auth-js";
export {

@@ -403,2 +483,3 @@ ApiClient,

InvalidRequestError,
MissingClientAuthError2 as MissingClientAuthError,
MissingRequiredArgumentError,

@@ -408,2 +489,3 @@ MissingTransactionError,

SigningAlgorithm,
TokenExchangeError,
VerifyAccessTokenError,

@@ -410,0 +492,0 @@ getToken

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/api-client.ts","../src/errors.ts","../src/protected-resource-metadata.ts","../src/token.ts"],"sourcesContent":["import * as oauth from 'oauth4webapi';\nimport { createRemoteJWKSet, jwtVerify, customFetch } from 'jose';\nimport { AuthClient, TokenForConnectionError } from '@auth0/auth0-auth-js';\nimport { AccessTokenForConnectionOptions, ApiClientOptions, ConnectionTokenSet, VerifyAccessTokenOptions } from './types.js';\nimport {\n MissingRequiredArgumentError,\n VerifyAccessTokenError,\n} from './errors.js';\n\nexport class ApiClient {\n #serverMetadata: oauth.AuthorizationServer | undefined;\n readonly #options: ApiClientOptions;\n #jwks?: ReturnType<typeof createRemoteJWKSet>;\n readonly #authClient: AuthClient | undefined;\n\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n if (options.clientId) {\n this.#authClient = new AuthClient({\n domain: options.domain,\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n clientAssertionSigningKey: options.clientAssertionSigningKey,\n clientAssertionSigningAlg: options.clientAssertionSigningAlg,\n customFetch: options.customFetch,\n });\n }\n\n if (!this.#options.audience) {\n throw new MissingRequiredArgumentError('audience');\n }\n }\n\n /**\n * Initialized the SDK by performing Metadata Discovery.\n */\n async #discover() {\n if (this.#serverMetadata) {\n return {\n serverMetadata: this.#serverMetadata,\n };\n }\n\n const issuer = new URL(`https://${this.#options.domain}`);\n const response = await oauth.discoveryRequest(issuer, {\n [oauth.customFetch]: this.#options.customFetch,\n });\n\n this.#serverMetadata = await oauth.processDiscoveryResponse(\n issuer,\n response\n );\n\n return {\n serverMetadata: this.#serverMetadata,\n };\n }\n\n /**\n * Verifies the provided access token.\n * @param options Options used to verify the logout token.\n * @returns\n */\n async verifyAccessToken(options: VerifyAccessTokenOptions) {\n const { serverMetadata } = await this.#discover();\n\n this.#jwks ||= createRemoteJWKSet(new URL(serverMetadata!.jwks_uri!), {\n [customFetch]: this.#options.customFetch,\n });\n\n try {\n const { payload } = await jwtVerify(options.accessToken, this.#jwks, {\n issuer: this.#serverMetadata!.issuer,\n audience: this.#options.audience,\n algorithms: ['RS256'],\n requiredClaims: ['iat', 'exp', ...(options.requiredClaims || [])],\n });\n return payload;\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n throw new VerifyAccessTokenError((e as any).message);\n }\n }\n\n /**\n * Retrieves an access token for a connection.\n *\n * @param options - Options for retrieving an access token for a connection.\n *\n * @throws {TokenForConnectionError} If there was an issue requesting the access token.\n *\n * @returns The Connection Token Set, containing the access token for the connection, as well as additional information.\n */\n public async getAccessTokenForConnection(options: AccessTokenForConnectionOptions): Promise<ConnectionTokenSet> {\n if (!this.#authClient) {\n throw new TokenForConnectionError(\n 'Client credentials are required to use getAccessTokenForConnection'\n );\n }\n\n const tokenEndpointResponse = await this.#authClient.getTokenForConnection({\n connection: options.connection,\n loginHint: options.loginHint,\n accessToken: options.accessToken,\n });\n\n return {\n accessToken: tokenEndpointResponse.accessToken,\n scope: tokenEndpointResponse.scope,\n expiresAt: tokenEndpointResponse.expiresAt,\n connection: options.connection,\n loginHint: options.loginHint,\n };\n }\n}\n","/**\n * Error thrown when the transaction is missing.\n */\nexport class MissingTransactionError extends Error {\n public code: string = 'missing_transaction_error';\n\n constructor(message?: string) {\n super(message ?? 'The transaction is missing.');\n this.name = 'MissingTransactionError';\n }\n}\n\n/**\n * Error thrown when verifying the access token.\n */\nexport class VerifyAccessTokenError extends Error {\n public code: string = 'verify_access_token_error';\n\n constructor(message: string) {\n super(message);\n this.name = 'VerifyAccessTokenError';\n }\n}\n\n/**\n * Error thrown when request is missing a valid token or\n * multiple auth methods used\n */\nexport class InvalidRequestError extends Error {\n public code: string = 'invalid_request';\n\n constructor(message: string) {\n super(message);\n this.name = 'InvalidRequestError';\n }\n}\n\n/**\n * Error thrown when a required argument is missing.\n */\nexport class MissingRequiredArgumentError extends Error {\n public code: string = 'missing_required_argument_error';\n\n constructor(argument: string) {\n super(`The argument '${argument}' is required but was not provided.`);\n this.name = 'MissingRequiredArgumentError';\n }\n}\n","/**\n * RFC 9728 - OAuth 2.0 Protected Resource Metadata\n * https://datatracker.ietf.org/doc/html/rfc9728\n */\n\nimport { MissingRequiredArgumentError } from \"./errors.js\";\n\n/**\n * Supported methods of sending an OAuth 2.0 bearer token\n */\nexport enum BearerMethod {\n HEADER = \"header\",\n BODY = \"body\",\n QUERY = \"query\",\n}\n\n/**\n * Supported signing algorithms\n */\nexport enum SigningAlgorithm {\n RS256 = \"RS256\",\n RS384 = \"RS384\",\n RS512 = \"RS512\",\n ES256 = \"ES256\",\n ES384 = \"ES384\",\n ES512 = \"ES512\",\n PS256 = \"PS256\",\n PS384 = \"PS384\",\n PS512 = \"PS512\",\n HS256 = \"HS256\",\n HS384 = \"HS384\",\n HS512 = \"HS512\",\n}\n\n/**\n * Grant types supported\n */\nexport enum GrantType {\n AUTHORIZATION_CODE = \"authorization_code\",\n IMPLICIT = \"implicit\",\n PASSWORD = \"password\",\n CLIENT_CREDENTIALS = \"client_credentials\",\n REFRESH_TOKEN = \"refresh_token\",\n JWT_BEARER = \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n SAML2_BEARER = \"urn:ietf:params:oauth:grant-type:saml2-bearer\",\n DEVICE_CODE = \"urn:ietf:params:oauth:grant-type:device_code\",\n}\n\n/**\n * Interface for Protected Resource Metadata\n */\nexport interface IProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n jwks_uri?: string;\n scopes_supported?: string[];\n bearer_methods_supported?: BearerMethod[];\n resource_signing_alg_values_supported?: SigningAlgorithm[];\n resource_name?: string;\n resource_documentation?: string;\n resource_policy_uri?: string;\n resource_tos_uri?: string;\n tls_client_certificate_bound_access_tokens?: boolean;\n authorization_details_types_supported?: string[];\n dpop_signing_alg_values_supported?: string[];\n dpop_bound_access_tokens_required?: boolean;\n}\n\n/**\n * Builder for creating a ProtectedResourceMetadata instance\n *\n * @example\n * ```typescript\n * const metadata = new ProtectedResourceMetadataBuilder('https://api.example.com', ['https://auth.example.com'])\n * .withJwksUri('https://api.example.com/.well-known/jwks.json')\n * .withScopesSupported(['read', 'write'])\n * .build();\n * // serialize to json\n * const json = metadata.toJSON();\n * ```\n */\nexport class ProtectedResourceMetadataBuilder {\n private readonly props: Partial<IProtectedResourceMetadata> &\n Pick<IProtectedResourceMetadata, \"resource\" | \"authorization_servers\">;\n\n /**\n * Constructor for the builder\n * @param resource - The protected resource identifier (REQUIRED)\n * @param authorization_servers - Array of authorization server URLs (REQUIRED)\n */\n constructor(resource: string, authorization_servers: string[]) {\n if (!resource?.trim()) {\n throw new MissingRequiredArgumentError(\"resource\");\n }\n if (\n !Array.isArray(authorization_servers) ||\n authorization_servers.length === 0\n ) {\n throw new MissingRequiredArgumentError(\"authorization_servers\");\n }\n this.props = { resource, authorization_servers };\n }\n\n get properties(): IProtectedResourceMetadata {\n return this.props;\n }\n\n /**\n * Builds the ProtectedResourceMetadata\n */\n public build() {\n return new ProtectedResourceMetadata(this);\n }\n\n /**\n * Builder method to add JWKS URI\n */\n withJwksUri(jwks_uri: string): this {\n this.props.jwks_uri = jwks_uri;\n return this;\n }\n\n /**\n * Builder method to add supported scopes\n */\n withScopesSupported(scopes_supported: string[]): this {\n this.props.scopes_supported = [...scopes_supported];\n return this;\n }\n\n /**\n * Builder method to add supported bearer methods\n */\n withBearerMethodsSupported(\n bearer_methods_supported: BearerMethod[]\n ): this {\n this.props.bearer_methods_supported = [...bearer_methods_supported];\n return this;\n }\n\n /**\n * Builder method to add supported resource signing algorithms\n */\n withResourceSigningAlgValuesSupported(\n resource_signing_alg_values_supported: SigningAlgorithm[]\n ): this {\n this.props.resource_signing_alg_values_supported = [...resource_signing_alg_values_supported];\n return this;\n }\n\n /**\n * Builder method to add resource_name\n */\n withResourceName(resource_name: string): this {\n this.props.resource_name = resource_name;\n return this;\n }\n\n /**\n * Builder method to add resource documentation URL\n */\n withResourceDocumentation(resource_documentation: string): this {\n this.props.resource_documentation = resource_documentation;\n return this;\n }\n\n /**\n * Builder method to add resource policy URI\n */\n withResourcePolicyUri(resource_policy_uri: string): this {\n this.props.resource_policy_uri = resource_policy_uri;\n return this;\n }\n\n /**\n * Builder method to add resource terms of service URI\n */\n withResourceTosUri(resource_tos_uri: string): this {\n this.props.resource_tos_uri = resource_tos_uri;\n return this;\n }\n\n /**\n * Builder method to enable TLS client certificate bound access tokens\n */\n withTlsClientCertificateBoundAccessTokens(tls_client_certificate_bound_access_tokens: boolean): this {\n this.props.tls_client_certificate_bound_access_tokens = tls_client_certificate_bound_access_tokens;\n return this;\n }\n\n /**\n * Builder method to add supported authorization details types\n */\n withAuthorizationDetailsTypesSupported(authorization_details_types_supported: string[]): this {\n this.props.authorization_details_types_supported = [...authorization_details_types_supported];\n return this;\n }\n\n /**\n * Builder method to add supported DPoP signing algorithms\n */\n withDpopSigningAlgValuesSupported(dpop_signing_alg_values_supported: string[]): this {\n this.props.dpop_signing_alg_values_supported = [...dpop_signing_alg_values_supported];\n return this;\n }\n\n /**\n * Builder method to require DPoP bound access tokens\n */\n withDpopBoundAccessTokensRequired(dpop_bound_access_tokens_required: boolean): this {\n this.props.dpop_bound_access_tokens_required = dpop_bound_access_tokens_required;\n return this;\n }\n\n\n}\n\nclass ProtectedResourceMetadata {\n readonly #resource: string;\n readonly #authorization_servers: string[];\n readonly #jwks_uri?: string;\n readonly #scopes_supported?: string[];\n readonly #bearer_methods_supported?: BearerMethod[];\n readonly #resource_signing_alg_values_supported?: SigningAlgorithm[];\n readonly #resource_documentation?: string;\n readonly #resource_policy_uri?: string;\n readonly #resource_tos_uri?: string;\n readonly #resource_name?: string;\n readonly #tls_client_certificate_bound_access_tokens?: boolean;\n readonly #authorization_details_types_supported?: string[];\n readonly #dpop_signing_alg_values_supported?: string[];\n readonly #dpop_bound_access_tokens_required?: boolean;\n\n constructor(builder: ProtectedResourceMetadataBuilder) {\n const props = builder.properties;\n this.#resource = props.resource;\n this.#authorization_servers = [...props.authorization_servers];\n this.#jwks_uri = props.jwks_uri;\n this.#scopes_supported = props.scopes_supported\n ? [...props.scopes_supported]\n : undefined;\n this.#bearer_methods_supported = props.bearer_methods_supported\n ? [...props.bearer_methods_supported]\n : undefined;\n this.#resource_signing_alg_values_supported = props.resource_signing_alg_values_supported\n ? [...props.resource_signing_alg_values_supported]\n : undefined;\n this.#resource_documentation = props.resource_documentation;\n this.#resource_policy_uri = props.resource_policy_uri;\n this.#resource_tos_uri = props.resource_tos_uri;\n this.#resource_name = props.resource_name;\n this.#tls_client_certificate_bound_access_tokens = props.tls_client_certificate_bound_access_tokens;\n this.#authorization_details_types_supported = props.authorization_details_types_supported\n ? [...props.authorization_details_types_supported]\n : undefined;\n this.#dpop_signing_alg_values_supported = props.dpop_signing_alg_values_supported\n ? [...props.dpop_signing_alg_values_supported]\n : undefined;\n this.#dpop_bound_access_tokens_required = props.dpop_bound_access_tokens_required;\n }\n\n /**\n * Convert to JSON representation\n */\n public toJSON(): IProtectedResourceMetadata {\n return {\n resource: this.#resource,\n authorization_servers: [...this.#authorization_servers],\n\n ...(this.#jwks_uri !== undefined && { jwks_uri: this.#jwks_uri }),\n ...(this.#scopes_supported !== undefined && {\n scopes_supported: [...this.#scopes_supported],\n }),\n ...(this.#bearer_methods_supported !== undefined && {\n bearer_methods_supported: [...this.#bearer_methods_supported],\n }),\n ...(this.#resource_signing_alg_values_supported !== undefined && {\n resource_signing_alg_values_supported: [...this.#resource_signing_alg_values_supported],\n }),\n ...(this.#resource_documentation !== undefined && {\n resource_documentation: this.#resource_documentation,\n }),\n ...(this.#resource_policy_uri !== undefined && {\n resource_policy_uri: this.#resource_policy_uri,\n }),\n ...(this.#resource_tos_uri !== undefined && {\n resource_tos_uri: this.#resource_tos_uri,\n }),\n ...(this.#resource_name !== undefined && {\n resource_name: this.#resource_name,\n }),\n ...(this.#tls_client_certificate_bound_access_tokens !== undefined && {\n tls_client_certificate_bound_access_tokens: this.#tls_client_certificate_bound_access_tokens,\n }),\n ...(this.#authorization_details_types_supported !== undefined && {\n authorization_details_types_supported: [...this.#authorization_details_types_supported],\n }),\n ...(this.#dpop_signing_alg_values_supported !== undefined && {\n dpop_signing_alg_values_supported: [...this.#dpop_signing_alg_values_supported],\n }),\n ...(this.#dpop_bound_access_tokens_required !== undefined && {\n dpop_bound_access_tokens_required: this.#dpop_bound_access_tokens_required,\n }),\n };\n }\n}\n","import { InvalidRequestError } from './errors.js';\n/**\n * Header-like object that can represent headers from different HTTP frameworks\n */\ntype HeadersLike = Record<string, unknown> & {\n authorization?: string;\n 'content-type'?: string;\n};\n\n/**\n * Query-like object for URL query parameters\n */\ntype QueryLike = Record<string, unknown> & { access_token?: string };\n\n/**\n * Body-like object for form-encoded request body\n */\ntype BodyLike = QueryLike;\n\n/**\n * Regular expression to match Bearer token in Authorization header\n */\nconst TOKEN_RE = /^Bearer (.+)$/i;\n\n/**\n * Extracts a Bearer token from HTTP request according to RFC 6750.\n * Supports all three methods defined in the RFC:\n * - Authorization header (Section 2.1)\n * - Form-encoded body parameter (Section 2.2)\n * - URI query parameter (Section 2.3)\n *\n * @param headers - HTTP headers object\n * @param query - Query parameters object (optional)\n * @param body - Request body object (optional)\n * @returns The extracted token string\n * @throws {InvalidRequestError} When no token is found or multiple methods are used\n *\n * @example\n * ```typescript\n * // Authorization header method (recommended)\n * const token1 = getToken({ authorization: 'Bearer mF_9.B5f-4.1JqM' });\n *\n * // Query parameter method\n * const token2 = getToken({}, { access_token: 'mF_9.B5f-4.1JqM' });\n *\n * // Form body method\n * const token3 = getToken(\n * { 'content-type': 'application/x-www-form-urlencoded' },\n * {},\n * { access_token: 'mF_9.B5f-4.1JqM' }\n * );\n *\n * // Express.js usage\n * const token4 = getToken(req.headers, req.query, req.body);\n * ```\n *\n * @see https://datatracker.ietf.org/doc/html/rfc6750#section-2 - RFC 6750 Section 2\n */\nexport function getToken(\n headers: HeadersLike,\n query?: QueryLike,\n body?: BodyLike\n): string {\n const fromHeader = getTokenFromHeader(headers);\n const fromQuery = getTokenFromQuery(query);\n const fromBody = getTokenFromBody(headers, body);\n\n if (!fromQuery && !fromHeader && !fromBody) {\n throw new InvalidRequestError('No Bearer token found in request');\n }\n\n // If multiple methods are used, throw an error\n if (+!!fromQuery + +!!fromBody + +!!fromHeader > 1) {\n throw new InvalidRequestError(\n 'More than one method used for authentication'\n );\n }\n\n return (fromQuery || fromBody || fromHeader) as string;\n}\n\n/**\n * Extract token from Authorization header\n */\nfunction getTokenFromHeader(headers: HeadersLike) {\n const authHeader = headers.authorization;\n if (typeof authHeader !== 'string') {\n return undefined;\n }\n\n const match = authHeader.match(TOKEN_RE);\n return match?.[1];\n}\n\n/**\n * Extract token from query parameters\n */\nfunction getTokenFromQuery(query?: QueryLike): string | undefined {\n const accessToken = query?.access_token;\n if (typeof accessToken === 'string') {\n return accessToken;\n }\n}\n\n/**\n * Extract token from form-encoded body\n */\nfunction getTokenFromBody(\n headers: HeadersLike,\n body?: BodyLike\n): string | undefined {\n if (!body || typeof body.access_token !== 'string') {\n return undefined;\n }\n\n const contentType = headers['content-type'];\n if (!contentType) {\n return undefined;\n }\n\n // Handle content-type with charset, e.g., \"application/x-www-form-urlencoded; charset=utf-8\"\n const isFormEncoded = contentType\n .toLowerCase()\n .includes('application/x-www-form-urlencoded');\n if (!isFormEncoded) {\n return undefined;\n }\n\n return body.access_token;\n}\n"],"mappings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,WAAW,CAAC,CAAC,CAAC,aAAa,GAAG;AAClD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAQ,aAAa,YAAY;AACnC;AAKA,SAAS,mBAAmB,SAAsB;AAChD,QAAM,aAAa,QAAQ;AAC3B,MAAI,OAAO,eAAe,UAAU;AAClC,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,WAAW,MAAM,QAAQ;AACvC,SAAO,QAAQ,CAAC;AAClB;AAKA,SAAS,kBAAkB,OAAuC;AAChE,QAAM,cAAc,OAAO;AAC3B,MAAI,OAAO,gBAAgB,UAAU;AACnC,WAAO;AAAA,EACT;AACF;AAKA,SAAS,iBACP,SACA,MACoB;AACpB,MAAI,CAAC,QAAQ,OAAO,KAAK,iBAAiB,UAAU;AAClD,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,QAAQ,cAAc;AAC1C,MAAI,CAAC,aAAa;AAChB,WAAO;AAAA,EACT;AAGA,QAAM,gBAAgB,YACnB,YAAY,EACZ,SAAS,mCAAmC;AAC/C,MAAI,CAAC,eAAe;AAClB,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AACd;","names":["customFetch","customFetch","BearerMethod","SigningAlgorithm","GrantType"]}
{"version":3,"sources":["../src/api-client.ts","../src/errors.ts","../src/protected-resource-metadata.ts","../src/token.ts","../src/index.ts"],"sourcesContent":["import * as oauth from 'oauth4webapi';\nimport { createRemoteJWKSet, jwtVerify, customFetch } from 'jose';\nimport { AuthClient, TokenForConnectionError, MissingClientAuthError } from '@auth0/auth0-auth-js';\nimport { AccessTokenForConnectionOptions, ApiClientOptions, ConnectionTokenSet, ExchangeProfileOptions, TokenExchangeProfileResult, VerifyAccessTokenOptions } from './types.js';\nimport {\n MissingRequiredArgumentError,\n VerifyAccessTokenError,\n} from './errors.js';\n\nexport class ApiClient {\n #serverMetadata: oauth.AuthorizationServer | undefined;\n readonly #options: ApiClientOptions;\n #jwks?: ReturnType<typeof createRemoteJWKSet>;\n readonly #authClient: AuthClient | undefined;\n\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n if (options.clientId) {\n this.#authClient = new AuthClient({\n domain: options.domain,\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n clientAssertionSigningKey: options.clientAssertionSigningKey,\n clientAssertionSigningAlg: options.clientAssertionSigningAlg,\n customFetch: options.customFetch,\n });\n }\n\n if (!this.#options.audience) {\n throw new MissingRequiredArgumentError('audience');\n }\n }\n\n /**\n * Initialized the SDK by performing Metadata Discovery.\n */\n async #discover() {\n if (this.#serverMetadata) {\n return {\n serverMetadata: this.#serverMetadata,\n };\n }\n\n const issuer = new URL(`https://${this.#options.domain}`);\n const response = await oauth.discoveryRequest(issuer, {\n [oauth.customFetch]: this.#options.customFetch,\n });\n\n this.#serverMetadata = await oauth.processDiscoveryResponse(\n issuer,\n response\n );\n\n return {\n serverMetadata: this.#serverMetadata,\n };\n }\n\n /**\n * Verifies the provided access token against the ApiClient's configured audience.\n *\n * This method validates the JWT signature using the Auth0 tenant's JWKS and verifies\n * standard claims including issuer, expiration, and issued-at time. The audience claim\n * is verified against the audience configured when constructing the ApiClient.\n *\n * @param options Options containing the access token and optional required claims.\n * @returns Promise resolving to the verified token payload containing all JWT claims.\n * @throws {VerifyAccessTokenError} When verification fails due to invalid signature,\n * expired token, mismatched audience, or missing required claims.\n *\n * @example\n * ```typescript\n * const apiClient = new ApiClient({\n * domain: 'example.auth0.com',\n * audience: 'https://api.example.com', // This audience is used for verification\n * clientId: 'client123',\n * clientSecret: 'secret'\n * });\n *\n * const payload = await apiClient.verifyAccessToken({\n * accessToken: 'eyJhbGc...'\n * });\n * ```\n */\n async verifyAccessToken(options: VerifyAccessTokenOptions) {\n const { serverMetadata } = await this.#discover();\n\n this.#jwks ||= createRemoteJWKSet(new URL(serverMetadata!.jwks_uri!), {\n [customFetch]: this.#options.customFetch,\n });\n\n try {\n const { payload } = await jwtVerify(options.accessToken, this.#jwks, {\n issuer: this.#serverMetadata!.issuer,\n audience: this.#options.audience,\n algorithms: ['RS256'],\n requiredClaims: ['iat', 'exp', ...(options.requiredClaims || [])],\n });\n return payload;\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n throw new VerifyAccessTokenError((e as any).message);\n }\n }\n\n /**\n * Retrieves an access token for a connection.\n *\n * @param options - Options for retrieving an access token for a connection.\n *\n * @throws {TokenForConnectionError} If there was an issue requesting the access token.\n *\n * @returns The Connection Token Set, containing the access token for the connection, as well as additional information.\n */\n public async getAccessTokenForConnection(options: AccessTokenForConnectionOptions): Promise<ConnectionTokenSet> {\n if (!this.#authClient) {\n throw new TokenForConnectionError(\n 'Client credentials are required to use getAccessTokenForConnection'\n );\n }\n\n const tokenEndpointResponse = await this.#authClient.getTokenForConnection({\n connection: options.connection,\n loginHint: options.loginHint,\n accessToken: options.accessToken,\n });\n\n return {\n accessToken: tokenEndpointResponse.accessToken,\n scope: tokenEndpointResponse.scope,\n expiresAt: tokenEndpointResponse.expiresAt,\n connection: options.connection,\n loginHint: options.loginHint,\n };\n }\n\n /**\n * Exchanges a token via a Custom Token Exchange Profile for a different API audience while preserving user identity (RFC 8693).\n *\n * This method supports **Custom Token Exchange** for custom token types via a configured Token Exchange Profile.\n *\n * For **Access Token Exchange with Token Vault** (external provider's access tokens), use {@link getAccessTokenForConnection} instead.\n *\n * **Note**: This method requires a confidential client (client credentials must be configured).\n * While Custom Token Exchange Early Access technically permits public clients, this implementation\n * currently requires client authentication. Public client support may be added in a future release.\n *\n * @param subjectToken - The raw token to be exchanged (without \"Bearer \" prefix)\n * @param options - Configuration for the token exchange\n *\n * @returns A promise that resolves with the {@link TokenExchangeProfileResult}\n *\n * @throws {TokenExchangeError} When client credentials are not configured or exchange fails\n *\n * @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Documentation}\n *\n * @example\n * ```typescript\n * const result = await apiClient.getTokenByExchangeProfile(\n * userToken,\n * {\n * subjectTokenType: 'urn:example:custom-token',\n * audience: 'https://api.backend.com',\n * scope: 'read:data write:data',\n * }\n * );\n * ```\n */\n public async getTokenByExchangeProfile(\n subjectToken: string,\n options: ExchangeProfileOptions\n ): Promise<TokenExchangeProfileResult> {\n if (!this.#authClient) {\n throw new MissingClientAuthError();\n }\n\n const response = await this.#authClient.exchangeToken({\n subjectTokenType: options.subjectTokenType,\n subjectToken,\n audience: options.audience,\n scope: options.scope,\n requestedTokenType: options.requestedTokenType,\n });\n\n return {\n accessToken: response.accessToken,\n expiresAt: response.expiresAt,\n ...(response.scope && { scope: response.scope }),\n ...(response.idToken && { idToken: response.idToken }),\n ...(response.refreshToken && { refreshToken: response.refreshToken }),\n ...(response.tokenType && { tokenType: response.tokenType }),\n ...(response.issuedTokenType && { issuedTokenType: response.issuedTokenType }),\n };\n }\n}\n","/**\n * Error thrown when the transaction is missing.\n */\nexport class MissingTransactionError extends Error {\n public code: string = 'missing_transaction_error';\n\n constructor(message?: string) {\n super(message ?? 'The transaction is missing.');\n this.name = 'MissingTransactionError';\n }\n}\n\n/**\n * Error thrown when verifying the access token.\n */\nexport class VerifyAccessTokenError extends Error {\n public code: string = 'verify_access_token_error';\n\n constructor(message: string) {\n super(message);\n this.name = 'VerifyAccessTokenError';\n }\n}\n\n/**\n * Error thrown when request is missing a valid token or\n * multiple auth methods used\n */\nexport class InvalidRequestError extends Error {\n public code: string = 'invalid_request';\n\n constructor(message: string) {\n super(message);\n this.name = 'InvalidRequestError';\n }\n}\n\n/**\n * Error thrown when a required argument is missing.\n */\nexport class MissingRequiredArgumentError extends Error {\n public code: string = 'missing_required_argument_error';\n\n constructor(argument: string) {\n super(`The argument '${argument}' is required but was not provided.`);\n this.name = 'MissingRequiredArgumentError';\n }\n}\n","/**\n * RFC 9728 - OAuth 2.0 Protected Resource Metadata\n * https://datatracker.ietf.org/doc/html/rfc9728\n */\n\nimport { MissingRequiredArgumentError } from \"./errors.js\";\n\n/**\n * Supported methods of sending an OAuth 2.0 bearer token\n */\nexport enum BearerMethod {\n HEADER = \"header\",\n BODY = \"body\",\n QUERY = \"query\",\n}\n\n/**\n * Supported signing algorithms\n */\nexport enum SigningAlgorithm {\n RS256 = \"RS256\",\n RS384 = \"RS384\",\n RS512 = \"RS512\",\n ES256 = \"ES256\",\n ES384 = \"ES384\",\n ES512 = \"ES512\",\n PS256 = \"PS256\",\n PS384 = \"PS384\",\n PS512 = \"PS512\",\n HS256 = \"HS256\",\n HS384 = \"HS384\",\n HS512 = \"HS512\",\n}\n\n/**\n * Grant types supported\n */\nexport enum GrantType {\n AUTHORIZATION_CODE = \"authorization_code\",\n IMPLICIT = \"implicit\",\n PASSWORD = \"password\",\n CLIENT_CREDENTIALS = \"client_credentials\",\n REFRESH_TOKEN = \"refresh_token\",\n JWT_BEARER = \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n SAML2_BEARER = \"urn:ietf:params:oauth:grant-type:saml2-bearer\",\n DEVICE_CODE = \"urn:ietf:params:oauth:grant-type:device_code\",\n}\n\n/**\n * Interface for Protected Resource Metadata\n */\nexport interface IProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n jwks_uri?: string;\n scopes_supported?: string[];\n bearer_methods_supported?: BearerMethod[];\n resource_signing_alg_values_supported?: SigningAlgorithm[];\n resource_name?: string;\n resource_documentation?: string;\n resource_policy_uri?: string;\n resource_tos_uri?: string;\n tls_client_certificate_bound_access_tokens?: boolean;\n authorization_details_types_supported?: string[];\n dpop_signing_alg_values_supported?: string[];\n dpop_bound_access_tokens_required?: boolean;\n}\n\n/**\n * Builder for creating a ProtectedResourceMetadata instance\n *\n * @example\n * ```typescript\n * const metadata = new ProtectedResourceMetadataBuilder('https://api.example.com', ['https://auth.example.com'])\n * .withJwksUri('https://api.example.com/.well-known/jwks.json')\n * .withScopesSupported(['read', 'write'])\n * .build();\n * // serialize to json\n * const json = metadata.toJSON();\n * ```\n */\nexport class ProtectedResourceMetadataBuilder {\n private readonly props: Partial<IProtectedResourceMetadata> &\n Pick<IProtectedResourceMetadata, \"resource\" | \"authorization_servers\">;\n\n /**\n * Constructor for the builder\n * @param resource - The protected resource identifier (REQUIRED)\n * @param authorization_servers - Array of authorization server URLs (REQUIRED)\n */\n constructor(resource: string, authorization_servers: string[]) {\n if (!resource?.trim()) {\n throw new MissingRequiredArgumentError(\"resource\");\n }\n if (\n !Array.isArray(authorization_servers) ||\n authorization_servers.length === 0\n ) {\n throw new MissingRequiredArgumentError(\"authorization_servers\");\n }\n this.props = { resource, authorization_servers };\n }\n\n get properties(): IProtectedResourceMetadata {\n return this.props;\n }\n\n /**\n * Builds the ProtectedResourceMetadata\n */\n public build() {\n return new ProtectedResourceMetadata(this);\n }\n\n /**\n * Builder method to add JWKS URI\n */\n withJwksUri(jwks_uri: string): this {\n this.props.jwks_uri = jwks_uri;\n return this;\n }\n\n /**\n * Builder method to add supported scopes\n */\n withScopesSupported(scopes_supported: string[]): this {\n this.props.scopes_supported = [...scopes_supported];\n return this;\n }\n\n /**\n * Builder method to add supported bearer methods\n */\n withBearerMethodsSupported(\n bearer_methods_supported: BearerMethod[]\n ): this {\n this.props.bearer_methods_supported = [...bearer_methods_supported];\n return this;\n }\n\n /**\n * Builder method to add supported resource signing algorithms\n */\n withResourceSigningAlgValuesSupported(\n resource_signing_alg_values_supported: SigningAlgorithm[]\n ): this {\n this.props.resource_signing_alg_values_supported = [...resource_signing_alg_values_supported];\n return this;\n }\n\n /**\n * Builder method to add resource_name\n */\n withResourceName(resource_name: string): this {\n this.props.resource_name = resource_name;\n return this;\n }\n\n /**\n * Builder method to add resource documentation URL\n */\n withResourceDocumentation(resource_documentation: string): this {\n this.props.resource_documentation = resource_documentation;\n return this;\n }\n\n /**\n * Builder method to add resource policy URI\n */\n withResourcePolicyUri(resource_policy_uri: string): this {\n this.props.resource_policy_uri = resource_policy_uri;\n return this;\n }\n\n /**\n * Builder method to add resource terms of service URI\n */\n withResourceTosUri(resource_tos_uri: string): this {\n this.props.resource_tos_uri = resource_tos_uri;\n return this;\n }\n\n /**\n * Builder method to enable TLS client certificate bound access tokens\n */\n withTlsClientCertificateBoundAccessTokens(tls_client_certificate_bound_access_tokens: boolean): this {\n this.props.tls_client_certificate_bound_access_tokens = tls_client_certificate_bound_access_tokens;\n return this;\n }\n\n /**\n * Builder method to add supported authorization details types\n */\n withAuthorizationDetailsTypesSupported(authorization_details_types_supported: string[]): this {\n this.props.authorization_details_types_supported = [...authorization_details_types_supported];\n return this;\n }\n\n /**\n * Builder method to add supported DPoP signing algorithms\n */\n withDpopSigningAlgValuesSupported(dpop_signing_alg_values_supported: string[]): this {\n this.props.dpop_signing_alg_values_supported = [...dpop_signing_alg_values_supported];\n return this;\n }\n\n /**\n * Builder method to require DPoP bound access tokens\n */\n withDpopBoundAccessTokensRequired(dpop_bound_access_tokens_required: boolean): this {\n this.props.dpop_bound_access_tokens_required = dpop_bound_access_tokens_required;\n return this;\n }\n\n\n}\n\nclass ProtectedResourceMetadata {\n readonly #resource: string;\n readonly #authorization_servers: string[];\n readonly #jwks_uri?: string;\n readonly #scopes_supported?: string[];\n readonly #bearer_methods_supported?: BearerMethod[];\n readonly #resource_signing_alg_values_supported?: SigningAlgorithm[];\n readonly #resource_documentation?: string;\n readonly #resource_policy_uri?: string;\n readonly #resource_tos_uri?: string;\n readonly #resource_name?: string;\n readonly #tls_client_certificate_bound_access_tokens?: boolean;\n readonly #authorization_details_types_supported?: string[];\n readonly #dpop_signing_alg_values_supported?: string[];\n readonly #dpop_bound_access_tokens_required?: boolean;\n\n constructor(builder: ProtectedResourceMetadataBuilder) {\n const props = builder.properties;\n this.#resource = props.resource;\n this.#authorization_servers = [...props.authorization_servers];\n this.#jwks_uri = props.jwks_uri;\n this.#scopes_supported = props.scopes_supported\n ? [...props.scopes_supported]\n : undefined;\n this.#bearer_methods_supported = props.bearer_methods_supported\n ? [...props.bearer_methods_supported]\n : undefined;\n this.#resource_signing_alg_values_supported = props.resource_signing_alg_values_supported\n ? [...props.resource_signing_alg_values_supported]\n : undefined;\n this.#resource_documentation = props.resource_documentation;\n this.#resource_policy_uri = props.resource_policy_uri;\n this.#resource_tos_uri = props.resource_tos_uri;\n this.#resource_name = props.resource_name;\n this.#tls_client_certificate_bound_access_tokens = props.tls_client_certificate_bound_access_tokens;\n this.#authorization_details_types_supported = props.authorization_details_types_supported\n ? [...props.authorization_details_types_supported]\n : undefined;\n this.#dpop_signing_alg_values_supported = props.dpop_signing_alg_values_supported\n ? [...props.dpop_signing_alg_values_supported]\n : undefined;\n this.#dpop_bound_access_tokens_required = props.dpop_bound_access_tokens_required;\n }\n\n /**\n * Convert to JSON representation\n */\n public toJSON(): IProtectedResourceMetadata {\n return {\n resource: this.#resource,\n authorization_servers: [...this.#authorization_servers],\n\n ...(this.#jwks_uri !== undefined && { jwks_uri: this.#jwks_uri }),\n ...(this.#scopes_supported !== undefined && {\n scopes_supported: [...this.#scopes_supported],\n }),\n ...(this.#bearer_methods_supported !== undefined && {\n bearer_methods_supported: [...this.#bearer_methods_supported],\n }),\n ...(this.#resource_signing_alg_values_supported !== undefined && {\n resource_signing_alg_values_supported: [...this.#resource_signing_alg_values_supported],\n }),\n ...(this.#resource_documentation !== undefined && {\n resource_documentation: this.#resource_documentation,\n }),\n ...(this.#resource_policy_uri !== undefined && {\n resource_policy_uri: this.#resource_policy_uri,\n }),\n ...(this.#resource_tos_uri !== undefined && {\n resource_tos_uri: this.#resource_tos_uri,\n }),\n ...(this.#resource_name !== undefined && {\n resource_name: this.#resource_name,\n }),\n ...(this.#tls_client_certificate_bound_access_tokens !== undefined && {\n tls_client_certificate_bound_access_tokens: this.#tls_client_certificate_bound_access_tokens,\n }),\n ...(this.#authorization_details_types_supported !== undefined && {\n authorization_details_types_supported: [...this.#authorization_details_types_supported],\n }),\n ...(this.#dpop_signing_alg_values_supported !== undefined && {\n dpop_signing_alg_values_supported: [...this.#dpop_signing_alg_values_supported],\n }),\n ...(this.#dpop_bound_access_tokens_required !== undefined && {\n dpop_bound_access_tokens_required: this.#dpop_bound_access_tokens_required,\n }),\n };\n }\n}\n","import { InvalidRequestError } from './errors.js';\n/**\n * Header-like object that can represent headers from different HTTP frameworks\n */\ntype HeadersLike = Record<string, unknown> & {\n authorization?: string;\n 'content-type'?: string;\n};\n\n/**\n * Query-like object for URL query parameters\n */\ntype QueryLike = Record<string, unknown> & { access_token?: string };\n\n/**\n * Body-like object for form-encoded request body\n */\ntype BodyLike = QueryLike;\n\n/**\n * Regular expression to match Bearer token in Authorization header\n */\nconst TOKEN_RE = /^Bearer (.+)$/i;\n\n/**\n * Extracts a Bearer token from HTTP request according to RFC 6750.\n * Supports all three methods defined in the RFC:\n * - Authorization header (Section 2.1)\n * - Form-encoded body parameter (Section 2.2)\n * - URI query parameter (Section 2.3)\n *\n * @param headers - HTTP headers object\n * @param query - Query parameters object (optional)\n * @param body - Request body object (optional)\n * @returns The extracted token string\n * @throws {InvalidRequestError} When no token is found or multiple methods are used\n *\n * @example\n * ```typescript\n * // Authorization header method (recommended)\n * const token1 = getToken({ authorization: 'Bearer mF_9.B5f-4.1JqM' });\n *\n * // Query parameter method\n * const token2 = getToken({}, { access_token: 'mF_9.B5f-4.1JqM' });\n *\n * // Form body method\n * const token3 = getToken(\n * { 'content-type': 'application/x-www-form-urlencoded' },\n * {},\n * { access_token: 'mF_9.B5f-4.1JqM' }\n * );\n *\n * // Express.js usage\n * const token4 = getToken(req.headers, req.query, req.body);\n * ```\n *\n * @see https://datatracker.ietf.org/doc/html/rfc6750#section-2 - RFC 6750 Section 2\n */\nexport function getToken(\n headers: HeadersLike,\n query?: QueryLike,\n body?: BodyLike\n): string {\n const fromHeader = getTokenFromHeader(headers);\n const fromQuery = getTokenFromQuery(query);\n const fromBody = getTokenFromBody(headers, body);\n\n if (!fromQuery && !fromHeader && !fromBody) {\n throw new InvalidRequestError('No Bearer token found in request');\n }\n\n // If multiple methods are used, throw an error\n if (+!!fromQuery + +!!fromBody + +!!fromHeader > 1) {\n throw new InvalidRequestError(\n 'More than one method used for authentication'\n );\n }\n\n return (fromQuery || fromBody || fromHeader) as string;\n}\n\n/**\n * Extract token from Authorization header\n */\nfunction getTokenFromHeader(headers: HeadersLike) {\n const authHeader = headers.authorization;\n if (typeof authHeader !== 'string') {\n return undefined;\n }\n\n const match = authHeader.match(TOKEN_RE);\n return match?.[1];\n}\n\n/**\n * Extract token from query parameters\n */\nfunction getTokenFromQuery(query?: QueryLike): string | undefined {\n const accessToken = query?.access_token;\n if (typeof accessToken === 'string') {\n return accessToken;\n }\n}\n\n/**\n * Extract token from form-encoded body\n */\nfunction getTokenFromBody(\n headers: HeadersLike,\n body?: BodyLike\n): string | undefined {\n if (!body || typeof body.access_token !== 'string') {\n return undefined;\n }\n\n const contentType = headers['content-type'];\n if (!contentType) {\n return undefined;\n }\n\n // Handle content-type with charset, e.g., \"application/x-www-form-urlencoded; charset=utf-8\"\n const isFormEncoded = contentType\n .toLowerCase()\n .includes('application/x-www-form-urlencoded');\n if (!isFormEncoded) {\n return undefined;\n }\n\n return body.access_token;\n}\n","export { ApiClient } from './api-client.js';\nexport * from './protected-resource-metadata.js';\nexport * from './errors.js';\nexport * from './types.js';\nexport { getToken } from './token.js';\n\n// Re-export shared errors from auth0-auth-js for convenience\nexport {\n MissingClientAuthError,\n TokenExchangeError,\n} from '@auth0/auth0-auth-js';\n"],"mappings":";AAAA,YAAY,WAAW;AACvB,SAAS,oBAAoB,WAAW,eAAAA,oBAAmB;AAC3D,SAAS,YAAY,yBAAyB,8BAA8B;;;ACCrE,IAAM,0BAAN,cAAsC,MAAM;AAAA,EAC1C,OAAe;AAAA,EAEtB,YAAY,SAAkB;AAC5B,UAAM,WAAW,6BAA6B;AAC9C,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EACzC,OAAe;AAAA,EAEtB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACtC,OAAe;AAAA,EAEtB,YAAY,SAAiB;AAC3B,UAAM,OAA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1HA;AAAA,EACE,0BAAAC;AAAA,EACA;AAAA,OACK;","names":["customFetch","customFetch","BearerMethod","SigningAlgorithm","GrantType","MissingClientAuthError"]}
{
"name": "@auth0/auth0-api-js",
"version": "1.1.0",
"version": "1.2.0",
"description": "Auth0 Authentication SDK for API's on JavaScript runtimes",

@@ -5,0 +5,0 @@ "author": "Auth0",

@@ -101,2 +101,57 @@ The `@auth0/auth0-api-js` library allows for securing API's running on a JavaScript runtime.

### 5. Token Exchange
The SDK supports RFC 8693 OAuth 2.0 Token Exchange, allowing you to exchange tokens for different API audiences while preserving user identity.
#### When to Use Which Flow
- **Custom Token Exchange**: Use when you control the subject token format. Common scenarios:
- Exchanging MCP server tokens for Auth0 tokens
- Migrating from legacy authentication systems
- Federating with partner systems using custom token formats
- Exchanging tokens issued by your own services
- **Access Token Exchange with Token Vault** (via `getAccessTokenForConnection`): Use when exchanging for external provider's access tokens:
- Accessing Google APIs with a user's Google token
- Calling Facebook Graph API with a user's Facebook token
- Any scenario where Auth0 manages the external provider's refresh tokens in the Token Vault
#### Custom Token Exchange Example
```ts
import { ApiClient } from '@auth0/auth0-api-js';
const apiClient = new ApiClient({
domain: '<AUTH0_DOMAIN>',
audience: '<AUTH0_AUDIENCE>',
clientId: '<AUTH0_CLIENT_ID>',
clientSecret: '<AUTH0_CLIENT_SECRET>',
});
// Exchange a custom token (e.g., from an MCP server or legacy system)
const result = await apiClient.getTokenByExchangeProfile(
userToken, // The token to exchange
{
subjectTokenType: 'urn:example:custom-token', // Your custom token type URN
audience: 'https://api.backend.com',
}
);
// Handle token expiry - check expiresAt and re-exchange when needed
// Note: expiresAt is in seconds, Date.now() is in milliseconds
const tokenIsValid = Math.floor(Date.now() / 1000) < result.expiresAt;
if (!tokenIsValid) {
// Re-exchange with a fresh subject token (e.g., from your auth provider)
const newSubjectToken = await getNewTokenFromYourProvider();
const refreshed = await apiClient.getTokenByExchangeProfile(newSubjectToken, {
subjectTokenType: 'urn:example:custom-token',
audience: 'https://api.backend.com',
});
}
```
> **Security Note**: The `extra` parameter (if exposed in your application) should never contain Personally Identifiable Information (PII) or sensitive data. Extra parameters may be logged by Auth0 or included in audit trails. Only use it for non-sensitive technical parameters that don't identify users.
Learn more: [Custom Token Exchange](https://auth0.com/docs/authenticate/custom-token-exchange) | [Token Vault](https://auth0.com/docs/secure/tokens/token-vault/access-token-exchange-with-token-vault)
## Feedback

@@ -103,0 +158,0 @@