@azure/identity 4.13.2 → 4.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/browser/constants.d.ts +1 -1
  2. package/dist/browser/constants.js +1 -1
  3. package/dist/browser/constants.js.map +1 -1
  4. package/dist/browser/errors.d.ts.map +1 -1
  5. package/dist/browser/errors.js +1 -4
  6. package/dist/browser/errors.js.map +1 -1
  7. package/dist/browser/package.json +6 -1
  8. package/dist/commonjs/constants.d.ts +1 -1
  9. package/dist/commonjs/constants.js +1 -1
  10. package/dist/commonjs/constants.js.map +1 -1
  11. package/dist/commonjs/credentials/azurePipelinesCredential.d.ts.map +1 -1
  12. package/dist/commonjs/credentials/azurePipelinesCredential.js +16 -10
  13. package/dist/commonjs/credentials/azurePipelinesCredential.js.map +2 -2
  14. package/dist/commonjs/credentials/azurePowerShellCredential.d.ts.map +1 -1
  15. package/dist/commonjs/credentials/azurePowerShellCredential.js +3 -1
  16. package/dist/commonjs/credentials/azurePowerShellCredential.js.map +2 -2
  17. package/dist/commonjs/credentials/defaultAzureCredential.d.ts.map +1 -1
  18. package/dist/commonjs/credentials/defaultAzureCredential.js +5 -2
  19. package/dist/commonjs/credentials/defaultAzureCredential.js.map +2 -2
  20. package/dist/commonjs/errors.d.ts.map +1 -1
  21. package/dist/commonjs/errors.js +1 -4
  22. package/dist/commonjs/errors.js.map +2 -2
  23. package/dist/commonjs/msal/nodeFlows/msalClient.js +1 -1
  24. package/dist/commonjs/msal/nodeFlows/msalClient.js.map +2 -2
  25. package/dist/commonjs/package.json +6 -1
  26. package/dist/esm/constants.d.ts +1 -1
  27. package/dist/esm/constants.js +1 -1
  28. package/dist/esm/constants.js.map +1 -1
  29. package/dist/esm/credentials/azurePipelinesCredential.d.ts.map +1 -1
  30. package/dist/esm/credentials/azurePipelinesCredential.js +16 -6
  31. package/dist/esm/credentials/azurePipelinesCredential.js.map +1 -1
  32. package/dist/esm/credentials/azurePowerShellCredential.d.ts.map +1 -1
  33. package/dist/esm/credentials/azurePowerShellCredential.js +3 -1
  34. package/dist/esm/credentials/azurePowerShellCredential.js.map +1 -1
  35. package/dist/esm/credentials/defaultAzureCredential.d.ts.map +1 -1
  36. package/dist/esm/credentials/defaultAzureCredential.js +5 -2
  37. package/dist/esm/credentials/defaultAzureCredential.js.map +1 -1
  38. package/dist/esm/errors.d.ts.map +1 -1
  39. package/dist/esm/errors.js +1 -4
  40. package/dist/esm/errors.js.map +1 -1
  41. package/dist/esm/msal/nodeFlows/msalClient.js +1 -1
  42. package/dist/esm/msal/nodeFlows/msalClient.js.map +1 -1
  43. package/dist/esm/package.json +6 -1
  44. package/dist/workerd/constants.d.ts +1 -1
  45. package/dist/workerd/constants.js +1 -1
  46. package/dist/workerd/constants.js.map +1 -1
  47. package/dist/workerd/credentials/azurePipelinesCredential.d.ts.map +1 -1
  48. package/dist/workerd/credentials/azurePipelinesCredential.js +16 -6
  49. package/dist/workerd/credentials/azurePipelinesCredential.js.map +1 -1
  50. package/dist/workerd/credentials/azurePowerShellCredential.d.ts.map +1 -1
  51. package/dist/workerd/credentials/azurePowerShellCredential.js +3 -1
  52. package/dist/workerd/credentials/azurePowerShellCredential.js.map +1 -1
  53. package/dist/workerd/credentials/defaultAzureCredential.d.ts.map +1 -1
  54. package/dist/workerd/credentials/defaultAzureCredential.js +5 -2
  55. package/dist/workerd/credentials/defaultAzureCredential.js.map +1 -1
  56. package/dist/workerd/errors.d.ts.map +1 -1
  57. package/dist/workerd/errors.js +1 -4
  58. package/dist/workerd/errors.js.map +1 -1
  59. package/dist/workerd/msal/nodeFlows/msalClient.js +1 -1
  60. package/dist/workerd/msal/nodeFlows/msalClient.js.map +1 -1
  61. package/dist/workerd/package.json +6 -1
  62. package/package.json +7 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/msal/nodeFlows/msalClient.ts"],
4
- "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as msal from \"@azure/msal-node\";\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport type { AuthenticationRecord, CertificateParts } from \"../types.js\";\nimport type { CredentialLogger } from \"../../util/logging.js\";\nimport { credentialLogger, formatSuccess } from \"../../util/logging.js\";\nimport type { PluginConfiguration } from \"./msalPlugins.js\";\nimport { msalPlugins } from \"./msalPlugins.js\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getAuthorityHost,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils.js\";\n\nimport { AuthenticationRequiredError } from \"../../errors.js\";\nimport type { BrokerOptions } from \"./brokerOptions.js\";\nimport type { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions.js\";\nimport { IdentityClient } from \"../../client/identityClient.js\";\nimport type { InteractiveBrowserCredentialNodeOptions } from \"../../credentials/interactiveBrowserCredentialOptions.js\";\nimport type { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions.js\";\nimport { calculateRegionalAuthority } from \"../../regionalAuthority.js\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { resolveTenantId } from \"../../util/tenantIdUtils.js\";\n\n/**\n * The default logger used if no logger was passed in by the credential.\n */\nconst msalLogger = credentialLogger(\"MsalClient\");\n\n/**\n * Represents the options for acquiring a token using flows that support silent authentication.\n */\nexport interface GetTokenWithSilentAuthOptions extends GetTokenOptions {\n /**\n * Disables automatic authentication. If set to true, the method will throw an error if the user needs to authenticate.\n *\n * @remarks\n *\n * This option will be set to `false` when the user calls `authenticate` directly on a credential that supports it.\n */\n disableAutomaticAuthentication?: boolean;\n}\n\n/**\n * Represents the options for acquiring a token interactively.\n */\nexport interface GetTokenInteractiveOptions extends GetTokenWithSilentAuthOptions {\n /**\n * Window handle for parent window, required for WAM authentication.\n */\n parentWindowHandle?: Buffer;\n /**\n * Shared configuration options for browser customization\n */\n browserCustomizationOptions?: InteractiveBrowserCredentialNodeOptions[\"browserCustomizationOptions\"];\n /**\n * loginHint allows a user name to be pre-selected for interactive logins.\n * Setting this option skips the account selection prompt and immediately attempts to login with the specified account.\n */\n loginHint?: string;\n}\n\n/**\n * Represents a client for interacting with the Microsoft Authentication Library (MSAL).\n */\nexport interface MsalClient {\n /**\n *\n * Retrieves an access token by using the on-behalf-of flow and a client assertion callback of the calling service.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userAssertionToken - The access token that was sent to the middle-tier API. This token must have an audience of the app making this OBO request.\n * @param clientCredentials - The client secret OR client certificate OR client `getAssertion` callback.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenOnBehalfOf(\n scopes: string[],\n userAssertionToken: string,\n clientCredentials: string | CertificateParts | (() => Promise<string>),\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using an interactive prompt (InteractiveBrowserCredential).\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByInteractiveRequest(\n scopes: string[],\n options: GetTokenInteractiveOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using a user's username and password.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param username - The username provided by the developer.\n * @param password - The user's password provided by the developer.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by prompting the user to authenticate using a device code.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userPromptCallback - The callback function that allows developers to customize the prompt message.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByDeviceCode(\n scopes: string[],\n userPromptCallback: DeviceCodePromptCallback,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using a client certificate.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param certificate - The client certificate used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client assertion.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientAssertion - The client `getAssertion` callback used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: () => Promise<string>,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client secret.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientSecret - The client secret of the application. This is a credential that the application can use to authenticate itself.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using an authorization code flow.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param authorizationCode - An authorization code that was received from following the\n authorization code flow. This authorization code must not\n have already been used to obtain an access token.\n * @param redirectUri - The redirect URI that was used to request the authorization code.\n Must be the same URI that is configured for the App Registration.\n * @param clientSecret - An optional client secret that was generated for the App Registration.\n * @param options - Additional options that may be provided to the method.\n */\n getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves the last authenticated account. This method expects an authentication record to have been previously loaded.\n *\n * An authentication record could be loaded by calling the `getToken` method, or by providing an `authenticationRecord` when creating a credential.\n */\n getActiveAccount(): AuthenticationRecord | undefined;\n\n /**\n * Retrieves an access token using brokered authentication.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param useDefaultBrokerAccount - Whether to use the default broker account for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getBrokeredToken(\n scopes: string[],\n useDefaultBrokerAccount: boolean,\n options?: GetTokenInteractiveOptions,\n ): Promise<AccessToken>;\n}\n\n/**\n * Represents the options for configuring the MsalClient.\n */\nexport interface MsalClientOptions {\n /**\n * Parameters that enable WAM broker authentication in the InteractiveBrowserCredential.\n */\n brokerOptions?: BrokerOptions;\n\n /**\n * Parameters that enable token cache persistence in the Identity credentials.\n */\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n\n /**\n * Indicates if this is being used by VSCode credential.\n */\n isVSCodeCredential?: boolean;\n\n /**\n * A custom authority host.\n */\n authorityHost?: IdentityClient[\"tokenCredentialOptions\"][\"authorityHost\"];\n\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: IdentityClient[\"tokenCredentialOptions\"][\"loggingOptions\"];\n\n /**\n * The token credential options for the MsalClient.\n */\n tokenCredentialOptions?: IdentityClient[\"tokenCredentialOptions\"];\n\n /**\n * Determines whether instance discovery is disabled.\n */\n disableInstanceDiscovery?: boolean;\n\n /**\n * The logger for the MsalClient.\n */\n logger?: CredentialLogger;\n\n /**\n * The authentication record for the MsalClient.\n */\n authenticationRecord?: AuthenticationRecord;\n}\n\n/**\n * Generates the configuration for MSAL (Microsoft Authentication Library).\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param msalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns The MSAL configuration object.\n */\nexport function generateMsalConfiguration(\n clientId: string,\n tenantId: string,\n msalClientOptions: MsalClientOptions = {},\n): msal.Configuration {\n const resolvedTenant = resolveTenantId(\n msalClientOptions.logger ?? msalLogger,\n tenantId,\n clientId,\n );\n\n // TODO: move and reuse getIdentityClientAuthorityHost\n const authority = getAuthority(resolvedTenant, getAuthorityHost(msalClientOptions));\n\n const httpClient = new IdentityClient({\n ...msalClientOptions.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: msalClientOptions.loggingOptions,\n });\n\n const msalConfig: msal.Configuration = {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(\n resolvedTenant,\n authority,\n msalClientOptions.disableInstanceDiscovery,\n ),\n },\n system: {\n networkClient: httpClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(msalClientOptions.logger ?? msalLogger),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: msalClientOptions.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n return msalConfig;\n}\n\n/**\n * Represents the state necessary for the MSAL (Microsoft Authentication Library) client to operate.\n * This includes the MSAL configuration, cached account information, Azure region, and a flag to disable automatic authentication.\n */\ninterface MsalClientState {\n /** The configuration for the MSAL client. */\n msalConfig: msal.Configuration;\n\n /** The cached account information, or null if no account information is cached. */\n cachedAccount: msal.AccountInfo | null;\n\n /** Configured plugins */\n pluginConfiguration: PluginConfiguration;\n\n /** Claims received from challenges, cached for the next request */\n cachedClaims?: string;\n\n /** The logger instance */\n logger: CredentialLogger;\n}\n\n/**\n * Creates an instance of the MSAL (Microsoft Authentication Library) client.\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param createMsalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns An instance of the MSAL client.\n *\n * @public\n */\nexport function createMsalClient(\n clientId: string,\n tenantId: string,\n createMsalClientOptions: MsalClientOptions = {},\n): MsalClient {\n const state: MsalClientState = {\n msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions),\n cachedAccount: createMsalClientOptions.authenticationRecord\n ? publicToMsal(createMsalClientOptions.authenticationRecord)\n : null,\n pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions),\n logger: createMsalClientOptions.logger ?? msalLogger,\n };\n\n const publicApps: Map<string, msal.PublicClientApplication> = new Map();\n async function getPublicApp(\n options: GetTokenOptions = {},\n ): Promise<msal.PublicClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let publicClientApp = publicApps.get(appKey);\n if (publicClientApp) {\n state.logger.getToken.info(\"Existing PublicClientApplication found in cache, returning it.\");\n return publicClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new PublicClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n publicClientApp = new msal.PublicClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n publicApps.set(appKey, publicClientApp);\n\n return publicClientApp;\n }\n\n const confidentialApps: Map<string, msal.ConfidentialClientApplication> = new Map();\n async function getConfidentialApp(\n options: GetTokenOptions = {},\n ): Promise<msal.ConfidentialClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let confidentialClientApp = confidentialApps.get(appKey);\n if (confidentialClientApp) {\n state.logger.getToken.info(\n \"Existing ConfidentialClientApplication found in cache, returning it.\",\n );\n return confidentialClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new ConfidentialClientApplication with CAE ${\n options.enableCae ? \"enabled\" : \"disabled\"\n }.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n confidentialClientApp = new msal.ConfidentialClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n confidentialApps.set(appKey, confidentialClientApp);\n\n return confidentialClientApp;\n }\n\n async function getTokenSilent(\n app: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: string[],\n options: GetTokenOptions = {},\n ): Promise<msal.AuthenticationResult> {\n if (state.cachedAccount === null) {\n state.logger.getToken.info(\"No cached account found in local state.\");\n throw new AuthenticationRequiredError({ scopes });\n }\n\n // Keep track and reuse the claims we received across challenges\n if (options.claims) {\n state.cachedClaims = options.claims;\n }\n\n const silentRequest: msal.SilentFlowRequest = {\n account: state.cachedAccount,\n scopes,\n claims: state.cachedClaims,\n };\n\n if (state.pluginConfiguration.broker.isEnabled) {\n silentRequest.extraQueryParameters ||= {};\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n silentRequest.extraQueryParameters[\"msal_request_type\"] = \"consumer_passthrough\";\n }\n }\n\n if (options.proofOfPossessionOptions) {\n silentRequest.shrNonce = options.proofOfPossessionOptions.nonce;\n silentRequest.authenticationScheme = \"pop\";\n silentRequest.resourceRequestMethod = options.proofOfPossessionOptions.resourceRequestMethod;\n silentRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl;\n }\n state.logger.getToken.info(\"Attempting to acquire token silently\");\n try {\n return await app.acquireTokenSilent(silentRequest);\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n /**\n * Builds an authority URL for the given request. The authority may be different than the one used when creating the MSAL client\n * if the user is creating cross-tenant requests\n */\n function calculateRequestAuthority(options?: GetTokenOptions): string | undefined {\n if (options?.tenantId) {\n return getAuthority(options.tenantId, getAuthorityHost(createMsalClientOptions));\n }\n return state.msalConfig.auth.authority;\n }\n\n /**\n * Performs silent authentication using MSAL to acquire an access token.\n * If silent authentication fails, falls back to interactive authentication.\n *\n * @param msalApp - The MSAL application instance.\n * @param scopes - The scopes for which to acquire the access token.\n * @param options - The options for acquiring the access token.\n * @param onAuthenticationRequired - A callback function to handle interactive authentication when silent authentication fails.\n * @returns A promise that resolves to an AccessToken object containing the access token and its expiration timestamp.\n */\n async function withSilentAuthentication(\n msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: Array<string>,\n options: GetTokenWithSilentAuthOptions,\n onAuthenticationRequired: () => Promise<msal.AuthenticationResult | null>,\n ): Promise<AccessToken> {\n let response: msal.AuthenticationResult | null = null;\n try {\n response = await getTokenSilent(msalApp, scopes, options);\n } catch (e: any) {\n if (e.name !== \"AuthenticationRequiredError\") {\n throw e;\n }\n if (options.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n }\n\n // Silent authentication failed\n if (response === null) {\n try {\n response = await onAuthenticationRequired();\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n // At this point we should have a token, process it\n ensureValidMsalToken(scopes, response, options);\n state.cachedAccount = response?.account ?? null;\n\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n }\n\n async function getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client secret`);\n\n state.msalConfig.auth.clientSecret = clientSecret;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: calculateRequestAuthority(options),\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: () => Promise<string>,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client assertion`);\n\n state.msalConfig.auth.clientAssertion = clientAssertion;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: calculateRequestAuthority(options),\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n clientAssertion,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client certificate`);\n\n state.msalConfig.auth.clientCertificate = certificate;\n\n const msalApp = await getConfidentialApp(options);\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: calculateRequestAuthority(options),\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByDeviceCode(\n scopes: string[],\n deviceCodeCallback: DeviceCodePromptCallback,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using device code`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.DeviceCodeRequest = {\n scopes,\n cancel: options?.abortSignal?.aborted ?? false,\n deviceCodeCallback,\n authority: calculateRequestAuthority(options),\n claims: options?.claims,\n };\n const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions);\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n requestOptions.cancel = true;\n });\n }\n\n return deviceCodeRequest;\n });\n }\n\n async function getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using username and password`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.UsernamePasswordRequest = {\n scopes,\n username,\n password,\n authority: calculateRequestAuthority(options),\n claims: options?.claims,\n };\n\n return msalApp.acquireTokenByUsernamePassword(requestOptions);\n });\n }\n\n function getActiveAccount(): AuthenticationRecord | undefined {\n if (!state.cachedAccount) {\n return undefined;\n }\n return msalToPublic(clientId, state.cachedAccount);\n }\n\n async function getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using authorization code`);\n\n let msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication;\n if (clientSecret) {\n // If a client secret is provided, we need to use a confidential client application\n // See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-client_secret\n state.msalConfig.auth.clientSecret = clientSecret;\n msalApp = await getConfidentialApp(options);\n } else {\n msalApp = await getPublicApp(options);\n }\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n return msalApp.acquireTokenByCode({\n scopes,\n redirectUri,\n code: authorizationCode,\n authority: calculateRequestAuthority(options),\n claims: options?.claims,\n });\n });\n }\n\n async function getTokenOnBehalfOf(\n scopes: string[],\n userAssertionToken: string,\n clientCredentials: string | CertificateParts | (() => Promise<string>),\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token on behalf of another user`);\n\n if (typeof clientCredentials === \"string\") {\n // Client secret\n msalLogger.getToken.info(`Using client secret for on behalf of flow`);\n state.msalConfig.auth.clientSecret = clientCredentials;\n } else if (typeof clientCredentials === \"function\") {\n // Client Assertion\n msalLogger.getToken.info(`Using client assertion callback for on behalf of flow`);\n state.msalConfig.auth.clientAssertion = clientCredentials;\n } else {\n // Client certificate\n msalLogger.getToken.info(`Using client certificate for on behalf of flow`);\n state.msalConfig.auth.clientCertificate = clientCredentials;\n }\n\n const msalApp = await getConfidentialApp(options);\n try {\n const response = await msalApp.acquireTokenOnBehalfOf({\n scopes,\n authority: calculateRequestAuthority(options),\n claims: options.claims,\n oboAssertion: userAssertionToken,\n });\n ensureValidMsalToken(scopes, response, options);\n\n msalLogger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n /**\n * Creates a base interactive request configuration for MSAL interactive authentication.\n * This is shared between interactive and brokered authentication flows.\n */\n function createBaseInteractiveRequest(\n scopes: string[],\n options: GetTokenInteractiveOptions,\n ): msal.InteractiveRequest {\n return {\n openBrowser: async (url) => {\n const open = await import(\"open\");\n await open.default(url, { newInstance: true });\n },\n scopes,\n authority: calculateRequestAuthority(options),\n claims: options?.claims,\n loginHint: options?.loginHint,\n errorTemplate: options?.browserCustomizationOptions?.errorMessage,\n successTemplate: options?.browserCustomizationOptions?.successMessage,\n prompt: options?.loginHint ? \"login\" : \"select_account\",\n };\n }\n\n /**\n * @internal\n */\n async function getBrokeredTokenInternal(\n scopes: string[],\n useDefaultBrokerAccount: boolean,\n options: GetTokenInteractiveOptions = {},\n ): Promise<msal.AuthenticationResult> {\n msalLogger.verbose(\"Authentication will resume through the broker\");\n\n const app = await getPublicApp(options);\n\n const interactiveRequest = createBaseInteractiveRequest(scopes, options);\n if (state.pluginConfiguration.broker.parentWindowHandle) {\n interactiveRequest.windowHandle = Buffer.from(\n state.pluginConfiguration.broker.parentWindowHandle,\n );\n } else {\n // this is a bug, as the pluginConfiguration handler should validate this case.\n msalLogger.warning(\n \"Parent window handle is not specified for the broker. This may cause unexpected behavior. Please provide the parentWindowHandle.\",\n );\n }\n\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n (interactiveRequest.extraQueryParameters ??= {})[\"msal_request_type\"] =\n \"consumer_passthrough\";\n }\n if (useDefaultBrokerAccount) {\n interactiveRequest.prompt = \"none\";\n msalLogger.verbose(\"Attempting broker authentication using the default broker account\");\n } else {\n msalLogger.verbose(\"Attempting broker authentication without the default broker account\");\n }\n\n if (options.proofOfPossessionOptions) {\n interactiveRequest.shrNonce = options.proofOfPossessionOptions.nonce;\n interactiveRequest.authenticationScheme = \"pop\";\n interactiveRequest.resourceRequestMethod =\n options.proofOfPossessionOptions.resourceRequestMethod;\n interactiveRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl;\n }\n try {\n return await app.acquireTokenInteractive(interactiveRequest);\n } catch (e: any) {\n msalLogger.verbose(`Failed to authenticate through the broker: ${e.message}`);\n if (options.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message: \"Cannot silently authenticate with default broker account.\",\n });\n }\n // If we tried to use the default broker account and failed, fall back to interactive authentication\n if (useDefaultBrokerAccount) {\n return getBrokeredTokenInternal(scopes, false, options);\n } else {\n throw e;\n }\n }\n }\n\n /**\n * A helper function that supports brokered authentication through the MSAL's public application.\n *\n * When useDefaultBrokerAccount is true, the method will attempt to authenticate using the default broker account.\n * If the default broker account is not available, the method will fall back to interactive authentication.\n */\n async function getBrokeredToken(\n scopes: string[],\n useDefaultBrokerAccount: boolean,\n options: GetTokenInteractiveOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(\n `Attempting to acquire token using brokered authentication with useDefaultBrokerAccount: ${useDefaultBrokerAccount}`,\n );\n const response = await getBrokeredTokenInternal(scopes, useDefaultBrokerAccount, options);\n ensureValidMsalToken(scopes, response, options);\n state.cachedAccount = response?.account ?? null;\n\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n }\n\n async function getTokenByInteractiveRequest(\n scopes: string[],\n options: GetTokenInteractiveOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token interactively`);\n\n const app = await getPublicApp(options);\n\n return withSilentAuthentication(app, scopes, options, async () => {\n const interactiveRequest = createBaseInteractiveRequest(scopes, options);\n\n if (state.pluginConfiguration.broker.isEnabled) {\n return getBrokeredTokenInternal(\n scopes,\n state.pluginConfiguration.broker.useDefaultBrokerAccount ?? false,\n options,\n );\n }\n if (options.proofOfPossessionOptions) {\n interactiveRequest.shrNonce = options.proofOfPossessionOptions.nonce;\n interactiveRequest.authenticationScheme = \"pop\";\n interactiveRequest.resourceRequestMethod =\n options.proofOfPossessionOptions.resourceRequestMethod;\n interactiveRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl;\n }\n return app.acquireTokenInteractive(interactiveRequest);\n });\n }\n\n return {\n getActiveAccount,\n getBrokeredToken,\n getTokenByClientSecret,\n getTokenByClientAssertion,\n getTokenByClientCertificate,\n getTokenByDeviceCode,\n getTokenByUsernamePassword,\n getTokenByAuthorizationCode,\n getTokenOnBehalfOf,\n getTokenByInteractiveRequest,\n };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,WAAsB;AAKtB,qBAAgD;AAEhD,yBAA4B;AAC5B,m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IAAI,wBAAwB,kBAAkB;AAAA,IACvD,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as msal from \"@azure/msal-node\";\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport type { AuthenticationRecord, CertificateParts } from \"../types.js\";\nimport type { CredentialLogger } from \"../../util/logging.js\";\nimport { credentialLogger, formatSuccess } from \"../../util/logging.js\";\nimport type { PluginConfiguration } from \"./msalPlugins.js\";\nimport { msalPlugins } from \"./msalPlugins.js\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getAuthorityHost,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils.js\";\n\nimport { AuthenticationRequiredError } from \"../../errors.js\";\nimport type { BrokerOptions } from \"./brokerOptions.js\";\nimport type { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions.js\";\nimport { IdentityClient } from \"../../client/identityClient.js\";\nimport type { InteractiveBrowserCredentialNodeOptions } from \"../../credentials/interactiveBrowserCredentialOptions.js\";\nimport type { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions.js\";\nimport { calculateRegionalAuthority } from \"../../regionalAuthority.js\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { resolveTenantId } from \"../../util/tenantIdUtils.js\";\n\n/**\n * The default logger used if no logger was passed in by the credential.\n */\nconst msalLogger = credentialLogger(\"MsalClient\");\n\n/**\n * Represents the options for acquiring a token using flows that support silent authentication.\n */\nexport interface GetTokenWithSilentAuthOptions extends GetTokenOptions {\n /**\n * Disables automatic authentication. If set to true, the method will throw an error if the user needs to authenticate.\n *\n * @remarks\n *\n * This option will be set to `false` when the user calls `authenticate` directly on a credential that supports it.\n */\n disableAutomaticAuthentication?: boolean;\n}\n\n/**\n * Represents the options for acquiring a token interactively.\n */\nexport interface GetTokenInteractiveOptions extends GetTokenWithSilentAuthOptions {\n /**\n * Window handle for parent window, required for WAM authentication.\n */\n parentWindowHandle?: Buffer;\n /**\n * Shared configuration options for browser customization\n */\n browserCustomizationOptions?: InteractiveBrowserCredentialNodeOptions[\"browserCustomizationOptions\"];\n /**\n * loginHint allows a user name to be pre-selected for interactive logins.\n * Setting this option skips the account selection prompt and immediately attempts to login with the specified account.\n */\n loginHint?: string;\n}\n\n/**\n * Represents a client for interacting with the Microsoft Authentication Library (MSAL).\n */\nexport interface MsalClient {\n /**\n *\n * Retrieves an access token by using the on-behalf-of flow and a client assertion callback of the calling service.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userAssertionToken - The access token that was sent to the middle-tier API. This token must have an audience of the app making this OBO request.\n * @param clientCredentials - The client secret OR client certificate OR client `getAssertion` callback.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenOnBehalfOf(\n scopes: string[],\n userAssertionToken: string,\n clientCredentials: string | CertificateParts | (() => Promise<string>),\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using an interactive prompt (InteractiveBrowserCredential).\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByInteractiveRequest(\n scopes: string[],\n options: GetTokenInteractiveOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using a user's username and password.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param username - The username provided by the developer.\n * @param password - The user's password provided by the developer.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by prompting the user to authenticate using a device code.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param userPromptCallback - The callback function that allows developers to customize the prompt message.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByDeviceCode(\n scopes: string[],\n userPromptCallback: DeviceCodePromptCallback,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n /**\n * Retrieves an access token by using a client certificate.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param certificate - The client certificate used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client assertion.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientAssertion - The client `getAssertion` callback used for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: () => Promise<string>,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using a client secret.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param clientSecret - The client secret of the application. This is a credential that the application can use to authenticate itself.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options?: GetTokenOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves an access token by using an authorization code flow.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param authorizationCode - An authorization code that was received from following the\n authorization code flow. This authorization code must not\n have already been used to obtain an access token.\n * @param redirectUri - The redirect URI that was used to request the authorization code.\n Must be the same URI that is configured for the App Registration.\n * @param clientSecret - An optional client secret that was generated for the App Registration.\n * @param options - Additional options that may be provided to the method.\n */\n getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options?: GetTokenWithSilentAuthOptions,\n ): Promise<AccessToken>;\n\n /**\n * Retrieves the last authenticated account. This method expects an authentication record to have been previously loaded.\n *\n * An authentication record could be loaded by calling the `getToken` method, or by providing an `authenticationRecord` when creating a credential.\n */\n getActiveAccount(): AuthenticationRecord | undefined;\n\n /**\n * Retrieves an access token using brokered authentication.\n *\n * @param scopes - The scopes for which the access token is requested. These represent the resources that the application wants to access.\n * @param useDefaultBrokerAccount - Whether to use the default broker account for authentication.\n * @param options - Additional options that may be provided to the method.\n * @returns An access token.\n */\n getBrokeredToken(\n scopes: string[],\n useDefaultBrokerAccount: boolean,\n options?: GetTokenInteractiveOptions,\n ): Promise<AccessToken>;\n}\n\n/**\n * Represents the options for configuring the MsalClient.\n */\nexport interface MsalClientOptions {\n /**\n * Parameters that enable WAM broker authentication in the InteractiveBrowserCredential.\n */\n brokerOptions?: BrokerOptions;\n\n /**\n * Parameters that enable token cache persistence in the Identity credentials.\n */\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n\n /**\n * Indicates if this is being used by VSCode credential.\n */\n isVSCodeCredential?: boolean;\n\n /**\n * A custom authority host.\n */\n authorityHost?: IdentityClient[\"tokenCredentialOptions\"][\"authorityHost\"];\n\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: IdentityClient[\"tokenCredentialOptions\"][\"loggingOptions\"];\n\n /**\n * The token credential options for the MsalClient.\n */\n tokenCredentialOptions?: IdentityClient[\"tokenCredentialOptions\"];\n\n /**\n * Determines whether instance discovery is disabled.\n */\n disableInstanceDiscovery?: boolean;\n\n /**\n * The logger for the MsalClient.\n */\n logger?: CredentialLogger;\n\n /**\n * The authentication record for the MsalClient.\n */\n authenticationRecord?: AuthenticationRecord;\n}\n\n/**\n * Generates the configuration for MSAL (Microsoft Authentication Library).\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param msalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns The MSAL configuration object.\n */\nexport function generateMsalConfiguration(\n clientId: string,\n tenantId: string,\n msalClientOptions: MsalClientOptions = {},\n): msal.Configuration {\n const resolvedTenant = resolveTenantId(\n msalClientOptions.logger ?? msalLogger,\n tenantId,\n clientId,\n );\n\n // TODO: move and reuse getIdentityClientAuthorityHost\n const authority = getAuthority(resolvedTenant, getAuthorityHost(msalClientOptions));\n\n const httpClient = new IdentityClient({\n ...msalClientOptions.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: msalClientOptions.loggingOptions,\n });\n\n const msalConfig: msal.Configuration = {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(\n resolvedTenant,\n authority,\n msalClientOptions.disableInstanceDiscovery,\n ),\n },\n system: {\n networkClient: httpClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(msalClientOptions.logger ?? msalLogger),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: msalClientOptions.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n return msalConfig;\n}\n\n/**\n * Represents the state necessary for the MSAL (Microsoft Authentication Library) client to operate.\n * This includes the MSAL configuration, cached account information, Azure region, and a flag to disable automatic authentication.\n */\ninterface MsalClientState {\n /** The configuration for the MSAL client. */\n msalConfig: msal.Configuration;\n\n /** The cached account information, or null if no account information is cached. */\n cachedAccount: msal.AccountInfo | null;\n\n /** Configured plugins */\n pluginConfiguration: PluginConfiguration;\n\n /** Claims received from challenges, cached for the next request */\n cachedClaims?: string;\n\n /** The logger instance */\n logger: CredentialLogger;\n}\n\n/**\n * Creates an instance of the MSAL (Microsoft Authentication Library) client.\n *\n * @param clientId - The client ID of the application.\n * @param tenantId - The tenant ID of the Azure Active Directory.\n * @param createMsalClientOptions - Optional. Additional options for creating the MSAL client.\n * @returns An instance of the MSAL client.\n *\n * @public\n */\nexport function createMsalClient(\n clientId: string,\n tenantId: string,\n createMsalClientOptions: MsalClientOptions = {},\n): MsalClient {\n const state: MsalClientState = {\n msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions),\n cachedAccount: createMsalClientOptions.authenticationRecord\n ? publicToMsal(createMsalClientOptions.authenticationRecord)\n : null,\n pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions),\n logger: createMsalClientOptions.logger ?? msalLogger,\n };\n\n const publicApps: Map<string, msal.PublicClientApplication> = new Map();\n async function getPublicApp(\n options: GetTokenOptions = {},\n ): Promise<msal.PublicClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let publicClientApp = publicApps.get(appKey);\n if (publicClientApp) {\n state.logger.getToken.info(\"Existing PublicClientApplication found in cache, returning it.\");\n return publicClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new PublicClientApplication with CAE ${options.enableCae ? \"enabled\" : \"disabled\"}.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n publicClientApp = new msal.PublicClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n publicApps.set(appKey, publicClientApp);\n\n return publicClientApp;\n }\n\n const confidentialApps: Map<string, msal.ConfidentialClientApplication> = new Map();\n async function getConfidentialApp(\n options: GetTokenOptions = {},\n ): Promise<msal.ConfidentialClientApplication> {\n const appKey = options.enableCae ? \"CAE\" : \"default\";\n\n let confidentialClientApp = confidentialApps.get(appKey);\n if (confidentialClientApp) {\n state.logger.getToken.info(\n \"Existing ConfidentialClientApplication found in cache, returning it.\",\n );\n return confidentialClientApp;\n }\n\n // Initialize a new app and cache it\n state.logger.getToken.info(\n `Creating new ConfidentialClientApplication with CAE ${\n options.enableCae ? \"enabled\" : \"disabled\"\n }.`,\n );\n\n const cachePlugin = options.enableCae\n ? state.pluginConfiguration.cache.cachePluginCae\n : state.pluginConfiguration.cache.cachePlugin;\n\n state.msalConfig.auth.clientCapabilities = options.enableCae ? [\"cp1\"] : undefined;\n\n confidentialClientApp = new msal.ConfidentialClientApplication({\n ...state.msalConfig,\n broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },\n cache: { cachePlugin: await cachePlugin },\n });\n\n confidentialApps.set(appKey, confidentialClientApp);\n\n return confidentialClientApp;\n }\n\n async function getTokenSilent(\n app: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: string[],\n options: GetTokenOptions = {},\n ): Promise<msal.AuthenticationResult> {\n if (state.cachedAccount === null) {\n state.logger.getToken.info(\"No cached account found in local state.\");\n throw new AuthenticationRequiredError({ scopes });\n }\n\n // Keep track and reuse the claims we received across challenges\n if (options.claims) {\n state.cachedClaims = options.claims;\n }\n\n const silentRequest: msal.SilentFlowRequest = {\n account: state.cachedAccount,\n scopes,\n claims: state.cachedClaims,\n };\n\n if (state.pluginConfiguration.broker.isEnabled) {\n silentRequest.extraQueryParameters ||= {};\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n silentRequest.extraQueryParameters[\"msal_request_type\"] = \"consumer_passthrough\";\n }\n }\n\n if (options.proofOfPossessionOptions) {\n silentRequest.shrNonce = options.proofOfPossessionOptions.nonce;\n silentRequest.authenticationScheme = \"pop\";\n silentRequest.resourceRequestMethod = options.proofOfPossessionOptions.resourceRequestMethod;\n silentRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl;\n }\n state.logger.getToken.info(\"Attempting to acquire token silently\");\n try {\n return await app.acquireTokenSilent(silentRequest);\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n /**\n * Builds an authority URL for the given request. The authority may be different than the one used when creating the MSAL client\n * if the user is creating cross-tenant requests\n */\n function calculateRequestAuthority(options?: GetTokenOptions): string | undefined {\n if (options?.tenantId) {\n return getAuthority(options.tenantId, getAuthorityHost(createMsalClientOptions));\n }\n return state.msalConfig.auth.authority;\n }\n\n /**\n * Performs silent authentication using MSAL to acquire an access token.\n * If silent authentication fails, falls back to interactive authentication.\n *\n * @param msalApp - The MSAL application instance.\n * @param scopes - The scopes for which to acquire the access token.\n * @param options - The options for acquiring the access token.\n * @param onAuthenticationRequired - A callback function to handle interactive authentication when silent authentication fails.\n * @returns A promise that resolves to an AccessToken object containing the access token and its expiration timestamp.\n */\n async function withSilentAuthentication(\n msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication,\n scopes: Array<string>,\n options: GetTokenWithSilentAuthOptions,\n onAuthenticationRequired: () => Promise<msal.AuthenticationResult | null>,\n ): Promise<AccessToken> {\n let response: msal.AuthenticationResult | null = null;\n try {\n response = await getTokenSilent(msalApp, scopes, options);\n } catch (e: any) {\n if (e.name !== \"AuthenticationRequiredError\") {\n throw e;\n }\n if (options.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n }\n\n // Silent authentication failed\n if (response === null) {\n try {\n response = await onAuthenticationRequired();\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n // At this point we should have a token, process it\n ensureValidMsalToken(scopes, response, options);\n state.cachedAccount = response?.account ?? null;\n\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n }\n\n async function getTokenByClientSecret(\n scopes: string[],\n clientSecret: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client secret`);\n\n state.msalConfig.auth.clientSecret = clientSecret;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: calculateRequestAuthority(options),\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientAssertion(\n scopes: string[],\n clientAssertion: () => Promise<string>,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client assertion`);\n\n state.msalConfig.auth.clientAssertion = clientAssertion;\n\n const msalApp = await getConfidentialApp(options);\n\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: calculateRequestAuthority(options),\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n clientAssertion,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByClientCertificate(\n scopes: string[],\n certificate: CertificateParts,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using client certificate`);\n\n state.msalConfig.auth.clientCertificate = certificate;\n\n const msalApp = await getConfidentialApp(options);\n try {\n const response = await msalApp.acquireTokenByClientCredential({\n scopes,\n authority: calculateRequestAuthority(options),\n azureRegion: calculateRegionalAuthority(),\n claims: options?.claims,\n });\n ensureValidMsalToken(scopes, response, options);\n\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n async function getTokenByDeviceCode(\n scopes: string[],\n deviceCodeCallback: DeviceCodePromptCallback,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using device code`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.DeviceCodeRequest = {\n scopes,\n cancel: options?.abortSignal?.aborted ?? false,\n deviceCodeCallback,\n authority: calculateRequestAuthority(options),\n claims: options?.claims,\n };\n const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions);\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n requestOptions.cancel = true;\n });\n }\n\n return deviceCodeRequest;\n });\n }\n\n async function getTokenByUsernamePassword(\n scopes: string[],\n username: string,\n password: string,\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using username and password`);\n\n const msalApp = await getPublicApp(options);\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n const requestOptions: msal.UsernamePasswordRequest = {\n scopes,\n username,\n password,\n authority: calculateRequestAuthority(options),\n claims: options?.claims,\n };\n\n return msalApp.acquireTokenByUsernamePassword(requestOptions);\n });\n }\n\n function getActiveAccount(): AuthenticationRecord | undefined {\n if (!state.cachedAccount) {\n return undefined;\n }\n return msalToPublic(clientId, state.cachedAccount);\n }\n\n async function getTokenByAuthorizationCode(\n scopes: string[],\n redirectUri: string,\n authorizationCode: string,\n clientSecret?: string,\n options: GetTokenWithSilentAuthOptions = {},\n ): Promise<AccessToken> {\n state.logger.getToken.info(`Attempting to acquire token using authorization code`);\n\n let msalApp: msal.ConfidentialClientApplication | msal.PublicClientApplication;\n if (clientSecret) {\n // If a client secret is provided, we need to use a confidential client application\n // See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-client_secret\n state.msalConfig.auth.clientSecret = clientSecret;\n msalApp = await getConfidentialApp(options);\n } else {\n msalApp = await getPublicApp(options);\n }\n\n return withSilentAuthentication(msalApp, scopes, options, () => {\n return msalApp.acquireTokenByCode({\n scopes,\n redirectUri,\n code: authorizationCode,\n authority: calculateRequestAuthority(options),\n claims: options?.claims,\n });\n });\n }\n\n async function getTokenOnBehalfOf(\n scopes: string[],\n userAssertionToken: string,\n clientCredentials: string | CertificateParts | (() => Promise<string>),\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token on behalf of another user`);\n\n if (typeof clientCredentials === \"string\") {\n // Client secret\n msalLogger.getToken.info(`Using client secret for on behalf of flow`);\n state.msalConfig.auth.clientSecret = clientCredentials;\n } else if (typeof clientCredentials === \"function\") {\n // Client Assertion\n msalLogger.getToken.info(`Using client assertion callback for on behalf of flow`);\n state.msalConfig.auth.clientAssertion = clientCredentials;\n } else {\n // Client certificate\n msalLogger.getToken.info(`Using client certificate for on behalf of flow`);\n state.msalConfig.auth.clientCertificate = clientCredentials;\n }\n\n const msalApp = await getConfidentialApp(options);\n try {\n const response = await msalApp.acquireTokenOnBehalfOf({\n scopes,\n authority: calculateRequestAuthority(options),\n claims: options.claims,\n oboAssertion: userAssertionToken,\n });\n ensureValidMsalToken(scopes, response, options);\n\n msalLogger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n } catch (err: any) {\n throw handleMsalError(scopes, err, options);\n }\n }\n\n /**\n * Creates a base interactive request configuration for MSAL interactive authentication.\n * This is shared between interactive and brokered authentication flows.\n */\n function createBaseInteractiveRequest(\n scopes: string[],\n options: GetTokenInteractiveOptions,\n ): msal.InteractiveRequest {\n return {\n openBrowser: async (url) => {\n const open = await import(\"open\");\n await open.default(url);\n },\n scopes,\n authority: calculateRequestAuthority(options),\n claims: options?.claims,\n loginHint: options?.loginHint,\n errorTemplate: options?.browserCustomizationOptions?.errorMessage,\n successTemplate: options?.browserCustomizationOptions?.successMessage,\n prompt: options?.loginHint ? \"login\" : \"select_account\",\n };\n }\n\n /**\n * @internal\n */\n async function getBrokeredTokenInternal(\n scopes: string[],\n useDefaultBrokerAccount: boolean,\n options: GetTokenInteractiveOptions = {},\n ): Promise<msal.AuthenticationResult> {\n msalLogger.verbose(\"Authentication will resume through the broker\");\n\n const app = await getPublicApp(options);\n\n const interactiveRequest = createBaseInteractiveRequest(scopes, options);\n if (state.pluginConfiguration.broker.parentWindowHandle) {\n interactiveRequest.windowHandle = Buffer.from(\n state.pluginConfiguration.broker.parentWindowHandle,\n );\n } else {\n // this is a bug, as the pluginConfiguration handler should validate this case.\n msalLogger.warning(\n \"Parent window handle is not specified for the broker. This may cause unexpected behavior. Please provide the parentWindowHandle.\",\n );\n }\n\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n (interactiveRequest.extraQueryParameters ??= {})[\"msal_request_type\"] =\n \"consumer_passthrough\";\n }\n if (useDefaultBrokerAccount) {\n interactiveRequest.prompt = \"none\";\n msalLogger.verbose(\"Attempting broker authentication using the default broker account\");\n } else {\n msalLogger.verbose(\"Attempting broker authentication without the default broker account\");\n }\n\n if (options.proofOfPossessionOptions) {\n interactiveRequest.shrNonce = options.proofOfPossessionOptions.nonce;\n interactiveRequest.authenticationScheme = \"pop\";\n interactiveRequest.resourceRequestMethod =\n options.proofOfPossessionOptions.resourceRequestMethod;\n interactiveRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl;\n }\n try {\n return await app.acquireTokenInteractive(interactiveRequest);\n } catch (e: any) {\n msalLogger.verbose(`Failed to authenticate through the broker: ${e.message}`);\n if (options.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message: \"Cannot silently authenticate with default broker account.\",\n });\n }\n // If we tried to use the default broker account and failed, fall back to interactive authentication\n if (useDefaultBrokerAccount) {\n return getBrokeredTokenInternal(scopes, false, options);\n } else {\n throw e;\n }\n }\n }\n\n /**\n * A helper function that supports brokered authentication through the MSAL's public application.\n *\n * When useDefaultBrokerAccount is true, the method will attempt to authenticate using the default broker account.\n * If the default broker account is not available, the method will fall back to interactive authentication.\n */\n async function getBrokeredToken(\n scopes: string[],\n useDefaultBrokerAccount: boolean,\n options: GetTokenInteractiveOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(\n `Attempting to acquire token using brokered authentication with useDefaultBrokerAccount: ${useDefaultBrokerAccount}`,\n );\n const response = await getBrokeredTokenInternal(scopes, useDefaultBrokerAccount, options);\n ensureValidMsalToken(scopes, response, options);\n state.cachedAccount = response?.account ?? null;\n\n state.logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.accessToken,\n expiresOnTimestamp: response.expiresOn.getTime(),\n refreshAfterTimestamp: response.refreshOn?.getTime(),\n tokenType: response.tokenType,\n } as AccessToken;\n }\n\n async function getTokenByInteractiveRequest(\n scopes: string[],\n options: GetTokenInteractiveOptions = {},\n ): Promise<AccessToken> {\n msalLogger.getToken.info(`Attempting to acquire token interactively`);\n\n const app = await getPublicApp(options);\n\n return withSilentAuthentication(app, scopes, options, async () => {\n const interactiveRequest = createBaseInteractiveRequest(scopes, options);\n\n if (state.pluginConfiguration.broker.isEnabled) {\n return getBrokeredTokenInternal(\n scopes,\n state.pluginConfiguration.broker.useDefaultBrokerAccount ?? false,\n options,\n );\n }\n if (options.proofOfPossessionOptions) {\n interactiveRequest.shrNonce = options.proofOfPossessionOptions.nonce;\n interactiveRequest.authenticationScheme = \"pop\";\n interactiveRequest.resourceRequestMethod =\n options.proofOfPossessionOptions.resourceRequestMethod;\n interactiveRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl;\n }\n return app.acquireTokenInteractive(interactiveRequest);\n });\n }\n\n return {\n getActiveAccount,\n getBrokeredToken,\n getTokenByClientSecret,\n getTokenByClientAssertion,\n getTokenByClientCertificate,\n getTokenByDeviceCode,\n getToken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;AACA,UAAI,QAAQ,0BAA0B;AACpC,2BAAmB,WAAW,QAAQ,yBAAyB;AAC/D,2BAAmB,uBAAuB;AAC1C,2BAAmB,wBACjB,QAAQ,yBAAyB;AACnC,2BAAmB,qBAAqB,QAAQ,yBAAyB;AAAA,MAC3E;AACA,aAAO,IAAI,wBAAwB,kBAAkB;AAAA,IACvD,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,3 +1,8 @@
1
1
  {
2
- "type": "commonjs"
2
+ "name": "@azure/identity",
3
+ "version": "4.13.3",
4
+ "type": "commonjs",
5
+ "exports": {
6
+ "./package.json": "./package.json"
7
+ }
3
8
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Current version of the `@azure/identity` package.
3
3
  */
4
- export declare const SDK_VERSION = "4.13.2";
4
+ export declare const SDK_VERSION = "4.13.3";
5
5
  /**
6
6
  * The default client ID for authentication
7
7
  * @internal
@@ -3,7 +3,7 @@
3
3
  /**
4
4
  * Current version of the `@azure/identity` package.
5
5
  */
6
- export const SDK_VERSION = `4.13.2`;
6
+ export const SDK_VERSION = `4.13.3`;
7
7
  /**
8
8
  * The default client ID for authentication
9
9
  * @internal
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC;AAEpC;;;GAGG;AACH,2EAA2E;AAC3E,6CAA6C;AAC7C,uGAAuG;AACvG,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AAExC;;GAEG;AACH,MAAM,CAAN,IAAY,mBAoBX;AApBD,WAAY,mBAAmB;IAC7B;;OAEG;IACH,oEAA6C,CAAA;IAC7C;;;;;SAKK;IACL,wEAAiD,CAAA;IACjD;;OAEG;IACH,2EAAoD,CAAA;IACpD;;OAEG;IACH,6EAAsD,CAAA;AACxD,CAAC,EApBW,mBAAmB,KAAnB,mBAAmB,QAoB9B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,mBAAmB,CAAC,gBAAgB,CAAC;AAEzE;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AAE5D;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAa,CAAC,GAAG,CAAC,CAAC;AAE3C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAEtC;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,YAAY,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Current version of the `@azure/identity` package.\n */\nexport const SDK_VERSION = `4.13.2`;\n\n/**\n * The default client ID for authentication\n * @internal\n */\n// TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n// Developer Sign On application is available\n// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9\nexport const DeveloperSignOnClientId = \"04b07795-8ddb-461a-bbee-02f9e1bf7b46\";\n\n/**\n * The default tenant for authentication\n * @internal\n */\nexport const DefaultTenantId = \"common\";\n\n/**\n * A list of known Azure authority hosts\n */\nexport enum AzureAuthorityHosts {\n /**\n * China-based Azure Authority Host\n */\n AzureChina = \"https://login.chinacloudapi.cn\",\n /**\n * Germany-based Azure Authority Host\n *\n * @deprecated Microsoft Cloud Germany was closed on October 29th, 2021.\n *\n * */\n AzureGermany = \"https://login.microsoftonline.de\",\n /**\n * US Government Azure Authority Host\n */\n AzureGovernment = \"https://login.microsoftonline.us\",\n /**\n * Public Cloud Azure Authority Host\n */\n AzurePublicCloud = \"https://login.microsoftonline.com\",\n}\n\n/**\n * @internal\n * The default authority host.\n */\nexport const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;\n\n/**\n * @internal\n * The default environment host for Azure Public Cloud\n */\nexport const DefaultAuthority = \"login.microsoftonline.com\";\n\n/**\n * @internal\n * Allow acquiring tokens for any tenant for multi-tentant auth.\n */\nexport const ALL_TENANTS: string[] = [\"*\"];\n\n/**\n * @internal\n */\nexport const CACHE_CAE_SUFFIX = \"cae\";\n\n/**\n * @internal\n */\nexport const CACHE_NON_CAE_SUFFIX = \"nocae\";\n\n/**\n * @internal\n *\n * The default name for the cache persistence plugin.\n * Matches the constant defined in the cache persistence package.\n */\nexport const DEFAULT_TOKEN_CACHE_NAME = \"msal.cache\";\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC;AAEpC;;;GAGG;AACH,2EAA2E;AAC3E,6CAA6C;AAC7C,uGAAuG;AACvG,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AAExC;;GAEG;AACH,MAAM,CAAN,IAAY,mBAoBX;AApBD,WAAY,mBAAmB;IAC7B;;OAEG;IACH,oEAA6C,CAAA;IAC7C;;;;;SAKK;IACL,wEAAiD,CAAA;IACjD;;OAEG;IACH,2EAAoD,CAAA;IACpD;;OAEG;IACH,6EAAsD,CAAA;AACxD,CAAC,EApBW,mBAAmB,KAAnB,mBAAmB,QAoB9B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,mBAAmB,CAAC,gBAAgB,CAAC;AAEzE;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AAE5D;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAa,CAAC,GAAG,CAAC,CAAC;AAE3C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAEtC;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,YAAY,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Current version of the `@azure/identity` package.\n */\nexport const SDK_VERSION = `4.13.3`;\n\n/**\n * The default client ID for authentication\n * @internal\n */\n// TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n// Developer Sign On application is available\n// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9\nexport const DeveloperSignOnClientId = \"04b07795-8ddb-461a-bbee-02f9e1bf7b46\";\n\n/**\n * The default tenant for authentication\n * @internal\n */\nexport const DefaultTenantId = \"common\";\n\n/**\n * A list of known Azure authority hosts\n */\nexport enum AzureAuthorityHosts {\n /**\n * China-based Azure Authority Host\n */\n AzureChina = \"https://login.chinacloudapi.cn\",\n /**\n * Germany-based Azure Authority Host\n *\n * @deprecated Microsoft Cloud Germany was closed on October 29th, 2021.\n *\n * */\n AzureGermany = \"https://login.microsoftonline.de\",\n /**\n * US Government Azure Authority Host\n */\n AzureGovernment = \"https://login.microsoftonline.us\",\n /**\n * Public Cloud Azure Authority Host\n */\n AzurePublicCloud = \"https://login.microsoftonline.com\",\n}\n\n/**\n * @internal\n * The default authority host.\n */\nexport const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;\n\n/**\n * @internal\n * The default environment host for Azure Public Cloud\n */\nexport const DefaultAuthority = \"login.microsoftonline.com\";\n\n/**\n * @internal\n * Allow acquiring tokens for any tenant for multi-tentant auth.\n */\nexport const ALL_TENANTS: string[] = [\"*\"];\n\n/**\n * @internal\n */\nexport const CACHE_CAE_SUFFIX = \"cae\";\n\n/**\n * @internal\n */\nexport const CACHE_NON_CAE_SUFFIX = \"nocae\";\n\n/**\n * @internal\n *\n * The default name for the cache persistence plugin.\n * Matches the constant defined in the cache persistence package.\n */\nexport const DEFAULT_TOKEN_CACHE_NAME = \"msal.cache\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"azurePipelinesCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/azurePipelinesCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAItF,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AAG5F,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAQlE;;;GAGG;AACH,qBAAa,wBAAyB,YAAW,eAAe;IAC9D,OAAO,CAAC,yBAAyB,CAAwC;IACzE,OAAO,CAAC,cAAc,CAAiB;IAEvC;;;;;;;OAOG;gBAED,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,mBAAmB,EAAE,MAAM,EAC3B,iBAAiB,EAAE,MAAM,EACzB,OAAO,GAAE,+BAAoC;IAwD/C;;;;;;;OAOG;IACU,QAAQ,CACnB,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EACzB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,WAAW,CAAC;IAgBvB;;;;;OAKG;YACW,gBAAgB;CAmB/B;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,MAAM,CA6CrE"}
1
+ {"version":3,"file":"azurePipelinesCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/azurePipelinesCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAItF,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AAG5F,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAQlE;;;GAGG;AACH,qBAAa,wBAAyB,YAAW,eAAe;IAC9D,OAAO,CAAC,yBAAyB,CAAwC;IACzE,OAAO,CAAC,cAAc,CAAiB;IAEvC;;;;;;;OAOG;gBAED,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,mBAAmB,EAAE,MAAM,EAC3B,iBAAiB,EAAE,MAAM,EACzB,OAAO,GAAE,+BAAoC;IAwD/C;;;;;;;OAOG;IACU,QAAQ,CACnB,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EACzB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,WAAW,CAAC;IAgBvB;;;;;OAKG;YACW,gBAAgB;CAmB/B;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,MAAM,CAyCrE"}
@@ -105,11 +105,12 @@ export class AzurePipelinesCredential {
105
105
  export function handleOidcResponse(response) {
106
106
  // OIDC token is present in `bodyAsText` field
107
107
  const text = response.bodyAsText;
108
+ const responseDetails = stringifyOidcResponse(response);
108
109
  if (!text) {
109
- logger.error(`${credentialName}: Authentication Failed. Received null token from OIDC request. Response status- ${response.status}. Complete response - ${JSON.stringify(response)}`);
110
+ logger.error(`${credentialName}: Authentication Failed. Received null token from OIDC request. Response status- ${response.status}. Complete response - ${responseDetails}`);
110
111
  throw new AuthenticationError(response.status, {
111
112
  error: `${credentialName}: Authentication Failed. Received null token from OIDC request.`,
112
- error_description: `${JSON.stringify(response)}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,
113
+ error_description: `Complete response - ${responseDetails}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,
113
114
  });
114
115
  }
115
116
  try {
@@ -121,7 +122,7 @@ export function handleOidcResponse(response) {
121
122
  const errorMessage = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;
122
123
  let errorDescription = ``;
123
124
  if (response.status !== 200) {
124
- errorDescription = `Response body = ${text}. Response Headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;
125
+ errorDescription = `${responseDetails}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;
125
126
  }
126
127
  logger.error(errorMessage);
127
128
  logger.error(errorDescription);
@@ -133,13 +134,22 @@ export function handleOidcResponse(response) {
133
134
  }
134
135
  catch (e) {
135
136
  const errorDetails = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;
136
- logger.error(`Response from service = ${text}, Response Headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")}
137
- and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}, error message = ${e.message}`);
137
+ logger.error(`Response from service = ${responseDetails}, error message = ${e.message}`);
138
138
  logger.error(errorDetails);
139
139
  throw new AuthenticationError(response.status, {
140
140
  error: errorDetails,
141
- error_description: `Response = ${text}. Response headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,
141
+ error_description: `Response from service = ${responseDetails}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,
142
142
  });
143
143
  }
144
144
  }
145
+ function stringifyOidcResponse(response) {
146
+ return JSON.stringify({
147
+ status: response.status,
148
+ bodyAsText: response.bodyAsText,
149
+ headers: {
150
+ "x-vss-e2eid": response.headers.get("x-vss-e2eid"),
151
+ "x-msedge-ref": response.headers.get("x-msedge-ref"),
152
+ },
153
+ });
154
+ }
145
155
  //# sourceMappingURL=azurePipelinesCredential.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"azurePipelinesCredential.js","sourceRoot":"","sources":["../../../src/credentials/azurePipelinesCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,mBAAmB,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAGrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,iDAAiD,CAAC;AAC5F,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAClD,MAAM,MAAM,GAAG,gBAAgB,CAAC,cAAc,CAAC,CAAC;AAChD,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAE/B;;;GAGG;AACH,MAAM,OAAO,wBAAwB;IAC3B,yBAAyB,CAAwC;IACjE,cAAc,CAAiB;IAEvC;;;;;;;OAOG;IACH,YACE,QAAgB,EAChB,QAAgB,EAChB,mBAA2B,EAC3B,iBAAyB,EACzB,UAA2C,EAAE;QAE7C,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,IAAI,0BAA0B,CAClC,GAAG,cAAc,qDAAqD,CACvE,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,IAAI,0BAA0B,CAClC,GAAG,cAAc,qDAAqD,CACvE,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,mBAAmB,EAAE,CAAC;YACzB,MAAM,IAAI,0BAA0B,CAClC,GAAG,cAAc,gEAAgE,CAClF,CAAC;QACJ,CAAC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;YAC7C,KAAK,EAAE,YAAY;YACnB,iBAAiB,EAAE,cAAc,IAAI,wCAAwC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,4BAA4B,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,8HAA8H;SAC/S,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../errors.js\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\n\nimport type { AzurePipelinesCredentialOptions } from \"./azurePipelinesCredentialOptions.js\";\nimport { ClientAssertionCredential } from \"#platform/credentials/clientAssertionCredential\";\nimport { IdentityClient } from \"../client/identityClient.js\";\nimport type { PipelineResponse } from \"@azure/core-rest-pipeline\";\nimport { checkTenantId } from \"../util/tenantIdUtils.js\";\nimport { credentialLogger } from \"../util/logging.js\";\n\nconst credentialName = \"AzurePipelinesCredential\";\nconst logger = credentialLogger(credentialName);\nconst OIDC_API_VERSION = \"7.1\";\n\n/**\n * This credential is designed to be used in Azure Pipelines with service connections\n * as a setup for workload identity federation.\n */\nexport class AzurePipelinesCredential implements TokenCredential {\n private clientAssertionCredential: ClientAssertionCredential | undefined;\n private identityClient: IdentityClient;\n\n /**\n * AzurePipelinesCredential supports Federated Identity on Azure Pipelines through Service Connections.\n * @param tenantId - tenantId associated with the service connection\n * @param clientId - clientId associated with the service connection\n * @param serviceConnectionId - Unique ID for the service connection, as found in the querystring's resourceId key\n * @param systemAccessToken - The pipeline's <see href=\"https://learn.microsoft.com/azure/devops/pipelines/build/variables?view=azure-devops%26tabs=yaml#systemaccesstoken\">System.AccessToken</see> value.\n * @param options - The identity client options to use for authentication.\n */\n constructor(\n tenantId: string,\n clientId: string,\n serviceConnectionId: string,\n systemAccessToken: string,\n options: AzurePipelinesCredentialOptions = {},\n ) {\n if (!clientId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. clientId is a required parameter.`,\n );\n }\n if (!tenantId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. tenantId is a required parameter.`,\n );\n }\n if (!serviceConnectionId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. serviceConnectionId is a required parameter.`,\n );\n }\n if (!systemAccessToken) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. systemAccessToken is a required parameter.`,\n );\n }\n\n // Allow these headers to be logged for troubleshooting by AzurePipelines.\n options.loggingOptions = {\n ...options?.loggingOptions,\n additionalAllowedHeaderNames: [\n ...(options.loggingOptions?.additionalAllowedHeaderNames ?? []),\n \"x-vss-e2eid\",\n \"x-msedge-ref\",\n ],\n };\n\n this.identityClient = new IdentityClient(options);\n checkTenantId(logger, tenantId);\n logger.info(\n `Invoking AzurePipelinesCredential with tenant ID: ${tenantId}, client ID: ${clientId}, and service connection ID: ${serviceConnectionId}`,\n );\n if (!process.env.SYSTEM_OIDCREQUESTURI) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- \"SYSTEM_OIDCREQUESTURI\"`,\n );\n }\n\n const oidcRequestUrl = `${process.env.SYSTEM_OIDCREQUESTURI}?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`;\n logger.info(\n `Invoking ClientAssertionCredential with tenant ID: ${tenantId}, client ID: ${clientId} and service connection ID: ${serviceConnectionId}`,\n );\n this.clientAssertionCredential = new ClientAssertionCredential(\n tenantId,\n clientId,\n this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken),\n options,\n );\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} or {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n if (!this.clientAssertionCredential) {\n const errorMessage = `${credentialName}: is unavailable. To use Federation Identity in Azure Pipelines, the following parameters are required - \n tenantId,\n clientId,\n serviceConnectionId,\n systemAccessToken,\n \"SYSTEM_OIDCREQUESTURI\". \n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;\n logger.error(errorMessage);\n throw new CredentialUnavailableError(errorMessage);\n }\n logger.info(\"Invoking getToken() of Client Assertion Credential\");\n return this.clientAssertionCredential.getToken(scopes, options);\n }\n\n /**\n *\n * @param oidcRequestUrl - oidc request url\n * @param systemAccessToken - system access token\n * @returns OIDC token from Azure Pipelines\n */\n private async requestOidcToken(\n oidcRequestUrl: string,\n systemAccessToken: string,\n ): Promise<string> {\n logger.info(\"Requesting OIDC token from Azure Pipelines...\");\n logger.info(oidcRequestUrl);\n const request = createPipelineRequest({\n url: oidcRequestUrl,\n method: \"POST\",\n headers: createHttpHeaders({\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${systemAccessToken}`,\n // Prevents the service from responding with a redirect HTTP status code (useful for automation).\n \"X-TFS-FedAuthRedirect\": \"Suppress\",\n }),\n });\n const response = await this.identityClient.sendRequest(request);\n return handleOidcResponse(response);\n }\n}\n\nexport function handleOidcResponse(response: PipelineResponse): string {\n // OIDC token is present in `bodyAsText` field\n const text = response.bodyAsText;\n if (!text) {\n logger.error(\n `${credentialName}: Authentication Failed. Received null token from OIDC request. Response status- ${\n response.status\n }. Complete response - ${JSON.stringify(response)}`,\n );\n throw new AuthenticationError(response.status, {\n error: `${credentialName}: Authentication Failed. Received null token from OIDC request.`,\n error_description: `${JSON.stringify(\n response,\n )}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,\n });\n }\n try {\n const result = JSON.parse(text);\n if (result?.oidcToken) {\n return result.oidcToken;\n } else {\n const errorMessage = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;\n let errorDescription = ``;\n if (response.status !== 200) {\n errorDescription = `Response body = ${text}. Response Headers [\"x-vss-e2eid\"] = ${response.headers.get(\"x-vss-e2eid\")} and [\"x-msedge-ref\"] = ${response.headers.get(\"x-msedge-ref\")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;\n }\n logger.error(errorMessage);\n logger.error(errorDescription);\n throw new AuthenticationError(response.status, {\n error: errorMessage,\n error_description: errorDescription,\n });\n }\n } catch (e: any) {\n const errorDetails = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;\n logger.error(\n `Response from service = ${text}, Response Headers [\"x-vss-e2eid\"] = ${response.headers.get(\"x-vss-e2eid\")} \n and [\"x-msedge-ref\"] = ${response.headers.get(\"x-msedge-ref\")}, error message = ${e.message}`,\n );\n logger.error(errorDetails);\n throw new AuthenticationError(response.status, {\n error: errorDetails,\n error_description: `Response = ${text}. Response headers [\"x-vss-e2eid\"] = ${response.headers.get(\"x-vss-e2eid\")} and [\"x-msedge-ref\"] = ${response.headers.get(\"x-msedge-ref\")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"azurePipelinesCredential.js","sourceRoot":"","sources":["../../../src/credentials/azurePipelinesCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,mBAAmB,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAGrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,iDAAiD,CAAC;AAC5F,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,gBAAg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C,gBAAgB,CAAC,CAAC;YAC/B,MAAM,IAAI,mBAAmB,CAAC,QAAQ,CAAC,MAAM,EAAE;gBAC7C,KAAK,EAAE,YAAY;gBACnB,iBAAiB,EAAE,gBAAgB;aACpC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAAC,OAAO,CAAM,EAAE,CAAC;QAChB,MAAM,YAAY,GAAG,GAAG,cAAc,wEAAwE,CAAC;QAC/G,MAAM,CAAC,KAAK,CAAC,2BAA2B,eAAe,qBAAqB,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QACzF,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QAC3B,MAAM,IAAI,mBAAmB,CAAC,QAAQ,CAAC,MAAM,EAAE;YAC7C,KAAK,EAAE,YAAY;YACnB,iBAAiB,EAAE,2BAA2B,eAAe,8HAA8H;SAC5L,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AAED,SAAS,qBAAqB,CAAC,QAA0B;IACvD,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,OAAO,EAAE;YACP,aAAa,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;YAClD,cAAc,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC;SACrD;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../errors.js\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\n\nimport type { AzurePipelinesCredentialOptions } from \"./azurePipelinesCredentialOptions.js\";\nimport { ClientAssertionCredential } from \"#platform/credentials/clientAssertionCredential\";\nimport { IdentityClient } from \"../client/identityClient.js\";\nimport type { PipelineResponse } from \"@azure/core-rest-pipeline\";\nimport { checkTenantId } from \"../util/tenantIdUtils.js\";\nimport { credentialLogger } from \"../util/logging.js\";\n\nconst credentialName = \"AzurePipelinesCredential\";\nconst logger = credentialLogger(credentialName);\nconst OIDC_API_VERSION = \"7.1\";\n\n/**\n * This credential is designed to be used in Azure Pipelines with service connections\n * as a setup for workload identity federation.\n */\nexport class AzurePipelinesCredential implements TokenCredential {\n private clientAssertionCredential: ClientAssertionCredential | undefined;\n private identityClient: IdentityClient;\n\n /**\n * AzurePipelinesCredential supports Federated Identity on Azure Pipelines through Service Connections.\n * @param tenantId - tenantId associated with the service connection\n * @param clientId - clientId associated with the service connection\n * @param serviceConnectionId - Unique ID for the service connection, as found in the querystring's resourceId key\n * @param systemAccessToken - The pipeline's <see href=\"https://learn.microsoft.com/azure/devops/pipelines/build/variables?view=azure-devops%26tabs=yaml#systemaccesstoken\">System.AccessToken</see> value.\n * @param options - The identity client options to use for authentication.\n */\n constructor(\n tenantId: string,\n clientId: string,\n serviceConnectionId: string,\n systemAccessToken: string,\n options: AzurePipelinesCredentialOptions = {},\n ) {\n if (!clientId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. clientId is a required parameter.`,\n );\n }\n if (!tenantId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. tenantId is a required parameter.`,\n );\n }\n if (!serviceConnectionId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. serviceConnectionId is a required parameter.`,\n );\n }\n if (!systemAccessToken) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. systemAccessToken is a required parameter.`,\n );\n }\n\n // Allow these headers to be logged for troubleshooting by AzurePipelines.\n options.loggingOptions = {\n ...options?.loggingOptions,\n additionalAllowedHeaderNames: [\n ...(options.loggingOptions?.additionalAllowedHeaderNames ?? []),\n \"x-vss-e2eid\",\n \"x-msedge-ref\",\n ],\n };\n\n this.identityClient = new IdentityClient(options);\n checkTenantId(logger, tenantId);\n logger.info(\n `Invoking AzurePipelinesCredential with tenant ID: ${tenantId}, client ID: ${clientId}, and service connection ID: ${serviceConnectionId}`,\n );\n if (!process.env.SYSTEM_OIDCREQUESTURI) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- \"SYSTEM_OIDCREQUESTURI\"`,\n );\n }\n\n const oidcRequestUrl = `${process.env.SYSTEM_OIDCREQUESTURI}?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`;\n logger.info(\n `Invoking ClientAssertionCredential with tenant ID: ${tenantId}, client ID: ${clientId} and service connection ID: ${serviceConnectionId}`,\n );\n this.clientAssertionCredential = new ClientAssertionCredential(\n tenantId,\n clientId,\n this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken),\n options,\n );\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} or {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions,\n ): Promise<AccessToken> {\n if (!this.clientAssertionCredential) {\n const errorMessage = `${credentialName}: is unavailable. To use Federation Identity in Azure Pipelines, the following parameters are required - \n tenantId,\n clientId,\n serviceConnectionId,\n systemAccessToken,\n \"SYSTEM_OIDCREQUESTURI\". \n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;\n logger.error(errorMessage);\n throw new CredentialUnavailableError(errorMessage);\n }\n logger.info(\"Invoking getToken() of Client Assertion Credential\");\n return this.clientAssertionCredential.getToken(scopes, options);\n }\n\n /**\n *\n * @param oidcRequestUrl - oidc request url\n * @param systemAccessToken - system access token\n * @returns OIDC token from Azure Pipelines\n */\n private async requestOidcToken(\n oidcRequestUrl: string,\n systemAccessToken: string,\n ): Promise<string> {\n logger.info(\"Requesting OIDC token from Azure Pipelines...\");\n logger.info(oidcRequestUrl);\n const request = createPipelineRequest({\n url: oidcRequestUrl,\n method: \"POST\",\n headers: createHttpHeaders({\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${systemAccessToken}`,\n // Prevents the service from responding with a redirect HTTP status code (useful for automation).\n \"X-TFS-FedAuthRedirect\": \"Suppress\",\n }),\n });\n const response = await this.identityClient.sendRequest(request);\n return handleOidcResponse(response);\n }\n}\n\nexport function handleOidcResponse(response: PipelineResponse): string {\n // OIDC token is present in `bodyAsText` field\n const text = response.bodyAsText;\n const responseDetails = stringifyOidcResponse(response);\n if (!text) {\n logger.error(\n `${credentialName}: Authentication Failed. Received null token from OIDC request. Response status- ${\n response.status\n }. Complete response - ${responseDetails}`,\n );\n throw new AuthenticationError(response.status, {\n error: `${credentialName}: Authentication Failed. Received null token from OIDC request.`,\n error_description: `Complete response - ${responseDetails}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,\n });\n }\n try {\n const result = JSON.parse(text);\n if (result?.oidcToken) {\n return result.oidcToken;\n } else {\n const errorMessage = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;\n let errorDescription = ``;\n if (response.status !== 200) {\n errorDescription = `${responseDetails}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`;\n }\n logger.error(errorMessage);\n logger.error(errorDescription);\n throw new AuthenticationError(response.status, {\n error: errorMessage,\n error_description: errorDescription,\n });\n }\n } catch (e: any) {\n const errorDetails = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`;\n logger.error(`Response from service = ${responseDetails}, error message = ${e.message}`);\n logger.error(errorDetails);\n throw new AuthenticationError(response.status, {\n error: errorDetails,\n error_description: `Response from service = ${responseDetails}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`,\n });\n }\n}\n\nfunction stringifyOidcResponse(response: PipelineResponse): string {\n return JSON.stringify({\n status: response.status,\n bodyAsText: response.bodyAsText,\n headers: {\n \"x-vss-e2eid\": response.headers.get(\"x-vss-e2eid\"),\n \"x-msedge-ref\": response.headers.get(\"x-msedge-ref\"),\n },\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"azurePowerShellCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/azurePowerShellCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAStF,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AAgB9F;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,WAAW,GAAE,MAAM,CAAC,UAAwB,GAC3C,MAAM,CAAC,UAAU,CASnB;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAMzD;AA4BD;;;GAGG;AACH,eAAO,MAAM,gBAAgB;;;CAI5B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,6BAA6B;;;;;CAOzC,CAAC;AAUF;;;;GAIG;AACH,eAAO,MAAM,YAAY,UAA0B,CAAC;AAMpD;;;;GAIG;AACH,qBAAa,yBAA0B,YAAW,eAAe;IAC/D,OAAO,CAAC,QAAQ,CAAC,CAAS;IAC1B,OAAO,CAAC,4BAA4B,CAAW;IAC/C,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB;;;;;;;;;;OAUG;gBACS,OAAO,CAAC,EAAE,gCAAgC;IAWtD;;;OAGG;YACW,6BAA6B;IA6E3C;;;;;;OAMG;IACU,QAAQ,CACnB,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EACzB,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,WAAW,CAAC;CA0DxB;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,MAAM,EAAE,MAAM,GACb,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,CAyB/C"}
1
+ {"version":3,"file":"azurePowerShellCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/azurePowerShellCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAStF,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AAgB9F;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,WAAW,GAAE,MAAM,CAAC,UAAwB,GAC3C,MAAM,CAAC,UAAU,CASnB;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAMzD;AA4BD;;;GAGG;AACH,eAAO,MAAM,gBAAgB;;;CAI5B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,6BAA6B;;;;;CAOzC,CAAC;AAUF;;;;GAIG;AACH,eAAO,MAAM,YAAY,UAA0B,CAAC;AAMpD;;;;GAIG;AACH,qBAAa,yBAA0B,YAAW,eAAe;IAC/D,OAAO,CAAC,QAAQ,CAAC,CAAS;IAC1B,OAAO,CAAC,4BAA4B,CAAW;IAC/C,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB;;;;;;;;;;OAUG;gBACS,OAAO,CAAC,EAAE,gCAAgC;IAWtD;;;OAGG;YACW,6BAA6B;IA6E3C;;;;;;OAMG;IACU,QAAQ,CACnB,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EACzB,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,WAAW,CAAC;CA0DxB;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,MAAM,EAAE,MAAM,GACb,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,CA2B/C"}
@@ -270,7 +270,9 @@ export async function parseJsonToken(result) {
270
270
  }
271
271
  }
272
272
  catch (e) {
273
- throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);
273
+ throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`, {
274
+ cause: e,
275
+ });
274
276
  }
275
277
  }
276
278
  throw new Error(`No access token found in the output. Received output: ${result}`);
@@ -1 +1 @@
1
- {"version":3,"file":"azurePowerShellCredential.js","sourceRoot":"","sources":["../../../src/credentials/azurePowerShellCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EACL,aAAa,EACb,yBAAyB,EACzB,mCAAmC,GACpC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,+BAA+B,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG1F,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D,MAAM,SAAS,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;AAC/C,MAAM,qCAAqC,GAAG,oCAAoC,CAAC;AACnF,MAAM,mCAAmC,GAAG,qCAAqC,CAAC;AAClF,MAAM,qCAAqC,GAAG,IAAI,GAAG,CACnD,CAAC,qCAAqC,EAAE,mCAAmC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACxF,IAAI,CAAC,WAAW,EAAE,CACnB,CACF,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2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AAkB,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;wBAC1D,IAAI,kBAAkB,EAAE,CAAC;4BACvB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;wBAC9C,CAAC;wBACD,OAAO,WAAW,CAAC;oBACrB,CAAC;gBACH,CAAC;gBAAC,OAAO,CAAC,EAAE,CAAC;oBACX,SAAS;gBACX,CAAC;YACH,CAAC;QACH,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,8DAA8D,MAAM,EAAE,CAAC,CAAC;QAC1F,CAAC;IACH,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,yDAAyD,MAAM,EAAE,CAAC,CAAC;AACrF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils.js\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging.js\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils.js\";\n\nimport type { AzurePowerShellCredentialOptions } from \"./azurePowerShellCredentialOptions.js\";\nimport { CredentialUnavailableError } from \"../errors.js\";\nimport { processUtils } from \"../util/processUtils.js\";\nimport { tracingClient } from \"../util/tracing.js\";\n\nconst logger = credentialLogger(\"AzurePowerShellCredential\");\n\nconst isWindows = process.platform === \"win32\";\nconst powerShellResourceEnvironmentVariable = \"AZURE_IDENTITY_POWERSHELL_RESOURCE\";\nconst powerShellTenantEnvironmentVariable = \"AZURE_IDENTITY_POWERSHELL_TENANT_ID\";\nconst powerShellPrivateEnvironmentVariables = new Set(\n [powerShellResourceEnvironmentVariable, powerShellTenantEnvironmentVariable].map((name) =>\n name.toLowerCase(),\n ),\n);\n\n/**\n * Creates the child environment used to pass private values to PowerShell.\n *\n * @param resource - The resource passed to PowerShell.\n * @param tenantId - The optional tenant ID passed to PowerShell.\n * @param environment - The environment to copy.\n * @returns A child environment containing canonical private variable names.\n * @internal\n */\nexport function createPowerShellEnvironment(\n resource: string,\n tenantId: string | undefined,\n environment: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n const childEnvironment = Object.fromEntries(\n Object.entries(environment).filter(\n ([name]) => !powerShellPrivateEnvironmentVariables.has(name.toLowerCase()),\n ),\n );\n childEnvironment[powerShellResourceEnvironmentVariable] = resource;\n childEnvironment[powerShellTenantEnvironmentVariable] = tenantId ?? \"\";\n return childEnvironment;\n}\n\n/**\n * Returns a platform-appropriate command name by appending \".exe\" on Windows.\n *\n * @internal\n */\nexport function formatCommand(commandName: string): string {\n if (isWindows) {\n return `${commandName}.exe`;\n } else {\n return commandName;\n }\n}\n\n/**\n * Receives a list of commands to run, executes them, then returns the outputs.\n * If anything fails, an error is thrown.\n * @internal\n */\nasync function runCommands(\n commands: string[][],\n timeout?: number,\n env?: NodeJS.ProcessEnv,\n): Promise<string[]> {\n const results: string[] = [];\n\n for (const command of commands) {\n const [file, ...parameters] = command;\n const result = await processUtils.execFile(file, parameters, {\n encoding: \"utf8\",\n env,\n timeout,\n });\n\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Known PowerShell errors\n * @internal\n */\nexport const powerShellErrors = {\n login: \"Run Connect-AzAccount to login\",\n installed:\n \"The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory\",\n};\n\n/**\n * Messages to use when throwing in this credential.\n * @internal\n */\nexport const powerShellPublicErrorMessages = {\n login:\n \"Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.\",\n installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: \"Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force\".`,\n claim:\n \"This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:\",\n troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`,\n};\n\n// PowerShell Azure User not logged in error check.\nconst isLoginError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(`(.*)${powerShellErrors.login}(.*)`);\n\n// Az Module not Installed in Azure PowerShell check.\nconst isNotInstalledError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(powerShellErrors.installed);\n\n/**\n * The PowerShell commands to be tried, in order.\n *\n * @internal\n */\nexport const commandStack = [formatCommand(\"pwsh\")];\n\nif (isWindows) {\n commandStack.push(formatCommand(\"powershell\"));\n}\n\n/**\n * This credential will use the currently logged-in user information from the\n * Azure PowerShell module. To do so, it will read the user access token and\n * expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}`\n */\nexport class AzurePowerShellCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzurePowerShellCredential}.\n *\n * To use this credential:\n * - Install the Azure Az PowerShell module with:\n * `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`.\n * - You have already logged in to Azure PowerShell using the command\n * `Connect-AzAccount` from the command line.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzurePowerShellCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Gets the access token from Azure PowerShell\n * @param resource - The resource to use when getting the token\n */\n private async getAzurePowerShellAccessToken(\n resource: string,\n tenantId?: string,\n timeout?: number,\n ): Promise<{ Token: string; ExpiresOn: string }> {\n // Clone the stack to avoid mutating it while iterating\n for (const powerShellCommand of [...commandStack]) {\n try {\n await runCommands([[powerShellCommand, \"/?\"]], timeout);\n } catch (e: any) {\n // Remove this credential from the original stack so that we don't try it again.\n commandStack.shift();\n continue;\n }\n\n const results = await runCommands(\n [\n [\n powerShellCommand,\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `\n $tenantId = $env:${powerShellTenantEnvironmentVariable}\n $resource = $env:${powerShellResourceEnvironmentVariable}\n $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru\n $useSecureString = $m.Version -ge [version]'2.17.0' -and $m.Version -lt [version]'5.0.0'\n\n $params = @{\n ResourceUrl = $resource\n }\n\n if ($tenantId.Length -gt 0) {\n $params[\"TenantId\"] = $tenantId\n }\n\n if ($useSecureString) {\n $params[\"AsSecureString\"] = $true\n }\n\n $token = Get-AzAccessToken @params\n\n $result = New-Object -TypeName PSObject\n $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn\n\n if ($token.Token -is [System.Security.SecureString]) {\n if ($PSVersionTable.PSVersion.Major -lt 7) {\n $ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($token.Token)\n try {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value ([System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr))\n }\n finally {\n [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)\n }\n }\n else {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value ($token.Token | ConvertFrom-SecureString -AsPlainText)\n }\n }\n else {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token\n }\n\n Write-Output (ConvertTo-Json $result)\n `,\n ],\n ],\n timeout,\n createPowerShellEnvironment(resource, tenantId),\n );\n\n const result = results[0];\n return parseJsonToken(result);\n }\n throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n\n const claimsValue = options.claims;\n if (claimsValue && claimsValue.trim()) {\n const encodedClaims = btoa(claimsValue);\n let loginCmd = `Connect-AzAccount -ClaimsChallenge ${encodedClaims}`;\n\n const tenantIdFromOptions = options.tenantId;\n if (tenantIdFromOptions) {\n loginCmd += ` -Tenant ${tenantIdFromOptions}`;\n }\n const error = new CredentialUnavailableError(\n `${powerShellPublicErrorMessages.claim} ${loginCmd}`,\n );\n\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n try {\n ensureValidScopeForDevTimeCreds(scope, logger);\n logger.getToken.info(`Using the scope ${scope}`);\n const resource = getScopeResource(scope);\n const response = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.Token,\n expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n if (isNotInstalledError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);\n logger.getToken.info(formatError(scope, error));\n throw error;\n } else if (isLoginError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n const error = new CredentialUnavailableError(\n `${err}. ${powerShellPublicErrorMessages.troubleshoot}`,\n );\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n });\n }\n}\n\n/**\n *\n * @internal\n */\nexport async function parseJsonToken(\n result: string,\n): Promise<{ Token: string; ExpiresOn: string }> {\n const jsonRegex = /{[^{}]*}/g;\n const matches = result.match(jsonRegex);\n let resultWithoutToken = result;\n if (matches) {\n try {\n for (const item of matches) {\n try {\n const jsonContent = JSON.parse(item);\n if (jsonContent?.Token) {\n resultWithoutToken = resultWithoutToken.replace(item, \"\");\n if (resultWithoutToken) {\n logger.getToken.warning(resultWithoutToken);\n }\n return jsonContent;\n }\n } catch (e) {\n continue;\n }\n }\n } catch (e: any) {\n throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);\n }\n }\n throw new Error(`No access token found in the output. Received output: ${result}`);\n}\n"]}
1
+ {"version":3,"file":"azurePowerShellCredential.js","sourceRoot":"","sources":["../../../src/credentials/azurePowerShellCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EACL,aAAa,EACb,yBAAyB,EACzB,mCAAmC,GACpC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,+BAA+B,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG1F,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D,MAAM,SAAS,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;AAC/C,MAAM,qCAAqC,GAAG,oCAAoC,CAAC;AACnF,MAAM,mCAAmC,GAAG,qCAAqC,CAAC;AAClF,MAAM,qCAAqC,GAAG,IAAI,GAAG,CACnD,CAAC,qCAAqC,EAAE,mCAAmC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACxF,IAAI,CAAC,WAAW,EAAE,CACnB,CACF,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CACzC,QAAgB,EAChB,QAA4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AI,EAAE,EAAE,CAAC,CAAC;wBAC1D,IAAI,kBAAkB,EAAE,CAAC;4BACvB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;wBAC9C,CAAC;wBACD,OAAO,WAAW,CAAC;oBACrB,CAAC;gBACH,CAAC;gBAAC,OAAO,CAAC,EAAE,CAAC;oBACX,SAAS;gBACX,CAAC;YACH,CAAC;QACH,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,8DAA8D,MAAM,EAAE,EAAE;gBACtF,KAAK,EAAE,CAAC;aACT,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,yDAAyD,MAAM,EAAE,CAAC,CAAC;AACrF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils.js\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging.js\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils.js\";\n\nimport type { AzurePowerShellCredentialOptions } from \"./azurePowerShellCredentialOptions.js\";\nimport { CredentialUnavailableError } from \"../errors.js\";\nimport { processUtils } from \"../util/processUtils.js\";\nimport { tracingClient } from \"../util/tracing.js\";\n\nconst logger = credentialLogger(\"AzurePowerShellCredential\");\n\nconst isWindows = process.platform === \"win32\";\nconst powerShellResourceEnvironmentVariable = \"AZURE_IDENTITY_POWERSHELL_RESOURCE\";\nconst powerShellTenantEnvironmentVariable = \"AZURE_IDENTITY_POWERSHELL_TENANT_ID\";\nconst powerShellPrivateEnvironmentVariables = new Set(\n [powerShellResourceEnvironmentVariable, powerShellTenantEnvironmentVariable].map((name) =>\n name.toLowerCase(),\n ),\n);\n\n/**\n * Creates the child environment used to pass private values to PowerShell.\n *\n * @param resource - The resource passed to PowerShell.\n * @param tenantId - The optional tenant ID passed to PowerShell.\n * @param environment - The environment to copy.\n * @returns A child environment containing canonical private variable names.\n * @internal\n */\nexport function createPowerShellEnvironment(\n resource: string,\n tenantId: string | undefined,\n environment: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n const childEnvironment = Object.fromEntries(\n Object.entries(environment).filter(\n ([name]) => !powerShellPrivateEnvironmentVariables.has(name.toLowerCase()),\n ),\n );\n childEnvironment[powerShellResourceEnvironmentVariable] = resource;\n childEnvironment[powerShellTenantEnvironmentVariable] = tenantId ?? \"\";\n return childEnvironment;\n}\n\n/**\n * Returns a platform-appropriate command name by appending \".exe\" on Windows.\n *\n * @internal\n */\nexport function formatCommand(commandName: string): string {\n if (isWindows) {\n return `${commandName}.exe`;\n } else {\n return commandName;\n }\n}\n\n/**\n * Receives a list of commands to run, executes them, then returns the outputs.\n * If anything fails, an error is thrown.\n * @internal\n */\nasync function runCommands(\n commands: string[][],\n timeout?: number,\n env?: NodeJS.ProcessEnv,\n): Promise<string[]> {\n const results: string[] = [];\n\n for (const command of commands) {\n const [file, ...parameters] = command;\n const result = await processUtils.execFile(file, parameters, {\n encoding: \"utf8\",\n env,\n timeout,\n });\n\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Known PowerShell errors\n * @internal\n */\nexport const powerShellErrors = {\n login: \"Run Connect-AzAccount to login\",\n installed:\n \"The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory\",\n};\n\n/**\n * Messages to use when throwing in this credential.\n * @internal\n */\nexport const powerShellPublicErrorMessages = {\n login:\n \"Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.\",\n installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: \"Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force\".`,\n claim:\n \"This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:\",\n troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`,\n};\n\n// PowerShell Azure User not logged in error check.\nconst isLoginError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(`(.*)${powerShellErrors.login}(.*)`);\n\n// Az Module not Installed in Azure PowerShell check.\nconst isNotInstalledError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(powerShellErrors.installed);\n\n/**\n * The PowerShell commands to be tried, in order.\n *\n * @internal\n */\nexport const commandStack = [formatCommand(\"pwsh\")];\n\nif (isWindows) {\n commandStack.push(formatCommand(\"powershell\"));\n}\n\n/**\n * This credential will use the currently logged-in user information from the\n * Azure PowerShell module. To do so, it will read the user access token and\n * expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}`\n */\nexport class AzurePowerShellCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzurePowerShellCredential}.\n *\n * To use this credential:\n * - Install the Azure Az PowerShell module with:\n * `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`.\n * - You have already logged in to Azure PowerShell using the command\n * `Connect-AzAccount` from the command line.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzurePowerShellCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Gets the access token from Azure PowerShell\n * @param resource - The resource to use when getting the token\n */\n private async getAzurePowerShellAccessToken(\n resource: string,\n tenantId?: string,\n timeout?: number,\n ): Promise<{ Token: string; ExpiresOn: string }> {\n // Clone the stack to avoid mutating it while iterating\n for (const powerShellCommand of [...commandStack]) {\n try {\n await runCommands([[powerShellCommand, \"/?\"]], timeout);\n } catch (e: any) {\n // Remove this credential from the original stack so that we don't try it again.\n commandStack.shift();\n continue;\n }\n\n const results = await runCommands(\n [\n [\n powerShellCommand,\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `\n $tenantId = $env:${powerShellTenantEnvironmentVariable}\n $resource = $env:${powerShellResourceEnvironmentVariable}\n $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru\n $useSecureString = $m.Version -ge [version]'2.17.0' -and $m.Version -lt [version]'5.0.0'\n\n $params = @{\n ResourceUrl = $resource\n }\n\n if ($tenantId.Length -gt 0) {\n $params[\"TenantId\"] = $tenantId\n }\n\n if ($useSecureString) {\n $params[\"AsSecureString\"] = $true\n }\n\n $token = Get-AzAccessToken @params\n\n $result = New-Object -TypeName PSObject\n $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn\n\n if ($token.Token -is [System.Security.SecureString]) {\n if ($PSVersionTable.PSVersion.Major -lt 7) {\n $ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($token.Token)\n try {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value ([System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr))\n }\n finally {\n [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)\n }\n }\n else {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value ($token.Token | ConvertFrom-SecureString -AsPlainText)\n }\n }\n else {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token\n }\n\n Write-Output (ConvertTo-Json $result)\n `,\n ],\n ],\n timeout,\n createPowerShellEnvironment(resource, tenantId),\n );\n\n const result = results[0];\n return parseJsonToken(result);\n }\n throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n\n const claimsValue = options.claims;\n if (claimsValue && claimsValue.trim()) {\n const encodedClaims = btoa(claimsValue);\n let loginCmd = `Connect-AzAccount -ClaimsChallenge ${encodedClaims}`;\n\n const tenantIdFromOptions = options.tenantId;\n if (tenantIdFromOptions) {\n loginCmd += ` -Tenant ${tenantIdFromOptions}`;\n }\n const error = new CredentialUnavailableError(\n `${powerShellPublicErrorMessages.claim} ${loginCmd}`,\n );\n\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n try {\n ensureValidScopeForDevTimeCreds(scope, logger);\n logger.getToken.info(`Using the scope ${scope}`);\n const resource = getScopeResource(scope);\n const response = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.Token,\n expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n if (isNotInstalledError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);\n logger.getToken.info(formatError(scope, error));\n throw error;\n } else if (isLoginError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n const error = new CredentialUnavailableError(\n `${err}. ${powerShellPublicErrorMessages.troubleshoot}`,\n );\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n });\n }\n}\n\n/**\n *\n * @internal\n */\nexport async function parseJsonToken(\n result: string,\n): Promise<{ Token: string; ExpiresOn: string }> {\n const jsonRegex = /{[^{}]*}/g;\n const matches = result.match(jsonRegex);\n let resultWithoutToken = result;\n if (matches) {\n try {\n for (const item of matches) {\n try {\n const jsonContent = JSON.parse(item);\n if (jsonContent?.Token) {\n resultWithoutToken = resultWithoutToken.replace(item, \"\");\n if (resultWithoutToken) {\n logger.getToken.warning(resultWithoutToken);\n }\n return jsonContent;\n }\n } catch (e) {\n continue;\n }\n }\n } catch (e: any) {\n throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`, {\n cause: e,\n });\n }\n }\n throw new Error(`No access token found in the output. Received output: ${result}`);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"defaultAzureCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/defaultAzureCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,qCAAqC,EACrC,6BAA6B,EAC7B,uCAAuC,EACxC,MAAM,oCAAoC,CAAC;AAO5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAErE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAgBxD;;;GAGG;AACH,qBAAa,4BAA6B,YAAW,eAAe;IAClE,iCAAiC,EAAE,MAAM,CAAC;IAC1C,cAAc,EAAE,MAAM,CAAC;gBAEX,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;IAKnD,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAM1B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,qBAAa,sBAAuB,SAAQ,sBAAsB;IAChE;;;;OAIG;gBACS,OAAO,CAAC,EAAE,qCAAqC;IAE3D;;;;OAIG;gBACS,OAAO,CAAC,EAAE,uCAAuC;IAE7D;;;;OAIG;gBACS,OAAO,CAAC,EAAE,6BAA6B;CAyFpD"}
1
+ {"version":3,"file":"defaultAzureCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/defaultAzureCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,qCAAqC,EACrC,6BAA6B,EAC7B,uCAAuC,EACxC,MAAM,oCAAoC,CAAC;AAO5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAErE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAgBxD;;;GAGG;AACH,qBAAa,4BAA6B,YAAW,eAAe;IAClE,iCAAiC,EAAE,MAAM,CAAC;IAC1C,cAAc,EAAE,MAAM,CAAC;gBAEX,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;IAKnD,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAM1B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,qBAAa,sBAAuB,SAAQ,sBAAsB;IAChE;;;;OAIG;gBACS,OAAO,CAAC,EAAE,qCAAqC;IAE3D;;;;OAIG;gBACS,OAAO,CAAC,EAAE,uCAAuC;IAE7D;;;;OAIG;gBACS,OAAO,CAAC,EAAE,6BAA6B;CA6FpD"}
@@ -75,7 +75,7 @@ export class DefaultAzureCredential extends ChainedTokenCredential {
75
75
  createDefaultWorkloadIdentityCredential,
76
76
  createDefaultManagedIdentityCredential,
77
77
  ];
78
- let credentialFunctions = [];
78
+ let credentialFunctions;
79
79
  const validCredentialNames = "EnvironmentCredential, WorkloadIdentityCredential, ManagedIdentityCredential, VisualStudioCodeCredential, AzureCliCredential, AzurePowerShellCredential, AzureDeveloperCliCredential";
80
80
  // If AZURE_TOKEN_CREDENTIALS is set, use it to determine which credentials to use.
81
81
  // The value of AZURE_TOKEN_CREDENTIALS should be either "dev" or "prod" or any one of these credentials - {validCredentialNames}.
@@ -97,7 +97,10 @@ export class DefaultAzureCredential extends ChainedTokenCredential {
97
97
  // Setting `sendProbeRequest` to false to ensure ManagedIdentityCredential behavior
98
98
  // is consistent when used standalone in DAC chain or used directly.
99
99
  credentialFunctions = [
100
- () => createDefaultManagedIdentityCredential({ sendProbeRequest: false }),
100
+ () => createDefaultManagedIdentityCredential({
101
+ ...options,
102
+ sendProbeRequest: false,
103
+ }),
101
104
  ];
102
105
  break;
103
106
  case "visualstudiocodecredential":