@azure/identity 4.5.1-alpha.20241028.2 → 4.5.1-alpha.20241030.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (99) hide show
  1. package/dist/index.js.map +1 -1
  2. package/dist-esm/src/client/identityClient.js +1 -1
  3. package/dist-esm/src/client/identityClient.js.map +1 -1
  4. package/dist-esm/src/credentials/authorizationCodeCredential.browser.js.map +1 -1
  5. package/dist-esm/src/credentials/authorizationCodeCredential.js.map +1 -1
  6. package/dist-esm/src/credentials/authorizationCodeCredentialOptions.js.map +1 -1
  7. package/dist-esm/src/credentials/azureApplicationCredential.browser.js.map +1 -1
  8. package/dist-esm/src/credentials/azureApplicationCredential.js.map +1 -1
  9. package/dist-esm/src/credentials/azureApplicationCredentialOptions.js.map +1 -1
  10. package/dist-esm/src/credentials/azureCliCredential.browser.js.map +1 -1
  11. package/dist-esm/src/credentials/azureCliCredential.js.map +1 -1
  12. package/dist-esm/src/credentials/azureCliCredentialOptions.js.map +1 -1
  13. package/dist-esm/src/credentials/azureDeveloperCliCredential.browser.js.map +1 -1
  14. package/dist-esm/src/credentials/azureDeveloperCliCredential.js.map +1 -1
  15. package/dist-esm/src/credentials/azureDeveloperCliCredentialOptions.js.map +1 -1
  16. package/dist-esm/src/credentials/azurePipelinesCredential.browser.js.map +1 -1
  17. package/dist-esm/src/credentials/azurePipelinesCredential.js.map +1 -1
  18. package/dist-esm/src/credentials/azurePipelinesCredentialOptions.js.map +1 -1
  19. package/dist-esm/src/credentials/azurePowerShellCredential.browser.js.map +1 -1
  20. package/dist-esm/src/credentials/azurePowerShellCredential.js.map +1 -1
  21. package/dist-esm/src/credentials/azurePowerShellCredentialOptions.js.map +1 -1
  22. package/dist-esm/src/credentials/brokerAuthOptions.js.map +1 -1
  23. package/dist-esm/src/credentials/chainedTokenCredential.js.map +1 -1
  24. package/dist-esm/src/credentials/clientAssertionCredential.browser.js.map +1 -1
  25. package/dist-esm/src/credentials/clientAssertionCredential.js.map +1 -1
  26. package/dist-esm/src/credentials/clientAssertionCredentialOptions.js.map +1 -1
  27. package/dist-esm/src/credentials/clientCertificateCredential.browser.js.map +1 -1
  28. package/dist-esm/src/credentials/clientCertificateCredential.js.map +1 -1
  29. package/dist-esm/src/credentials/clientCertificateCredentialOptions.js.map +1 -1
  30. package/dist-esm/src/credentials/clientSecretCredential.browser.js.map +1 -1
  31. package/dist-esm/src/credentials/clientSecretCredential.js.map +1 -1
  32. package/dist-esm/src/credentials/clientSecretCredentialOptions.js.map +1 -1
  33. package/dist-esm/src/credentials/credentialPersistenceOptions.js.map +1 -1
  34. package/dist-esm/src/credentials/defaultAzureCredential.browser.js.map +1 -1
  35. package/dist-esm/src/credentials/defaultAzureCredential.js +1 -1
  36. package/dist-esm/src/credentials/defaultAzureCredential.js.map +1 -1
  37. package/dist-esm/src/credentials/defaultAzureCredentialOptions.js.map +1 -1
  38. package/dist-esm/src/credentials/deviceCodeCredential.browser.js.map +1 -1
  39. package/dist-esm/src/credentials/deviceCodeCredential.js.map +1 -1
  40. package/dist-esm/src/credentials/deviceCodeCredentialOptions.js.map +1 -1
  41. package/dist-esm/src/credentials/environmentCredential.browser.js.map +1 -1
  42. package/dist-esm/src/credentials/environmentCredential.js.map +1 -1
  43. package/dist-esm/src/credentials/environmentCredentialOptions.js.map +1 -1
  44. package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js.map +1 -1
  45. package/dist-esm/src/credentials/interactiveBrowserCredential.js.map +1 -1
  46. package/dist-esm/src/credentials/interactiveBrowserCredentialOptions.js.map +1 -1
  47. package/dist-esm/src/credentials/interactiveCredentialOptions.js.map +1 -1
  48. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js +1 -1
  49. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2017.js.map +1 -1
  50. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2019.js +1 -1
  51. package/dist-esm/src/credentials/managedIdentityCredential/appServiceMsi2019.js.map +1 -1
  52. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js +1 -1
  53. package/dist-esm/src/credentials/managedIdentityCredential/arcMsi.js.map +1 -1
  54. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js +1 -1
  55. package/dist-esm/src/credentials/managedIdentityCredential/cloudShellMsi.js.map +1 -1
  56. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js +1 -1
  57. package/dist-esm/src/credentials/managedIdentityCredential/fabricMsi.js.map +1 -1
  58. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js +1 -1
  59. package/dist-esm/src/credentials/managedIdentityCredential/imdsMsi.js.map +1 -1
  60. package/dist-esm/src/credentials/managedIdentityCredential/imdsRetryPolicy.js.map +1 -1
  61. package/dist-esm/src/credentials/managedIdentityCredential/index.browser.js.map +1 -1
  62. package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
  63. package/dist-esm/src/credentials/managedIdentityCredential/legacyMsiProvider.js.map +1 -1
  64. package/dist-esm/src/credentials/managedIdentityCredential/models.js.map +1 -1
  65. package/dist-esm/src/credentials/managedIdentityCredential/msalMsiProvider.js.map +1 -1
  66. package/dist-esm/src/credentials/managedIdentityCredential/tokenExchangeMsi.js.map +1 -1
  67. package/dist-esm/src/credentials/multiTenantTokenCredentialOptions.js.map +1 -1
  68. package/dist-esm/src/credentials/onBehalfOfCredential.browser.js.map +1 -1
  69. package/dist-esm/src/credentials/onBehalfOfCredential.js.map +1 -1
  70. package/dist-esm/src/credentials/onBehalfOfCredentialOptions.js.map +1 -1
  71. package/dist-esm/src/credentials/usernamePasswordCredential.browser.js.map +1 -1
  72. package/dist-esm/src/credentials/usernamePasswordCredential.js.map +1 -1
  73. package/dist-esm/src/credentials/usernamePasswordCredentialOptions.js.map +1 -1
  74. package/dist-esm/src/credentials/visualStudioCodeCredential.browser.js.map +1 -1
  75. package/dist-esm/src/credentials/visualStudioCodeCredential.js.map +1 -1
  76. package/dist-esm/src/credentials/visualStudioCodeCredentialOptions.js.map +1 -1
  77. package/dist-esm/src/credentials/workloadIdentityCredential.browser.js.map +1 -1
  78. package/dist-esm/src/credentials/workloadIdentityCredential.js.map +1 -1
  79. package/dist-esm/src/credentials/workloadIdentityCredentialOptions.js.map +1 -1
  80. package/dist-esm/src/errors.js.map +1 -1
  81. package/dist-esm/src/index.js.map +1 -1
  82. package/dist-esm/src/msal/browserFlows/flows.js.map +1 -1
  83. package/dist-esm/src/msal/browserFlows/msalAuthCode.js.map +1 -1
  84. package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js.map +1 -1
  85. package/dist-esm/src/msal/credentials.js.map +1 -1
  86. package/dist-esm/src/msal/nodeFlows/msalClient.js.map +1 -1
  87. package/dist-esm/src/msal/nodeFlows/msalPlugins.js.map +1 -1
  88. package/dist-esm/src/msal/utils.js.map +1 -1
  89. package/dist-esm/src/plugins/consumer.js.map +1 -1
  90. package/dist-esm/src/plugins/provider.js.map +1 -1
  91. package/dist-esm/src/tokenCredentialOptions.js.map +1 -1
  92. package/dist-esm/src/util/logging.js.map +1 -1
  93. package/dist-esm/src/util/processMultiTenantRequest.browser.js.map +1 -1
  94. package/dist-esm/src/util/processMultiTenantRequest.js.map +1 -1
  95. package/dist-esm/src/util/scopeUtils.js.map +1 -1
  96. package/dist-esm/src/util/subscriptionUtils.js.map +1 -1
  97. package/dist-esm/src/util/tenantIdUtils.js.map +1 -1
  98. package/package.json +1 -1
  99. package/types/identity.d.ts +3 -3
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/constants.ts","../src/msal/nodeFlows/msalPlugins.ts","../src/util/logging.ts","../src/errors.ts","../src/util/processMultiTenantRequest.ts","../src/util/tenantIdUtils.ts","../src/util/identityTokenEndpoint.ts","../src/util/tracing.ts","../src/credentials/managedIdentityCredential/constants.ts","../src/credentials/managedIdentityCredential/utils.ts","../src/client/identityClient.ts","../src/credentials/visualStudioCodeCredential.ts","../src/plugins/consumer.ts","../src/msal/utils.ts","../src/credentials/managedIdentityCredential/imdsMsi.ts","../src/credentials/managedIdentityCredential/imdsRetryPolicy.ts","../src/regionalAuthority.ts","../src/msal/nodeFlows/msalClient.ts","../src/credentials/clientAssertionCredential.ts","../src/credentials/workloadIdentityCredential.ts","../src/credentials/managedIdentityCredential/tokenExchangeMsi.ts","../src/credentials/managedIdentityCredential/msalMsiProvider.ts","../src/credentials/managedIdentityCredential/index.ts","../src/util/scopeUtils.ts","../src/util/subscriptionUtils.ts","../src/credentials/azureCliCredential.ts","../src/credentials/azureDeveloperCliCredential.ts","../src/util/processUtils.ts","../src/credentials/azurePowerShellCredential.ts","../src/credentials/chainedTokenCredential.ts","../src/credentials/clientCertificateCredential.ts","../src/credentials/clientSecretCredential.ts","../src/credentials/usernamePasswordCredential.ts","../src/credentials/environmentCredential.ts","../src/credentials/defaultAzureCredential.ts","../src/credentials/interactiveBrowserCredential.ts","../src/credentials/deviceCodeCredential.ts","../src/credentials/azurePipelinesCredential.ts","../src/credentials/authorizationCodeCredential.ts","../src/credentials/onBehalfOfCredential.ts","../src/tokenProvider.ts","../src/index.ts"],"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.5.1`;\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 * 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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as msalNode from \"@azure/msal-node\";\n\nimport { CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX, DEFAULT_TOKEN_CACHE_NAME } from \"../../constants\";\n\nimport { MsalClientOptions } from \"./msalClient\";\nimport { NativeBrokerPluginControl } from \"../../plugins/provider\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\n\n/**\n * Configuration for the plugins used by the MSAL node client.\n */\nexport interface PluginConfiguration {\n /**\n * Configuration for the cache plugin.\n */\n cache: {\n /**\n * The non-CAE cache plugin handler.\n */\n cachePlugin?: Promise<msalNode.ICachePlugin>;\n /**\n * The CAE cache plugin handler - persisted to a different file.\n */\n cachePluginCae?: Promise<msalNode.ICachePlugin>;\n };\n /**\n * Configuration for the broker plugin.\n */\n broker: {\n /**\n * True if the broker plugin is enabled and available. False otherwise.\n *\n * It is a bug if this is true and the broker plugin is not available.\n */\n isEnabled: boolean;\n /**\n * If true, MSA account will be passed through, required for WAM authentication.\n */\n enableMsaPassthrough: boolean;\n /**\n * The parent window handle for the broker.\n */\n parentWindowHandle?: Uint8Array;\n /**\n * The native broker plugin handler.\n */\n nativeBrokerPlugin?: msalNode.INativeBrokerPlugin;\n /**\n * If set to true, the credential will attempt to use the default broker account for authentication before falling back to interactive authentication. Default is set to false.\n */\n useDefaultBrokerAccount?: boolean;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nexport let persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalNode.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n },\n};\n\n/**\n * The current native broker provider, undefined by default.\n * @internal\n */\nexport let nativeBrokerInfo:\n | {\n broker: msalNode.INativeBrokerPlugin;\n }\n | undefined = undefined;\n\nexport function hasNativeBroker(): boolean {\n return nativeBrokerInfo !== undefined;\n}\n\n/**\n * An object that allows setting the native broker provider.\n * @internal\n */\nexport const msalNodeFlowNativeBrokerControl: NativeBrokerPluginControl = {\n setNativeBroker(broker): void {\n nativeBrokerInfo = {\n broker,\n };\n },\n};\n\n/**\n * Configures plugins, validating that required plugins are available and enabled.\n *\n * Does not create the plugins themselves, but rather returns the configuration that will be used to create them.\n *\n * @param options - options for creating the MSAL client\n * @returns plugin configuration\n */\nfunction generatePluginConfiguration(options: MsalClientOptions): PluginConfiguration {\n const config: PluginConfiguration = {\n cache: {},\n broker: {\n isEnabled: options.brokerOptions?.enabled ?? false,\n enableMsaPassthrough: options.brokerOptions?.legacyEnableMsaPassthrough ?? false,\n parentWindowHandle: options.brokerOptions?.parentWindowHandle,\n },\n };\n\n if (options.tokenCachePersistenceOptions?.enabled) {\n if (persistenceProvider === undefined) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\",\n ].join(\" \"),\n );\n }\n\n const cacheBaseName = options.tokenCachePersistenceOptions.name || DEFAULT_TOKEN_CACHE_NAME;\n config.cache.cachePlugin = persistenceProvider({\n name: `${cacheBaseName}.${CACHE_NON_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n });\n config.cache.cachePluginCae = persistenceProvider({\n name: `${cacheBaseName}.${CACHE_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n });\n }\n\n if (options.brokerOptions?.enabled) {\n if (nativeBrokerInfo === undefined) {\n throw new Error(\n [\n \"Broker for WAM was requested to be enabled, but no native broker was configured.\",\n \"You must install the identity-broker plugin package (`npm install --save @azure/identity-broker`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(createNativeBrokerPlugin())` before using `enableBroker`.\",\n ].join(\" \"),\n );\n }\n config.broker.nativeBrokerPlugin = nativeBrokerInfo!.broker;\n }\n\n return config;\n}\n\n/**\n * Wraps generatePluginConfiguration as a writeable property for test stubbing purposes.\n */\nexport const msalPlugins = {\n generatePluginConfiguration,\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AzureLogger, createClientLogger } from \"@azure/logger\";\n\n/**\n * The AzureLogger used for all clients within the identity package\n */\nexport const logger = createClientLogger(\"identity\");\n\ninterface EnvironmentAccumulator {\n missing: string[];\n assigned: string[];\n}\n\n/**\n * Separates a list of environment variable names into a plain object with two arrays: an array of missing environment variables and another array with assigned environment variables.\n * @param supportedEnvVars - List of environment variable names\n */\nexport function processEnvVars(supportedEnvVars: string[]): EnvironmentAccumulator {\n return supportedEnvVars.reduce(\n (acc: EnvironmentAccumulator, envVariable: string) => {\n if (process.env[envVariable]) {\n acc.assigned.push(envVariable);\n } else {\n acc.missing.push(envVariable);\n }\n return acc;\n },\n { missing: [], assigned: [] },\n );\n}\n\n/**\n * Based on a given list of environment variable names,\n * logs the environment variables currently assigned during the usage of a credential that goes by the given name.\n * @param credentialName - Name of the credential in use\n * @param supportedEnvVars - List of environment variables supported by that credential\n */\nexport function logEnvVars(credentialName: string, supportedEnvVars: string[]): void {\n const { assigned } = processEnvVars(supportedEnvVars);\n logger.info(\n `${credentialName} => Found the following environment variables: ${assigned.join(\", \")}`,\n );\n}\n\n/**\n * Formatting the success event on the credentials\n */\nexport function formatSuccess(scope: string | string[]): string {\n return `SUCCESS. Scopes: ${Array.isArray(scope) ? scope.join(\", \") : scope}.`;\n}\n\n/**\n * Formatting the success event on the credentials\n */\nexport function formatError(scope: string | string[] | undefined, error: Error | string): string {\n let message = \"ERROR.\";\n if (scope?.length) {\n message += ` Scopes: ${Array.isArray(scope) ? scope.join(\", \") : scope}.`;\n }\n return `${message} Error message: ${typeof error === \"string\" ? error : error.message}.`;\n}\n\n/**\n * A CredentialLoggerInstance is a logger properly formatted to work in a credential's constructor, and its methods.\n */\nexport interface CredentialLoggerInstance {\n title: string;\n fullTitle: string;\n info(message: string): void;\n warning(message: string): void;\n verbose(message: string): void;\n error(err: string): void;\n}\n\n/**\n * Generates a CredentialLoggerInstance.\n *\n * It logs with the format:\n *\n * `[title] => [message]`\n *\n */\nexport function credentialLoggerInstance(\n title: string,\n parent?: CredentialLoggerInstance,\n log: AzureLogger = logger,\n): CredentialLoggerInstance {\n const fullTitle = parent ? `${parent.fullTitle} ${title}` : title;\n\n function info(message: string): void {\n log.info(`${fullTitle} =>`, message);\n }\n\n function warning(message: string): void {\n log.warning(`${fullTitle} =>`, message);\n }\n\n function verbose(message: string): void {\n log.verbose(`${fullTitle} =>`, message);\n }\n\n function error(message: string): void {\n log.error(`${fullTitle} =>`, message);\n }\n\n return {\n title,\n fullTitle,\n info,\n warning,\n verbose,\n error,\n };\n}\n\n/**\n * A CredentialLogger is a logger declared at the credential's constructor, and used at any point in the credential.\n * It has all the properties of a CredentialLoggerInstance, plus other logger instances, one per method.\n */\nexport interface CredentialLogger extends CredentialLoggerInstance {\n parent: AzureLogger;\n getToken: CredentialLoggerInstance;\n}\n\n/**\n * Generates a CredentialLogger, which is a logger declared at the credential's constructor, and used at any point in the credential.\n * It has all the properties of a CredentialLoggerInstance, plus other logger instances, one per method.\n *\n * It logs with the format:\n *\n * `[title] => [message]`\n * `[title] => getToken() => [message]`\n *\n */\nexport function credentialLogger(title: string, log: AzureLogger = logger): CredentialLogger {\n const credLogger = credentialLoggerInstance(title, undefined, log);\n return {\n ...credLogger,\n parent: log,\n getToken: credentialLoggerInstance(\"=> getToken()\", credLogger, log),\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * See the official documentation for more details:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n /**\n * The string identifier for the error.\n */\n error: string;\n\n /**\n * The error's description.\n */\n errorDescription: string;\n\n /**\n * An array of codes pertaining to the error(s) that occurred.\n */\n errorCodes?: number[];\n\n /**\n * The timestamp at which the error occurred.\n */\n timestamp?: string;\n\n /**\n * The trace identifier for this error occurrence.\n */\n traceId?: string;\n\n /**\n * The correlation ID to be used for tracking the source of the error.\n */\n correlationId?: string;\n}\n\n/**\n * Used for internal deserialization of OAuth responses. Public model is ErrorResponse\n * @internal\n */\nexport interface OAuthErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is OAuthErrorResponse {\n return (\n errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\"\n );\n}\n\n/**\n * The Error.name value of an CredentialUnavailable\n */\nexport const CredentialUnavailableErrorName = \"CredentialUnavailableError\";\n\n/**\n * This signifies that the credential that was tried in a chained credential\n * was not available to be used as the credential. Rather than treating this as\n * an error that should halt the chain, it's caught and the chain continues\n */\nexport class CredentialUnavailableError extends Error {\n constructor(message?: string, options?: { cause?: unknown }) {\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n super(message, options);\n this.name = CredentialUnavailableErrorName;\n }\n}\n\n/**\n * The Error.name value of an AuthenticationError\n */\nexport const AuthenticationErrorName = \"AuthenticationError\";\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n /**\n * The HTTP status code returned from the authentication request.\n */\n public readonly statusCode: number;\n\n /**\n * The error response details.\n */\n public readonly errorResponse: ErrorResponse;\n\n constructor(\n statusCode: number,\n errorBody: object | string | undefined | null,\n options?: { cause?: unknown },\n ) {\n let errorResponse: ErrorResponse = {\n error: \"unknown\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n const oauthErrorResponse: OAuthErrorResponse = JSON.parse(errorBody);\n errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);\n } catch (e: any) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"invalid_request\",\n errorDescription: `The service indicated that the request was invalid.\\n\\n${errorBody}`,\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: `An unknown error has occurred. Response body:\\n\\n${errorBody}`,\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n }\n\n super(\n `${errorResponse.error} Status code: ${statusCode}\\nMore details:\\n${errorResponse.errorDescription},`,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options,\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = AuthenticationErrorName;\n }\n}\n\n/**\n * The Error.name value of an AggregateAuthenticationError\n */\nexport const AggregateAuthenticationErrorName = \"AggregateAuthenticationError\";\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n /**\n * The array of error objects that were thrown while trying to authenticate\n * with the credentials in a {@link ChainedTokenCredential}.\n */\n public errors: any[];\n\n constructor(errors: any[], errorMessage?: string) {\n const errorDetail = errors.join(\"\\n\");\n super(`${errorMessage}\\n${errorDetail}`);\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = AggregateAuthenticationErrorName;\n }\n}\n\nfunction convertOAuthErrorResponseToErrorResponse(errorBody: OAuthErrorResponse): ErrorResponse {\n return {\n error: errorBody.error,\n errorDescription: errorBody.error_description,\n correlationId: errorBody.correlation_id,\n errorCodes: errorBody.error_codes,\n timestamp: errorBody.timestamp,\n traceId: errorBody.trace_id,\n };\n}\n\n/**\n * Optional parameters to the {@link AuthenticationRequiredError}\n */\nexport interface AuthenticationRequiredErrorOptions {\n /**\n * The list of scopes for which the token will have access.\n */\n scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n getTokenOptions?: GetTokenOptions;\n /**\n * The message of the error.\n */\n message?: string;\n /**\n * The underlying cause, if any, that caused the authentication to fail.\n */\n cause?: unknown;\n}\n\n/**\n * Error used to enforce authentication after trying to retrieve a token silently.\n */\nexport class AuthenticationRequiredError extends Error {\n /**\n * The list of scopes for which the token will have access.\n */\n public scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n public getTokenOptions?: GetTokenOptions;\n\n constructor(\n /**\n * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters.\n */\n options: AuthenticationRequiredErrorOptions,\n ) {\n super(\n options.message,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options.cause ? { cause: options.cause } : undefined,\n );\n this.scopes = options.scopes;\n this.getTokenOptions = options.getTokenOptions;\n this.name = \"AuthenticationRequiredError\";\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { CredentialLogger } from \"./logging\";\n\nfunction createConfigurationErrorMessage(tenantId: string): string {\n return `The current credential is not configured to acquire tokens for tenant ${tenantId}. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add \"*\" to AdditionallyAllowedTenants to allow acquiring tokens for any tenant.`;\n}\n\n/**\n * Of getToken contains a tenantId, this functions allows picking this tenantId as the appropriate for authentication,\n * unless multitenant authentication has been disabled through the AZURE_IDENTITY_DISABLE_MULTITENANTAUTH (on Node.js),\n * or unless the original tenant Id is `adfs`.\n * @internal\n */\nexport function processMultiTenantRequest(\n tenantId?: string,\n getTokenOptions?: GetTokenOptions,\n additionallyAllowedTenantIds: string[] = [],\n logger?: CredentialLogger,\n): string | undefined {\n let resolvedTenantId: string | undefined;\n if (process.env.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH) {\n resolvedTenantId = tenantId;\n } else if (tenantId === \"adfs\") {\n resolvedTenantId = tenantId;\n } else {\n resolvedTenantId = getTokenOptions?.tenantId ?? tenantId;\n }\n if (\n tenantId &&\n resolvedTenantId !== tenantId &&\n !additionallyAllowedTenantIds.includes(\"*\") &&\n !additionallyAllowedTenantIds.some((t) => t.localeCompare(resolvedTenantId!) === 0)\n ) {\n const message = createConfigurationErrorMessage(tenantId);\n logger?.info(message);\n throw new CredentialUnavailableError(message);\n }\n\n return resolvedTenantId;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { ALL_TENANTS, DeveloperSignOnClientId } from \"../constants\";\nimport { CredentialLogger, formatError } from \"./logging\";\nexport { processMultiTenantRequest } from \"./processMultiTenantRequest\";\n\n/**\n * @internal\n */\nexport function checkTenantId(logger: CredentialLogger, tenantId: string): void {\n if (!tenantId.match(/^[0-9a-zA-Z-.]+$/)) {\n const error = new Error(\n \"Invalid tenant id provided. You can locate your tenant id by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names.\",\n );\n logger.info(formatError(\"\", error));\n throw error;\n }\n}\n\n/**\n * @internal\n */\nexport function resolveTenantId(\n logger: CredentialLogger,\n tenantId?: string,\n clientId?: string,\n): string {\n if (tenantId) {\n checkTenantId(logger, tenantId);\n return tenantId;\n }\n if (!clientId) {\n clientId = DeveloperSignOnClientId;\n }\n if (clientId !== DeveloperSignOnClientId) {\n return \"common\";\n }\n return \"organizations\";\n}\n\n/**\n * @internal\n */\nexport function resolveAdditionallyAllowedTenantIds(\n additionallyAllowedTenants?: string[],\n): string[] {\n if (!additionallyAllowedTenants || additionallyAllowedTenants.length === 0) {\n return [];\n }\n\n if (additionallyAllowedTenants.includes(\"*\")) {\n return ALL_TENANTS;\n }\n\n return additionallyAllowedTenants;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport function getIdentityTokenEndpointSuffix(tenantId: string): string {\n if (tenantId === \"adfs\") {\n return \"oauth2/token\";\n } else {\n return \"oauth2/v2.0/token\";\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { SDK_VERSION } from \"../constants\";\nimport { createTracingClient } from \"@azure/core-tracing\";\n\n/**\n * Creates a span using the global tracer.\n * @internal\n */\nexport const tracingClient = createTracingClient({\n namespace: \"Microsoft.AAD\",\n packageName: \"@azure/identity\",\n packageVersion: SDK_VERSION,\n});\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport const DefaultScopeSuffix = \"/.default\";\nexport const imdsHost = \"http://169.254.169.254\";\nexport const imdsEndpointPath = \"/metadata/identity/oauth2/token\";\nexport const imdsApiVersion = \"2018-02-01\";\nexport const azureArcAPIVersion = \"2019-11-01\";\nexport const azureFabricVersion = \"2019-07-01-preview\";\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { DefaultScopeSuffix } from \"./constants\";\n\n/**\n * Most MSIs send requests to the IMDS endpoint, or a similar endpoint.\n * These are GET requests that require sending a `resource` parameter on the query.\n * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received.\n * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case.\n *\n * For that reason, when we encounter multiple scopes, we return undefined.\n * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors).\n */\nexport function mapScopesToResource(scopes: string | string[]): string | undefined {\n let scope = \"\";\n if (Array.isArray(scopes)) {\n if (scopes.length !== 1) {\n return;\n }\n\n scope = scopes[0];\n } else if (typeof scopes === \"string\") {\n scope = scopes;\n }\n\n if (!scope.endsWith(DefaultScopeSuffix)) {\n return scope;\n }\n\n return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n refresh_on?: number | string;\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseExpirationTimestamp(body: TokenResponseParsedBody): number {\n if (typeof body.expires_on === \"number\") {\n return body.expires_on * 1000;\n }\n\n if (typeof body.expires_on === \"string\") {\n const asNumber = +body.expires_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.expires_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n\n if (typeof body.expires_in === \"number\") {\n return Date.now() + body.expires_in * 1000;\n }\n\n throw new Error(\n `Failed to parse token expiration from body. expires_in=\"${body.expires_in}\", expires_on=\"${body.expires_on}\"`,\n );\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseRefreshTimestamp(body: TokenResponseParsedBody): number | undefined {\n if (body.refresh_on) {\n if (typeof body.refresh_on === \"number\") {\n return body.refresh_on * 1000;\n }\n\n if (typeof body.refresh_on === \"string\") {\n const asNumber = +body.refresh_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.refresh_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n throw new Error(`Failed to parse refresh_on from body. refresh_on=\"${body.refresh_on}\"`);\n } else {\n return undefined;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-node\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport {\n PipelineRequest,\n PipelineResponse,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost, SDK_VERSION } from \"../constants\";\nimport { tracingClient } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\nimport {\n TokenResponseParsedBody,\n parseExpirationTimestamp,\n parseRefreshTimestamp,\n} from \"../credentials/managedIdentityCredential/utils\";\n\nconst noCorrelationId = \"noCorrelationId\";\n\n/**\n * An internal type used to communicate details of a token request's\n * response that should not be sent back as part of the access token.\n */\nexport interface TokenResponse {\n /**\n * The AccessToken to be returned from getToken.\n */\n accessToken: AccessToken;\n /**\n * The refresh token if the 'offline_access' scope was used.\n */\n refreshToken?: string;\n}\n\n/**\n * @internal\n */\nexport function getIdentityClientAuthorityHost(options?: TokenCredentialOptions): string {\n // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.\n let authorityHost = options?.authorityHost;\n\n // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.\n if (isNode) {\n authorityHost = authorityHost ?? process.env.AZURE_AUTHORITY_HOST;\n }\n\n // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * The network module used by the Identity credentials.\n *\n * It allows for credentials to abort any pending request independently of the MSAL flow,\n * by calling to the `abortRequests()` method.\n *\n */\nexport class IdentityClient extends ServiceClient implements INetworkModule {\n public authorityHost: string;\n private allowLoggingAccountIdentifiers?: boolean;\n private abortControllers: Map<string, AbortController[] | undefined>;\n private allowInsecureConnection: boolean = false;\n // used for WorkloadIdentity\n private tokenCredentialOptions: TokenCredentialOptions;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/${SDK_VERSION}`;\n const userAgentPrefix = options?.userAgentOptions?.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const baseUri = getIdentityClientAuthorityHost(options);\n if (!baseUri.startsWith(\"https:\")) {\n throw new Error(\"The authorityHost address must use the 'https' protocol.\");\n }\n\n super({\n requestContentType: \"application/json; charset=utf-8\",\n retryOptions: {\n maxRetries: 3,\n },\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n baseUri,\n });\n\n this.authorityHost = baseUri;\n this.abortControllers = new Map();\n this.allowLoggingAccountIdentifiers = options?.loggingOptions?.allowLoggingAccountIdentifiers;\n // used for WorkloadIdentity\n this.tokenCredentialOptions = { ...options };\n\n // used for ManagedIdentity\n if (options?.allowInsecureConnection) {\n this.allowInsecureConnection = options.allowInsecureConnection;\n }\n }\n\n async sendTokenRequest(request: PipelineRequest): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: TokenResponseParsedBody = JSON.parse(response.bodyAsText);\n\n if (!parsedBody.access_token) {\n return null;\n }\n\n this.logIdentifiers(response);\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: parseExpirationTimestamp(parsedBody),\n refreshAfterTimestamp: parseRefreshTimestamp(parsedBody),\n tokenType: \"Bearer\",\n } as AccessToken,\n refreshToken: parsedBody.refresh_token,\n };\n\n logger.info(\n `IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`,\n );\n return token;\n } else {\n const error = new AuthenticationError(response.status, response.bodyAsText);\n logger.warning(\n `IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`,\n );\n throw error;\n }\n }\n\n async refreshAccessToken(\n tenantId: string,\n clientId: string,\n scopes: string,\n refreshToken: string | undefined,\n clientSecret: string | undefined,\n options: GetTokenOptions = {},\n ): Promise<TokenResponse | null> {\n if (refreshToken === undefined) {\n return null;\n }\n logger.info(\n `IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`,\n );\n\n const refreshParams = {\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scopes,\n };\n\n if (clientSecret !== undefined) {\n (refreshParams as any).client_secret = clientSecret;\n }\n\n const query = new URLSearchParams(refreshParams);\n\n return tracingClient.withSpan(\n \"IdentityClient.refreshAccessToken\",\n options,\n async (updatedOptions) => {\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);\n const request = createPipelineRequest({\n url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,\n method: \"POST\",\n body: query.toString(),\n abortSignal: options.abortSignal,\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n tracingOptions: updatedOptions.tracingOptions,\n });\n\n const response = await this.sendTokenRequest(request);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err: any) {\n if (\n err.name === AuthenticationErrorName &&\n err.errorResponse.error === \"interaction_required\"\n ) {\n // It's likely that the refresh token has expired, so\n // return null so that the credential implementation will\n // initiate the authentication flow again.\n logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);\n return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`,\n );\n throw err;\n }\n }\n },\n );\n }\n\n // Here is a custom layer that allows us to abort requests that go through MSAL,\n // since MSAL doesn't allow us to pass options all the way through.\n\n generateAbortSignal(correlationId: string): AbortSignalLike {\n const controller = new AbortController();\n const controllers = this.abortControllers.get(correlationId) || [];\n controllers.push(controller);\n this.abortControllers.set(correlationId, controllers);\n const existingOnAbort = controller.signal.onabort;\n controller.signal.onabort = (...params) => {\n this.abortControllers.set(correlationId, undefined);\n if (existingOnAbort) {\n existingOnAbort.apply(controller.signal, params);\n }\n };\n return controller.signal;\n }\n\n abortRequests(correlationId?: string): void {\n const key = correlationId || noCorrelationId;\n const controllers = [\n ...(this.abortControllers.get(key) || []),\n // MSAL passes no correlation ID to the get requests...\n ...(this.abortControllers.get(noCorrelationId) || []),\n ];\n if (!controllers.length) {\n return;\n }\n for (const controller of controllers) {\n controller.abort();\n }\n this.abortControllers.set(key, undefined);\n }\n\n getCorrelationId(options?: NetworkRequestOptions): string {\n const parameter = options?.body\n ?.split(\"&\")\n .map((part) => part.split(\"=\"))\n .find(([key]) => key === \"client-request-id\");\n return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;\n }\n\n // The MSAL network module methods follow\n\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"GET\",\n body: options?.body,\n allowInsecureConnection: this.allowInsecureConnection,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"POST\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n allowInsecureConnection: this.allowInsecureConnection,\n // MSAL doesn't send the correlation ID on the get requests.\n abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n /**\n *\n * @internal\n */\n getTokenCredentialOptions(): TokenCredentialOptions {\n return this.tokenCredentialOptions;\n }\n /**\n * If allowLoggingAccountIdentifiers was set on the constructor options\n * we try to log the account identifiers by parsing the received access token.\n *\n * The account identifiers we try to log are:\n * - `appid`: The application or Client Identifier.\n * - `upn`: User Principal Name.\n * - It might not be available in some authentication scenarios.\n * - If it's not available, we put a placeholder: \"No User Principal Name available\".\n * - `tid`: Tenant Identifier.\n * - `oid`: Object Identifier of the authenticated user.\n */\n private logIdentifiers(response: PipelineResponse): void {\n if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {\n return;\n }\n const unavailableUpn = \"No User Principal Name available\";\n try {\n const parsed = (response as any).parsedBody || JSON.parse(response.bodyAsText);\n const accessToken = parsed.access_token;\n if (!accessToken) {\n // Without an access token allowLoggingAccountIdentifiers isn't useful.\n return;\n }\n const base64Metadata = accessToken.split(\".\")[1];\n const { appid, upn, tid, oid } = JSON.parse(\n Buffer.from(base64Metadata, \"base64\").toString(\"utf8\"),\n );\n\n logger.info(\n `[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${\n upn || unavailableUpn\n }. Object ID (user): ${oid}`,\n );\n } catch (e: any) {\n logger.warning(\n \"allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:\",\n e.message,\n );\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { AzureAuthorityHosts } from \"../constants\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport { VisualStudioCodeCredentialOptions } from \"./visualStudioCodeCredentialOptions\";\nimport { VSCodeCredentialFinder } from \"./visualStudioCodeCredentialPlugin\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\n\nconst CommonTenantId = \"common\";\nconst AzureAccountClientId = \"aebc6443-996d-45c2-90f0-388ff96faa56\"; // VSC: 'aebc6443-996d-45c2-90f0-388ff96faa56'\nconst logger = credentialLogger(\"VisualStudioCodeCredential\");\n\nlet findCredentials: VSCodeCredentialFinder | undefined = undefined;\n\nexport const vsCodeCredentialControl = {\n setVsCodeCredentialFinder(finder: VSCodeCredentialFinder): void {\n findCredentials = finder;\n },\n};\n\n// Map of unsupported Tenant IDs and the errors we will be throwing.\nconst unsupportedTenantIds: Record<string, string> = {\n adfs: \"The VisualStudioCodeCredential does not support authentication with ADFS tenants.\",\n};\n\nfunction checkUnsupportedTenant(tenantId: string): void {\n // If the Tenant ID isn't supported, we throw.\n const unsupportedTenantError = unsupportedTenantIds[tenantId];\n if (unsupportedTenantError) {\n throw new CredentialUnavailableError(unsupportedTenantError);\n }\n}\n\ntype VSCodeCloudNames = \"AzureCloud\" | \"AzureChina\" | \"AzureGermanCloud\" | \"AzureUSGovernment\";\n\nconst mapVSCodeAuthorityHosts: Record<VSCodeCloudNames, string> = {\n AzureCloud: AzureAuthorityHosts.AzurePublicCloud,\n AzureChina: AzureAuthorityHosts.AzureChina,\n AzureGermanCloud: AzureAuthorityHosts.AzureGermany,\n AzureUSGovernment: AzureAuthorityHosts.AzureGovernment,\n};\n\n/**\n * Attempts to load a specific property from the VSCode configurations of the current OS.\n * If it fails at any point, returns undefined.\n */\nexport function getPropertyFromVSCode(property: string): string | undefined {\n const settingsPath = [\"User\", \"settings.json\"];\n // Eventually we can add more folders for more versions of VSCode.\n const vsCodeFolder = \"Code\";\n const homedir = os.homedir();\n\n function loadProperty(...pathSegments: string[]): string | undefined {\n const fullPath = path.join(...pathSegments, vsCodeFolder, ...settingsPath);\n const settings = JSON.parse(fs.readFileSync(fullPath, { encoding: \"utf8\" }));\n return settings[property];\n }\n\n try {\n let appData: string;\n switch (process.platform) {\n case \"win32\":\n appData = process.env.APPDATA!;\n return appData ? loadProperty(appData) : undefined;\n case \"darwin\":\n return loadProperty(homedir, \"Library\", \"Application Support\");\n case \"linux\":\n return loadProperty(homedir, \".config\");\n default:\n return;\n }\n } catch (e: any) {\n logger.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`);\n return;\n }\n}\n\n/**\n * Connects to Azure using the credential provided by the VSCode extension 'Azure Account'.\n * Once the user has logged in via the extension, this credential can share the same refresh token\n * that is cached by the extension.\n *\n * It's a [known issue](https://github.com/Azure/azure-sdk-for-js/issues/20500) that this credential doesn't\n * work with [Azure Account extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account)\n * versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider\n * authenticating with {@link AzureCliCredential}.\n */\nexport class VisualStudioCodeCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private cloudName: VSCodeCloudNames;\n\n /**\n * Creates an instance of VisualStudioCodeCredential to use for automatically authenticating via VSCode.\n *\n * **Note**: `VisualStudioCodeCredential` is provided by a plugin package:\n * `@azure/identity-vscode`. If this package is not installed and registered\n * using the plugin API (`useIdentityPlugin`), then authentication using\n * `VisualStudioCodeCredential` will not be available.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: VisualStudioCodeCredentialOptions) {\n // We want to make sure we use the one assigned by the user on the VSCode settings.\n // Or just `AzureCloud` by default.\n this.cloudName = (getPropertyFromVSCode(\"azure.cloud\") || \"AzureCloud\") as VSCodeCloudNames;\n\n // Picking an authority host based on the cloud name.\n const authorityHost = mapVSCodeAuthorityHosts[this.cloudName];\n\n this.identityClient = new IdentityClient({\n authorityHost,\n ...options,\n });\n\n if (options && options.tenantId) {\n checkTenantId(logger, options.tenantId);\n this.tenantId = options.tenantId;\n } else {\n this.tenantId = CommonTenantId;\n }\n\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n checkUnsupportedTenant(this.tenantId);\n }\n\n /**\n * Runs preparations for any further getToken request.\n */\n private async prepare(): Promise<void> {\n // Attempts to load the tenant from the VSCode configuration file.\n const settingsTenant = getPropertyFromVSCode(\"azure.tenant\");\n if (settingsTenant) {\n this.tenantId = settingsTenant;\n }\n checkUnsupportedTenant(this.tenantId);\n }\n\n /**\n * The promise of the single preparation that will be executed at the first getToken request for an instance of this class.\n */\n private preparePromise: Promise<void> | undefined;\n\n /**\n * Runs preparations for any further getToken, but only once.\n */\n private prepareOnce(): Promise<void> | undefined {\n if (!this.preparePromise) {\n this.preparePromise = this.prepare();\n }\n return this.preparePromise;\n }\n\n /**\n * Returns the token found by searching VSCode's authentication cache or\n * returns null if no token could be found.\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 await this.prepareOnce();\n\n const tenantId =\n processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n logger,\n ) || this.tenantId;\n\n if (findCredentials === undefined) {\n throw new CredentialUnavailableError(\n [\n \"No implementation of `VisualStudioCodeCredential` is available.\",\n \"You must install the identity-vscode plugin package (`npm install --save-dev @azure/identity-vscode`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(vsCodePlugin)` before creating a `VisualStudioCodeCredential`.\",\n \"To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\",\n ].join(\" \"),\n );\n }\n\n let scopeString = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n\n // Check to make sure the scope we get back is a valid scope\n if (!scopeString.match(/^[0-9a-zA-Z-.:/]+$/)) {\n const error = new Error(\"Invalid scope was specified by the user or calling client\");\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n if (scopeString.indexOf(\"offline_access\") < 0) {\n scopeString += \" offline_access\";\n }\n\n // findCredentials returns an array similar to:\n // [\n // {\n // account: \"\",\n // password: \"\",\n // },\n // /* ... */\n // ]\n const credentials = await findCredentials();\n\n // If we can't find the credential based on the name, we'll pick the first one available.\n const { password: refreshToken } =\n credentials.find(({ account }) => account === this.cloudName) ?? credentials[0] ?? {};\n\n if (refreshToken) {\n const tokenResponse = await this.identityClient.refreshAccessToken(\n tenantId,\n AzureAccountClientId,\n scopeString,\n refreshToken,\n undefined,\n );\n\n if (tokenResponse) {\n logger.getToken.info(formatSuccess(scopes));\n return tokenResponse.accessToken;\n } else {\n const error = new CredentialUnavailableError(\n \"Could not retrieve the token associated with Visual Studio Code. Have you connected using the 'Azure Account' extension recently? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n } else {\n const error = new CredentialUnavailableError(\n \"Could not retrieve the token associated with Visual Studio Code. Did you connect using the 'Azure Account' extension? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AzurePluginContext, IdentityPlugin } from \"./provider\";\nimport {\n msalNodeFlowCacheControl,\n msalNodeFlowNativeBrokerControl,\n} from \"../msal/nodeFlows/msalPlugins\";\n\nimport { vsCodeCredentialControl } from \"../credentials/visualStudioCodeCredential\";\n\n/**\n * The context passed to an Identity plugin. This contains objects that\n * plugins can use to set backend implementations.\n * @internal\n */\nconst pluginContext: AzurePluginContext = {\n cachePluginControl: msalNodeFlowCacheControl,\n nativeBrokerPluginControl: msalNodeFlowNativeBrokerControl,\n vsCodeCredentialControl: vsCodeCredentialControl,\n};\n\n/**\n * Extend Azure Identity with additional functionality. Pass a plugin from\n * a plugin package, such as:\n *\n * - `@azure/identity-cache-persistence`: provides persistent token caching\n * - `@azure/identity-vscode`: provides the dependencies of\n * `VisualStudioCodeCredential` and enables it\n *\n * Example:\n *\n * ```ts snippet:consumer_example\n * import { useIdentityPlugin, DeviceCodeCredential } from \"@azure/identity\";\n *\n * useIdentityPlugin(cachePersistencePlugin);\n * // The plugin has the capability to extend `DeviceCodeCredential` and to\n * // add middleware to the underlying credentials, such as persistence.\n * const credential = new DeviceCodeCredential({\n * tokenCachePersistenceOptions: {\n * enabled: true,\n * },\n * });\n * ```\n *\n * @param plugin - the plugin to register\n */\nexport function useIdentityPlugin(plugin: IdentityPlugin): void {\n plugin(pluginContext);\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AuthenticationRecord, MsalAccountInfo, MsalToken, ValidMsalToken } from \"./types\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../errors\";\nimport { CredentialLogger, credentialLogger, formatError } from \"../util/logging\";\nimport { DefaultAuthorityHost, DefaultTenantId } from \"../constants\";\nimport { randomUUID as coreRandomUUID, isNode, isNodeLike } from \"@azure/core-util\";\n\nimport { AbortError } from \"@azure/abort-controller\";\nimport { AzureLogLevel } from \"@azure/logger\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { msalCommon } from \"./msal\";\n\nexport interface ILoggerCallback {\n (level: msalCommon.LogLevel, message: string, containsPii: boolean): void;\n}\n\n/**\n * @internal\n */\nconst logger = credentialLogger(\"IdentityUtils\");\n\n/**\n * Latest AuthenticationRecord version\n * @internal\n */\nconst LatestAuthenticationRecordVersion = \"1.0\";\n\n/**\n * Ensures the validity of the MSAL token\n * @internal\n */\nexport function ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken | null,\n getTokenOptions?: GetTokenOptions,\n): asserts msalToken is ValidMsalToken {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n}\n\n/**\n * Returns the authority host from either the options bag or the AZURE_AUTHORITY_HOST environment variable.\n *\n * Defaults to {@link DefaultAuthorityHost}.\n * @internal\n */\nexport function getAuthorityHost(options?: { authorityHost?: string }): string {\n let authorityHost = options?.authorityHost;\n\n if (!authorityHost && isNodeLike) {\n authorityHost = process.env.AZURE_AUTHORITY_HOST;\n }\n\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * Generates a valid authority by combining a host with a tenantId.\n * @internal\n */\nexport function getAuthority(tenantId: string, host?: string): string {\n if (!host) {\n host = DefaultAuthorityHost;\n }\n if (new RegExp(`${tenantId}/?$`).test(host)) {\n return host;\n }\n if (host.endsWith(\"/\")) {\n return host + tenantId;\n } else {\n return `${host}/${tenantId}`;\n }\n}\n\n/**\n * Generates the known authorities.\n * If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.\n * For that reason, we have to force MSAL to disable validating the authority\n * by sending it within the known authorities in the MSAL configuration.\n * @internal\n */\nexport function getKnownAuthorities(\n tenantId: string,\n authorityHost: string,\n disableInstanceDiscovery?: boolean,\n): string[] {\n if ((tenantId === \"adfs\" && authorityHost) || disableInstanceDiscovery) {\n return [authorityHost];\n }\n return [];\n}\n\n/**\n * Generates a logger that can be passed to the MSAL clients.\n * @param credLogger - The logger of the credential.\n * @internal\n */\nexport const defaultLoggerCallback: (\n logger: CredentialLogger,\n platform?: \"Node\" | \"Browser\",\n) => ILoggerCallback =\n (credLogger: CredentialLogger, platform: \"Node\" | \"Browser\" = isNode ? \"Node\" : \"Browser\") =>\n (level, message, containsPii): void => {\n if (containsPii) {\n return;\n }\n switch (level) {\n case msalCommon.LogLevel.Error:\n credLogger.info(`MSAL ${platform} V2 error: ${message}`);\n return;\n case msalCommon.LogLevel.Info:\n credLogger.info(`MSAL ${platform} V2 info message: ${message}`);\n return;\n case msalCommon.LogLevel.Verbose:\n credLogger.info(`MSAL ${platform} V2 verbose message: ${message}`);\n return;\n case msalCommon.LogLevel.Warning:\n credLogger.info(`MSAL ${platform} V2 warning: ${message}`);\n return;\n }\n };\n\n/**\n * @internal\n */\nexport function getMSALLogLevel(logLevel: AzureLogLevel | undefined): msalCommon.LogLevel {\n switch (logLevel) {\n case \"error\":\n return msalCommon.LogLevel.Error;\n case \"info\":\n return msalCommon.LogLevel.Info;\n case \"verbose\":\n return msalCommon.LogLevel.Verbose;\n case \"warning\":\n return msalCommon.LogLevel.Warning;\n default:\n // default msal logging level should be Info\n return msalCommon.LogLevel.Info;\n }\n}\n\n/**\n * Wraps core-util's randomUUID in order to allow for mocking in tests.\n * This prepares the library for the upcoming core-util update to ESM.\n *\n * @internal\n * @returns A string containing a random UUID\n */\nexport function randomUUID(): string {\n return coreRandomUUID();\n}\n\n/**\n * Handles MSAL errors.\n */\nexport function handleMsalError(\n scopes: string[],\n error: Error,\n getTokenOptions?: GetTokenOptions,\n): Error {\n if (\n error.name === \"AuthError\" ||\n error.name === \"ClientAuthError\" ||\n error.name === \"BrowserAuthError\"\n ) {\n const msalError = error as msalCommon.AuthError;\n switch (msalError.errorCode) {\n case \"endpoints_resolution_error\":\n logger.info(formatError(scopes, error.message));\n return new CredentialUnavailableError(error.message);\n case \"device_code_polling_cancelled\":\n return new AbortError(\"The authentication has been aborted by the caller.\");\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n logger.info(\n formatError(scopes, `Authentication returned errorCode ${msalError.errorCode}`),\n );\n break;\n default:\n logger.info(formatError(scopes, `Failed to acquire token: ${error.message}`));\n break;\n }\n }\n if (\n error.name === \"ClientConfigurationError\" ||\n error.name === \"BrowserConfigurationAuthError\" ||\n error.name === \"AbortError\" ||\n error.name === \"AuthenticationError\"\n ) {\n return error;\n }\n if (error.name === \"NativeAuthError\") {\n logger.info(\n formatError(\n scopes,\n `Error from the native broker: ${error.message} with status code: ${\n (error as any).statusCode\n }`,\n ),\n );\n return error;\n }\n return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message });\n}\n\n// transformations.ts\n\nexport function publicToMsal(account: AuthenticationRecord): msalCommon.AccountInfo {\n const [environment] = account.authority.match(/([a-z]*\\.[a-z]*\\.[a-z]*)/) || [\"\"];\n return {\n ...account,\n localAccountId: account.homeAccountId,\n environment,\n };\n}\n\nexport function msalToPublic(clientId: string, account: MsalAccountInfo): AuthenticationRecord {\n const record = {\n authority: getAuthority(account.tenantId, account.environment),\n homeAccountId: account.homeAccountId,\n tenantId: account.tenantId || DefaultTenantId,\n username: account.username,\n clientId,\n version: LatestAuthenticationRecordVersion,\n };\n return record;\n}\n\n/**\n * Serializes an `AuthenticationRecord` into a string.\n *\n * The output of a serialized authentication record will contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`.\n */\nexport function serializeAuthenticationRecord(record: AuthenticationRecord): string {\n return JSON.stringify(record);\n}\n\n/**\n * Deserializes a previously serialized authentication record from a string into an object.\n *\n * The input string must contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * If the version we receive is unsupported, an error will be thrown.\n *\n * At the moment, the only available version is: \"1.0\", which is always set when the authentication record is serialized.\n *\n * @param serializedRecord - Authentication record previously serialized into string.\n * @returns AuthenticationRecord.\n */\nexport function deserializeAuthenticationRecord(serializedRecord: string): AuthenticationRecord {\n const parsed: AuthenticationRecord & { version?: string } = JSON.parse(serializedRecord);\n\n if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) {\n throw Error(\"Unsupported AuthenticationRecord version\");\n }\n\n return parsed;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport {\n PipelineRequestOptions,\n PipelineResponse,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { delay, isError } from \"@azure/core-util\";\nimport { imdsApiVersion, imdsEndpointPath, imdsHost } from \"./constants\";\n\nimport { AuthenticationError } from \"../../errors\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst msiName = \"ManagedIdentityCredential - IMDS\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string,\n options?: {\n skipQuery?: boolean;\n skipMetadataHeader?: boolean;\n },\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const { skipQuery, skipMetadataHeader } = options || {};\n let query = \"\";\n\n // Pod Identity will try to process this request even if the Metadata header is missing.\n // We can exclude the request query to ensure no IMDS endpoint tries to process the ping request.\n if (!skipQuery) {\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": imdsApiVersion,\n };\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n const params = new URLSearchParams(queryParameters);\n query = `?${params.toString()}`;\n }\n\n const url = new URL(imdsEndpointPath, process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST ?? imdsHost);\n\n const rawHeaders: Record<string, string> = {\n Accept: \"application/json\",\n Metadata: \"true\",\n };\n\n // Remove the Metadata header to invoke a request error from some IMDS endpoints.\n if (skipMetadataHeader) {\n delete rawHeaders.Metadata;\n }\n\n return {\n // In this case, the `?` should be added in the \"query\" variable `skipQuery` is not set.\n url: `${url}${query}`,\n method: \"GET\",\n headers: createHttpHeaders(rawHeaders),\n };\n}\n\n/**\n * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.\n */\nexport const imdsMsi: MSI = {\n name: \"imdsMsi\",\n async isAvailable({\n scopes,\n identityClient,\n clientId,\n resourceId,\n getTokenOptions = {},\n }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n\n // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n return true;\n }\n\n if (!identityClient) {\n throw new Error(\"Missing IdentityClient\");\n }\n\n const requestOptions = prepareRequestOptions(resource, clientId, resourceId, {\n skipMetadataHeader: true,\n skipQuery: true,\n });\n\n return tracingClient.withSpan(\n \"ManagedIdentityCredential-pingImdsEndpoint\",\n getTokenOptions,\n async (options) => {\n requestOptions.tracingOptions = options.tracingOptions;\n\n // Create a request with a timeout since we expect that\n // not having a \"Metadata\" header should cause an error to be\n // returned quickly from the endpoint, proving its availability.\n const request = createPipelineRequest(requestOptions);\n\n // Default to 1000 if the default of 0 is used.\n // Negative values can still be used to disable the timeout.\n request.timeout = options.requestOptions?.timeout || 1000;\n\n // This MSI uses the imdsEndpoint to get the token, which only uses http://\n request.allowInsecureConnection = true;\n let response: PipelineResponse;\n try {\n logger.info(`${msiName}: Pinging the Azure IMDS endpoint`);\n response = await identityClient.sendRequest(request);\n } catch (err: unknown) {\n // If the request failed, or Node.js was unable to establish a connection,\n // or the host was down, we'll assume the IMDS endpoint isn't available.\n if (isError(err)) {\n logger.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`);\n }\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n return false;\n }\n if (response.status === 403) {\n if (response.bodyAsText?.includes(\"unreachable\")) {\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n logger.info(`${msiName}: ${response.bodyAsText}`);\n return false;\n }\n }\n // If we received any response, the endpoint is available\n logger.info(`${msiName}: The Azure IMDS endpoint is available`);\n return true;\n },\n );\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n logger.info(\n `${msiName}: Using the Azure IMDS endpoint coming from the environment variable AZURE_POD_IDENTITY_AUTHORITY_HOST=${process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST}.`,\n );\n } else {\n logger.info(`${msiName}: Using the default Azure IMDS endpoint ${imdsHost}.`);\n }\n\n let nextDelayInMs = configuration.retryConfig.startDelayInMs;\n for (let retries = 0; retries < configuration.retryConfig.maxRetries; retries++) {\n try {\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (error: any) {\n if (error.statusCode === 404) {\n await delay(nextDelayInMs);\n nextDelayInMs *= configuration.retryConfig.intervalIncrement;\n continue;\n }\n throw error;\n }\n }\n\n throw new AuthenticationError(\n 404,\n `${msiName}: Failed to retrieve IMDS token after ${configuration.retryConfig.maxRetries} retries.`,\n );\n },\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { PipelinePolicy, retryPolicy } from \"@azure/core-rest-pipeline\";\n\nimport { MSIConfiguration } from \"./models\";\nimport { calculateRetryDelay } from \"@azure/core-util\";\n\n// Matches the default retry configuration in expontentialRetryStrategy.ts\nconst DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;\n\n/**\n * An additional policy that retries on 404 errors. The default retry policy does not retry on\n * 404s, but the IMDS endpoint can return 404s when the token is not yet available. This policy\n * will retry on 404s with an exponential backoff.\n *\n * @param msiRetryConfig - The retry configuration for the MSI credential.\n * @returns - The policy that will retry on 404s.\n */\nexport function imdsRetryPolicy(msiRetryConfig: MSIConfiguration[\"retryConfig\"]): PipelinePolicy {\n return retryPolicy(\n [\n {\n name: \"imdsRetryPolicy\",\n retry: ({ retryCount, response }) => {\n if (response?.status !== 404) {\n return { skipStrategy: true };\n }\n\n return calculateRetryDelay(retryCount, {\n retryDelayInMs: msiRetryConfig.startDelayInMs,\n maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL,\n });\n },\n },\n ],\n {\n maxRetries: msiRetryConfig.maxRetries,\n },\n );\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Helps specify a regional authority, or \"AutoDiscoverRegion\" to auto-detect the region.\n */\nexport enum RegionalAuthority {\n /** Instructs MSAL to attempt to discover the region */\n AutoDiscoverRegion = \"AutoDiscoverRegion\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westus' region. */\n USWest = \"westus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westus2' region. */\n USWest2 = \"westus2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'centralus' region. */\n USCentral = \"centralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'eastus' region. */\n USEast = \"eastus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'eastus2' region. */\n USEast2 = \"eastus2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'northcentralus' region. */\n USNorthCentral = \"northcentralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southcentralus' region. */\n USSouthCentral = \"southcentralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westcentralus' region. */\n USWestCentral = \"westcentralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'canadacentral' region. */\n CanadaCentral = \"canadacentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'canadaeast' region. */\n CanadaEast = \"canadaeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'brazilsouth' region. */\n BrazilSouth = \"brazilsouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'northeurope' region. */\n EuropeNorth = \"northeurope\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westeurope' region. */\n EuropeWest = \"westeurope\",\n /** Uses the {@link RegionalAuthority} for the Azure 'uksouth' region. */\n UKSouth = \"uksouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'ukwest' region. */\n UKWest = \"ukwest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'francecentral' region. */\n FranceCentral = \"francecentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'francesouth' region. */\n FranceSouth = \"francesouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandnorth' region. */\n SwitzerlandNorth = \"switzerlandnorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandwest' region. */\n SwitzerlandWest = \"switzerlandwest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanynorth' region. */\n GermanyNorth = \"germanynorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanywestcentral' region. */\n GermanyWestCentral = \"germanywestcentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'norwaywest' region. */\n NorwayWest = \"norwaywest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'norwayeast' region. */\n NorwayEast = \"norwayeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'eastasia' region. */\n AsiaEast = \"eastasia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southeastasia' region. */\n AsiaSouthEast = \"southeastasia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'japaneast' region. */\n JapanEast = \"japaneast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'japanwest' region. */\n JapanWest = \"japanwest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiaeast' region. */\n AustraliaEast = \"australiaeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiasoutheast' region. */\n AustraliaSouthEast = \"australiasoutheast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral' region. */\n AustraliaCentral = \"australiacentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral2' region. */\n AustraliaCentral2 = \"australiacentral2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'centralindia' region. */\n IndiaCentral = \"centralindia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southindia' region. */\n IndiaSouth = \"southindia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westindia' region. */\n IndiaWest = \"westindia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'koreasouth' region. */\n KoreaSouth = \"koreasouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'koreacentral' region. */\n KoreaCentral = \"koreacentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'uaecentral' region. */\n UAECentral = \"uaecentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'uaenorth' region. */\n UAENorth = \"uaenorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southafricanorth' region. */\n SouthAfricaNorth = \"southafricanorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southafricawest' region. */\n SouthAfricaWest = \"southafricawest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth' region. */\n ChinaNorth = \"chinanorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast' region. */\n ChinaEast = \"chinaeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth2' region. */\n ChinaNorth2 = \"chinanorth2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast2' region. */\n ChinaEast2 = \"chinaeast2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanycentral' region. */\n GermanyCentral = \"germanycentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanynortheast' region. */\n GermanyNorthEast = \"germanynortheast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgovvirginia' region. */\n GovernmentUSVirginia = \"usgovvirginia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgoviowa' region. */\n GovernmentUSIowa = \"usgoviowa\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgovarizona' region. */\n GovernmentUSArizona = \"usgovarizona\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgovtexas' region. */\n GovernmentUSTexas = \"usgovtexas\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usdodeast' region. */\n GovernmentUSDodEast = \"usdodeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usdodcentral' region. */\n GovernmentUSDodCentral = \"usdodcentral\",\n}\n\n/**\n * Calculates the correct regional authority based on the supplied value\n * and the AZURE_REGIONAL_AUTHORITY_NAME environment variable.\n *\n * Values will be returned verbatim, except for {@link RegionalAuthority.AutoDiscoverRegion}\n * which is mapped to a value MSAL can understand.\n *\n * @internal\n */\nexport function calculateRegionalAuthority(regionalAuthority?: string): string | undefined {\n // Note: as of today only 3 credentials support regional authority, and the parameter\n // is not exposed via the public API. Regional Authority is _only_ supported\n // via the AZURE_REGIONAL_AUTHORITY_NAME env var and _only_ for: ClientSecretCredential, ClientCertificateCredential, and ClientAssertionCredential.\n\n // Accepting the regionalAuthority parameter will allow us to support it in the future.\n let azureRegion = regionalAuthority;\n\n if (\n azureRegion === undefined &&\n globalThis.process?.env?.AZURE_REGIONAL_AUTHORITY_NAME !== undefined\n ) {\n azureRegion = process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n }\n\n if (azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n return \"AUTO_DISCOVER\";\n }\n\n return azureRegion;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as msal from \"@azure/msal-node\";\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRecord, CertificateParts } from \"../types\";\nimport { CredentialLogger, credentialLogger, formatSuccess } from \"../../util/logging\";\nimport { PluginConfiguration, msalPlugins } from \"./msalPlugins\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getAuthorityHost,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\n\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { BrokerOptions } from \"./brokerOptions\";\nimport { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { InteractiveBrowserCredentialNodeOptions } from \"../../credentials/interactiveBrowserCredentialOptions\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { calculateRegionalAuthority } from \"../../regionalAuthority\";\nimport { getLogLevel } from \"@azure/logger\";\nimport open from \"open\";\nimport { resolveTenantId } from \"../../util/tenantIdUtils\";\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/**\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 * 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 * A call to open(), but mockable\n * @internal\n */\nexport const interactiveBrowserMockable = {\n open,\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 *\n * @internal\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(\n \"No cached account found in local state, attempting to load it from MSAL cache.\",\n );\n const cache = app.getTokenCache();\n const accounts = await cache.getAllAccounts();\n\n if (accounts === undefined || accounts.length === 0) {\n throw new AuthenticationRequiredError({ scopes });\n }\n\n if (accounts.length > 1) {\n state.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n throw new AuthenticationRequiredError({ scopes });\n }\n\n state.cachedAccount = accounts[0];\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.tokenQueryParameters ||= {};\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n silentRequest.tokenQueryParameters[\"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 return app.acquireTokenSilent(silentRequest);\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 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 /**\n * A helper function that supports brokered authentication through the MSAL's public application.\n *\n * When options.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 useDefaultBrokerAccount: boolean,\n ): Promise<msal.AuthenticationResult> {\n msalLogger.verbose(\"Authentication will resume through the broker\");\n const interactiveRequest = createBaseInteractiveRequest();\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.tokenQueryParameters ??= {})[\"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 we tried to use the default broker account and failed, fall back to interactive authentication\n if (useDefaultBrokerAccount) {\n return getBrokeredToken(/* useDefaultBrokerAccount: */ false);\n } else {\n throw e;\n }\n }\n }\n\n function createBaseInteractiveRequest(): msal.InteractiveRequest {\n return {\n openBrowser: async (url) => {\n await interactiveBrowserMockable.open(url, { wait: true, 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 };\n }\n\n return withSilentAuthentication(app, scopes, options, async () => {\n const interactiveRequest = createBaseInteractiveRequest();\n\n if (state.pluginConfiguration.broker.isEnabled) {\n return getBrokeredToken(state.pluginConfiguration.broker.useDefaultBrokerAccount ?? false);\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 getTokenByClientSecret,\n getTokenByClientAssertion,\n getTokenByClientCertificate,\n getTokenByDeviceCode,\n getTokenByUsernamePassword,\n getTokenByAuthorizationCode,\n getTokenOnBehalfOf,\n getTokenByInteractiveRequest,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { MsalClient, createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport { ClientAssertionCredentialOptions } from \"./clientAssertionCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"ClientAssertionCredential\");\n\n/**\n * Authenticates a service principal with a JWT assertion.\n */\nexport class ClientAssertionCredential implements TokenCredential {\n private msalClient: MsalClient;\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private getAssertion: () => Promise<string>;\n private options: ClientAssertionCredentialOptions;\n\n /**\n * Creates an instance of the ClientAssertionCredential with the details\n * needed to authenticate against Microsoft Entra ID with a client\n * assertion provided by the developer through the `getAssertion` function parameter.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param getAssertion - A function that retrieves the assertion for the credential to use.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n getAssertion: () => Promise<string>,\n options: ClientAssertionCredentialOptions = {},\n ) {\n if (!tenantId) {\n throw new CredentialUnavailableError(\n \"ClientAssertionCredential: tenantId is a required parameter.\",\n );\n }\n\n if (!clientId) {\n throw new CredentialUnavailableError(\n \"ClientAssertionCredential: clientId is a required parameter.\",\n );\n }\n\n if (!getAssertion) {\n throw new CredentialUnavailableError(\n \"ClientAssertionCredential: clientAssertion is a required parameter.\",\n );\n }\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.options = options;\n this.getAssertion = getAssertion;\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: this.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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n return this.msalClient.getTokenByClientAssertion(\n arrayScopes,\n this.getAssertion,\n newOptions,\n );\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, processEnvVars } from \"../util/logging\";\n\nimport { ClientAssertionCredential } from \"./clientAssertionCredential\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { WorkloadIdentityCredentialOptions } from \"./workloadIdentityCredentialOptions\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { readFile } from \"fs/promises\";\n\nconst credentialName = \"WorkloadIdentityCredential\";\n/**\n * Contains the list of all supported environment variable names so that an\n * appropriate error message can be generated when no credentials can be\n * configured.\n *\n * @internal\n */\nexport const SupportedWorkloadEnvironmentVariables = [\n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_FEDERATED_TOKEN_FILE\",\n];\nconst logger = credentialLogger(credentialName);\n/**\n * Workload Identity authentication is a feature in Azure that allows applications running on virtual machines (VMs)\n * to access other Azure resources without the need for a service principal or managed identity. With Workload Identity\n * authentication, applications authenticate themselves using their own identity, rather than using a shared service\n * principal or managed identity. Under the hood, Workload Identity authentication uses the concept of Service Account\n * Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using Workload\n * Identity authentication, you can avoid the need to manage and rotate service principals or managed identities for\n * each application on each VM. Additionally, because SACs are created automatically and managed by Azure, you don't\n * need to worry about storing and securing sensitive credentials themselves.\n * The WorkloadIdentityCredential supports Microsoft Entra Workload ID authentication on Azure Kubernetes and acquires\n * a token using the SACs available in the Azure Kubernetes environment.\n * Refer to <a href=\"https://learn.microsoft.com/azure/aks/workload-identity-overview\">Microsoft Entra\n * Workload ID</a> for more information.\n */\nexport class WorkloadIdentityCredential implements TokenCredential {\n private client: ClientAssertionCredential | undefined;\n private azureFederatedTokenFileContent: string | undefined = undefined;\n private cacheDate: number | undefined = undefined;\n private federatedTokenFilePath: string | undefined;\n\n /**\n * WorkloadIdentityCredential supports Microsoft Entra Workload ID on Kubernetes.\n *\n * @param options - The identity client options to use for authentication.\n */\n constructor(options?: WorkloadIdentityCredentialOptions) {\n // Logging environment variables for error details\n const assignedEnv = processEnvVars(SupportedWorkloadEnvironmentVariables).assigned.join(\", \");\n logger.info(`Found the following environment variables: ${assignedEnv}`);\n\n const workloadIdentityCredentialOptions = options ?? {};\n const tenantId = workloadIdentityCredentialOptions.tenantId || process.env.AZURE_TENANT_ID;\n const clientId = workloadIdentityCredentialOptions.clientId || process.env.AZURE_CLIENT_ID;\n this.federatedTokenFilePath =\n workloadIdentityCredentialOptions.tokenFilePath || process.env.AZURE_FEDERATED_TOKEN_FILE;\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n if (!clientId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. clientId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - \"AZURE_CLIENT_ID\".\n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`,\n );\n }\n\n if (!tenantId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. tenantId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - \"AZURE_TENANT_ID\".\n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`,\n );\n }\n\n if (!this.federatedTokenFilePath) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. federatedTokenFilePath is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - \"AZURE_FEDERATED_TOKEN_FILE\".\n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`,\n );\n }\n\n logger.info(\n `Invoking ClientAssertionCredential with tenant ID: ${tenantId}, clientId: ${workloadIdentityCredentialOptions.clientId} and federated token path: [REDACTED]`,\n );\n this.client = new ClientAssertionCredential(\n tenantId,\n clientId,\n this.readFileContents.bind(this),\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} 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 | null> {\n if (!this.client) {\n const errorMessage = `${credentialName}: is unavailable. tenantId, clientId, and federatedTokenFilePath are required parameters. \n In DefaultAzureCredential and ManagedIdentityCredential, these can be provided as environment variables - \n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_FEDERATED_TOKEN_FILE\". See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`;\n logger.info(errorMessage);\n throw new CredentialUnavailableError(errorMessage);\n }\n logger.info(\"Invoking getToken() of Client Assertion Credential\");\n return this.client.getToken(scopes, options);\n }\n\n private async readFileContents(): Promise<string> {\n // Cached assertions expire after 5 minutes\n if (this.cacheDate !== undefined && Date.now() - this.cacheDate >= 1000 * 60 * 5) {\n this.azureFederatedTokenFileContent = undefined;\n }\n if (!this.federatedTokenFilePath) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. Invalid file path provided ${this.federatedTokenFilePath}.`,\n );\n }\n if (!this.azureFederatedTokenFileContent) {\n const file = await readFile(this.federatedTokenFilePath, \"utf8\");\n const value = file.trim();\n if (!value) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. No content on the file ${this.federatedTokenFilePath}.`,\n );\n } else {\n this.azureFederatedTokenFileContent = value;\n this.cacheDate = Date.now();\n }\n }\n return this.azureFederatedTokenFileContent;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { WorkloadIdentityCredential } from \"../workloadIdentityCredential\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { WorkloadIdentityCredentialOptions } from \"../workloadIdentityCredentialOptions\";\n\nconst msiName = \"ManagedIdentityCredential - Token Exchange\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI.\n */\nexport const tokenExchangeMsi: MSI = {\n name: \"tokenExchangeMsi\",\n async isAvailable({ clientId }): Promise<boolean> {\n const env = process.env;\n const result = Boolean(\n (clientId || env.AZURE_CLIENT_ID) &&\n env.AZURE_TENANT_ID &&\n process.env.AZURE_FEDERATED_TOKEN_FILE,\n );\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`,\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<AccessToken | null> {\n const { scopes, clientId } = configuration;\n const identityClientTokenCredentialOptions = {};\n const workloadIdentityCredential = new WorkloadIdentityCredential({\n clientId,\n tenantId: process.env.AZURE_TENANT_ID,\n tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE,\n ...identityClientTokenCredentialOptions,\n disableInstanceDiscovery: true,\n } as WorkloadIdentityCredentialOptions);\n return workloadIdentityCredential.getToken(scopes, getTokenOptions);\n },\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport { MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { defaultLoggerCallback, getMSALLogLevel } from \"../../msal/utils\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { MSIConfiguration } from \"./models\";\nimport { ManagedIdentityApplication } from \"@azure/msal-node\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { imdsRetryPolicy } from \"./imdsRetryPolicy\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential(MSAL)\");\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID and is not required for system-assigned managed identities.\n */\n objectId?: string;\n}\n\nexport class MsalMsiProvider {\n private managedIdentityApp: ManagedIdentityApplication;\n private identityClient: IdentityClient;\n private clientId?: string;\n private resourceId?: string;\n private objectId?: string;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n private isAvailableIdentityClient: IdentityClient;\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options: ManagedIdentityCredentialOptions = {},\n ) {\n let _options: ManagedIdentityCredentialOptions = {};\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = clientIdOrOptions?.clientId;\n _options = clientIdOrOptions ?? {};\n }\n this.resourceId = _options?.resourceId;\n this.objectId = _options?.objectId;\n\n // For JavaScript users.\n const providedIds = [this.clientId, this.resourceId, this.objectId].filter(Boolean);\n if (providedIds.length > 1) {\n throw new Error(\n `ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify(\n { clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId },\n )}`,\n );\n }\n\n // ManagedIdentity uses http for local requests\n _options.allowInsecureConnection = true;\n\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n\n this.identityClient = new IdentityClient({\n ..._options,\n additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: \"perCall\" }],\n });\n\n this.managedIdentityApp = new ManagedIdentityApplication({\n managedIdentityIdParams: {\n userAssignedClientId: this.clientId,\n userAssignedResourceId: this.resourceId,\n userAssignedObjectId: this.objectId,\n },\n system: {\n // todo: proxyUrl?\n disableInternalRetries: true,\n networkClient: this.identityClient,\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n loggerCallback: defaultLoggerCallback(logger),\n },\n },\n });\n\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible.\n if (this.managedIdentityApp.getManagedIdentitySource() === \"CloudShell\") {\n if (this.clientId || this.resourceId || this.objectId) {\n logger.warning(\n `CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify(\n {\n clientId: this.clientId,\n resourceId: this.resourceId,\n objectId: this.objectId,\n },\n )}.`,\n );\n throw new CredentialUnavailableError(\n \"ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.\",\n );\n }\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@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 logger.getToken.info(\"Using the MSAL provider for Managed Identity.\");\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(\n scopes,\n )}`,\n );\n }\n\n return tracingClient.withSpan(\"ManagedIdentityCredential.getToken\", options, async () => {\n try {\n const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.identityClient,\n resourceId: this.resourceId,\n });\n\n // Most scenarios are handled by MSAL except for two:\n // AKS pod identity - MSAL does not implement the token exchange flow.\n // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.\n // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token\n // We will continue to implement these features in the Identity library.\n\n const identitySource = this.managedIdentityApp.getManagedIdentitySource();\n const isImdsMsi = identitySource === \"DefaultToImds\" || identitySource === \"Imds\"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.\n\n logger.getToken.info(`MSAL Identity source: ${identitySource}`);\n\n if (isTokenExchangeMsi) {\n // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.\n logger.getToken.info(\"Using the token exchange managed identity.\");\n const result = await tokenExchangeMsi.getToken({\n scopes,\n clientId: this.clientId,\n identityClient: this.identityClient,\n retryConfig: this.msiRetryConfig,\n resourceId: this.resourceId,\n });\n\n if (result === null) {\n throw new CredentialUnavailableError(\n \"Attempted to use the token exchange managed identity, but received a null response.\",\n );\n }\n\n return result;\n } else if (isImdsMsi) {\n // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.\n // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.\n logger.getToken.info(\"Using the IMDS endpoint to probe for availability.\");\n const isAvailable = await imdsMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.isAvailableIdentityClient,\n resourceId: this.resourceId,\n });\n\n if (!isAvailable) {\n throw new CredentialUnavailableError(\n `Attempted to use the IMDS endpoint, but it is not available.`,\n );\n }\n }\n\n // If we got this far, it means:\n // - This is not a tokenExchangeMsi,\n // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.\n // We can proceed normally by calling MSAL for a token.\n logger.getToken.info(\"Calling into MSAL for managed identity token.\");\n const token = await this.managedIdentityApp.acquireToken({\n resource,\n });\n\n this.ensureValidMsalToken(scopes, token, options);\n logger.getToken.info(formatSuccess(scopes));\n\n return {\n expiresOnTimestamp: token.expiresOn.getTime(),\n token: token.accessToken,\n refreshAfterTimestamp: token.refreshOn?.getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n logger.getToken.error(formatError(scopes, err));\n\n // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.\n // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n if (isNetworkError(err)) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Network unreachable. Message: ${err.message}`,\n { cause: err },\n );\n }\n\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n { cause: err },\n );\n }\n });\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const createError = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw createError(\"No response.\");\n }\n if (!msalToken.expiresOn) {\n throw createError(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw createError(`Response had no \"accessToken\" property.`);\n }\n }\n}\n\nfunction isNetworkError(err: any): boolean {\n // MSAL error\n if (err.errorCode === \"network_error\") {\n return true;\n }\n\n // Probe errors\n if (err.code === \"ENETUNREACH\" || err.code === \"EHOSTUNREACH\") {\n return true;\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n return true;\n }\n }\n\n return false;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport { LegacyMsiProvider } from \"./legacyMsiProvider\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { MsalMsiProvider } from \"./msalMsiProvider\";\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `clientId` and not `resourceId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialClientIdOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `resourceId` and not `clientId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialResourceIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `objectId` as a constructor argument.\n */\nexport interface ManagedIdentityCredentialObjectIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID or resource ID and is not required for system-assigned managed identities.\n */\n objectId: string;\n}\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private implProvider: LegacyMsiProvider | MsalMsiProvider;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a client ID\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a resource ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with an object ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialObjectIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions\n | ManagedIdentityCredentialObjectIdOptions,\n options?: TokenCredentialOptions,\n ) {\n // https://github.com/Azure/azure-sdk-for-js/issues/30189\n // If needed, you may release a hotfix to quickly rollback to the legacy implementation by changing the following line to:\n // this.implProvider = new LegacyMsiProvider(clientIdOrOptions, options);\n // Once stabilized, you can remove the legacy implementation and inline the msalMsiProvider code here as a drop-in replacement.\n this.implProvider = new MsalMsiProvider(clientIdOrOptions, options);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@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 return this.implProvider.getToken(scopes, options);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { CredentialLogger, formatError } from \"./logging\";\n\n/**\n * Ensures the scopes value is an array.\n * @internal\n */\nexport function ensureScopes(scopes: string | string[]): string[] {\n return Array.isArray(scopes) ? scopes : [scopes];\n}\n\n/**\n * Throws if the received scope is not valid.\n * @internal\n */\nexport function ensureValidScopeForDevTimeCreds(scope: string, logger: CredentialLogger): void {\n if (!scope.match(/^[0-9a-zA-Z-_.:/]+$/)) {\n const error = new Error(\"Invalid scope was specified by the user or calling client\");\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n}\n\n/**\n * Returns the resource out of a scope.\n * @internal\n */\nexport function getScopeResource(scope: string): string {\n return scope.replace(/\\/.default$/, \"\");\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { CredentialLogger, formatError } from \"./logging\";\n\n/**\n * @internal\n */\nexport function checkSubscription(logger: CredentialLogger, subscription: string): void {\n if (!subscription.match(/^[0-9a-zA-Z-._ ]+$/)) {\n const error = new Error(\n \"Invalid subscription provided. You can locate your subscription by following the instructions listed here: https://learn.microsoft.com/azure/azure-portal/get-subscription-tenant-id.\",\n );\n logger.info(formatError(\"\", error));\n throw error;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils\";\n\nimport { AzureCliCredentialOptions } from \"./azureCliCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport child_process from \"child_process\";\nimport { tracingClient } from \"../util/tracing\";\nimport { checkSubscription } from \"../util/subscriptionUtils\";\n\n/**\n * Mockable reference to the CLI credential cliCredentialFunctions\n * @internal\n */\nexport const cliCredentialInternals = {\n /**\n * @internal\n */\n getSafeWorkingDir(): string {\n if (process.platform === \"win32\") {\n if (!process.env.SystemRoot) {\n throw new Error(\"Azure CLI credential expects a 'SystemRoot' environment variable\");\n }\n return process.env.SystemRoot;\n } else {\n return \"/bin\";\n }\n },\n\n /**\n * Gets the access token from Azure CLI\n * @param resource - The resource to use when getting the token\n * @internal\n */\n async getAzureCliAccessToken(\n resource: string,\n tenantId?: string,\n subscription?: string,\n timeout?: number,\n ): Promise<{ stdout: string; stderr: string; error: Error | null }> {\n let tenantSection: string[] = [];\n let subscriptionSection: string[] = [];\n if (tenantId) {\n tenantSection = [\"--tenant\", tenantId];\n }\n if (subscription) {\n // Add quotes around the subscription to handle subscriptions with spaces\n subscriptionSection = [\"--subscription\", `\"${subscription}\"`];\n }\n return new Promise((resolve, reject) => {\n try {\n child_process.execFile(\n \"az\",\n [\n \"account\",\n \"get-access-token\",\n \"--output\",\n \"json\",\n \"--resource\",\n resource,\n ...tenantSection,\n ...subscriptionSection,\n ],\n { cwd: cliCredentialInternals.getSafeWorkingDir(), shell: true, timeout },\n (error, stdout, stderr) => {\n resolve({ stdout: stdout, stderr: stderr, error });\n },\n );\n } catch (err: any) {\n reject(err);\n }\n });\n },\n};\n\nconst logger = credentialLogger(\"AzureCliCredential\");\n\n/**\n * This credential will use the currently logged-in user login information\n * via the Azure CLI ('az') commandline tool.\n * To do so, it will read the user access token and expire time\n * with Azure CLI command \"az account get-access-token\".\n */\nexport class AzureCliCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n private subscription?: string;\n\n /**\n * Creates an instance of the {@link AzureCliCredential}.\n *\n * To use this credential, ensure that you have already logged\n * in via the 'az' tool using the command \"az login\" from the commandline.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzureCliCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n if (options?.subscription) {\n checkSubscription(logger, options?.subscription);\n this.subscription = options?.subscription;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} 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 const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n if (this.subscription) {\n checkSubscription(logger, this.subscription);\n }\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n logger.getToken.info(`Using the scope ${scope}`);\n\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n try {\n ensureValidScopeForDevTimeCreds(scope, logger);\n const resource = getScopeResource(scope);\n const obj = await cliCredentialInternals.getAzureCliAccessToken(\n resource,\n tenantId,\n this.subscription,\n this.timeout,\n );\n const specificScope = obj.stderr?.match(\"(.*)az login --scope(.*)\");\n const isLoginError = obj.stderr?.match(\"(.*)az login(.*)\") && !specificScope;\n const isNotInstallError =\n obj.stderr?.match(\"az:(.*)not found\") || obj.stderr?.startsWith(\"'az' is not recognized\");\n\n if (isNotInstallError) {\n const error = new CredentialUnavailableError(\n \"Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n if (isLoginError) {\n const error = new CredentialUnavailableError(\n \"Please run 'az login' from a command prompt to authenticate before using this credential.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n try {\n const responseData = obj.stdout;\n const response: AccessToken = this.parseRawResponse(responseData);\n logger.getToken.info(formatSuccess(scopes));\n return response;\n } catch (e: any) {\n if (obj.stderr) {\n throw new CredentialUnavailableError(obj.stderr);\n }\n throw e;\n }\n } catch (err: any) {\n const error =\n err.name === \"CredentialUnavailableError\"\n ? err\n : new CredentialUnavailableError(\n (err as Error).message || \"Unknown error while trying to retrieve the access token\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n });\n }\n\n /**\n * Parses the raw JSON response from the Azure CLI into a usable AccessToken object\n *\n * @param rawResponse - The raw JSON response from the Azure CLI\n * @returns An access token with the expiry time parsed from the raw response\n *\n * The expiryTime of the credential's access token, in milliseconds, is calculated as follows:\n *\n * When available, expires_on (introduced in Azure CLI v2.54.0) will be preferred. Otherwise falls back to expiresOn.\n */\n private parseRawResponse(rawResponse: string): AccessToken {\n const response: any = JSON.parse(rawResponse);\n const token = response.accessToken;\n // if available, expires_on will be a number representing seconds since epoch.\n // ensure it's a number or NaN\n let expiresOnTimestamp = Number.parseInt(response.expires_on, 10) * 1000;\n if (!isNaN(expiresOnTimestamp)) {\n logger.getToken.info(\"expires_on is available and is valid, using it\");\n return {\n token,\n expiresOnTimestamp,\n tokenType: \"Bearer\",\n };\n }\n\n // fallback to the older expiresOn - an RFC3339 date string\n expiresOnTimestamp = new Date(response.expiresOn).getTime();\n\n // ensure expiresOn is well-formatted\n if (isNaN(expiresOnTimestamp)) {\n throw new CredentialUnavailableError(\n `Unexpected response from Azure CLI when getting token. Expected \"expiresOn\" to be a RFC3339 date string. Got: \"${response.expiresOn}\"`,\n );\n }\n\n return {\n token,\n expiresOnTimestamp,\n tokenType: \"Bearer\",\n };\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { AzureDeveloperCliCredentialOptions } from \"./azureDeveloperCliCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport child_process from \"child_process\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport { ensureValidScopeForDevTimeCreds } from \"../util/scopeUtils\";\n\n/**\n * Mockable reference to the Developer CLI credential cliCredentialFunctions\n * @internal\n */\nexport const developerCliCredentialInternals = {\n /**\n * @internal\n */\n getSafeWorkingDir(): string {\n if (process.platform === \"win32\") {\n if (!process.env.SystemRoot) {\n throw new Error(\n \"Azure Developer CLI credential expects a 'SystemRoot' environment variable\",\n );\n }\n return process.env.SystemRoot;\n } else {\n return \"/bin\";\n }\n },\n\n /**\n * Gets the access token from Azure Developer CLI\n * @param scopes - The scopes to use when getting the token\n * @internal\n */\n async getAzdAccessToken(\n scopes: string[],\n tenantId?: string,\n timeout?: number,\n ): Promise<{ stdout: string; stderr: string; error: Error | null }> {\n let tenantSection: string[] = [];\n if (tenantId) {\n tenantSection = [\"--tenant-id\", tenantId];\n }\n return new Promise((resolve, reject) => {\n try {\n child_process.execFile(\n \"azd\",\n [\n \"auth\",\n \"token\",\n \"--output\",\n \"json\",\n ...scopes.reduce<string[]>(\n (previous, current) => previous.concat(\"--scope\", current),\n [],\n ),\n ...tenantSection,\n ],\n {\n cwd: developerCliCredentialInternals.getSafeWorkingDir(),\n timeout,\n },\n (error, stdout, stderr) => {\n resolve({ stdout, stderr, error });\n },\n );\n } catch (err: any) {\n reject(err);\n }\n });\n },\n};\n\nconst logger = credentialLogger(\"AzureDeveloperCliCredential\");\n\n/**\n * Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy\n * resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific\n * to Azure developers. It allows users to authenticate as a user and/or a service principal against\n * <a href=\"https://learn.microsoft.com/entra/fundamentals/\">Microsoft Entra ID</a>. The\n * AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of\n * the logged-in user or service principal in the Azure Developer CLI. It acts as the Azure Developer CLI logged in user or\n * service principal and executes an Azure CLI command underneath to authenticate the application against\n * Microsoft Entra ID.\n *\n * <h2> Configure AzureDeveloperCliCredential </h2>\n *\n * To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the\n * commands below:\n *\n * <ol>\n * <li>Run \"azd auth login\" in Azure Developer CLI to authenticate interactively as a user.</li>\n * <li>Run \"azd auth login --client-id clientID --client-secret clientSecret\n * --tenant-id tenantID\" to authenticate as a service principal.</li>\n * </ol>\n *\n * You may need to repeat this process after a certain time period, depending on the refresh token validity in your\n * organization. Generally, the refresh token validity period is a few weeks to a few months.\n * AzureDeveloperCliCredential will prompt you to sign in again.\n */\nexport class AzureDeveloperCliCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzureDeveloperCliCredential}.\n *\n * To use this credential, ensure that you have already logged\n * in via the 'azd' tool using the command \"azd auth login\" from the commandline.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzureDeveloperCliCredentialOptions) {\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 * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} 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 const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n let scopeList: string[];\n if (typeof scopes === \"string\") {\n scopeList = [scopes];\n } else {\n scopeList = scopes;\n }\n logger.getToken.info(`Using the scopes ${scopes}`);\n\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n try {\n scopeList.forEach((scope) => {\n ensureValidScopeForDevTimeCreds(scope, logger);\n });\n const obj = await developerCliCredentialInternals.getAzdAccessToken(\n scopeList,\n tenantId,\n this.timeout,\n );\n const isNotLoggedInError =\n obj.stderr?.match(\"not logged in, run `azd login` to login\") ||\n obj.stderr?.match(\"not logged in, run `azd auth login` to login\");\n const isNotInstallError =\n obj.stderr?.match(\"azd:(.*)not found\") ||\n obj.stderr?.startsWith(\"'azd' is not recognized\");\n\n if (isNotInstallError || (obj.error && (obj.error as any).code === \"ENOENT\")) {\n const error = new CredentialUnavailableError(\n \"Azure Developer CLI couldn't be found. To mitigate this issue, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n if (isNotLoggedInError) {\n const error = new CredentialUnavailableError(\n \"Please run 'azd auth login' from a command prompt to authenticate before using this credential. For more information, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n try {\n const resp: { token: string; expiresOn: string } = JSON.parse(obj.stdout);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: resp.token,\n expiresOnTimestamp: new Date(resp.expiresOn).getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (e: any) {\n if (obj.stderr) {\n throw new CredentialUnavailableError(obj.stderr);\n }\n throw e;\n }\n } catch (err: any) {\n const error =\n err.name === \"CredentialUnavailableError\"\n ? err\n : new CredentialUnavailableError(\n (err as Error).message || \"Unknown error while trying to retrieve the access token\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n });\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as childProcess from \"child_process\";\n\n/**\n * Easy to mock childProcess utils.\n * @internal\n */\nexport const processUtils = {\n /**\n * Promisifying childProcess.execFile\n * @internal\n */\n execFile(\n file: string,\n params: string[],\n options?: childProcess.ExecFileOptionsWithStringEncoding,\n ): Promise<string | Buffer> {\n return new Promise((resolve, reject) => {\n childProcess.execFile(file, params, options, (error, stdout, stderr) => {\n if (Buffer.isBuffer(stdout)) {\n stdout = stdout.toString(\"utf8\");\n }\n if (Buffer.isBuffer(stderr)) {\n stderr = stderr.toString(\"utf8\");\n }\n if (stderr || error) {\n reject(stderr ? new Error(stderr) : error);\n } else {\n resolve(stdout);\n }\n });\n });\n },\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils\";\n\nimport { AzurePowerShellCredentialOptions } from \"./azurePowerShellCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { processUtils } from \"../util/processUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"AzurePowerShellCredential\");\n\nconst isWindows = process.platform === \"win32\";\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(commands: string[][], timeout?: number): 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 timeout,\n })) as string;\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 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 powerShellCommand,\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `\n $tenantId = \"${tenantId ?? \"\"}\"\n $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru\n $useSecureString = $m.Version -ge [version]'2.17.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 if ($useSecureString) {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value (ConvertFrom-SecureString -AsPlainText $token.Token)\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\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 tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AggregateAuthenticationError, CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\n\n/**\n * @internal\n */\nexport const logger = credentialLogger(\"ChainedTokenCredential\");\n\n/**\n * Enables multiple `TokenCredential` implementations to be tried in order until\n * one of the getToken methods returns an access token. For more information, see\n * [ChainedTokenCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-chainedtokencredential-for-granularity).\n */\nexport class ChainedTokenCredential implements TokenCredential {\n private _sources: TokenCredential[] = [];\n\n /**\n * Creates an instance of ChainedTokenCredential using the given credentials.\n *\n * @param sources - `TokenCredential` implementations to be tried in order.\n *\n * Example usage:\n * ```ts snippet:chained_token_credential_example\n * import { ClientSecretCredential, ChainedTokenCredential } from \"@azure/identity\";\n *\n * const tenantId = \"<tenant-id>\";\n * const clientId = \"<client-id>\";\n * const clientSecret = \"<client-secret>\";\n * const anotherClientId = \"<another-client-id>\";\n * const anotherSecret = \"<another-client-secret>\";\n * const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);\n * const secondCredential = new ClientSecretCredential(tenantId, anotherClientId, anotherSecret);\n * const credentialChain = new ChainedTokenCredential(firstCredential, secondCredential);\n * ```\n */\n constructor(...sources: TokenCredential[]) {\n this._sources = sources;\n }\n\n /**\n * Returns the first access token returned by one of the chained\n * `TokenCredential` implementations. Throws an {@link AggregateAuthenticationError}\n * when one or more credentials throws an {@link AuthenticationError} and\n * no credentials have returned an access token.\n *\n * This method is called automatically by Azure SDK client libraries. You may call this method\n * directly, but you must also handle token caching and token refreshing.\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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n const { token } = await this.getTokenInternal(scopes, options);\n return token;\n }\n\n private async getTokenInternal(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<{ token: AccessToken; successfulCredential: TokenCredential }> {\n let token: AccessToken | null = null;\n let successfulCredential: TokenCredential;\n const errors: Error[] = [];\n\n return tracingClient.withSpan(\n \"ChainedTokenCredential.getToken\",\n options,\n async (updatedOptions) => {\n for (let i = 0; i < this._sources.length && token === null; i++) {\n try {\n token = await this._sources[i].getToken(scopes, updatedOptions);\n successfulCredential = this._sources[i];\n } catch (err: any) {\n if (\n err.name === \"CredentialUnavailableError\" ||\n err.name === \"AuthenticationRequiredError\"\n ) {\n errors.push(err);\n } else {\n logger.getToken.info(formatError(scopes, err));\n throw err;\n }\n }\n }\n\n if (!token && errors.length > 0) {\n const err = new AggregateAuthenticationError(\n errors,\n \"ChainedTokenCredential authentication failed.\",\n );\n logger.getToken.info(formatError(scopes, err));\n throw err;\n }\n\n logger.getToken.info(\n `Result for ${successfulCredential.constructor.name}: ${formatSuccess(scopes)}`,\n );\n\n if (token === null) {\n throw new CredentialUnavailableError(\"Failed to retrieve a valid token\");\n }\n return { token, successfulCredential };\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { MsalClient, createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createHash, createPrivateKey } from \"crypto\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport { CertificateParts } from \"../msal/types\";\nimport { ClientCertificateCredentialOptions } from \"./clientCertificateCredentialOptions\";\nimport { credentialLogger } from \"../util/logging\";\nimport { readFile } from \"fs/promises\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst credentialName = \"ClientCertificateCredential\";\nconst logger = credentialLogger(credentialName);\n\n/**\n * Required configuration options for the {@link ClientCertificateCredential}, with the string contents of a PEM certificate\n */\nexport interface ClientCertificatePEMCertificate {\n /**\n * The PEM-encoded public/private key certificate on the filesystem.\n */\n certificate: string;\n\n /**\n * The password for the certificate file.\n */\n certificatePassword?: string;\n}\n/**\n * Required configuration options for the {@link ClientCertificateCredential}, with the path to a PEM certificate.\n */\nexport interface ClientCertificatePEMCertificatePath {\n /**\n * The path to the PEM-encoded public/private key certificate on the filesystem.\n */\n certificatePath: string;\n\n /**\n * The password for the certificate file.\n */\n certificatePassword?: string;\n}\n/**\n * Required configuration options for the {@link ClientCertificateCredential}, with either the string contents of a PEM certificate, or the path to a PEM certificate.\n */\nexport type ClientCertificateCredentialPEMConfiguration =\n | ClientCertificatePEMCertificate\n | ClientCertificatePEMCertificatePath;\n\n/**\n * Enables authentication to Microsoft Entra ID using a PEM-encoded\n * certificate that is assigned to an App Registration. More information\n * on how to configure certificate authentication can be found here:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad\n *\n */\nexport class ClientCertificateCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private certificateConfiguration: ClientCertificateCredentialPEMConfiguration;\n private sendCertificateChain?: boolean;\n private msalClient: MsalClient;\n\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param certificatePath - The path to a PEM-encoded public/private key certificate on the filesystem.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n certificatePath: string,\n options?: ClientCertificateCredentialOptions,\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the path of the certificate on the filesystem.\n * If the type is ignored, we will throw the value of the path to a PEM certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificatePath,\n options?: ClientCertificateCredentialOptions,\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the PEM-encoded certificate as a string.\n * If the type is ignored, we will throw the value of the PEM-encoded certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificate,\n options?: ClientCertificateCredentialOptions,\n );\n constructor(\n tenantId: string,\n clientId: string,\n certificatePathOrConfiguration: string | ClientCertificateCredentialPEMConfiguration,\n options: ClientCertificateCredentialOptions = {},\n ) {\n if (!tenantId || !clientId) {\n throw new Error(`${credentialName}: tenantId and clientId are required parameters.`);\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.sendCertificateChain = options.sendCertificateChain;\n\n this.certificateConfiguration = {\n ...(typeof certificatePathOrConfiguration === \"string\"\n ? {\n certificatePath: certificatePathOrConfiguration,\n }\n : certificatePathOrConfiguration),\n };\n const certificate: string | undefined = (\n this.certificateConfiguration as ClientCertificatePEMCertificate\n ).certificate;\n const certificatePath: string | undefined = (\n this.certificateConfiguration as ClientCertificatePEMCertificatePath\n ).certificatePath;\n if (!this.certificateConfiguration || !(certificate || certificatePath)) {\n throw new Error(\n `${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n if (certificate && certificatePath) {\n throw new Error(\n `${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n const certificate = await this.buildClientCertificate();\n return this.msalClient.getTokenByClientCertificate(arrayScopes, certificate, newOptions);\n });\n }\n\n private async buildClientCertificate(): Promise<CertificateParts> {\n const parts = await parseCertificate(\n this.certificateConfiguration,\n this.sendCertificateChain ?? false,\n );\n\n let privateKey: string;\n if (this.certificateConfiguration.certificatePassword !== undefined) {\n privateKey = createPrivateKey({\n key: parts.certificateContents,\n passphrase: this.certificateConfiguration.certificatePassword,\n format: \"pem\",\n })\n .export({\n format: \"pem\",\n type: \"pkcs8\",\n })\n .toString();\n } else {\n privateKey = parts.certificateContents;\n }\n\n return {\n thumbprint: parts.thumbprint,\n privateKey,\n x5c: parts.x5c,\n };\n }\n}\n\n/**\n * Parses a certificate into its relevant parts\n *\n * @param certificateConfiguration - The certificate contents or path to the certificate\n * @param sendCertificateChain - true if the entire certificate chain should be sent for SNI, false otherwise\n * @returns The parsed certificate parts and the certificate contents\n */\nexport async function parseCertificate(\n certificateConfiguration: ClientCertificateCredentialPEMConfiguration,\n sendCertificateChain: boolean,\n): Promise<Omit<CertificateParts, \"privateKey\"> & { certificateContents: string }> {\n const certificate: string | undefined = (\n certificateConfiguration as ClientCertificatePEMCertificate\n ).certificate;\n const certificatePath: string | undefined = (\n certificateConfiguration as ClientCertificatePEMCertificatePath\n ).certificatePath;\n const certificateContents = certificate || (await readFile(certificatePath!, \"utf8\"));\n const x5c = sendCertificateChain ? certificateContents : undefined;\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n const thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return {\n certificateContents,\n thumbprint,\n x5c,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { MsalClient, createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport { ClientSecretCredentialOptions } from \"./clientSecretCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"ClientSecretCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID using a client secret\n * that was generated for an App Registration. More information on how\n * to configure a client secret can be found here:\n *\n * https://learn.microsoft.com/entra/identity-platform/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application\n *\n */\nexport class ClientSecretCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalClient: MsalClient;\n private clientSecret: string;\n\n /**\n * Creates an instance of the ClientSecretCredential with the details\n * needed to authenticate against Microsoft Entra ID with a client\n * secret.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n clientSecret: string,\n options: ClientSecretCredentialOptions = {},\n ) {\n if (!tenantId) {\n throw new CredentialUnavailableError(\n \"ClientSecretCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.\",\n );\n }\n\n if (!clientId) {\n throw new CredentialUnavailableError(\n \"ClientSecretCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.\",\n );\n }\n\n if (!clientSecret) {\n throw new CredentialUnavailableError(\n \"ClientSecretCredential: clientSecret is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.\",\n );\n }\n\n this.clientSecret = clientSecret;\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByClientSecret(arrayScopes, this.clientSecret, newOptions);\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { MsalClient, createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport { CredentialUnavailableError } from \"../errors\";\nimport { UsernamePasswordCredentialOptions } from \"./usernamePasswordCredentialOptions\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"UsernamePasswordCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID with a user's\n * username and password. This credential requires a high degree of\n * trust so you should only use it when other, more secure credential\n * types can't be used.\n */\nexport class UsernamePasswordCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalClient: MsalClient;\n private username: string;\n private password: string;\n\n /**\n * Creates an instance of the UsernamePasswordCredential with the details\n * needed to authenticate against Microsoft Entra ID with a username\n * and password.\n *\n * @param tenantId - The Microsoft Entra tenant (directory).\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param username - The user account's e-mail address (user name).\n * @param password - The user account's account password\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n username: string,\n password: string,\n options: UsernamePasswordCredentialOptions = {},\n ) {\n if (!tenantId) {\n throw new CredentialUnavailableError(\n \"UsernamePasswordCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.\",\n );\n }\n\n if (!clientId) {\n throw new CredentialUnavailableError(\n \"UsernamePasswordCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.\",\n );\n }\n\n if (!username) {\n throw new CredentialUnavailableError(\n \"UsernamePasswordCredential: username is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.\",\n );\n }\n\n if (!password) {\n throw new CredentialUnavailableError(\n \"UsernamePasswordCredential: password is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.\",\n );\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.username = username;\n this.password = password;\n\n this.msalClient = createMsalClient(clientId, this.tenantId, {\n ...options,\n tokenCredentialOptions: 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} will be thrown with the details of the failure.\n *\n * If the user provided the option `disableAutomaticAuthentication`,\n * once the token can't be retrieved silently,\n * this method won't attempt to request user interaction to retrieve the token.\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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByUsernamePassword(\n arrayScopes,\n this.username,\n this.password,\n newOptions,\n );\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger, formatError, formatSuccess, processEnvVars } from \"../util/logging\";\n\nimport { ClientCertificateCredential } from \"./clientCertificateCredential\";\nimport { ClientSecretCredential } from \"./clientSecretCredential\";\nimport { EnvironmentCredentialOptions } from \"./environmentCredentialOptions\";\nimport { UsernamePasswordCredential } from \"./usernamePasswordCredential\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\n/**\n * Contains the list of all supported environment variable names so that an\n * appropriate error message can be generated when no credentials can be\n * configured.\n *\n * @internal\n */\nexport const AllSupportedEnvironmentVariables = [\n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_CLIENT_SECRET\",\n \"AZURE_CLIENT_CERTIFICATE_PATH\",\n \"AZURE_CLIENT_CERTIFICATE_PASSWORD\",\n \"AZURE_USERNAME\",\n \"AZURE_PASSWORD\",\n \"AZURE_ADDITIONALLY_ALLOWED_TENANTS\",\n \"AZURE_CLIENT_SEND_CERTIFICATE_CHAIN\",\n];\n\nfunction getAdditionallyAllowedTenants(): string[] {\n const additionallyAllowedValues = process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS ?? \"\";\n return additionallyAllowedValues.split(\";\");\n}\n\nconst credentialName = \"EnvironmentCredential\";\nconst logger = credentialLogger(credentialName);\n\nexport function getSendCertificateChain(): boolean {\n const sendCertificateChain = (\n process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN ?? \"\"\n ).toLowerCase();\n const result = sendCertificateChain === \"true\" || sendCertificateChain === \"1\";\n logger.verbose(\n `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN: ${process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN}; sendCertificateChain: ${result}`,\n );\n return result;\n}\n\n/**\n * Enables authentication to Microsoft Entra ID using a client secret or certificate, or as a user\n * with a username and password.\n */\nexport class EnvironmentCredential implements TokenCredential {\n private _credential?:\n | ClientSecretCredential\n | ClientCertificateCredential\n | UsernamePasswordCredential = undefined;\n /**\n * Creates an instance of the EnvironmentCredential class and decides what credential to use depending on the available environment variables.\n *\n * Required environment variables:\n * - `AZURE_TENANT_ID`: The Microsoft Entra tenant (directory) ID.\n * - `AZURE_CLIENT_ID`: The client (application) ID of an App Registration in the tenant.\n *\n * If setting the AZURE_TENANT_ID, then you can also set the additionally allowed tenants\n * - `AZURE_ADDITIONALLY_ALLOWED_TENANTS`: For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens with a single semicolon delimited string. Use * to allow all tenants.\n *\n * Environment variables used for client credential authentication:\n * - `AZURE_CLIENT_SECRET`: A client secret that was generated for the App Registration.\n * - `AZURE_CLIENT_CERTIFICATE_PATH`: The path to a PEM certificate to use during the authentication, instead of the client secret.\n * - `AZURE_CLIENT_CERTIFICATE_PASSWORD`: (optional) password for the certificate file.\n * - `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN`: (optional) indicates that the certificate chain should be set in x5c header to support subject name / issuer based authentication.\n *\n * Alternatively, users can provide environment variables for username and password authentication:\n * - `AZURE_USERNAME`: Username to authenticate with.\n * - `AZURE_PASSWORD`: Password to authenticate with.\n *\n * If the environment variables required to perform the authentication are missing, a {@link CredentialUnavailableError} will be thrown.\n * If the authentication fails, or if there's an unknown error, an {@link AuthenticationError} will be thrown.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: EnvironmentCredentialOptions) {\n // Keep track of any missing environment variables for error details\n\n const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(\", \");\n logger.info(`Found the following environment variables: ${assigned}`);\n\n const tenantId = process.env.AZURE_TENANT_ID,\n clientId = process.env.AZURE_CLIENT_ID,\n clientSecret = process.env.AZURE_CLIENT_SECRET;\n\n const additionallyAllowedTenantIds = getAdditionallyAllowedTenants();\n const sendCertificateChain = getSendCertificateChain();\n const newOptions = { ...options, additionallyAllowedTenantIds, sendCertificateChain };\n\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n\n if (tenantId && clientId && clientSecret) {\n logger.info(\n `Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`,\n );\n this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, newOptions);\n return;\n }\n\n const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;\n const certificatePassword = process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD;\n if (tenantId && clientId && certificatePath) {\n logger.info(\n `Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`,\n );\n this._credential = new ClientCertificateCredential(\n tenantId,\n clientId,\n { certificatePath, certificatePassword },\n newOptions,\n );\n return;\n }\n\n const username = process.env.AZURE_USERNAME;\n const password = process.env.AZURE_PASSWORD;\n if (tenantId && clientId && username && password) {\n logger.info(\n `Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`,\n );\n this._credential = new UsernamePasswordCredential(\n tenantId,\n clientId,\n username,\n password,\n newOptions,\n );\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - Optional parameters. See {@link GetTokenOptions}.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n if (this._credential) {\n try {\n const result = await this._credential.getToken(scopes, newOptions);\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err: any) {\n const authenticationError = new AuthenticationError(400, {\n error: `${credentialName} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,\n error_description: err.message.toString().split(\"More details:\").join(\"\"),\n });\n logger.getToken.info(formatError(scopes, authenticationError));\n throw authenticationError;\n }\n }\n throw new CredentialUnavailableError(\n `${credentialName} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,\n );\n });\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport {\n DefaultAzureCredentialClientIdOptions,\n DefaultAzureCredentialOptions,\n DefaultAzureCredentialResourceIdOptions,\n} from \"./defaultAzureCredentialOptions\";\nimport {\n ManagedIdentityCredential,\n ManagedIdentityCredentialClientIdOptions,\n ManagedIdentityCredentialResourceIdOptions,\n} from \"./managedIdentityCredential\";\n\nimport { AzureCliCredential } from \"./azureCliCredential\";\nimport { AzureDeveloperCliCredential } from \"./azureDeveloperCliCredential\";\nimport { AzurePowerShellCredential } from \"./azurePowerShellCredential\";\nimport { ChainedTokenCredential } from \"./chainedTokenCredential\";\nimport { EnvironmentCredential } from \"./environmentCredential\";\nimport { TokenCredential } from \"@azure/core-auth\";\nimport { WorkloadIdentityCredential } from \"./workloadIdentityCredential\";\nimport { WorkloadIdentityCredentialOptions } from \"./workloadIdentityCredentialOptions\";\nimport { credentialLogger } from \"../util/logging\";\n\nconst logger = credentialLogger(\"DefaultAzureCredential\");\n\n/**\n * Creates a {@link ManagedIdentityCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nexport function createDefaultManagedIdentityCredential(\n options:\n | DefaultAzureCredentialOptions\n | DefaultAzureCredentialResourceIdOptions\n | DefaultAzureCredentialClientIdOptions = {},\n): TokenCredential {\n options.retryOptions ??= {\n maxRetries: 5,\n retryDelayInMs: 800,\n };\n const managedIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.managedIdentityClientId ??\n process.env.AZURE_CLIENT_ID;\n const workloadIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.workloadIdentityClientId ??\n managedIdentityClientId;\n const managedResourceId = (options as DefaultAzureCredentialResourceIdOptions)\n ?.managedIdentityResourceId;\n const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;\n const tenantId = options?.tenantId ?? process.env.AZURE_TENANT_ID;\n if (managedResourceId) {\n const managedIdentityResourceIdOptions: ManagedIdentityCredentialResourceIdOptions = {\n ...options,\n resourceId: managedResourceId,\n };\n return new ManagedIdentityCredential(managedIdentityResourceIdOptions);\n }\n\n if (workloadFile && workloadIdentityClientId) {\n const workloadIdentityCredentialOptions: DefaultAzureCredentialOptions = {\n ...options,\n tenantId: tenantId,\n };\n\n return new ManagedIdentityCredential(\n workloadIdentityClientId,\n workloadIdentityCredentialOptions,\n );\n }\n\n if (managedIdentityClientId) {\n const managedIdentityClientOptions: ManagedIdentityCredentialClientIdOptions = {\n ...options,\n clientId: managedIdentityClientId,\n };\n\n return new ManagedIdentityCredential(managedIdentityClientOptions);\n }\n\n // We may be able to return a UnavailableCredential here, but that may be a breaking change\n return new ManagedIdentityCredential(options);\n}\n\n/**\n * Creates a {@link WorkloadIdentityCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nfunction createDefaultWorkloadIdentityCredential(\n options?: DefaultAzureCredentialOptions | DefaultAzureCredentialClientIdOptions,\n): TokenCredential {\n const managedIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.managedIdentityClientId ??\n process.env.AZURE_CLIENT_ID;\n const workloadIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.workloadIdentityClientId ??\n managedIdentityClientId;\n const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;\n const tenantId = options?.tenantId ?? process.env.AZURE_TENANT_ID;\n if (workloadFile && workloadIdentityClientId) {\n const workloadIdentityCredentialOptions: WorkloadIdentityCredentialOptions = {\n ...options,\n tenantId,\n clientId: workloadIdentityClientId,\n tokenFilePath: workloadFile,\n };\n return new WorkloadIdentityCredential(workloadIdentityCredentialOptions);\n }\n if (tenantId) {\n const workloadIdentityClientTenantOptions: WorkloadIdentityCredentialOptions = {\n ...options,\n tenantId,\n };\n return new WorkloadIdentityCredential(workloadIdentityClientTenantOptions);\n }\n\n // We may be able to return a UnavailableCredential here, but that may be a breaking change\n return new WorkloadIdentityCredential(options);\n}\n\n/**\n * Creates a {@link AzureDeveloperCliCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nfunction createDefaultAzureDeveloperCliCredential(\n options: DefaultAzureCredentialOptions = {},\n): TokenCredential {\n const processTimeoutInMs = options.processTimeoutInMs;\n return new AzureDeveloperCliCredential({ processTimeoutInMs, ...options });\n}\n\n/**\n * Creates a {@link AzureCliCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nfunction createDefaultAzureCliCredential(\n options: DefaultAzureCredentialOptions = {},\n): TokenCredential {\n const processTimeoutInMs = options.processTimeoutInMs;\n return new AzureCliCredential({ processTimeoutInMs, ...options });\n}\n\n/**\n * Creates a {@link AzurePowerShellCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nfunction createDefaultAzurePowershellCredential(\n options: DefaultAzureCredentialOptions = {},\n): TokenCredential {\n const processTimeoutInMs = options.processTimeoutInMs;\n return new AzurePowerShellCredential({ processTimeoutInMs, ...options });\n}\n\n/**\n * Creates an {@link EnvironmentCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nexport function createEnvironmentCredential(\n options: DefaultAzureCredentialOptions = {},\n): TokenCredential {\n return new EnvironmentCredential(options);\n}\n\n/**\n * A no-op credential that logs the reason it was skipped if getToken is called.\n * @internal\n */\nexport class UnavailableDefaultCredential implements TokenCredential {\n credentialUnavailableErrorMessage: string;\n credentialName: string;\n\n constructor(credentialName: string, message: string) {\n this.credentialName = credentialName;\n this.credentialUnavailableErrorMessage = message;\n }\n\n getToken(): Promise<null> {\n logger.getToken.info(\n `Skipping ${this.credentialName}, reason: ${this.credentialUnavailableErrorMessage}`,\n );\n return Promise.resolve(null);\n }\n}\n\n/**\n * Provides a default {@link ChainedTokenCredential} configuration that works for most\n * applications that use Azure SDK client libraries. For more information, see\n * [DefaultAzureCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-defaultazurecredential-for-flexibility).\n *\n * The following credential types will be tried, in order:\n *\n * - {@link EnvironmentCredential}\n * - {@link WorkloadIdentityCredential}\n * - {@link ManagedIdentityCredential}\n * - {@link AzureCliCredential}\n * - {@link AzurePowerShellCredential}\n * - {@link AzureDeveloperCliCredential}\n *\n * Consult the documentation of these credential types for more information\n * on how they attempt authentication.\n */\nexport class DefaultAzureCredential extends ChainedTokenCredential {\n /**\n * Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialClientIdOptions}.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialClientIdOptions}.\n */\n constructor(options?: DefaultAzureCredentialClientIdOptions);\n\n /**\n * Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialResourceIdOptions}.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialResourceIdOptions}.\n */\n constructor(options?: DefaultAzureCredentialResourceIdOptions);\n\n /**\n * Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialOptions}.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialOptions}.\n */\n constructor(options?: DefaultAzureCredentialOptions);\n\n constructor(options?: DefaultAzureCredentialOptions) {\n const credentialFunctions = [\n createEnvironmentCredential,\n createDefaultWorkloadIdentityCredential,\n createDefaultManagedIdentityCredential,\n createDefaultAzureCliCredential,\n createDefaultAzurePowershellCredential,\n createDefaultAzureDeveloperCliCredential,\n ];\n\n // DefaultCredential constructors should not throw, instead throwing on getToken() which is handled by ChainedTokenCredential.\n\n // When adding new credentials to the default chain, consider:\n // 1. Making the constructor parameters required and explicit\n // 2. Validating any required parameters in the factory function\n // 3. Returning a UnavailableDefaultCredential from the factory function if a credential is unavailable for any reason\n const credentials: TokenCredential[] = credentialFunctions.map((createCredentialFn) => {\n try {\n return createCredentialFn(options);\n } catch (err: any) {\n logger.warning(\n `Skipped ${createCredentialFn.name} because of an error creating the credential: ${err}`,\n );\n return new UnavailableDefaultCredential(createCredentialFn.name, err.message);\n }\n });\n\n super(...credentials);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n InteractiveBrowserCredentialInBrowserOptions,\n InteractiveBrowserCredentialNodeOptions,\n} from \"./interactiveBrowserCredentialOptions\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../util/tenantIdUtils\";\n\nimport { AuthenticationRecord } from \"../msal/types\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport { MsalClient, MsalClientOptions, createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { DeveloperSignOnClientId } from \"../constants\";\n\nconst logger = credentialLogger(\"InteractiveBrowserCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID inside of the web browser\n * using the interactive login flow.\n */\nexport class InteractiveBrowserCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private msalClient: MsalClient;\n private disableAutomaticAuthentication?: boolean;\n private browserCustomizationOptions: InteractiveBrowserCredentialNodeOptions[\"browserCustomizationOptions\"];\n private loginHint?: string;\n\n /**\n * Creates an instance of InteractiveBrowserCredential with the details needed.\n *\n * This credential uses the [Authorization Code Flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow).\n * On Node.js, it will open a browser window while it listens for a redirect response from the authentication service.\n * On browsers, it authenticates via popups. The `loginStyle` optional parameter can be set to `redirect` to authenticate by redirecting the user to an Azure secure login page, which then will redirect the user back to the web application where the authentication started.\n *\n * For Node.js, if a `clientId` is provided, the Microsoft Entra application will need to be configured to have a \"Mobile and desktop applications\" redirect endpoint.\n * Follow our guide on [setting up Redirect URIs for Desktop apps that calls to web APIs](https://learn.microsoft.com/entra/identity-platform/scenario-desktop-app-registration#redirect-uris).\n *\n * @param options - Options for configuring the client which makes the authentication requests.\n */\n constructor(\n options: InteractiveBrowserCredentialNodeOptions | InteractiveBrowserCredentialInBrowserOptions,\n ) {\n this.tenantId = resolveTenantId(logger, options.tenantId, options.clientId);\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n const msalClientOptions: MsalClientOptions = {\n ...options,\n tokenCredentialOptions: options,\n logger,\n };\n const ibcNodeOptions = options as InteractiveBrowserCredentialNodeOptions;\n this.browserCustomizationOptions = ibcNodeOptions.browserCustomizationOptions;\n this.loginHint = ibcNodeOptions.loginHint;\n if (ibcNodeOptions?.brokerOptions?.enabled) {\n if (!ibcNodeOptions?.brokerOptions?.parentWindowHandle) {\n throw new Error(\n \"In order to do WAM authentication, `parentWindowHandle` under `brokerOptions` is a required parameter\",\n );\n } else {\n msalClientOptions.brokerOptions = {\n enabled: true,\n parentWindowHandle: ibcNodeOptions.brokerOptions.parentWindowHandle,\n legacyEnableMsaPassthrough: ibcNodeOptions.brokerOptions?.legacyEnableMsaPassthrough,\n useDefaultBrokerAccount: ibcNodeOptions.brokerOptions?.useDefaultBrokerAccount,\n };\n }\n }\n this.msalClient = createMsalClient(\n options.clientId ?? DeveloperSignOnClientId,\n this.tenantId,\n msalClientOptions,\n );\n this.disableAutomaticAuthentication = options?.disableAutomaticAuthentication;\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the user provided the option `disableAutomaticAuthentication`,\n * once the token can't be retrieved silently,\n * this method won't attempt to request user interaction to retrieve the token.\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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByInteractiveRequest(arrayScopes, {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n browserCustomizationOptions: this.browserCustomizationOptions,\n loginHint: this.loginHint,\n });\n },\n );\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the token can't be retrieved silently, this method will always generate a challenge for the user.\n *\n * On Node.js, this credential has [Proof Key for Code Exchange (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636) enabled by default.\n * PKCE is a security feature that mitigates authentication code interception attacks.\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 async authenticate(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AuthenticationRecord | undefined> {\n return tracingClient.withSpan(\n `${this.constructor.name}.authenticate`,\n options,\n async (newOptions) => {\n const arrayScopes = ensureScopes(scopes);\n await this.msalClient.getTokenByInteractiveRequest(arrayScopes, {\n ...newOptions,\n disableAutomaticAuthentication: false, // this method should always allow user interaction\n browserCustomizationOptions: this.browserCustomizationOptions,\n loginHint: this.loginHint,\n });\n return this.msalClient.getActiveAccount();\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../util/tenantIdUtils\";\nimport {\n DeviceCodeCredentialOptions,\n DeviceCodeInfo,\n DeviceCodePromptCallback,\n} from \"./deviceCodeCredentialOptions\";\nimport { AuthenticationRecord } from \"../msal/types\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport { MsalClient, createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { DeveloperSignOnClientId } from \"../constants\";\n\nconst logger = credentialLogger(\"DeviceCodeCredential\");\n\n/**\n * Method that logs the user code from the DeviceCodeCredential.\n * @param deviceCodeInfo - The device code.\n */\nexport function defaultDeviceCodePromptCallback(deviceCodeInfo: DeviceCodeInfo): void {\n console.log(deviceCodeInfo.message);\n}\n\n/**\n * Enables authentication to Microsoft Entra ID using a device code\n * that the user can enter into https://microsoft.com/devicelogin.\n */\nexport class DeviceCodeCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private disableAutomaticAuthentication?: boolean;\n private msalClient: MsalClient;\n private userPromptCallback: DeviceCodePromptCallback;\n\n /**\n * Creates an instance of DeviceCodeCredential with the details needed\n * to initiate the device code authorization flow with Microsoft Entra ID.\n *\n * A message will be logged, giving users a code that they can use to authenticate once they go to https://microsoft.com/devicelogin\n *\n * Developers can configure how this message is shown by passing a custom `userPromptCallback`:\n *\n * ```ts snippet:device_code_credential_example\n * import { DeviceCodeCredential } from \"@azure/identity\";\n *\n * const credential = new DeviceCodeCredential({\n * tenantId: process.env.AZURE_TENANT_ID,\n * clientId: process.env.AZURE_CLIENT_ID,\n * userPromptCallback: (info) => {\n * console.log(\"CUSTOMIZED PROMPT CALLBACK\", info.message);\n * },\n * });\n * ```\n *\n * @param options - Options for configuring the client which makes the authentication requests.\n */\n constructor(options?: DeviceCodeCredentialOptions) {\n this.tenantId = options?.tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n const clientId = options?.clientId ?? DeveloperSignOnClientId;\n const tenantId = resolveTenantId(logger, options?.tenantId, clientId);\n this.userPromptCallback = options?.userPromptCallback ?? defaultDeviceCodePromptCallback;\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: options || {},\n });\n this.disableAutomaticAuthentication = options?.disableAutomaticAuthentication;\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the user provided the option `disableAutomaticAuthentication`,\n * once the token can't be retrieved silently,\n * this method won't attempt to request user interaction to retrieve the token.\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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n });\n },\n );\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the token can't be retrieved silently, this method will always generate a challenge for the user.\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 async authenticate(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AuthenticationRecord | undefined> {\n return tracingClient.withSpan(\n `${this.constructor.name}.authenticate`,\n options,\n async (newOptions) => {\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n await this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, {\n ...newOptions,\n disableAutomaticAuthentication: false, // this method should always allow user interaction\n });\n return this.msalClient.getActiveAccount();\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../errors\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\n\nimport { AzurePipelinesCredentialOptions } from \"./azurePipelinesCredentialOptions\";\nimport { ClientAssertionCredential } from \"./clientAssertionCredential\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport { PipelineResponse } from \"@azure/core-rest-pipeline\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { credentialLogger } from \"../util/logging\";\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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { AuthorizationCodeCredentialOptions } from \"./authorizationCodeCredentialOptions\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport { MsalClient, createMsalClient } from \"../msal/nodeFlows/msalClient\";\n\nconst logger = credentialLogger(\"AuthorizationCodeCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID using an authorization code\n * that was obtained through the authorization code flow, described in more detail\n * in the Microsoft Entra ID documentation:\n *\n * https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow\n */\nexport class AuthorizationCodeCredential implements TokenCredential {\n private msalClient: MsalClient;\n private disableAutomaticAuthentication?: boolean;\n private authorizationCode: string;\n private redirectUri: string;\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private clientSecret?: string;\n\n /**\n * Creates an instance of AuthorizationCodeCredential with the details needed\n * to request an access token using an authentication that was obtained\n * from Microsoft Entra ID.\n *\n * It is currently necessary for the user of this credential to initiate\n * the authorization code flow to obtain an authorization code to be used\n * with this credential. A full example of this flow is provided here:\n *\n * https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/v2/manual/authorizationCodeSample.ts\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID or name.\n * 'common' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration\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 options - Options for configuring the client which makes the access token request.\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n clientSecret: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions,\n );\n /**\n * Creates an instance of AuthorizationCodeCredential with the details needed\n * to request an access token using an authentication that was obtained\n * from Microsoft Entra ID.\n *\n * It is currently necessary for the user of this credential to initiate\n * the authorization code flow to obtain an authorization code to be used\n * with this credential. A full example of this flow is provided here:\n *\n * https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/v2/manual/authorizationCodeSample.ts\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID or name.\n * 'common' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\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 options - Options for configuring the client which makes the access token request.\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions,\n );\n /**\n * @hidden\n * @internal\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n clientSecretOrAuthorizationCode: string,\n authorizationCodeOrRedirectUri: string,\n redirectUriOrOptions: string | AuthorizationCodeCredentialOptions | undefined,\n options?: AuthorizationCodeCredentialOptions,\n ) {\n checkTenantId(logger, tenantId);\n this.clientSecret = clientSecretOrAuthorizationCode;\n\n if (typeof redirectUriOrOptions === \"string\") {\n // the clientId+clientSecret constructor\n this.authorizationCode = authorizationCodeOrRedirectUri;\n this.redirectUri = redirectUriOrOptions;\n // in this case, options are good as they come\n } else {\n // clientId only\n this.authorizationCode = clientSecretOrAuthorizationCode;\n this.redirectUri = authorizationCodeOrRedirectUri as string;\n this.clientSecret = undefined;\n options = redirectUriOrOptions as AuthorizationCodeCredentialOptions;\n }\n\n // TODO: Validate tenant if provided\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n );\n newOptions.tenantId = tenantId;\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByAuthorizationCode(\n arrayScopes,\n this.redirectUri,\n this.authorizationCode,\n this.clientSecret,\n {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n },\n );\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { MsalClient, createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport {\n OnBehalfOfCredentialAssertionOptions,\n OnBehalfOfCredentialCertificateOptions,\n OnBehalfOfCredentialOptions,\n OnBehalfOfCredentialSecretOptions,\n} from \"./onBehalfOfCredentialOptions\";\nimport { credentialLogger, formatError } from \"../util/logging\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport { CertificateParts } from \"../msal/types\";\nimport { ClientCertificatePEMCertificatePath } from \"./clientCertificateCredential\";\nimport { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\nimport { createHash } from \"node:crypto\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { readFile } from \"node:fs/promises\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst credentialName = \"OnBehalfOfCredential\";\nconst logger = credentialLogger(credentialName);\n\n/**\n * Enables authentication to Microsoft Entra ID using the [On Behalf Of flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow).\n */\nexport class OnBehalfOfCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalClient: MsalClient;\n private sendCertificateChain?: boolean;\n private certificatePath?: string;\n private clientSecret?: string;\n private userAssertionToken: string;\n private clientAssertion?: () => Promise<string>;\n\n /**\n * Creates an instance of the {@link OnBehalfOfCredential} with the details\n * needed to authenticate against Microsoft Entra ID with path to a PEM certificate,\n * and an user assertion.\n *\n * Example using the `KeyClient` from [\\@azure/keyvault-keys](https://www.npmjs.com/package/\\@azure/keyvault-keys):\n *\n * ```ts snippet:on_behalf_of_credential_pem_example\n * import { OnBehalfOfCredential } from \"@azure/identity\";\n * import { KeyClient } from \"@azure/keyvault-keys\";\n *\n * const tokenCredential = new OnBehalfOfCredential({\n * tenantId: \"tenant-id\",\n * clientId: \"client-id\",\n * certificatePath: \"/path/to/certificate.pem\",\n * userAssertionToken: \"access-token\",\n * });\n * const client = new KeyClient(\"vault-url\", tokenCredential);\n * await client.getKey(\"key-name\");\n * ```\n *\n * @param options - Optional parameters, generally common across credentials.\n */\n constructor(\n options: OnBehalfOfCredentialCertificateOptions &\n MultiTenantTokenCredentialOptions &\n CredentialPersistenceOptions,\n );\n /**\n * Creates an instance of the {@link OnBehalfOfCredential} with the details\n * needed to authenticate against Microsoft Entra ID with a client\n * secret and an user assertion.\n *\n * Example using the `KeyClient` from [\\@azure/keyvault-keys](https://www.npmjs.com/package/\\@azure/keyvault-keys):\n *\n * ```ts snippet:on_behalf_of_credential_secret_example\n * import { OnBehalfOfCredential } from \"@azure/identity\";\n * import { KeyClient } from \"@azure/keyvault-keys\";\n *\n * const tokenCredential = new OnBehalfOfCredential({\n * tenantId: \"tenant-id\",\n * clientId: \"client-id\",\n * clientSecret: \"client-secret\",\n * userAssertionToken: \"access-token\",\n * });\n * const client = new KeyClient(\"vault-url\", tokenCredential);\n * await client.getKey(\"key-name\");\n * ```\n *\n * @param options - Optional parameters, generally common across credentials.\n */\n constructor(\n options: OnBehalfOfCredentialSecretOptions &\n MultiTenantTokenCredentialOptions &\n CredentialPersistenceOptions,\n );\n\n /**\n * Creates an instance of the {@link OnBehalfOfCredential} with the details\n * needed to authenticate against Microsoft Entra ID with a client `getAssertion`\n * and an user assertion.\n *\n * Example using the `KeyClient` from [\\@azure/keyvault-keys](https://www.npmjs.com/package/\\@azure/keyvault-keys):\n *\n * ```ts snippet:on_behalf_of_credential_assertion_example\n * import { OnBehalfOfCredential } from \"@azure/identity\";\n * import { KeyClient } from \"@azure/keyvault-keys\";\n *\n * const tokenCredential = new OnBehalfOfCredential({\n * tenantId: \"tenant-id\",\n * clientId: \"client-id\",\n * getAssertion: () => {\n * return Promise.resolve(\"my-jwt\");\n * },\n * userAssertionToken: \"access-token\",\n * });\n * const client = new KeyClient(\"vault-url\", tokenCredential);\n * await client.getKey(\"key-name\");\n * ```\n *\n * @param options - Optional parameters, generally common across credentials.\n */\n constructor(\n options: OnBehalfOfCredentialAssertionOptions &\n MultiTenantTokenCredentialOptions &\n CredentialPersistenceOptions,\n );\n\n constructor(options: OnBehalfOfCredentialOptions) {\n const { clientSecret } = options as OnBehalfOfCredentialSecretOptions;\n const { certificatePath, sendCertificateChain } =\n options as OnBehalfOfCredentialCertificateOptions;\n const { getAssertion } = options as OnBehalfOfCredentialAssertionOptions;\n const {\n tenantId,\n clientId,\n userAssertionToken,\n additionallyAllowedTenants: additionallyAllowedTenantIds,\n } = options;\n if (!tenantId) {\n throw new CredentialUnavailableError(\n `${credentialName}: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n\n if (!clientId) {\n throw new CredentialUnavailableError(\n `${credentialName}: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n\n if (!clientSecret && !certificatePath && !getAssertion) {\n throw new CredentialUnavailableError(\n `${credentialName}: You must provide one of clientSecret, certificatePath, or a getAssertion callback but none were provided. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n\n if (!userAssertionToken) {\n throw new CredentialUnavailableError(\n `${credentialName}: userAssertionToken is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n this.certificatePath = certificatePath;\n this.clientSecret = clientSecret;\n this.userAssertionToken = userAssertionToken;\n this.sendCertificateChain = sendCertificateChain;\n this.clientAssertion = getAssertion;\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n additionallyAllowedTenantIds,\n );\n\n this.msalClient = createMsalClient(clientId, this.tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 the underlying network requests.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n if (this.certificatePath) {\n const clientCertificate = await this.buildClientCertificate(this.certificatePath);\n\n return this.msalClient.getTokenOnBehalfOf(\n arrayScopes,\n this.userAssertionToken,\n clientCertificate,\n newOptions,\n );\n } else if (this.clientSecret) {\n return this.msalClient.getTokenOnBehalfOf(\n arrayScopes,\n this.userAssertionToken,\n this.clientSecret,\n options,\n );\n } else if (this.clientAssertion) {\n return this.msalClient.getTokenOnBehalfOf(\n arrayScopes,\n this.userAssertionToken,\n this.clientAssertion,\n options,\n );\n } else {\n // this is an invalid scenario and is a bug, as the constructor should have thrown an error if neither clientSecret nor certificatePath nor clientAssertion were provided\n throw new Error(\n \"Expected either clientSecret or certificatePath or clientAssertion to be defined.\",\n );\n }\n });\n }\n\n private async buildClientCertificate(certificatePath: string): Promise<CertificateParts> {\n try {\n const parts = await this.parseCertificate({ certificatePath }, this.sendCertificateChain);\n return {\n thumbprint: parts.thumbprint,\n privateKey: parts.certificateContents,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n logger.info(formatError(\"\", error));\n throw error;\n }\n }\n\n private async parseCertificate(\n configuration: ClientCertificatePEMCertificatePath,\n sendCertificateChain?: boolean,\n ): Promise<Omit<CertificateParts, \"privateKey\"> & { certificateContents: string }> {\n const certificatePath = configuration.certificatePath;\n const certificateContents = await readFile(certificatePath, \"utf8\");\n const x5c = sendCertificateChain ? certificateContents : undefined;\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n const thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return {\n certificateContents,\n thumbprint,\n x5c,\n };\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { TokenCredential, TracingContext } from \"@azure/core-auth\";\nimport {\n bearerTokenAuthenticationPolicy,\n createEmptyPipeline,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\n\n/**\n * The options to configure the token provider.\n */\nexport interface GetBearerTokenProviderOptions {\n /** The abort signal to abort requests to get tokens */\n abortSignal?: AbortSignal;\n /** The tracing options for the requests to get tokens */\n tracingOptions?: {\n /**\n * Tracing Context for the current request to get a token.\n */\n tracingContext?: TracingContext;\n };\n}\n\n/**\n * Returns a callback that provides a bearer token.\n * For example, the bearer token can be used to authenticate a request as follows:\n * ```ts snippet:token_provider_example\n * import { DefaultAzureCredential, getBearerTokenProvider } from \"@azure/identity\";\n * import { createPipelineRequest } from \"@azure/core-rest-pipeline\";\n *\n * const credential = new DefaultAzureCredential();\n * const scope = \"https://cognitiveservices.azure.com/.default\";\n * const getAccessToken = getBearerTokenProvider(credential, scope);\n * const token = await getAccessToken();\n * // usage\n * const request = createPipelineRequest({ url: \"https://example.com\" });\n * request.headers.set(\"Authorization\", `Bearer ${token}`);\n * ```\n *\n * @param credential - The credential used to authenticate the request.\n * @param scopes - The scopes required for the bearer token.\n * @param options - Options to configure the token provider.\n * @returns a callback that provides a bearer token.\n */\nexport function getBearerTokenProvider(\n credential: TokenCredential,\n scopes: string | string[],\n options?: GetBearerTokenProviderOptions,\n): () => Promise<string> {\n const { abortSignal, tracingOptions } = options || {};\n const pipeline = createEmptyPipeline();\n pipeline.addPolicy(bearerTokenAuthenticationPolicy({ credential, scopes }));\n async function getRefreshedToken(): Promise<string> {\n // Create a pipeline with just the bearer token policy\n // and run a dummy request through it to get the token\n const res = await pipeline.sendRequest(\n {\n sendRequest: (request) =>\n Promise.resolve({\n request,\n status: 200,\n headers: request.headers,\n }),\n },\n createPipelineRequest({\n url: \"https://example.com\",\n abortSignal,\n tracingOptions,\n }),\n );\n const accessToken = res.headers.get(\"authorization\")?.split(\" \")[1];\n if (!accessToken) {\n throw new Error(\"Failed to get access token\");\n }\n return accessToken;\n }\n return getRefreshedToken;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport * from \"./plugins/consumer\";\n\nexport { IdentityPlugin } from \"./plugins/provider\";\n\nimport { TokenCredential } from \"@azure/core-auth\";\nimport { DefaultAzureCredential } from \"./credentials/defaultAzureCredential\";\n\nexport {\n AuthenticationError,\n ErrorResponse,\n AggregateAuthenticationError,\n AuthenticationErrorName,\n AggregateAuthenticationErrorName,\n CredentialUnavailableError,\n CredentialUnavailableErrorName,\n AuthenticationRequiredError,\n AuthenticationRequiredErrorOptions,\n} from \"./errors\";\n\nexport { AuthenticationRecord } from \"./msal/types\";\nexport { serializeAuthenticationRecord, deserializeAuthenticationRecord } from \"./msal/utils\";\nexport { TokenCredentialOptions } from \"./tokenCredentialOptions\";\nexport { MultiTenantTokenCredentialOptions } from \"./credentials/multiTenantTokenCredentialOptions\";\nexport { AuthorityValidationOptions } from \"./credentials/authorityValidationOptions\";\n// TODO: Export again once we're ready to release this feature.\n// export { RegionalAuthority } from \"./regionalAuthority\";\n\nexport { BrokerAuthOptions } from \"./credentials/brokerAuthOptions\";\nexport {\n BrokerOptions,\n BrokerEnabledOptions,\n BrokerDisabledOptions,\n} from \"./msal/nodeFlows/brokerOptions\";\nexport { InteractiveCredentialOptions } from \"./credentials/interactiveCredentialOptions\";\n\nexport { ChainedTokenCredential } from \"./credentials/chainedTokenCredential\";\n\nexport { ClientSecretCredential } from \"./credentials/clientSecretCredential\";\nexport { ClientSecretCredentialOptions } from \"./credentials/clientSecretCredentialOptions\";\n\nexport { DefaultAzureCredential } from \"./credentials/defaultAzureCredential\";\nexport {\n DefaultAzureCredentialOptions,\n DefaultAzureCredentialClientIdOptions,\n DefaultAzureCredentialResourceIdOptions,\n} from \"./credentials/defaultAzureCredentialOptions\";\n\nexport { EnvironmentCredential } from \"./credentials/environmentCredential\";\nexport { EnvironmentCredentialOptions } from \"./credentials/environmentCredentialOptions\";\n\nexport {\n ClientCertificateCredential,\n ClientCertificateCredentialPEMConfiguration,\n ClientCertificatePEMCertificatePath,\n ClientCertificatePEMCertificate,\n} from \"./credentials/clientCertificateCredential\";\nexport { ClientCertificateCredentialOptions } from \"./credentials/clientCertificateCredentialOptions\";\nexport { ClientAssertionCredential } from \"./credentials/clientAssertionCredential\";\nexport { ClientAssertionCredentialOptions } from \"./credentials/clientAssertionCredentialOptions\";\nexport { CredentialPersistenceOptions } from \"./credentials/credentialPersistenceOptions\";\nexport { AzureCliCredential } from \"./credentials/azureCliCredential\";\nexport { AzureCliCredentialOptions } from \"./credentials/azureCliCredentialOptions\";\nexport { AzureDeveloperCliCredential } from \"./credentials/azureDeveloperCliCredential\";\nexport { AzureDeveloperCliCredentialOptions } from \"./credentials/azureDeveloperCliCredentialOptions\";\nexport { InteractiveBrowserCredential } from \"./credentials/interactiveBrowserCredential\";\nexport {\n InteractiveBrowserCredentialNodeOptions,\n InteractiveBrowserCredentialInBrowserOptions,\n BrowserLoginStyle,\n} from \"./credentials/interactiveBrowserCredentialOptions\";\nexport {\n ManagedIdentityCredential,\n ManagedIdentityCredentialClientIdOptions,\n ManagedIdentityCredentialResourceIdOptions,\n ManagedIdentityCredentialObjectIdOptions,\n} from \"./credentials/managedIdentityCredential\";\nexport { DeviceCodeCredential } from \"./credentials/deviceCodeCredential\";\nexport {\n DeviceCodePromptCallback,\n DeviceCodeInfo,\n} from \"./credentials/deviceCodeCredentialOptions\";\nexport { DeviceCodeCredentialOptions } from \"./credentials/deviceCodeCredentialOptions\";\nexport { AzurePipelinesCredential as AzurePipelinesCredential } from \"./credentials/azurePipelinesCredential\";\nexport { AzurePipelinesCredentialOptions as AzurePipelinesCredentialOptions } from \"./credentials/azurePipelinesCredentialOptions\";\nexport { AuthorizationCodeCredential } from \"./credentials/authorizationCodeCredential\";\nexport { AuthorizationCodeCredentialOptions } from \"./credentials/authorizationCodeCredentialOptions\";\nexport { AzurePowerShellCredential } from \"./credentials/azurePowerShellCredential\";\nexport { AzurePowerShellCredentialOptions } from \"./credentials/azurePowerShellCredentialOptions\";\nexport {\n OnBehalfOfCredentialOptions,\n OnBehalfOfCredentialSecretOptions,\n OnBehalfOfCredentialCertificateOptions,\n OnBehalfOfCredentialAssertionOptions,\n} from \"./credentials/onBehalfOfCredentialOptions\";\nexport { UsernamePasswordCredential } from \"./credentials/usernamePasswordCredential\";\nexport { UsernamePasswordCredentialOptions } from \"./credentials/usernamePasswordCredentialOptions\";\nexport { VisualStudioCodeCredential } from \"./credentials/visualStudioCodeCredential\";\nexport { VisualStudioCodeCredentialOptions } from \"./credentials/visualStudioCodeCredentialOptions\";\nexport { OnBehalfOfCredential } from \"./credentials/onBehalfOfCredential\";\nexport { WorkloadIdentityCredential } from \"./credentials/workloadIdentityCredential\";\nexport { WorkloadIdentityCredentialOptions } from \"./credentials/workloadIdentityCredentialOptions\";\nexport { BrowserCustomizationOptions } from \"./credentials/browserCustomizationOptions\";\nexport { TokenCachePersistenceOptions } from \"./msal/nodeFlows/tokenCachePersistenceOptions\";\n\nexport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-auth\";\nexport { logger } from \"./util/logging\";\n\nexport { AzureAuthorityHosts } from \"./constants\";\n\n/**\n * Returns a new instance of the {@link DefaultAzureCredential}.\n */\nexport function getDefaultAzureCredential(): TokenCredential {\n return new DefaultAzureCredential();\n}\n\nexport { getBearerTokenProvider, GetBearerTokenProviderOptions } from \"./tokenProvider\";\n"],"names":["AzureAuthorityHosts","logger","createClientLogger","createTracingClient","isNode","ServiceClient","createPipelineRequest","createHttpHeaders","isNodeLike","msalCommon","AbortError","msiName","isError","delay","retryPolicy","calculateRetryDelay","getLogLevel","msal","credentialName","readFile","ManagedIdentityApplication","childProcess","createPrivateKey","createHash","createEmptyPipeline","bearerTokenAuthenticationPolicy"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;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sBAAsB,EAAE,CAAC;AACtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/constants.ts","../src/msal/nodeFlows/msalPlugins.ts","../src/util/logging.ts","../src/errors.ts","../src/util/processMultiTenantRequest.ts","../src/util/tenantIdUtils.ts","../src/util/identityTokenEndpoint.ts","../src/util/tracing.ts","../src/credentials/managedIdentityCredential/constants.ts","../src/credentials/managedIdentityCredential/utils.ts","../src/client/identityClient.ts","../src/credentials/visualStudioCodeCredential.ts","../src/plugins/consumer.ts","../src/msal/utils.ts","../src/credentials/managedIdentityCredential/imdsMsi.ts","../src/credentials/managedIdentityCredential/imdsRetryPolicy.ts","../src/regionalAuthority.ts","../src/msal/nodeFlows/msalClient.ts","../src/credentials/clientAssertionCredential.ts","../src/credentials/workloadIdentityCredential.ts","../src/credentials/managedIdentityCredential/tokenExchangeMsi.ts","../src/credentials/managedIdentityCredential/msalMsiProvider.ts","../src/credentials/managedIdentityCredential/index.ts","../src/util/scopeUtils.ts","../src/util/subscriptionUtils.ts","../src/credentials/azureCliCredential.ts","../src/credentials/azureDeveloperCliCredential.ts","../src/util/processUtils.ts","../src/credentials/azurePowerShellCredential.ts","../src/credentials/chainedTokenCredential.ts","../src/credentials/clientCertificateCredential.ts","../src/credentials/clientSecretCredential.ts","../src/credentials/usernamePasswordCredential.ts","../src/credentials/environmentCredential.ts","../src/credentials/defaultAzureCredential.ts","../src/credentials/interactiveBrowserCredential.ts","../src/credentials/deviceCodeCredential.ts","../src/credentials/azurePipelinesCredential.ts","../src/credentials/authorizationCodeCredential.ts","../src/credentials/onBehalfOfCredential.ts","../src/tokenProvider.ts","../src/index.ts"],"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.5.1`;\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 * 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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type * as msalNode from \"@azure/msal-node\";\n\nimport { CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX, DEFAULT_TOKEN_CACHE_NAME } from \"../../constants\";\n\nimport type { MsalClientOptions } from \"./msalClient\";\nimport type { NativeBrokerPluginControl } from \"../../plugins/provider\";\nimport type { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\n\n/**\n * Configuration for the plugins used by the MSAL node client.\n */\nexport interface PluginConfiguration {\n /**\n * Configuration for the cache plugin.\n */\n cache: {\n /**\n * The non-CAE cache plugin handler.\n */\n cachePlugin?: Promise<msalNode.ICachePlugin>;\n /**\n * The CAE cache plugin handler - persisted to a different file.\n */\n cachePluginCae?: Promise<msalNode.ICachePlugin>;\n };\n /**\n * Configuration for the broker plugin.\n */\n broker: {\n /**\n * True if the broker plugin is enabled and available. False otherwise.\n *\n * It is a bug if this is true and the broker plugin is not available.\n */\n isEnabled: boolean;\n /**\n * If true, MSA account will be passed through, required for WAM authentication.\n */\n enableMsaPassthrough: boolean;\n /**\n * The parent window handle for the broker.\n */\n parentWindowHandle?: Uint8Array;\n /**\n * The native broker plugin handler.\n */\n nativeBrokerPlugin?: msalNode.INativeBrokerPlugin;\n /**\n * If set to true, the credential will attempt to use the default broker account for authentication before falling back to interactive authentication. Default is set to false.\n */\n useDefaultBrokerAccount?: boolean;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nexport let persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalNode.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n },\n};\n\n/**\n * The current native broker provider, undefined by default.\n * @internal\n */\nexport let nativeBrokerInfo:\n | {\n broker: msalNode.INativeBrokerPlugin;\n }\n | undefined = undefined;\n\nexport function hasNativeBroker(): boolean {\n return nativeBrokerInfo !== undefined;\n}\n\n/**\n * An object that allows setting the native broker provider.\n * @internal\n */\nexport const msalNodeFlowNativeBrokerControl: NativeBrokerPluginControl = {\n setNativeBroker(broker): void {\n nativeBrokerInfo = {\n broker,\n };\n },\n};\n\n/**\n * Configures plugins, validating that required plugins are available and enabled.\n *\n * Does not create the plugins themselves, but rather returns the configuration that will be used to create them.\n *\n * @param options - options for creating the MSAL client\n * @returns plugin configuration\n */\nfunction generatePluginConfiguration(options: MsalClientOptions): PluginConfiguration {\n const config: PluginConfiguration = {\n cache: {},\n broker: {\n isEnabled: options.brokerOptions?.enabled ?? false,\n enableMsaPassthrough: options.brokerOptions?.legacyEnableMsaPassthrough ?? false,\n parentWindowHandle: options.brokerOptions?.parentWindowHandle,\n },\n };\n\n if (options.tokenCachePersistenceOptions?.enabled) {\n if (persistenceProvider === undefined) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\",\n ].join(\" \"),\n );\n }\n\n const cacheBaseName = options.tokenCachePersistenceOptions.name || DEFAULT_TOKEN_CACHE_NAME;\n config.cache.cachePlugin = persistenceProvider({\n name: `${cacheBaseName}.${CACHE_NON_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n });\n config.cache.cachePluginCae = persistenceProvider({\n name: `${cacheBaseName}.${CACHE_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n });\n }\n\n if (options.brokerOptions?.enabled) {\n if (nativeBrokerInfo === undefined) {\n throw new Error(\n [\n \"Broker for WAM was requested to be enabled, but no native broker was configured.\",\n \"You must install the identity-broker plugin package (`npm install --save @azure/identity-broker`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(createNativeBrokerPlugin())` before using `enableBroker`.\",\n ].join(\" \"),\n );\n }\n config.broker.nativeBrokerPlugin = nativeBrokerInfo!.broker;\n }\n\n return config;\n}\n\n/**\n * Wraps generatePluginConfiguration as a writeable property for test stubbing purposes.\n */\nexport const msalPlugins = {\n generatePluginConfiguration,\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AzureLogger } from \"@azure/logger\";\nimport { createClientLogger } from \"@azure/logger\";\n\n/**\n * The AzureLogger used for all clients within the identity package\n */\nexport const logger = createClientLogger(\"identity\");\n\ninterface EnvironmentAccumulator {\n missing: string[];\n assigned: string[];\n}\n\n/**\n * Separates a list of environment variable names into a plain object with two arrays: an array of missing environment variables and another array with assigned environment variables.\n * @param supportedEnvVars - List of environment variable names\n */\nexport function processEnvVars(supportedEnvVars: string[]): EnvironmentAccumulator {\n return supportedEnvVars.reduce(\n (acc: EnvironmentAccumulator, envVariable: string) => {\n if (process.env[envVariable]) {\n acc.assigned.push(envVariable);\n } else {\n acc.missing.push(envVariable);\n }\n return acc;\n },\n { missing: [], assigned: [] },\n );\n}\n\n/**\n * Based on a given list of environment variable names,\n * logs the environment variables currently assigned during the usage of a credential that goes by the given name.\n * @param credentialName - Name of the credential in use\n * @param supportedEnvVars - List of environment variables supported by that credential\n */\nexport function logEnvVars(credentialName: string, supportedEnvVars: string[]): void {\n const { assigned } = processEnvVars(supportedEnvVars);\n logger.info(\n `${credentialName} => Found the following environment variables: ${assigned.join(\", \")}`,\n );\n}\n\n/**\n * Formatting the success event on the credentials\n */\nexport function formatSuccess(scope: string | string[]): string {\n return `SUCCESS. Scopes: ${Array.isArray(scope) ? scope.join(\", \") : scope}.`;\n}\n\n/**\n * Formatting the success event on the credentials\n */\nexport function formatError(scope: string | string[] | undefined, error: Error | string): string {\n let message = \"ERROR.\";\n if (scope?.length) {\n message += ` Scopes: ${Array.isArray(scope) ? scope.join(\", \") : scope}.`;\n }\n return `${message} Error message: ${typeof error === \"string\" ? error : error.message}.`;\n}\n\n/**\n * A CredentialLoggerInstance is a logger properly formatted to work in a credential's constructor, and its methods.\n */\nexport interface CredentialLoggerInstance {\n title: string;\n fullTitle: string;\n info(message: string): void;\n warning(message: string): void;\n verbose(message: string): void;\n error(err: string): void;\n}\n\n/**\n * Generates a CredentialLoggerInstance.\n *\n * It logs with the format:\n *\n * `[title] => [message]`\n *\n */\nexport function credentialLoggerInstance(\n title: string,\n parent?: CredentialLoggerInstance,\n log: AzureLogger = logger,\n): CredentialLoggerInstance {\n const fullTitle = parent ? `${parent.fullTitle} ${title}` : title;\n\n function info(message: string): void {\n log.info(`${fullTitle} =>`, message);\n }\n\n function warning(message: string): void {\n log.warning(`${fullTitle} =>`, message);\n }\n\n function verbose(message: string): void {\n log.verbose(`${fullTitle} =>`, message);\n }\n\n function error(message: string): void {\n log.error(`${fullTitle} =>`, message);\n }\n\n return {\n title,\n fullTitle,\n info,\n warning,\n verbose,\n error,\n };\n}\n\n/**\n * A CredentialLogger is a logger declared at the credential's constructor, and used at any point in the credential.\n * It has all the properties of a CredentialLoggerInstance, plus other logger instances, one per method.\n */\nexport interface CredentialLogger extends CredentialLoggerInstance {\n parent: AzureLogger;\n getToken: CredentialLoggerInstance;\n}\n\n/**\n * Generates a CredentialLogger, which is a logger declared at the credential's constructor, and used at any point in the credential.\n * It has all the properties of a CredentialLoggerInstance, plus other logger instances, one per method.\n *\n * It logs with the format:\n *\n * `[title] => [message]`\n * `[title] => getToken() => [message]`\n *\n */\nexport function credentialLogger(title: string, log: AzureLogger = logger): CredentialLogger {\n const credLogger = credentialLoggerInstance(title, undefined, log);\n return {\n ...credLogger,\n parent: log,\n getToken: credentialLoggerInstance(\"=> getToken()\", credLogger, log),\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * See the official documentation for more details:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n /**\n * The string identifier for the error.\n */\n error: string;\n\n /**\n * The error's description.\n */\n errorDescription: string;\n\n /**\n * An array of codes pertaining to the error(s) that occurred.\n */\n errorCodes?: number[];\n\n /**\n * The timestamp at which the error occurred.\n */\n timestamp?: string;\n\n /**\n * The trace identifier for this error occurrence.\n */\n traceId?: string;\n\n /**\n * The correlation ID to be used for tracking the source of the error.\n */\n correlationId?: string;\n}\n\n/**\n * Used for internal deserialization of OAuth responses. Public model is ErrorResponse\n * @internal\n */\nexport interface OAuthErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is OAuthErrorResponse {\n return (\n errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\"\n );\n}\n\n/**\n * The Error.name value of an CredentialUnavailable\n */\nexport const CredentialUnavailableErrorName = \"CredentialUnavailableError\";\n\n/**\n * This signifies that the credential that was tried in a chained credential\n * was not available to be used as the credential. Rather than treating this as\n * an error that should halt the chain, it's caught and the chain continues\n */\nexport class CredentialUnavailableError extends Error {\n constructor(message?: string, options?: { cause?: unknown }) {\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n super(message, options);\n this.name = CredentialUnavailableErrorName;\n }\n}\n\n/**\n * The Error.name value of an AuthenticationError\n */\nexport const AuthenticationErrorName = \"AuthenticationError\";\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n /**\n * The HTTP status code returned from the authentication request.\n */\n public readonly statusCode: number;\n\n /**\n * The error response details.\n */\n public readonly errorResponse: ErrorResponse;\n\n constructor(\n statusCode: number,\n errorBody: object | string | undefined | null,\n options?: { cause?: unknown },\n ) {\n let errorResponse: ErrorResponse = {\n error: \"unknown\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n const oauthErrorResponse: OAuthErrorResponse = JSON.parse(errorBody);\n errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);\n } catch (e: any) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"invalid_request\",\n errorDescription: `The service indicated that the request was invalid.\\n\\n${errorBody}`,\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: `An unknown error has occurred. Response body:\\n\\n${errorBody}`,\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n }\n\n super(\n `${errorResponse.error} Status code: ${statusCode}\\nMore details:\\n${errorResponse.errorDescription},`,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options,\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = AuthenticationErrorName;\n }\n}\n\n/**\n * The Error.name value of an AggregateAuthenticationError\n */\nexport const AggregateAuthenticationErrorName = \"AggregateAuthenticationError\";\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n /**\n * The array of error objects that were thrown while trying to authenticate\n * with the credentials in a {@link ChainedTokenCredential}.\n */\n public errors: any[];\n\n constructor(errors: any[], errorMessage?: string) {\n const errorDetail = errors.join(\"\\n\");\n super(`${errorMessage}\\n${errorDetail}`);\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = AggregateAuthenticationErrorName;\n }\n}\n\nfunction convertOAuthErrorResponseToErrorResponse(errorBody: OAuthErrorResponse): ErrorResponse {\n return {\n error: errorBody.error,\n errorDescription: errorBody.error_description,\n correlationId: errorBody.correlation_id,\n errorCodes: errorBody.error_codes,\n timestamp: errorBody.timestamp,\n traceId: errorBody.trace_id,\n };\n}\n\n/**\n * Optional parameters to the {@link AuthenticationRequiredError}\n */\nexport interface AuthenticationRequiredErrorOptions {\n /**\n * The list of scopes for which the token will have access.\n */\n scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n getTokenOptions?: GetTokenOptions;\n /**\n * The message of the error.\n */\n message?: string;\n /**\n * The underlying cause, if any, that caused the authentication to fail.\n */\n cause?: unknown;\n}\n\n/**\n * Error used to enforce authentication after trying to retrieve a token silently.\n */\nexport class AuthenticationRequiredError extends Error {\n /**\n * The list of scopes for which the token will have access.\n */\n public scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n public getTokenOptions?: GetTokenOptions;\n\n constructor(\n /**\n * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters.\n */\n options: AuthenticationRequiredErrorOptions,\n ) {\n super(\n options.message,\n // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property\n options.cause ? { cause: options.cause } : undefined,\n );\n this.scopes = options.scopes;\n this.getTokenOptions = options.getTokenOptions;\n this.name = \"AuthenticationRequiredError\";\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { GetTokenOptions } from \"@azure/core-auth\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport type { CredentialLogger } from \"./logging\";\n\nfunction createConfigurationErrorMessage(tenantId: string): string {\n return `The current credential is not configured to acquire tokens for tenant ${tenantId}. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add \"*\" to AdditionallyAllowedTenants to allow acquiring tokens for any tenant.`;\n}\n\n/**\n * Of getToken contains a tenantId, this functions allows picking this tenantId as the appropriate for authentication,\n * unless multitenant authentication has been disabled through the AZURE_IDENTITY_DISABLE_MULTITENANTAUTH (on Node.js),\n * or unless the original tenant Id is `adfs`.\n * @internal\n */\nexport function processMultiTenantRequest(\n tenantId?: string,\n getTokenOptions?: GetTokenOptions,\n additionallyAllowedTenantIds: string[] = [],\n logger?: CredentialLogger,\n): string | undefined {\n let resolvedTenantId: string | undefined;\n if (process.env.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH) {\n resolvedTenantId = tenantId;\n } else if (tenantId === \"adfs\") {\n resolvedTenantId = tenantId;\n } else {\n resolvedTenantId = getTokenOptions?.tenantId ?? tenantId;\n }\n if (\n tenantId &&\n resolvedTenantId !== tenantId &&\n !additionallyAllowedTenantIds.includes(\"*\") &&\n !additionallyAllowedTenantIds.some((t) => t.localeCompare(resolvedTenantId!) === 0)\n ) {\n const message = createConfigurationErrorMessage(tenantId);\n logger?.info(message);\n throw new CredentialUnavailableError(message);\n }\n\n return resolvedTenantId;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { ALL_TENANTS, DeveloperSignOnClientId } from \"../constants\";\nimport type { CredentialLogger } from \"./logging\";\nimport { formatError } from \"./logging\";\nexport { processMultiTenantRequest } from \"./processMultiTenantRequest\";\n\n/**\n * @internal\n */\nexport function checkTenantId(logger: CredentialLogger, tenantId: string): void {\n if (!tenantId.match(/^[0-9a-zA-Z-.]+$/)) {\n const error = new Error(\n \"Invalid tenant id provided. You can locate your tenant id by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names.\",\n );\n logger.info(formatError(\"\", error));\n throw error;\n }\n}\n\n/**\n * @internal\n */\nexport function resolveTenantId(\n logger: CredentialLogger,\n tenantId?: string,\n clientId?: string,\n): string {\n if (tenantId) {\n checkTenantId(logger, tenantId);\n return tenantId;\n }\n if (!clientId) {\n clientId = DeveloperSignOnClientId;\n }\n if (clientId !== DeveloperSignOnClientId) {\n return \"common\";\n }\n return \"organizations\";\n}\n\n/**\n * @internal\n */\nexport function resolveAdditionallyAllowedTenantIds(\n additionallyAllowedTenants?: string[],\n): string[] {\n if (!additionallyAllowedTenants || additionallyAllowedTenants.length === 0) {\n return [];\n }\n\n if (additionallyAllowedTenants.includes(\"*\")) {\n return ALL_TENANTS;\n }\n\n return additionallyAllowedTenants;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport function getIdentityTokenEndpointSuffix(tenantId: string): string {\n if (tenantId === \"adfs\") {\n return \"oauth2/token\";\n } else {\n return \"oauth2/v2.0/token\";\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { SDK_VERSION } from \"../constants\";\nimport { createTracingClient } from \"@azure/core-tracing\";\n\n/**\n * Creates a span using the global tracer.\n * @internal\n */\nexport const tracingClient = createTracingClient({\n namespace: \"Microsoft.AAD\",\n packageName: \"@azure/identity\",\n packageVersion: SDK_VERSION,\n});\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport const DefaultScopeSuffix = \"/.default\";\nexport const imdsHost = \"http://169.254.169.254\";\nexport const imdsEndpointPath = \"/metadata/identity/oauth2/token\";\nexport const imdsApiVersion = \"2018-02-01\";\nexport const azureArcAPIVersion = \"2019-11-01\";\nexport const azureFabricVersion = \"2019-07-01-preview\";\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { DefaultScopeSuffix } from \"./constants\";\n\n/**\n * Most MSIs send requests to the IMDS endpoint, or a similar endpoint.\n * These are GET requests that require sending a `resource` parameter on the query.\n * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received.\n * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case.\n *\n * For that reason, when we encounter multiple scopes, we return undefined.\n * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors).\n */\nexport function mapScopesToResource(scopes: string | string[]): string | undefined {\n let scope = \"\";\n if (Array.isArray(scopes)) {\n if (scopes.length !== 1) {\n return;\n }\n\n scope = scopes[0];\n } else if (typeof scopes === \"string\") {\n scope = scopes;\n }\n\n if (!scope.endsWith(DefaultScopeSuffix)) {\n return scope;\n }\n\n return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n refresh_on?: number | string;\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseExpirationTimestamp(body: TokenResponseParsedBody): number {\n if (typeof body.expires_on === \"number\") {\n return body.expires_on * 1000;\n }\n\n if (typeof body.expires_on === \"string\") {\n const asNumber = +body.expires_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.expires_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n\n if (typeof body.expires_in === \"number\") {\n return Date.now() + body.expires_in * 1000;\n }\n\n throw new Error(\n `Failed to parse token expiration from body. expires_in=\"${body.expires_in}\", expires_on=\"${body.expires_on}\"`,\n );\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseRefreshTimestamp(body: TokenResponseParsedBody): number | undefined {\n if (body.refresh_on) {\n if (typeof body.refresh_on === \"number\") {\n return body.refresh_on * 1000;\n }\n\n if (typeof body.refresh_on === \"string\") {\n const asNumber = +body.refresh_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.refresh_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n throw new Error(`Failed to parse refresh_on from body. refresh_on=\"${body.refresh_on}\"`);\n } else {\n return undefined;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-node\";\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport type { PipelineRequest, PipelineResponse } from \"@azure/core-rest-pipeline\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost, SDK_VERSION } from \"../constants\";\nimport { tracingClient } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport type { TokenCredentialOptions } from \"../tokenCredentialOptions\";\nimport type { TokenResponseParsedBody } from \"../credentials/managedIdentityCredential/utils\";\nimport {\n parseExpirationTimestamp,\n parseRefreshTimestamp,\n} from \"../credentials/managedIdentityCredential/utils\";\n\nconst noCorrelationId = \"noCorrelationId\";\n\n/**\n * An internal type used to communicate details of a token request's\n * response that should not be sent back as part of the access token.\n */\nexport interface TokenResponse {\n /**\n * The AccessToken to be returned from getToken.\n */\n accessToken: AccessToken;\n /**\n * The refresh token if the 'offline_access' scope was used.\n */\n refreshToken?: string;\n}\n\n/**\n * @internal\n */\nexport function getIdentityClientAuthorityHost(options?: TokenCredentialOptions): string {\n // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.\n let authorityHost = options?.authorityHost;\n\n // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.\n if (isNode) {\n authorityHost = authorityHost ?? process.env.AZURE_AUTHORITY_HOST;\n }\n\n // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * The network module used by the Identity credentials.\n *\n * It allows for credentials to abort any pending request independently of the MSAL flow,\n * by calling to the `abortRequests()` method.\n *\n */\nexport class IdentityClient extends ServiceClient implements INetworkModule {\n public authorityHost: string;\n private allowLoggingAccountIdentifiers?: boolean;\n private abortControllers: Map<string, AbortController[] | undefined>;\n private allowInsecureConnection: boolean = false;\n // used for WorkloadIdentity\n private tokenCredentialOptions: TokenCredentialOptions;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/${SDK_VERSION}`;\n const userAgentPrefix = options?.userAgentOptions?.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const baseUri = getIdentityClientAuthorityHost(options);\n if (!baseUri.startsWith(\"https:\")) {\n throw new Error(\"The authorityHost address must use the 'https' protocol.\");\n }\n\n super({\n requestContentType: \"application/json; charset=utf-8\",\n retryOptions: {\n maxRetries: 3,\n },\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n baseUri,\n });\n\n this.authorityHost = baseUri;\n this.abortControllers = new Map();\n this.allowLoggingAccountIdentifiers = options?.loggingOptions?.allowLoggingAccountIdentifiers;\n // used for WorkloadIdentity\n this.tokenCredentialOptions = { ...options };\n\n // used for ManagedIdentity\n if (options?.allowInsecureConnection) {\n this.allowInsecureConnection = options.allowInsecureConnection;\n }\n }\n\n async sendTokenRequest(request: PipelineRequest): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: TokenResponseParsedBody = JSON.parse(response.bodyAsText);\n\n if (!parsedBody.access_token) {\n return null;\n }\n\n this.logIdentifiers(response);\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: parseExpirationTimestamp(parsedBody),\n refreshAfterTimestamp: parseRefreshTimestamp(parsedBody),\n tokenType: \"Bearer\",\n } as AccessToken,\n refreshToken: parsedBody.refresh_token,\n };\n\n logger.info(\n `IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`,\n );\n return token;\n } else {\n const error = new AuthenticationError(response.status, response.bodyAsText);\n logger.warning(\n `IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`,\n );\n throw error;\n }\n }\n\n async refreshAccessToken(\n tenantId: string,\n clientId: string,\n scopes: string,\n refreshToken: string | undefined,\n clientSecret: string | undefined,\n options: GetTokenOptions = {},\n ): Promise<TokenResponse | null> {\n if (refreshToken === undefined) {\n return null;\n }\n logger.info(\n `IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`,\n );\n\n const refreshParams = {\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scopes,\n };\n\n if (clientSecret !== undefined) {\n (refreshParams as any).client_secret = clientSecret;\n }\n\n const query = new URLSearchParams(refreshParams);\n\n return tracingClient.withSpan(\n \"IdentityClient.refreshAccessToken\",\n options,\n async (updatedOptions) => {\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);\n const request = createPipelineRequest({\n url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,\n method: \"POST\",\n body: query.toString(),\n abortSignal: options.abortSignal,\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n tracingOptions: updatedOptions.tracingOptions,\n });\n\n const response = await this.sendTokenRequest(request);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err: any) {\n if (\n err.name === AuthenticationErrorName &&\n err.errorResponse.error === \"interaction_required\"\n ) {\n // It's likely that the refresh token has expired, so\n // return null so that the credential implementation will\n // initiate the authentication flow again.\n logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);\n return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`,\n );\n throw err;\n }\n }\n },\n );\n }\n\n // Here is a custom layer that allows us to abort requests that go through MSAL,\n // since MSAL doesn't allow us to pass options all the way through.\n\n generateAbortSignal(correlationId: string): AbortSignalLike {\n const controller = new AbortController();\n const controllers = this.abortControllers.get(correlationId) || [];\n controllers.push(controller);\n this.abortControllers.set(correlationId, controllers);\n const existingOnAbort = controller.signal.onabort;\n controller.signal.onabort = (...params) => {\n this.abortControllers.set(correlationId, undefined);\n if (existingOnAbort) {\n existingOnAbort.apply(controller.signal, params);\n }\n };\n return controller.signal;\n }\n\n abortRequests(correlationId?: string): void {\n const key = correlationId || noCorrelationId;\n const controllers = [\n ...(this.abortControllers.get(key) || []),\n // MSAL passes no correlation ID to the get requests...\n ...(this.abortControllers.get(noCorrelationId) || []),\n ];\n if (!controllers.length) {\n return;\n }\n for (const controller of controllers) {\n controller.abort();\n }\n this.abortControllers.set(key, undefined);\n }\n\n getCorrelationId(options?: NetworkRequestOptions): string {\n const parameter = options?.body\n ?.split(\"&\")\n .map((part) => part.split(\"=\"))\n .find(([key]) => key === \"client-request-id\");\n return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;\n }\n\n // The MSAL network module methods follow\n\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"GET\",\n body: options?.body,\n allowInsecureConnection: this.allowInsecureConnection,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"POST\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n allowInsecureConnection: this.allowInsecureConnection,\n // MSAL doesn't send the correlation ID on the get requests.\n abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n /**\n *\n * @internal\n */\n getTokenCredentialOptions(): TokenCredentialOptions {\n return this.tokenCredentialOptions;\n }\n /**\n * If allowLoggingAccountIdentifiers was set on the constructor options\n * we try to log the account identifiers by parsing the received access token.\n *\n * The account identifiers we try to log are:\n * - `appid`: The application or Client Identifier.\n * - `upn`: User Principal Name.\n * - It might not be available in some authentication scenarios.\n * - If it's not available, we put a placeholder: \"No User Principal Name available\".\n * - `tid`: Tenant Identifier.\n * - `oid`: Object Identifier of the authenticated user.\n */\n private logIdentifiers(response: PipelineResponse): void {\n if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {\n return;\n }\n const unavailableUpn = \"No User Principal Name available\";\n try {\n const parsed = (response as any).parsedBody || JSON.parse(response.bodyAsText);\n const accessToken = parsed.access_token;\n if (!accessToken) {\n // Without an access token allowLoggingAccountIdentifiers isn't useful.\n return;\n }\n const base64Metadata = accessToken.split(\".\")[1];\n const { appid, upn, tid, oid } = JSON.parse(\n Buffer.from(base64Metadata, \"base64\").toString(\"utf8\"),\n );\n\n logger.info(\n `[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${\n upn || unavailableUpn\n }. Object ID (user): ${oid}`,\n );\n } catch (e: any) {\n logger.warning(\n \"allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:\",\n e.message,\n );\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { AzureAuthorityHosts } from \"../constants\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport type { VisualStudioCodeCredentialOptions } from \"./visualStudioCodeCredentialOptions\";\nimport type { VSCodeCredentialFinder } from \"./visualStudioCodeCredentialPlugin\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\n\nconst CommonTenantId = \"common\";\nconst AzureAccountClientId = \"aebc6443-996d-45c2-90f0-388ff96faa56\"; // VSC: 'aebc6443-996d-45c2-90f0-388ff96faa56'\nconst logger = credentialLogger(\"VisualStudioCodeCredential\");\n\nlet findCredentials: VSCodeCredentialFinder | undefined = undefined;\n\nexport const vsCodeCredentialControl = {\n setVsCodeCredentialFinder(finder: VSCodeCredentialFinder): void {\n findCredentials = finder;\n },\n};\n\n// Map of unsupported Tenant IDs and the errors we will be throwing.\nconst unsupportedTenantIds: Record<string, string> = {\n adfs: \"The VisualStudioCodeCredential does not support authentication with ADFS tenants.\",\n};\n\nfunction checkUnsupportedTenant(tenantId: string): void {\n // If the Tenant ID isn't supported, we throw.\n const unsupportedTenantError = unsupportedTenantIds[tenantId];\n if (unsupportedTenantError) {\n throw new CredentialUnavailableError(unsupportedTenantError);\n }\n}\n\ntype VSCodeCloudNames = \"AzureCloud\" | \"AzureChina\" | \"AzureGermanCloud\" | \"AzureUSGovernment\";\n\nconst mapVSCodeAuthorityHosts: Record<VSCodeCloudNames, string> = {\n AzureCloud: AzureAuthorityHosts.AzurePublicCloud,\n AzureChina: AzureAuthorityHosts.AzureChina,\n AzureGermanCloud: AzureAuthorityHosts.AzureGermany,\n AzureUSGovernment: AzureAuthorityHosts.AzureGovernment,\n};\n\n/**\n * Attempts to load a specific property from the VSCode configurations of the current OS.\n * If it fails at any point, returns undefined.\n */\nexport function getPropertyFromVSCode(property: string): string | undefined {\n const settingsPath = [\"User\", \"settings.json\"];\n // Eventually we can add more folders for more versions of VSCode.\n const vsCodeFolder = \"Code\";\n const homedir = os.homedir();\n\n function loadProperty(...pathSegments: string[]): string | undefined {\n const fullPath = path.join(...pathSegments, vsCodeFolder, ...settingsPath);\n const settings = JSON.parse(fs.readFileSync(fullPath, { encoding: \"utf8\" }));\n return settings[property];\n }\n\n try {\n let appData: string;\n switch (process.platform) {\n case \"win32\":\n appData = process.env.APPDATA!;\n return appData ? loadProperty(appData) : undefined;\n case \"darwin\":\n return loadProperty(homedir, \"Library\", \"Application Support\");\n case \"linux\":\n return loadProperty(homedir, \".config\");\n default:\n return;\n }\n } catch (e: any) {\n logger.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`);\n return;\n }\n}\n\n/**\n * Connects to Azure using the credential provided by the VSCode extension 'Azure Account'.\n * Once the user has logged in via the extension, this credential can share the same refresh token\n * that is cached by the extension.\n *\n * It's a [known issue](https://github.com/Azure/azure-sdk-for-js/issues/20500) that this credential doesn't\n * work with [Azure Account extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account)\n * versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider\n * authenticating with {@link AzureCliCredential}.\n */\nexport class VisualStudioCodeCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private cloudName: VSCodeCloudNames;\n\n /**\n * Creates an instance of VisualStudioCodeCredential to use for automatically authenticating via VSCode.\n *\n * **Note**: `VisualStudioCodeCredential` is provided by a plugin package:\n * `@azure/identity-vscode`. If this package is not installed and registered\n * using the plugin API (`useIdentityPlugin`), then authentication using\n * `VisualStudioCodeCredential` will not be available.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: VisualStudioCodeCredentialOptions) {\n // We want to make sure we use the one assigned by the user on the VSCode settings.\n // Or just `AzureCloud` by default.\n this.cloudName = (getPropertyFromVSCode(\"azure.cloud\") || \"AzureCloud\") as VSCodeCloudNames;\n\n // Picking an authority host based on the cloud name.\n const authorityHost = mapVSCodeAuthorityHosts[this.cloudName];\n\n this.identityClient = new IdentityClient({\n authorityHost,\n ...options,\n });\n\n if (options && options.tenantId) {\n checkTenantId(logger, options.tenantId);\n this.tenantId = options.tenantId;\n } else {\n this.tenantId = CommonTenantId;\n }\n\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n checkUnsupportedTenant(this.tenantId);\n }\n\n /**\n * Runs preparations for any further getToken request.\n */\n private async prepare(): Promise<void> {\n // Attempts to load the tenant from the VSCode configuration file.\n const settingsTenant = getPropertyFromVSCode(\"azure.tenant\");\n if (settingsTenant) {\n this.tenantId = settingsTenant;\n }\n checkUnsupportedTenant(this.tenantId);\n }\n\n /**\n * The promise of the single preparation that will be executed at the first getToken request for an instance of this class.\n */\n private preparePromise: Promise<void> | undefined;\n\n /**\n * Runs preparations for any further getToken, but only once.\n */\n private prepareOnce(): Promise<void> | undefined {\n if (!this.preparePromise) {\n this.preparePromise = this.prepare();\n }\n return this.preparePromise;\n }\n\n /**\n * Returns the token found by searching VSCode's authentication cache or\n * returns null if no token could be found.\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 await this.prepareOnce();\n\n const tenantId =\n processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n logger,\n ) || this.tenantId;\n\n if (findCredentials === undefined) {\n throw new CredentialUnavailableError(\n [\n \"No implementation of `VisualStudioCodeCredential` is available.\",\n \"You must install the identity-vscode plugin package (`npm install --save-dev @azure/identity-vscode`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(vsCodePlugin)` before creating a `VisualStudioCodeCredential`.\",\n \"To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\",\n ].join(\" \"),\n );\n }\n\n let scopeString = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n\n // Check to make sure the scope we get back is a valid scope\n if (!scopeString.match(/^[0-9a-zA-Z-.:/]+$/)) {\n const error = new Error(\"Invalid scope was specified by the user or calling client\");\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n if (scopeString.indexOf(\"offline_access\") < 0) {\n scopeString += \" offline_access\";\n }\n\n // findCredentials returns an array similar to:\n // [\n // {\n // account: \"\",\n // password: \"\",\n // },\n // /* ... */\n // ]\n const credentials = await findCredentials();\n\n // If we can't find the credential based on the name, we'll pick the first one available.\n const { password: refreshToken } =\n credentials.find(({ account }) => account === this.cloudName) ?? credentials[0] ?? {};\n\n if (refreshToken) {\n const tokenResponse = await this.identityClient.refreshAccessToken(\n tenantId,\n AzureAccountClientId,\n scopeString,\n refreshToken,\n undefined,\n );\n\n if (tokenResponse) {\n logger.getToken.info(formatSuccess(scopes));\n return tokenResponse.accessToken;\n } else {\n const error = new CredentialUnavailableError(\n \"Could not retrieve the token associated with Visual Studio Code. Have you connected using the 'Azure Account' extension recently? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n } else {\n const error = new CredentialUnavailableError(\n \"Could not retrieve the token associated with Visual Studio Code. Did you connect using the 'Azure Account' extension? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AzurePluginContext, IdentityPlugin } from \"./provider\";\nimport {\n msalNodeFlowCacheControl,\n msalNodeFlowNativeBrokerControl,\n} from \"../msal/nodeFlows/msalPlugins\";\n\nimport { vsCodeCredentialControl } from \"../credentials/visualStudioCodeCredential\";\n\n/**\n * The context passed to an Identity plugin. This contains objects that\n * plugins can use to set backend implementations.\n * @internal\n */\nconst pluginContext: AzurePluginContext = {\n cachePluginControl: msalNodeFlowCacheControl,\n nativeBrokerPluginControl: msalNodeFlowNativeBrokerControl,\n vsCodeCredentialControl: vsCodeCredentialControl,\n};\n\n/**\n * Extend Azure Identity with additional functionality. Pass a plugin from\n * a plugin package, such as:\n *\n * - `@azure/identity-cache-persistence`: provides persistent token caching\n * - `@azure/identity-vscode`: provides the dependencies of\n * `VisualStudioCodeCredential` and enables it\n *\n * Example:\n *\n * ```ts snippet:consumer_example\n * import { useIdentityPlugin, DeviceCodeCredential } from \"@azure/identity\";\n *\n * useIdentityPlugin(cachePersistencePlugin);\n * // The plugin has the capability to extend `DeviceCodeCredential` and to\n * // add middleware to the underlying credentials, such as persistence.\n * const credential = new DeviceCodeCredential({\n * tokenCachePersistenceOptions: {\n * enabled: true,\n * },\n * });\n * ```\n *\n * @param plugin - the plugin to register\n */\nexport function useIdentityPlugin(plugin: IdentityPlugin): void {\n plugin(pluginContext);\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AuthenticationRecord, MsalAccountInfo, MsalToken, ValidMsalToken } from \"./types\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../errors\";\nimport type { CredentialLogger } from \"../util/logging\";\nimport { credentialLogger, formatError } from \"../util/logging\";\nimport { DefaultAuthorityHost, DefaultTenantId } from \"../constants\";\nimport { randomUUID as coreRandomUUID, isNode, isNodeLike } from \"@azure/core-util\";\n\nimport { AbortError } from \"@azure/abort-controller\";\nimport type { AzureLogLevel } from \"@azure/logger\";\nimport type { GetTokenOptions } from \"@azure/core-auth\";\nimport { msalCommon } from \"./msal\";\n\nexport interface ILoggerCallback {\n (level: msalCommon.LogLevel, message: string, containsPii: boolean): void;\n}\n\n/**\n * @internal\n */\nconst logger = credentialLogger(\"IdentityUtils\");\n\n/**\n * Latest AuthenticationRecord version\n * @internal\n */\nconst LatestAuthenticationRecordVersion = \"1.0\";\n\n/**\n * Ensures the validity of the MSAL token\n * @internal\n */\nexport function ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken | null,\n getTokenOptions?: GetTokenOptions,\n): asserts msalToken is ValidMsalToken {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n}\n\n/**\n * Returns the authority host from either the options bag or the AZURE_AUTHORITY_HOST environment variable.\n *\n * Defaults to {@link DefaultAuthorityHost}.\n * @internal\n */\nexport function getAuthorityHost(options?: { authorityHost?: string }): string {\n let authorityHost = options?.authorityHost;\n\n if (!authorityHost && isNodeLike) {\n authorityHost = process.env.AZURE_AUTHORITY_HOST;\n }\n\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * Generates a valid authority by combining a host with a tenantId.\n * @internal\n */\nexport function getAuthority(tenantId: string, host?: string): string {\n if (!host) {\n host = DefaultAuthorityHost;\n }\n if (new RegExp(`${tenantId}/?$`).test(host)) {\n return host;\n }\n if (host.endsWith(\"/\")) {\n return host + tenantId;\n } else {\n return `${host}/${tenantId}`;\n }\n}\n\n/**\n * Generates the known authorities.\n * If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.\n * For that reason, we have to force MSAL to disable validating the authority\n * by sending it within the known authorities in the MSAL configuration.\n * @internal\n */\nexport function getKnownAuthorities(\n tenantId: string,\n authorityHost: string,\n disableInstanceDiscovery?: boolean,\n): string[] {\n if ((tenantId === \"adfs\" && authorityHost) || disableInstanceDiscovery) {\n return [authorityHost];\n }\n return [];\n}\n\n/**\n * Generates a logger that can be passed to the MSAL clients.\n * @param credLogger - The logger of the credential.\n * @internal\n */\nexport const defaultLoggerCallback: (\n logger: CredentialLogger,\n platform?: \"Node\" | \"Browser\",\n) => ILoggerCallback =\n (credLogger: CredentialLogger, platform: \"Node\" | \"Browser\" = isNode ? \"Node\" : \"Browser\") =>\n (level, message, containsPii): void => {\n if (containsPii) {\n return;\n }\n switch (level) {\n case msalCommon.LogLevel.Error:\n credLogger.info(`MSAL ${platform} V2 error: ${message}`);\n return;\n case msalCommon.LogLevel.Info:\n credLogger.info(`MSAL ${platform} V2 info message: ${message}`);\n return;\n case msalCommon.LogLevel.Verbose:\n credLogger.info(`MSAL ${platform} V2 verbose message: ${message}`);\n return;\n case msalCommon.LogLevel.Warning:\n credLogger.info(`MSAL ${platform} V2 warning: ${message}`);\n return;\n }\n };\n\n/**\n * @internal\n */\nexport function getMSALLogLevel(logLevel: AzureLogLevel | undefined): msalCommon.LogLevel {\n switch (logLevel) {\n case \"error\":\n return msalCommon.LogLevel.Error;\n case \"info\":\n return msalCommon.LogLevel.Info;\n case \"verbose\":\n return msalCommon.LogLevel.Verbose;\n case \"warning\":\n return msalCommon.LogLevel.Warning;\n default:\n // default msal logging level should be Info\n return msalCommon.LogLevel.Info;\n }\n}\n\n/**\n * Wraps core-util's randomUUID in order to allow for mocking in tests.\n * This prepares the library for the upcoming core-util update to ESM.\n *\n * @internal\n * @returns A string containing a random UUID\n */\nexport function randomUUID(): string {\n return coreRandomUUID();\n}\n\n/**\n * Handles MSAL errors.\n */\nexport function handleMsalError(\n scopes: string[],\n error: Error,\n getTokenOptions?: GetTokenOptions,\n): Error {\n if (\n error.name === \"AuthError\" ||\n error.name === \"ClientAuthError\" ||\n error.name === \"BrowserAuthError\"\n ) {\n const msalError = error as msalCommon.AuthError;\n switch (msalError.errorCode) {\n case \"endpoints_resolution_error\":\n logger.info(formatError(scopes, error.message));\n return new CredentialUnavailableError(error.message);\n case \"device_code_polling_cancelled\":\n return new AbortError(\"The authentication has been aborted by the caller.\");\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n logger.info(\n formatError(scopes, `Authentication returned errorCode ${msalError.errorCode}`),\n );\n break;\n default:\n logger.info(formatError(scopes, `Failed to acquire token: ${error.message}`));\n break;\n }\n }\n if (\n error.name === \"ClientConfigurationError\" ||\n error.name === \"BrowserConfigurationAuthError\" ||\n error.name === \"AbortError\" ||\n error.name === \"AuthenticationError\"\n ) {\n return error;\n }\n if (error.name === \"NativeAuthError\") {\n logger.info(\n formatError(\n scopes,\n `Error from the native broker: ${error.message} with status code: ${\n (error as any).statusCode\n }`,\n ),\n );\n return error;\n }\n return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message });\n}\n\n// transformations.ts\n\nexport function publicToMsal(account: AuthenticationRecord): msalCommon.AccountInfo {\n const [environment] = account.authority.match(/([a-z]*\\.[a-z]*\\.[a-z]*)/) || [\"\"];\n return {\n ...account,\n localAccountId: account.homeAccountId,\n environment,\n };\n}\n\nexport function msalToPublic(clientId: string, account: MsalAccountInfo): AuthenticationRecord {\n const record = {\n authority: getAuthority(account.tenantId, account.environment),\n homeAccountId: account.homeAccountId,\n tenantId: account.tenantId || DefaultTenantId,\n username: account.username,\n clientId,\n version: LatestAuthenticationRecordVersion,\n };\n return record;\n}\n\n/**\n * Serializes an `AuthenticationRecord` into a string.\n *\n * The output of a serialized authentication record will contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`.\n */\nexport function serializeAuthenticationRecord(record: AuthenticationRecord): string {\n return JSON.stringify(record);\n}\n\n/**\n * Deserializes a previously serialized authentication record from a string into an object.\n *\n * The input string must contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * If the version we receive is unsupported, an error will be thrown.\n *\n * At the moment, the only available version is: \"1.0\", which is always set when the authentication record is serialized.\n *\n * @param serializedRecord - Authentication record previously serialized into string.\n * @returns AuthenticationRecord.\n */\nexport function deserializeAuthenticationRecord(serializedRecord: string): AuthenticationRecord {\n const parsed: AuthenticationRecord & { version?: string } = JSON.parse(serializedRecord);\n\n if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) {\n throw Error(\"Unsupported AuthenticationRecord version\");\n }\n\n return parsed;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport type { PipelineRequestOptions, PipelineResponse } from \"@azure/core-rest-pipeline\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\nimport { delay, isError } from \"@azure/core-util\";\nimport { imdsApiVersion, imdsEndpointPath, imdsHost } from \"./constants\";\n\nimport { AuthenticationError } from \"../../errors\";\nimport type { GetTokenOptions } from \"@azure/core-auth\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst msiName = \"ManagedIdentityCredential - IMDS\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string,\n options?: {\n skipQuery?: boolean;\n skipMetadataHeader?: boolean;\n },\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const { skipQuery, skipMetadataHeader } = options || {};\n let query = \"\";\n\n // Pod Identity will try to process this request even if the Metadata header is missing.\n // We can exclude the request query to ensure no IMDS endpoint tries to process the ping request.\n if (!skipQuery) {\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": imdsApiVersion,\n };\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n const params = new URLSearchParams(queryParameters);\n query = `?${params.toString()}`;\n }\n\n const url = new URL(imdsEndpointPath, process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST ?? imdsHost);\n\n const rawHeaders: Record<string, string> = {\n Accept: \"application/json\",\n Metadata: \"true\",\n };\n\n // Remove the Metadata header to invoke a request error from some IMDS endpoints.\n if (skipMetadataHeader) {\n delete rawHeaders.Metadata;\n }\n\n return {\n // In this case, the `?` should be added in the \"query\" variable `skipQuery` is not set.\n url: `${url}${query}`,\n method: \"GET\",\n headers: createHttpHeaders(rawHeaders),\n };\n}\n\n/**\n * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.\n */\nexport const imdsMsi: MSI = {\n name: \"imdsMsi\",\n async isAvailable({\n scopes,\n identityClient,\n clientId,\n resourceId,\n getTokenOptions = {},\n }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n\n // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n return true;\n }\n\n if (!identityClient) {\n throw new Error(\"Missing IdentityClient\");\n }\n\n const requestOptions = prepareRequestOptions(resource, clientId, resourceId, {\n skipMetadataHeader: true,\n skipQuery: true,\n });\n\n return tracingClient.withSpan(\n \"ManagedIdentityCredential-pingImdsEndpoint\",\n getTokenOptions,\n async (options) => {\n requestOptions.tracingOptions = options.tracingOptions;\n\n // Create a request with a timeout since we expect that\n // not having a \"Metadata\" header should cause an error to be\n // returned quickly from the endpoint, proving its availability.\n const request = createPipelineRequest(requestOptions);\n\n // Default to 1000 if the default of 0 is used.\n // Negative values can still be used to disable the timeout.\n request.timeout = options.requestOptions?.timeout || 1000;\n\n // This MSI uses the imdsEndpoint to get the token, which only uses http://\n request.allowInsecureConnection = true;\n let response: PipelineResponse;\n try {\n logger.info(`${msiName}: Pinging the Azure IMDS endpoint`);\n response = await identityClient.sendRequest(request);\n } catch (err: unknown) {\n // If the request failed, or Node.js was unable to establish a connection,\n // or the host was down, we'll assume the IMDS endpoint isn't available.\n if (isError(err)) {\n logger.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`);\n }\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n return false;\n }\n if (response.status === 403) {\n if (response.bodyAsText?.includes(\"unreachable\")) {\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n logger.info(`${msiName}: ${response.bodyAsText}`);\n return false;\n }\n }\n // If we received any response, the endpoint is available\n logger.info(`${msiName}: The Azure IMDS endpoint is available`);\n return true;\n },\n );\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n logger.info(\n `${msiName}: Using the Azure IMDS endpoint coming from the environment variable AZURE_POD_IDENTITY_AUTHORITY_HOST=${process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST}.`,\n );\n } else {\n logger.info(`${msiName}: Using the default Azure IMDS endpoint ${imdsHost}.`);\n }\n\n let nextDelayInMs = configuration.retryConfig.startDelayInMs;\n for (let retries = 0; retries < configuration.retryConfig.maxRetries; retries++) {\n try {\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (error: any) {\n if (error.statusCode === 404) {\n await delay(nextDelayInMs);\n nextDelayInMs *= configuration.retryConfig.intervalIncrement;\n continue;\n }\n throw error;\n }\n }\n\n throw new AuthenticationError(\n 404,\n `${msiName}: Failed to retrieve IMDS token after ${configuration.retryConfig.maxRetries} retries.`,\n );\n },\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"@azure/core-rest-pipeline\";\nimport { retryPolicy } from \"@azure/core-rest-pipeline\";\n\nimport type { MSIConfiguration } from \"./models\";\nimport { calculateRetryDelay } from \"@azure/core-util\";\n\n// Matches the default retry configuration in expontentialRetryStrategy.ts\nconst DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;\n\n/**\n * An additional policy that retries on 404 errors. The default retry policy does not retry on\n * 404s, but the IMDS endpoint can return 404s when the token is not yet available. This policy\n * will retry on 404s with an exponential backoff.\n *\n * @param msiRetryConfig - The retry configuration for the MSI credential.\n * @returns - The policy that will retry on 404s.\n */\nexport function imdsRetryPolicy(msiRetryConfig: MSIConfiguration[\"retryConfig\"]): PipelinePolicy {\n return retryPolicy(\n [\n {\n name: \"imdsRetryPolicy\",\n retry: ({ retryCount, response }) => {\n if (response?.status !== 404) {\n return { skipStrategy: true };\n }\n\n return calculateRetryDelay(retryCount, {\n retryDelayInMs: msiRetryConfig.startDelayInMs,\n maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL,\n });\n },\n },\n ],\n {\n maxRetries: msiRetryConfig.maxRetries,\n },\n );\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Helps specify a regional authority, or \"AutoDiscoverRegion\" to auto-detect the region.\n */\nexport enum RegionalAuthority {\n /** Instructs MSAL to attempt to discover the region */\n AutoDiscoverRegion = \"AutoDiscoverRegion\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westus' region. */\n USWest = \"westus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westus2' region. */\n USWest2 = \"westus2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'centralus' region. */\n USCentral = \"centralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'eastus' region. */\n USEast = \"eastus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'eastus2' region. */\n USEast2 = \"eastus2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'northcentralus' region. */\n USNorthCentral = \"northcentralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southcentralus' region. */\n USSouthCentral = \"southcentralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westcentralus' region. */\n USWestCentral = \"westcentralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'canadacentral' region. */\n CanadaCentral = \"canadacentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'canadaeast' region. */\n CanadaEast = \"canadaeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'brazilsouth' region. */\n BrazilSouth = \"brazilsouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'northeurope' region. */\n EuropeNorth = \"northeurope\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westeurope' region. */\n EuropeWest = \"westeurope\",\n /** Uses the {@link RegionalAuthority} for the Azure 'uksouth' region. */\n UKSouth = \"uksouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'ukwest' region. */\n UKWest = \"ukwest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'francecentral' region. */\n FranceCentral = \"francecentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'francesouth' region. */\n FranceSouth = \"francesouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandnorth' region. */\n SwitzerlandNorth = \"switzerlandnorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandwest' region. */\n SwitzerlandWest = \"switzerlandwest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanynorth' region. */\n GermanyNorth = \"germanynorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanywestcentral' region. */\n GermanyWestCentral = \"germanywestcentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'norwaywest' region. */\n NorwayWest = \"norwaywest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'norwayeast' region. */\n NorwayEast = \"norwayeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'eastasia' region. */\n AsiaEast = \"eastasia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southeastasia' region. */\n AsiaSouthEast = \"southeastasia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'japaneast' region. */\n JapanEast = \"japaneast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'japanwest' region. */\n JapanWest = \"japanwest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiaeast' region. */\n AustraliaEast = \"australiaeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiasoutheast' region. */\n AustraliaSouthEast = \"australiasoutheast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral' region. */\n AustraliaCentral = \"australiacentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral2' region. */\n AustraliaCentral2 = \"australiacentral2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'centralindia' region. */\n IndiaCentral = \"centralindia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southindia' region. */\n IndiaSouth = \"southindia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westindia' region. */\n IndiaWest = \"westindia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'koreasouth' region. */\n KoreaSouth = \"koreasouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'koreacentral' region. */\n KoreaCentral = \"koreacentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'uaecentral' region. */\n UAECentral = \"uaecentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'uaenorth' region. */\n UAENorth = \"uaenorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southafricanorth' region. */\n SouthAfricaNorth = \"southafricanorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southafricawest' region. */\n SouthAfricaWest = \"southafricawest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth' region. */\n ChinaNorth = \"chinanorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast' region. */\n ChinaEast = \"chinaeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth2' region. */\n ChinaNorth2 = \"chinanorth2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast2' region. */\n ChinaEast2 = \"chinaeast2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanycentral' region. */\n GermanyCentral = \"germanycentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanynortheast' region. */\n GermanyNorthEast = \"germanynortheast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgovvirginia' region. */\n GovernmentUSVirginia = \"usgovvirginia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgoviowa' region. */\n GovernmentUSIowa = \"usgoviowa\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgovarizona' region. */\n GovernmentUSArizona = \"usgovarizona\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgovtexas' region. */\n GovernmentUSTexas = \"usgovtexas\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usdodeast' region. */\n GovernmentUSDodEast = \"usdodeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usdodcentral' region. */\n GovernmentUSDodCentral = \"usdodcentral\",\n}\n\n/**\n * Calculates the correct regional authority based on the supplied value\n * and the AZURE_REGIONAL_AUTHORITY_NAME environment variable.\n *\n * Values will be returned verbatim, except for {@link RegionalAuthority.AutoDiscoverRegion}\n * which is mapped to a value MSAL can understand.\n *\n * @internal\n */\nexport function calculateRegionalAuthority(regionalAuthority?: string): string | undefined {\n // Note: as of today only 3 credentials support regional authority, and the parameter\n // is not exposed via the public API. Regional Authority is _only_ supported\n // via the AZURE_REGIONAL_AUTHORITY_NAME env var and _only_ for: ClientSecretCredential, ClientCertificateCredential, and ClientAssertionCredential.\n\n // Accepting the regionalAuthority parameter will allow us to support it in the future.\n let azureRegion = regionalAuthority;\n\n if (\n azureRegion === undefined &&\n globalThis.process?.env?.AZURE_REGIONAL_AUTHORITY_NAME !== undefined\n ) {\n azureRegion = process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n }\n\n if (azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n return \"AUTO_DISCOVER\";\n }\n\n return azureRegion;\n}\n","// 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\";\nimport type { CredentialLogger } from \"../../util/logging\";\nimport { credentialLogger, formatSuccess } from \"../../util/logging\";\nimport type { PluginConfiguration } from \"./msalPlugins\";\nimport { msalPlugins } from \"./msalPlugins\";\nimport {\n defaultLoggerCallback,\n ensureValidMsalToken,\n getAuthority,\n getAuthorityHost,\n getKnownAuthorities,\n getMSALLogLevel,\n handleMsalError,\n msalToPublic,\n publicToMsal,\n} from \"../utils\";\n\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport type { BrokerOptions } from \"./brokerOptions\";\nimport type { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport type { InteractiveBrowserCredentialNodeOptions } from \"../../credentials/interactiveBrowserCredentialOptions\";\nimport type { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\nimport { calculateRegionalAuthority } from \"../../regionalAuthority\";\nimport { getLogLevel } from \"@azure/logger\";\nimport open from \"open\";\nimport { resolveTenantId } from \"../../util/tenantIdUtils\";\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/**\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 * 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 * A call to open(), but mockable\n * @internal\n */\nexport const interactiveBrowserMockable = {\n open,\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 *\n * @internal\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(\n \"No cached account found in local state, attempting to load it from MSAL cache.\",\n );\n const cache = app.getTokenCache();\n const accounts = await cache.getAllAccounts();\n\n if (accounts === undefined || accounts.length === 0) {\n throw new AuthenticationRequiredError({ scopes });\n }\n\n if (accounts.length > 1) {\n state.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n throw new AuthenticationRequiredError({ scopes });\n }\n\n state.cachedAccount = accounts[0];\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.tokenQueryParameters ||= {};\n if (state.pluginConfiguration.broker.enableMsaPassthrough) {\n silentRequest.tokenQueryParameters[\"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 return app.acquireTokenSilent(silentRequest);\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 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 /**\n * A helper function that supports brokered authentication through the MSAL's public application.\n *\n * When options.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 useDefaultBrokerAccount: boolean,\n ): Promise<msal.AuthenticationResult> {\n msalLogger.verbose(\"Authentication will resume through the broker\");\n const interactiveRequest = createBaseInteractiveRequest();\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.tokenQueryParameters ??= {})[\"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 we tried to use the default broker account and failed, fall back to interactive authentication\n if (useDefaultBrokerAccount) {\n return getBrokeredToken(/* useDefaultBrokerAccount: */ false);\n } else {\n throw e;\n }\n }\n }\n\n function createBaseInteractiveRequest(): msal.InteractiveRequest {\n return {\n openBrowser: async (url) => {\n await interactiveBrowserMockable.open(url, { wait: true, 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 };\n }\n\n return withSilentAuthentication(app, scopes, options, async () => {\n const interactiveRequest = createBaseInteractiveRequest();\n\n if (state.pluginConfiguration.broker.isEnabled) {\n return getBrokeredToken(state.pluginConfiguration.broker.useDefaultBrokerAccount ?? false);\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 getTokenByClientSecret,\n getTokenByClientAssertion,\n getTokenByClientCertificate,\n getTokenByDeviceCode,\n getTokenByUsernamePassword,\n getTokenByAuthorizationCode,\n getTokenOnBehalfOf,\n getTokenByInteractiveRequest,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport type { ClientAssertionCredentialOptions } from \"./clientAssertionCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"ClientAssertionCredential\");\n\n/**\n * Authenticates a service principal with a JWT assertion.\n */\nexport class ClientAssertionCredential implements TokenCredential {\n private msalClient: MsalClient;\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private getAssertion: () => Promise<string>;\n private options: ClientAssertionCredentialOptions;\n\n /**\n * Creates an instance of the ClientAssertionCredential with the details\n * needed to authenticate against Microsoft Entra ID with a client\n * assertion provided by the developer through the `getAssertion` function parameter.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param getAssertion - A function that retrieves the assertion for the credential to use.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n getAssertion: () => Promise<string>,\n options: ClientAssertionCredentialOptions = {},\n ) {\n if (!tenantId) {\n throw new CredentialUnavailableError(\n \"ClientAssertionCredential: tenantId is a required parameter.\",\n );\n }\n\n if (!clientId) {\n throw new CredentialUnavailableError(\n \"ClientAssertionCredential: clientId is a required parameter.\",\n );\n }\n\n if (!getAssertion) {\n throw new CredentialUnavailableError(\n \"ClientAssertionCredential: clientAssertion is a required parameter.\",\n );\n }\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.options = options;\n this.getAssertion = getAssertion;\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: this.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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n return this.msalClient.getTokenByClientAssertion(\n arrayScopes,\n this.getAssertion,\n newOptions,\n );\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, processEnvVars } from \"../util/logging\";\n\nimport { ClientAssertionCredential } from \"./clientAssertionCredential\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport type { WorkloadIdentityCredentialOptions } from \"./workloadIdentityCredentialOptions\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { readFile } from \"fs/promises\";\n\nconst credentialName = \"WorkloadIdentityCredential\";\n/**\n * Contains the list of all supported environment variable names so that an\n * appropriate error message can be generated when no credentials can be\n * configured.\n *\n * @internal\n */\nexport const SupportedWorkloadEnvironmentVariables = [\n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_FEDERATED_TOKEN_FILE\",\n];\nconst logger = credentialLogger(credentialName);\n/**\n * Workload Identity authentication is a feature in Azure that allows applications running on virtual machines (VMs)\n * to access other Azure resources without the need for a service principal or managed identity. With Workload Identity\n * authentication, applications authenticate themselves using their own identity, rather than using a shared service\n * principal or managed identity. Under the hood, Workload Identity authentication uses the concept of Service Account\n * Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using Workload\n * Identity authentication, you can avoid the need to manage and rotate service principals or managed identities for\n * each application on each VM. Additionally, because SACs are created automatically and managed by Azure, you don't\n * need to worry about storing and securing sensitive credentials themselves.\n * The WorkloadIdentityCredential supports Microsoft Entra Workload ID authentication on Azure Kubernetes and acquires\n * a token using the SACs available in the Azure Kubernetes environment.\n * Refer to <a href=\"https://learn.microsoft.com/azure/aks/workload-identity-overview\">Microsoft Entra\n * Workload ID</a> for more information.\n */\nexport class WorkloadIdentityCredential implements TokenCredential {\n private client: ClientAssertionCredential | undefined;\n private azureFederatedTokenFileContent: string | undefined = undefined;\n private cacheDate: number | undefined = undefined;\n private federatedTokenFilePath: string | undefined;\n\n /**\n * WorkloadIdentityCredential supports Microsoft Entra Workload ID on Kubernetes.\n *\n * @param options - The identity client options to use for authentication.\n */\n constructor(options?: WorkloadIdentityCredentialOptions) {\n // Logging environment variables for error details\n const assignedEnv = processEnvVars(SupportedWorkloadEnvironmentVariables).assigned.join(\", \");\n logger.info(`Found the following environment variables: ${assignedEnv}`);\n\n const workloadIdentityCredentialOptions = options ?? {};\n const tenantId = workloadIdentityCredentialOptions.tenantId || process.env.AZURE_TENANT_ID;\n const clientId = workloadIdentityCredentialOptions.clientId || process.env.AZURE_CLIENT_ID;\n this.federatedTokenFilePath =\n workloadIdentityCredentialOptions.tokenFilePath || process.env.AZURE_FEDERATED_TOKEN_FILE;\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n if (!clientId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. clientId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - \"AZURE_CLIENT_ID\".\n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`,\n );\n }\n\n if (!tenantId) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. tenantId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - \"AZURE_TENANT_ID\".\n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`,\n );\n }\n\n if (!this.federatedTokenFilePath) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. federatedTokenFilePath is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - \"AZURE_FEDERATED_TOKEN_FILE\".\n See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`,\n );\n }\n\n logger.info(\n `Invoking ClientAssertionCredential with tenant ID: ${tenantId}, clientId: ${workloadIdentityCredentialOptions.clientId} and federated token path: [REDACTED]`,\n );\n this.client = new ClientAssertionCredential(\n tenantId,\n clientId,\n this.readFileContents.bind(this),\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} 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 | null> {\n if (!this.client) {\n const errorMessage = `${credentialName}: is unavailable. tenantId, clientId, and federatedTokenFilePath are required parameters. \n In DefaultAzureCredential and ManagedIdentityCredential, these can be provided as environment variables - \n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_FEDERATED_TOKEN_FILE\". See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`;\n logger.info(errorMessage);\n throw new CredentialUnavailableError(errorMessage);\n }\n logger.info(\"Invoking getToken() of Client Assertion Credential\");\n return this.client.getToken(scopes, options);\n }\n\n private async readFileContents(): Promise<string> {\n // Cached assertions expire after 5 minutes\n if (this.cacheDate !== undefined && Date.now() - this.cacheDate >= 1000 * 60 * 5) {\n this.azureFederatedTokenFileContent = undefined;\n }\n if (!this.federatedTokenFilePath) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. Invalid file path provided ${this.federatedTokenFilePath}.`,\n );\n }\n if (!this.azureFederatedTokenFileContent) {\n const file = await readFile(this.federatedTokenFilePath, \"utf8\");\n const value = file.trim();\n if (!value) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. No content on the file ${this.federatedTokenFilePath}.`,\n );\n } else {\n this.azureFederatedTokenFileContent = value;\n this.cacheDate = Date.now();\n }\n }\n return this.azureFederatedTokenFileContent;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport type { MSI, MSIConfiguration } from \"./models\";\nimport { WorkloadIdentityCredential } from \"../workloadIdentityCredential\";\nimport { credentialLogger } from \"../../util/logging\";\nimport type { WorkloadIdentityCredentialOptions } from \"../workloadIdentityCredentialOptions\";\n\nconst msiName = \"ManagedIdentityCredential - Token Exchange\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI.\n */\nexport const tokenExchangeMsi: MSI = {\n name: \"tokenExchangeMsi\",\n async isAvailable({ clientId }): Promise<boolean> {\n const env = process.env;\n const result = Boolean(\n (clientId || env.AZURE_CLIENT_ID) &&\n env.AZURE_TENANT_ID &&\n process.env.AZURE_FEDERATED_TOKEN_FILE,\n );\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`,\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {},\n ): Promise<AccessToken | null> {\n const { scopes, clientId } = configuration;\n const identityClientTokenCredentialOptions = {};\n const workloadIdentityCredential = new WorkloadIdentityCredential({\n clientId,\n tenantId: process.env.AZURE_TENANT_ID,\n tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE,\n ...identityClientTokenCredentialOptions,\n disableInstanceDiscovery: true,\n } as WorkloadIdentityCredentialOptions);\n return workloadIdentityCredential.getToken(scopes, getTokenOptions);\n },\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../../errors\";\nimport type { MsalToken, ValidMsalToken } from \"../../msal/types\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { defaultLoggerCallback, getMSALLogLevel } from \"../../msal/utils\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport type { MSIConfiguration } from \"./models\";\nimport { ManagedIdentityApplication } from \"@azure/msal-node\";\nimport type { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { getLogLevel } from \"@azure/logger\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { imdsRetryPolicy } from \"./imdsRetryPolicy\";\nimport { mapScopesToResource } from \"./utils\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { tracingClient } from \"../../util/tracing\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential(MSAL)\");\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * Since this is an internal implementation, uses a looser interface than the public one.\n */\ninterface ManagedIdentityCredentialOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId?: string;\n\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID and is not required for system-assigned managed identities.\n */\n objectId?: string;\n}\n\nexport class MsalMsiProvider {\n private managedIdentityApp: ManagedIdentityApplication;\n private identityClient: IdentityClient;\n private clientId?: string;\n private resourceId?: string;\n private objectId?: string;\n private msiRetryConfig: MSIConfiguration[\"retryConfig\"] = {\n maxRetries: 5,\n startDelayInMs: 800,\n intervalIncrement: 2,\n };\n private isAvailableIdentityClient: IdentityClient;\n\n constructor(\n clientIdOrOptions?: string | ManagedIdentityCredentialOptions,\n options: ManagedIdentityCredentialOptions = {},\n ) {\n let _options: ManagedIdentityCredentialOptions = {};\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = clientIdOrOptions?.clientId;\n _options = clientIdOrOptions ?? {};\n }\n this.resourceId = _options?.resourceId;\n this.objectId = _options?.objectId;\n\n // For JavaScript users.\n const providedIds = [this.clientId, this.resourceId, this.objectId].filter(Boolean);\n if (providedIds.length > 1) {\n throw new Error(\n `ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify(\n { clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId },\n )}`,\n );\n }\n\n // ManagedIdentity uses http for local requests\n _options.allowInsecureConnection = true;\n\n if (_options?.retryOptions?.maxRetries !== undefined) {\n this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries;\n }\n\n this.identityClient = new IdentityClient({\n ..._options,\n additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: \"perCall\" }],\n });\n\n this.managedIdentityApp = new ManagedIdentityApplication({\n managedIdentityIdParams: {\n userAssignedClientId: this.clientId,\n userAssignedResourceId: this.resourceId,\n userAssignedObjectId: this.objectId,\n },\n system: {\n // todo: proxyUrl?\n disableInternalRetries: true,\n networkClient: this.identityClient,\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n loggerCallback: defaultLoggerCallback(logger),\n },\n },\n });\n\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible.\n if (this.managedIdentityApp.getManagedIdentitySource() === \"CloudShell\") {\n if (this.clientId || this.resourceId || this.objectId) {\n logger.warning(\n `CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify(\n {\n clientId: this.clientId,\n resourceId: this.resourceId,\n objectId: this.objectId,\n },\n )}.`,\n );\n throw new CredentialUnavailableError(\n \"ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.\",\n );\n }\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@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 logger.getToken.info(\"Using the MSAL provider for Managed Identity.\");\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(\n scopes,\n )}`,\n );\n }\n\n return tracingClient.withSpan(\"ManagedIdentityCredential.getToken\", options, async () => {\n try {\n const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.identityClient,\n resourceId: this.resourceId,\n });\n\n // Most scenarios are handled by MSAL except for two:\n // AKS pod identity - MSAL does not implement the token exchange flow.\n // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token.\n // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token\n // We will continue to implement these features in the Identity library.\n\n const identitySource = this.managedIdentityApp.getManagedIdentitySource();\n const isImdsMsi = identitySource === \"DefaultToImds\" || identitySource === \"Imds\"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use.\n\n logger.getToken.info(`MSAL Identity source: ${identitySource}`);\n\n if (isTokenExchangeMsi) {\n // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely.\n logger.getToken.info(\"Using the token exchange managed identity.\");\n const result = await tokenExchangeMsi.getToken({\n scopes,\n clientId: this.clientId,\n identityClient: this.identityClient,\n retryConfig: this.msiRetryConfig,\n resourceId: this.resourceId,\n });\n\n if (result === null) {\n throw new CredentialUnavailableError(\n \"Attempted to use the token exchange managed identity, but received a null response.\",\n );\n }\n\n return result;\n } else if (isImdsMsi) {\n // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token.\n // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential.\n logger.getToken.info(\"Using the IMDS endpoint to probe for availability.\");\n const isAvailable = await imdsMsi.isAvailable({\n scopes,\n clientId: this.clientId,\n getTokenOptions: options,\n identityClient: this.isAvailableIdentityClient,\n resourceId: this.resourceId,\n });\n\n if (!isAvailable) {\n throw new CredentialUnavailableError(\n `Attempted to use the IMDS endpoint, but it is not available.`,\n );\n }\n }\n\n // If we got this far, it means:\n // - This is not a tokenExchangeMsi,\n // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable.\n // We can proceed normally by calling MSAL for a token.\n logger.getToken.info(\"Calling into MSAL for managed identity token.\");\n const token = await this.managedIdentityApp.acquireToken({\n resource,\n });\n\n this.ensureValidMsalToken(scopes, token, options);\n logger.getToken.info(formatSuccess(scopes));\n\n return {\n expiresOnTimestamp: token.expiresOn.getTime(),\n token: token.accessToken,\n refreshAfterTimestamp: token.refreshOn?.getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n logger.getToken.error(formatError(scopes, err));\n\n // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently.\n // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow?\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n if (isNetworkError(err)) {\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Network unreachable. Message: ${err.message}`,\n { cause: err },\n );\n }\n\n throw new CredentialUnavailableError(\n `ManagedIdentityCredential: Authentication failed. Message ${err.message}`,\n { cause: err },\n );\n }\n });\n }\n\n /**\n * Ensures the validity of the MSAL token\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions,\n ): asserts msalToken is ValidMsalToken {\n const createError = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw createError(\"No response.\");\n }\n if (!msalToken.expiresOn) {\n throw createError(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw createError(`Response had no \"accessToken\" property.`);\n }\n }\n}\n\nfunction isNetworkError(err: any): boolean {\n // MSAL error\n if (err.errorCode === \"network_error\") {\n return true;\n }\n\n // Probe errors\n if (err.code === \"ENETUNREACH\" || err.code === \"EHOSTUNREACH\") {\n return true;\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\" or \"A socket operation was attempted to an unreachable host\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"unreachable\")) {\n return true;\n }\n }\n\n return false;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport type { LegacyMsiProvider } from \"./legacyMsiProvider\";\nimport type { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport { MsalMsiProvider } from \"./msalMsiProvider\";\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `clientId` and not `resourceId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialClientIdOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `resourceId` and not `clientId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialResourceIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `objectId` as a constructor argument.\n */\nexport interface ManagedIdentityCredentialObjectIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying the object ID of the underlying service principal used to authenticate a user-assigned managed identity.\n * This is an alternative to providing a client ID or resource ID and is not required for system-assigned managed identities.\n */\n objectId: string;\n}\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private implProvider: LegacyMsiProvider | MsalMsiProvider;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a client ID\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with a resource ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with an object ID\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialObjectIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions\n | ManagedIdentityCredentialObjectIdOptions,\n options?: TokenCredentialOptions,\n ) {\n // https://github.com/Azure/azure-sdk-for-js/issues/30189\n // If needed, you may release a hotfix to quickly rollback to the legacy implementation by changing the following line to:\n // this.implProvider = new LegacyMsiProvider(clientIdOrOptions, options);\n // Once stabilized, you can remove the legacy implementation and inline the msalMsiProvider code here as a drop-in replacement.\n this.implProvider = new MsalMsiProvider(clientIdOrOptions, options);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@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 return this.implProvider.getToken(scopes, options);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { CredentialLogger } from \"./logging\";\nimport { formatError } from \"./logging\";\n\n/**\n * Ensures the scopes value is an array.\n * @internal\n */\nexport function ensureScopes(scopes: string | string[]): string[] {\n return Array.isArray(scopes) ? scopes : [scopes];\n}\n\n/**\n * Throws if the received scope is not valid.\n * @internal\n */\nexport function ensureValidScopeForDevTimeCreds(scope: string, logger: CredentialLogger): void {\n if (!scope.match(/^[0-9a-zA-Z-_.:/]+$/)) {\n const error = new Error(\"Invalid scope was specified by the user or calling client\");\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n}\n\n/**\n * Returns the resource out of a scope.\n * @internal\n */\nexport function getScopeResource(scope: string): string {\n return scope.replace(/\\/.default$/, \"\");\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { CredentialLogger } from \"./logging\";\nimport { formatError } from \"./logging\";\n\n/**\n * @internal\n */\nexport function checkSubscription(logger: CredentialLogger, subscription: string): void {\n if (!subscription.match(/^[0-9a-zA-Z-._ ]+$/)) {\n const error = new Error(\n \"Invalid subscription provided. You can locate your subscription by following the instructions listed here: https://learn.microsoft.com/azure/azure-portal/get-subscription-tenant-id.\",\n );\n logger.info(formatError(\"\", error));\n throw error;\n }\n}\n","// 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\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils\";\n\nimport type { AzureCliCredentialOptions } from \"./azureCliCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport child_process from \"child_process\";\nimport { tracingClient } from \"../util/tracing\";\nimport { checkSubscription } from \"../util/subscriptionUtils\";\n\n/**\n * Mockable reference to the CLI credential cliCredentialFunctions\n * @internal\n */\nexport const cliCredentialInternals = {\n /**\n * @internal\n */\n getSafeWorkingDir(): string {\n if (process.platform === \"win32\") {\n if (!process.env.SystemRoot) {\n throw new Error(\"Azure CLI credential expects a 'SystemRoot' environment variable\");\n }\n return process.env.SystemRoot;\n } else {\n return \"/bin\";\n }\n },\n\n /**\n * Gets the access token from Azure CLI\n * @param resource - The resource to use when getting the token\n * @internal\n */\n async getAzureCliAccessToken(\n resource: string,\n tenantId?: string,\n subscription?: string,\n timeout?: number,\n ): Promise<{ stdout: string; stderr: string; error: Error | null }> {\n let tenantSection: string[] = [];\n let subscriptionSection: string[] = [];\n if (tenantId) {\n tenantSection = [\"--tenant\", tenantId];\n }\n if (subscription) {\n // Add quotes around the subscription to handle subscriptions with spaces\n subscriptionSection = [\"--subscription\", `\"${subscription}\"`];\n }\n return new Promise((resolve, reject) => {\n try {\n child_process.execFile(\n \"az\",\n [\n \"account\",\n \"get-access-token\",\n \"--output\",\n \"json\",\n \"--resource\",\n resource,\n ...tenantSection,\n ...subscriptionSection,\n ],\n { cwd: cliCredentialInternals.getSafeWorkingDir(), shell: true, timeout },\n (error, stdout, stderr) => {\n resolve({ stdout: stdout, stderr: stderr, error });\n },\n );\n } catch (err: any) {\n reject(err);\n }\n });\n },\n};\n\nconst logger = credentialLogger(\"AzureCliCredential\");\n\n/**\n * This credential will use the currently logged-in user login information\n * via the Azure CLI ('az') commandline tool.\n * To do so, it will read the user access token and expire time\n * with Azure CLI command \"az account get-access-token\".\n */\nexport class AzureCliCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n private subscription?: string;\n\n /**\n * Creates an instance of the {@link AzureCliCredential}.\n *\n * To use this credential, ensure that you have already logged\n * in via the 'az' tool using the command \"az login\" from the commandline.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzureCliCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n if (options?.subscription) {\n checkSubscription(logger, options?.subscription);\n this.subscription = options?.subscription;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} 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 const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n if (this.subscription) {\n checkSubscription(logger, this.subscription);\n }\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n logger.getToken.info(`Using the scope ${scope}`);\n\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n try {\n ensureValidScopeForDevTimeCreds(scope, logger);\n const resource = getScopeResource(scope);\n const obj = await cliCredentialInternals.getAzureCliAccessToken(\n resource,\n tenantId,\n this.subscription,\n this.timeout,\n );\n const specificScope = obj.stderr?.match(\"(.*)az login --scope(.*)\");\n const isLoginError = obj.stderr?.match(\"(.*)az login(.*)\") && !specificScope;\n const isNotInstallError =\n obj.stderr?.match(\"az:(.*)not found\") || obj.stderr?.startsWith(\"'az' is not recognized\");\n\n if (isNotInstallError) {\n const error = new CredentialUnavailableError(\n \"Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n if (isLoginError) {\n const error = new CredentialUnavailableError(\n \"Please run 'az login' from a command prompt to authenticate before using this credential.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n try {\n const responseData = obj.stdout;\n const response: AccessToken = this.parseRawResponse(responseData);\n logger.getToken.info(formatSuccess(scopes));\n return response;\n } catch (e: any) {\n if (obj.stderr) {\n throw new CredentialUnavailableError(obj.stderr);\n }\n throw e;\n }\n } catch (err: any) {\n const error =\n err.name === \"CredentialUnavailableError\"\n ? err\n : new CredentialUnavailableError(\n (err as Error).message || \"Unknown error while trying to retrieve the access token\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n });\n }\n\n /**\n * Parses the raw JSON response from the Azure CLI into a usable AccessToken object\n *\n * @param rawResponse - The raw JSON response from the Azure CLI\n * @returns An access token with the expiry time parsed from the raw response\n *\n * The expiryTime of the credential's access token, in milliseconds, is calculated as follows:\n *\n * When available, expires_on (introduced in Azure CLI v2.54.0) will be preferred. Otherwise falls back to expiresOn.\n */\n private parseRawResponse(rawResponse: string): AccessToken {\n const response: any = JSON.parse(rawResponse);\n const token = response.accessToken;\n // if available, expires_on will be a number representing seconds since epoch.\n // ensure it's a number or NaN\n let expiresOnTimestamp = Number.parseInt(response.expires_on, 10) * 1000;\n if (!isNaN(expiresOnTimestamp)) {\n logger.getToken.info(\"expires_on is available and is valid, using it\");\n return {\n token,\n expiresOnTimestamp,\n tokenType: \"Bearer\",\n };\n }\n\n // fallback to the older expiresOn - an RFC3339 date string\n expiresOnTimestamp = new Date(response.expiresOn).getTime();\n\n // ensure expiresOn is well-formatted\n if (isNaN(expiresOnTimestamp)) {\n throw new CredentialUnavailableError(\n `Unexpected response from Azure CLI when getting token. Expected \"expiresOn\" to be a RFC3339 date string. Got: \"${response.expiresOn}\"`,\n );\n }\n\n return {\n token,\n expiresOnTimestamp,\n tokenType: \"Bearer\",\n };\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport type { AzureDeveloperCliCredentialOptions } from \"./azureDeveloperCliCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport child_process from \"child_process\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport { ensureValidScopeForDevTimeCreds } from \"../util/scopeUtils\";\n\n/**\n * Mockable reference to the Developer CLI credential cliCredentialFunctions\n * @internal\n */\nexport const developerCliCredentialInternals = {\n /**\n * @internal\n */\n getSafeWorkingDir(): string {\n if (process.platform === \"win32\") {\n if (!process.env.SystemRoot) {\n throw new Error(\n \"Azure Developer CLI credential expects a 'SystemRoot' environment variable\",\n );\n }\n return process.env.SystemRoot;\n } else {\n return \"/bin\";\n }\n },\n\n /**\n * Gets the access token from Azure Developer CLI\n * @param scopes - The scopes to use when getting the token\n * @internal\n */\n async getAzdAccessToken(\n scopes: string[],\n tenantId?: string,\n timeout?: number,\n ): Promise<{ stdout: string; stderr: string; error: Error | null }> {\n let tenantSection: string[] = [];\n if (tenantId) {\n tenantSection = [\"--tenant-id\", tenantId];\n }\n return new Promise((resolve, reject) => {\n try {\n child_process.execFile(\n \"azd\",\n [\n \"auth\",\n \"token\",\n \"--output\",\n \"json\",\n ...scopes.reduce<string[]>(\n (previous, current) => previous.concat(\"--scope\", current),\n [],\n ),\n ...tenantSection,\n ],\n {\n cwd: developerCliCredentialInternals.getSafeWorkingDir(),\n timeout,\n },\n (error, stdout, stderr) => {\n resolve({ stdout, stderr, error });\n },\n );\n } catch (err: any) {\n reject(err);\n }\n });\n },\n};\n\nconst logger = credentialLogger(\"AzureDeveloperCliCredential\");\n\n/**\n * Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy\n * resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific\n * to Azure developers. It allows users to authenticate as a user and/or a service principal against\n * <a href=\"https://learn.microsoft.com/entra/fundamentals/\">Microsoft Entra ID</a>. The\n * AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of\n * the logged-in user or service principal in the Azure Developer CLI. It acts as the Azure Developer CLI logged in user or\n * service principal and executes an Azure CLI command underneath to authenticate the application against\n * Microsoft Entra ID.\n *\n * <h2> Configure AzureDeveloperCliCredential </h2>\n *\n * To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the\n * commands below:\n *\n * <ol>\n * <li>Run \"azd auth login\" in Azure Developer CLI to authenticate interactively as a user.</li>\n * <li>Run \"azd auth login --client-id clientID --client-secret clientSecret\n * --tenant-id tenantID\" to authenticate as a service principal.</li>\n * </ol>\n *\n * You may need to repeat this process after a certain time period, depending on the refresh token validity in your\n * organization. Generally, the refresh token validity period is a few weeks to a few months.\n * AzureDeveloperCliCredential will prompt you to sign in again.\n */\nexport class AzureDeveloperCliCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzureDeveloperCliCredential}.\n *\n * To use this credential, ensure that you have already logged\n * in via the 'azd' tool using the command \"azd auth login\" from the commandline.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzureDeveloperCliCredentialOptions) {\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 * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} 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 const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n let scopeList: string[];\n if (typeof scopes === \"string\") {\n scopeList = [scopes];\n } else {\n scopeList = scopes;\n }\n logger.getToken.info(`Using the scopes ${scopes}`);\n\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n try {\n scopeList.forEach((scope) => {\n ensureValidScopeForDevTimeCreds(scope, logger);\n });\n const obj = await developerCliCredentialInternals.getAzdAccessToken(\n scopeList,\n tenantId,\n this.timeout,\n );\n const isNotLoggedInError =\n obj.stderr?.match(\"not logged in, run `azd login` to login\") ||\n obj.stderr?.match(\"not logged in, run `azd auth login` to login\");\n const isNotInstallError =\n obj.stderr?.match(\"azd:(.*)not found\") ||\n obj.stderr?.startsWith(\"'azd' is not recognized\");\n\n if (isNotInstallError || (obj.error && (obj.error as any).code === \"ENOENT\")) {\n const error = new CredentialUnavailableError(\n \"Azure Developer CLI couldn't be found. To mitigate this issue, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n if (isNotLoggedInError) {\n const error = new CredentialUnavailableError(\n \"Please run 'azd auth login' from a command prompt to authenticate before using this credential. For more information, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n try {\n const resp: { token: string; expiresOn: string } = JSON.parse(obj.stdout);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: resp.token,\n expiresOnTimestamp: new Date(resp.expiresOn).getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (e: any) {\n if (obj.stderr) {\n throw new CredentialUnavailableError(obj.stderr);\n }\n throw e;\n }\n } catch (err: any) {\n const error =\n err.name === \"CredentialUnavailableError\"\n ? err\n : new CredentialUnavailableError(\n (err as Error).message || \"Unknown error while trying to retrieve the access token\",\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n });\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as childProcess from \"child_process\";\n\n/**\n * Easy to mock childProcess utils.\n * @internal\n */\nexport const processUtils = {\n /**\n * Promisifying childProcess.execFile\n * @internal\n */\n execFile(\n file: string,\n params: string[],\n options?: childProcess.ExecFileOptionsWithStringEncoding,\n ): Promise<string | Buffer> {\n return new Promise((resolve, reject) => {\n childProcess.execFile(file, params, options, (error, stdout, stderr) => {\n if (Buffer.isBuffer(stdout)) {\n stdout = stdout.toString(\"utf8\");\n }\n if (Buffer.isBuffer(stderr)) {\n stderr = stderr.toString(\"utf8\");\n }\n if (stderr || error) {\n reject(stderr ? new Error(stderr) : error);\n } else {\n resolve(stdout);\n }\n });\n });\n },\n};\n","// 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\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils\";\n\nimport type { AzurePowerShellCredentialOptions } from \"./azurePowerShellCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { processUtils } from \"../util/processUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"AzurePowerShellCredential\");\n\nconst isWindows = process.platform === \"win32\";\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(commands: string[][], timeout?: number): 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 timeout,\n })) as string;\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 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 powerShellCommand,\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `\n $tenantId = \"${tenantId ?? \"\"}\"\n $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru\n $useSecureString = $m.Version -ge [version]'2.17.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 if ($useSecureString) {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value (ConvertFrom-SecureString -AsPlainText $token.Token)\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\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 tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AggregateAuthenticationError, CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\n\n/**\n * @internal\n */\nexport const logger = credentialLogger(\"ChainedTokenCredential\");\n\n/**\n * Enables multiple `TokenCredential` implementations to be tried in order until\n * one of the getToken methods returns an access token. For more information, see\n * [ChainedTokenCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-chainedtokencredential-for-granularity).\n */\nexport class ChainedTokenCredential implements TokenCredential {\n private _sources: TokenCredential[] = [];\n\n /**\n * Creates an instance of ChainedTokenCredential using the given credentials.\n *\n * @param sources - `TokenCredential` implementations to be tried in order.\n *\n * Example usage:\n * ```ts snippet:chained_token_credential_example\n * import { ClientSecretCredential, ChainedTokenCredential } from \"@azure/identity\";\n *\n * const tenantId = \"<tenant-id>\";\n * const clientId = \"<client-id>\";\n * const clientSecret = \"<client-secret>\";\n * const anotherClientId = \"<another-client-id>\";\n * const anotherSecret = \"<another-client-secret>\";\n * const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);\n * const secondCredential = new ClientSecretCredential(tenantId, anotherClientId, anotherSecret);\n * const credentialChain = new ChainedTokenCredential(firstCredential, secondCredential);\n * ```\n */\n constructor(...sources: TokenCredential[]) {\n this._sources = sources;\n }\n\n /**\n * Returns the first access token returned by one of the chained\n * `TokenCredential` implementations. Throws an {@link AggregateAuthenticationError}\n * when one or more credentials throws an {@link AuthenticationError} and\n * no credentials have returned an access token.\n *\n * This method is called automatically by Azure SDK client libraries. You may call this method\n * directly, but you must also handle token caching and token refreshing.\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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n const { token } = await this.getTokenInternal(scopes, options);\n return token;\n }\n\n private async getTokenInternal(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<{ token: AccessToken; successfulCredential: TokenCredential }> {\n let token: AccessToken | null = null;\n let successfulCredential: TokenCredential;\n const errors: Error[] = [];\n\n return tracingClient.withSpan(\n \"ChainedTokenCredential.getToken\",\n options,\n async (updatedOptions) => {\n for (let i = 0; i < this._sources.length && token === null; i++) {\n try {\n token = await this._sources[i].getToken(scopes, updatedOptions);\n successfulCredential = this._sources[i];\n } catch (err: any) {\n if (\n err.name === \"CredentialUnavailableError\" ||\n err.name === \"AuthenticationRequiredError\"\n ) {\n errors.push(err);\n } else {\n logger.getToken.info(formatError(scopes, err));\n throw err;\n }\n }\n }\n\n if (!token && errors.length > 0) {\n const err = new AggregateAuthenticationError(\n errors,\n \"ChainedTokenCredential authentication failed.\",\n );\n logger.getToken.info(formatError(scopes, err));\n throw err;\n }\n\n logger.getToken.info(\n `Result for ${successfulCredential.constructor.name}: ${formatSuccess(scopes)}`,\n );\n\n if (token === null) {\n throw new CredentialUnavailableError(\"Failed to retrieve a valid token\");\n }\n return { token, successfulCredential };\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createHash, createPrivateKey } from \"crypto\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport type { CertificateParts } from \"../msal/types\";\nimport type { ClientCertificateCredentialOptions } from \"./clientCertificateCredentialOptions\";\nimport { credentialLogger } from \"../util/logging\";\nimport { readFile } from \"fs/promises\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst credentialName = \"ClientCertificateCredential\";\nconst logger = credentialLogger(credentialName);\n\n/**\n * Required configuration options for the {@link ClientCertificateCredential}, with the string contents of a PEM certificate\n */\nexport interface ClientCertificatePEMCertificate {\n /**\n * The PEM-encoded public/private key certificate on the filesystem.\n */\n certificate: string;\n\n /**\n * The password for the certificate file.\n */\n certificatePassword?: string;\n}\n/**\n * Required configuration options for the {@link ClientCertificateCredential}, with the path to a PEM certificate.\n */\nexport interface ClientCertificatePEMCertificatePath {\n /**\n * The path to the PEM-encoded public/private key certificate on the filesystem.\n */\n certificatePath: string;\n\n /**\n * The password for the certificate file.\n */\n certificatePassword?: string;\n}\n/**\n * Required configuration options for the {@link ClientCertificateCredential}, with either the string contents of a PEM certificate, or the path to a PEM certificate.\n */\nexport type ClientCertificateCredentialPEMConfiguration =\n | ClientCertificatePEMCertificate\n | ClientCertificatePEMCertificatePath;\n\n/**\n * Enables authentication to Microsoft Entra ID using a PEM-encoded\n * certificate that is assigned to an App Registration. More information\n * on how to configure certificate authentication can be found here:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad\n *\n */\nexport class ClientCertificateCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private certificateConfiguration: ClientCertificateCredentialPEMConfiguration;\n private sendCertificateChain?: boolean;\n private msalClient: MsalClient;\n\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param certificatePath - The path to a PEM-encoded public/private key certificate on the filesystem.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n certificatePath: string,\n options?: ClientCertificateCredentialOptions,\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the path of the certificate on the filesystem.\n * If the type is ignored, we will throw the value of the path to a PEM certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificatePath,\n options?: ClientCertificateCredentialOptions,\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Microsoft Entra ID with a certificate.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the PEM-encoded certificate as a string.\n * If the type is ignored, we will throw the value of the PEM-encoded certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificate,\n options?: ClientCertificateCredentialOptions,\n );\n constructor(\n tenantId: string,\n clientId: string,\n certificatePathOrConfiguration: string | ClientCertificateCredentialPEMConfiguration,\n options: ClientCertificateCredentialOptions = {},\n ) {\n if (!tenantId || !clientId) {\n throw new Error(`${credentialName}: tenantId and clientId are required parameters.`);\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.sendCertificateChain = options.sendCertificateChain;\n\n this.certificateConfiguration = {\n ...(typeof certificatePathOrConfiguration === \"string\"\n ? {\n certificatePath: certificatePathOrConfiguration,\n }\n : certificatePathOrConfiguration),\n };\n const certificate: string | undefined = (\n this.certificateConfiguration as ClientCertificatePEMCertificate\n ).certificate;\n const certificatePath: string | undefined = (\n this.certificateConfiguration as ClientCertificatePEMCertificatePath\n ).certificatePath;\n if (!this.certificateConfiguration || !(certificate || certificatePath)) {\n throw new Error(\n `${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n if (certificate && certificatePath) {\n throw new Error(\n `${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n const certificate = await this.buildClientCertificate();\n return this.msalClient.getTokenByClientCertificate(arrayScopes, certificate, newOptions);\n });\n }\n\n private async buildClientCertificate(): Promise<CertificateParts> {\n const parts = await parseCertificate(\n this.certificateConfiguration,\n this.sendCertificateChain ?? false,\n );\n\n let privateKey: string;\n if (this.certificateConfiguration.certificatePassword !== undefined) {\n privateKey = createPrivateKey({\n key: parts.certificateContents,\n passphrase: this.certificateConfiguration.certificatePassword,\n format: \"pem\",\n })\n .export({\n format: \"pem\",\n type: \"pkcs8\",\n })\n .toString();\n } else {\n privateKey = parts.certificateContents;\n }\n\n return {\n thumbprint: parts.thumbprint,\n privateKey,\n x5c: parts.x5c,\n };\n }\n}\n\n/**\n * Parses a certificate into its relevant parts\n *\n * @param certificateConfiguration - The certificate contents or path to the certificate\n * @param sendCertificateChain - true if the entire certificate chain should be sent for SNI, false otherwise\n * @returns The parsed certificate parts and the certificate contents\n */\nexport async function parseCertificate(\n certificateConfiguration: ClientCertificateCredentialPEMConfiguration,\n sendCertificateChain: boolean,\n): Promise<Omit<CertificateParts, \"privateKey\"> & { certificateContents: string }> {\n const certificate: string | undefined = (\n certificateConfiguration as ClientCertificatePEMCertificate\n ).certificate;\n const certificatePath: string | undefined = (\n certificateConfiguration as ClientCertificatePEMCertificatePath\n ).certificatePath;\n const certificateContents = certificate || (await readFile(certificatePath!, \"utf8\"));\n const x5c = sendCertificateChain ? certificateContents : undefined;\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n const thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return {\n certificateContents,\n thumbprint,\n x5c,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport type { ClientSecretCredentialOptions } from \"./clientSecretCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"ClientSecretCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID using a client secret\n * that was generated for an App Registration. More information on how\n * to configure a client secret can be found here:\n *\n * https://learn.microsoft.com/entra/identity-platform/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application\n *\n */\nexport class ClientSecretCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalClient: MsalClient;\n private clientSecret: string;\n\n /**\n * Creates an instance of the ClientSecretCredential with the details\n * needed to authenticate against Microsoft Entra ID with a client\n * secret.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n clientSecret: string,\n options: ClientSecretCredentialOptions = {},\n ) {\n if (!tenantId) {\n throw new CredentialUnavailableError(\n \"ClientSecretCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.\",\n );\n }\n\n if (!clientId) {\n throw new CredentialUnavailableError(\n \"ClientSecretCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.\",\n );\n }\n\n if (!clientSecret) {\n throw new CredentialUnavailableError(\n \"ClientSecretCredential: clientSecret is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.\",\n );\n }\n\n this.clientSecret = clientSecret;\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByClientSecret(arrayScopes, this.clientSecret, newOptions);\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport { CredentialUnavailableError } from \"../errors\";\nimport type { UsernamePasswordCredentialOptions } from \"./usernamePasswordCredentialOptions\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"UsernamePasswordCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID with a user's\n * username and password. This credential requires a high degree of\n * trust so you should only use it when other, more secure credential\n * types can't be used.\n */\nexport class UsernamePasswordCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalClient: MsalClient;\n private username: string;\n private password: string;\n\n /**\n * Creates an instance of the UsernamePasswordCredential with the details\n * needed to authenticate against Microsoft Entra ID with a username\n * and password.\n *\n * @param tenantId - The Microsoft Entra tenant (directory).\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param username - The user account's e-mail address (user name).\n * @param password - The user account's account password\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n username: string,\n password: string,\n options: UsernamePasswordCredentialOptions = {},\n ) {\n if (!tenantId) {\n throw new CredentialUnavailableError(\n \"UsernamePasswordCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.\",\n );\n }\n\n if (!clientId) {\n throw new CredentialUnavailableError(\n \"UsernamePasswordCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.\",\n );\n }\n\n if (!username) {\n throw new CredentialUnavailableError(\n \"UsernamePasswordCredential: username is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.\",\n );\n }\n\n if (!password) {\n throw new CredentialUnavailableError(\n \"UsernamePasswordCredential: password is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.\",\n );\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.username = username;\n this.password = password;\n\n this.msalClient = createMsalClient(clientId, this.tenantId, {\n ...options,\n tokenCredentialOptions: 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} will be thrown with the details of the failure.\n *\n * If the user provided the option `disableAutomaticAuthentication`,\n * once the token can't be retrieved silently,\n * this method won't attempt to request user interaction to retrieve the token.\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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByUsernamePassword(\n arrayScopes,\n this.username,\n this.password,\n newOptions,\n );\n },\n );\n }\n}\n","// 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\";\nimport { credentialLogger, formatError, formatSuccess, processEnvVars } from \"../util/logging\";\n\nimport { ClientCertificateCredential } from \"./clientCertificateCredential\";\nimport { ClientSecretCredential } from \"./clientSecretCredential\";\nimport type { EnvironmentCredentialOptions } from \"./environmentCredentialOptions\";\nimport { UsernamePasswordCredential } from \"./usernamePasswordCredential\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\n/**\n * Contains the list of all supported environment variable names so that an\n * appropriate error message can be generated when no credentials can be\n * configured.\n *\n * @internal\n */\nexport const AllSupportedEnvironmentVariables = [\n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_CLIENT_SECRET\",\n \"AZURE_CLIENT_CERTIFICATE_PATH\",\n \"AZURE_CLIENT_CERTIFICATE_PASSWORD\",\n \"AZURE_USERNAME\",\n \"AZURE_PASSWORD\",\n \"AZURE_ADDITIONALLY_ALLOWED_TENANTS\",\n \"AZURE_CLIENT_SEND_CERTIFICATE_CHAIN\",\n];\n\nfunction getAdditionallyAllowedTenants(): string[] {\n const additionallyAllowedValues = process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS ?? \"\";\n return additionallyAllowedValues.split(\";\");\n}\n\nconst credentialName = \"EnvironmentCredential\";\nconst logger = credentialLogger(credentialName);\n\nexport function getSendCertificateChain(): boolean {\n const sendCertificateChain = (\n process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN ?? \"\"\n ).toLowerCase();\n const result = sendCertificateChain === \"true\" || sendCertificateChain === \"1\";\n logger.verbose(\n `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN: ${process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN}; sendCertificateChain: ${result}`,\n );\n return result;\n}\n\n/**\n * Enables authentication to Microsoft Entra ID using a client secret or certificate, or as a user\n * with a username and password.\n */\nexport class EnvironmentCredential implements TokenCredential {\n private _credential?:\n | ClientSecretCredential\n | ClientCertificateCredential\n | UsernamePasswordCredential = undefined;\n /**\n * Creates an instance of the EnvironmentCredential class and decides what credential to use depending on the available environment variables.\n *\n * Required environment variables:\n * - `AZURE_TENANT_ID`: The Microsoft Entra tenant (directory) ID.\n * - `AZURE_CLIENT_ID`: The client (application) ID of an App Registration in the tenant.\n *\n * If setting the AZURE_TENANT_ID, then you can also set the additionally allowed tenants\n * - `AZURE_ADDITIONALLY_ALLOWED_TENANTS`: For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens with a single semicolon delimited string. Use * to allow all tenants.\n *\n * Environment variables used for client credential authentication:\n * - `AZURE_CLIENT_SECRET`: A client secret that was generated for the App Registration.\n * - `AZURE_CLIENT_CERTIFICATE_PATH`: The path to a PEM certificate to use during the authentication, instead of the client secret.\n * - `AZURE_CLIENT_CERTIFICATE_PASSWORD`: (optional) password for the certificate file.\n * - `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN`: (optional) indicates that the certificate chain should be set in x5c header to support subject name / issuer based authentication.\n *\n * Alternatively, users can provide environment variables for username and password authentication:\n * - `AZURE_USERNAME`: Username to authenticate with.\n * - `AZURE_PASSWORD`: Password to authenticate with.\n *\n * If the environment variables required to perform the authentication are missing, a {@link CredentialUnavailableError} will be thrown.\n * If the authentication fails, or if there's an unknown error, an {@link AuthenticationError} will be thrown.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: EnvironmentCredentialOptions) {\n // Keep track of any missing environment variables for error details\n\n const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(\", \");\n logger.info(`Found the following environment variables: ${assigned}`);\n\n const tenantId = process.env.AZURE_TENANT_ID,\n clientId = process.env.AZURE_CLIENT_ID,\n clientSecret = process.env.AZURE_CLIENT_SECRET;\n\n const additionallyAllowedTenantIds = getAdditionallyAllowedTenants();\n const sendCertificateChain = getSendCertificateChain();\n const newOptions = { ...options, additionallyAllowedTenantIds, sendCertificateChain };\n\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n\n if (tenantId && clientId && clientSecret) {\n logger.info(\n `Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`,\n );\n this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, newOptions);\n return;\n }\n\n const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;\n const certificatePassword = process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD;\n if (tenantId && clientId && certificatePath) {\n logger.info(\n `Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`,\n );\n this._credential = new ClientCertificateCredential(\n tenantId,\n clientId,\n { certificatePath, certificatePassword },\n newOptions,\n );\n return;\n }\n\n const username = process.env.AZURE_USERNAME;\n const password = process.env.AZURE_PASSWORD;\n if (tenantId && clientId && username && password) {\n logger.info(\n `Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`,\n );\n this._credential = new UsernamePasswordCredential(\n tenantId,\n clientId,\n username,\n password,\n newOptions,\n );\n }\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - Optional parameters. See {@link GetTokenOptions}.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n if (this._credential) {\n try {\n const result = await this._credential.getToken(scopes, newOptions);\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err: any) {\n const authenticationError = new AuthenticationError(400, {\n error: `${credentialName} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,\n error_description: err.message.toString().split(\"More details:\").join(\"\"),\n });\n logger.getToken.info(formatError(scopes, authenticationError));\n throw authenticationError;\n }\n }\n throw new CredentialUnavailableError(\n `${credentialName} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,\n );\n });\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DefaultAzureCredentialClientIdOptions,\n DefaultAzureCredentialOptions,\n DefaultAzureCredentialResourceIdOptions,\n} from \"./defaultAzureCredentialOptions\";\nimport type {\n ManagedIdentityCredentialClientIdOptions,\n ManagedIdentityCredentialResourceIdOptions,\n} from \"./managedIdentityCredential\";\nimport { ManagedIdentityCredential } from \"./managedIdentityCredential\";\n\nimport { AzureCliCredential } from \"./azureCliCredential\";\nimport { AzureDeveloperCliCredential } from \"./azureDeveloperCliCredential\";\nimport { AzurePowerShellCredential } from \"./azurePowerShellCredential\";\nimport { ChainedTokenCredential } from \"./chainedTokenCredential\";\nimport { EnvironmentCredential } from \"./environmentCredential\";\nimport type { TokenCredential } from \"@azure/core-auth\";\nimport { WorkloadIdentityCredential } from \"./workloadIdentityCredential\";\nimport type { WorkloadIdentityCredentialOptions } from \"./workloadIdentityCredentialOptions\";\nimport { credentialLogger } from \"../util/logging\";\n\nconst logger = credentialLogger(\"DefaultAzureCredential\");\n\n/**\n * Creates a {@link ManagedIdentityCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nexport function createDefaultManagedIdentityCredential(\n options:\n | DefaultAzureCredentialOptions\n | DefaultAzureCredentialResourceIdOptions\n | DefaultAzureCredentialClientIdOptions = {},\n): TokenCredential {\n options.retryOptions ??= {\n maxRetries: 5,\n retryDelayInMs: 800,\n };\n const managedIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.managedIdentityClientId ??\n process.env.AZURE_CLIENT_ID;\n const workloadIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.workloadIdentityClientId ??\n managedIdentityClientId;\n const managedResourceId = (options as DefaultAzureCredentialResourceIdOptions)\n ?.managedIdentityResourceId;\n const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;\n const tenantId = options?.tenantId ?? process.env.AZURE_TENANT_ID;\n if (managedResourceId) {\n const managedIdentityResourceIdOptions: ManagedIdentityCredentialResourceIdOptions = {\n ...options,\n resourceId: managedResourceId,\n };\n return new ManagedIdentityCredential(managedIdentityResourceIdOptions);\n }\n\n if (workloadFile && workloadIdentityClientId) {\n const workloadIdentityCredentialOptions: DefaultAzureCredentialOptions = {\n ...options,\n tenantId: tenantId,\n };\n\n return new ManagedIdentityCredential(\n workloadIdentityClientId,\n workloadIdentityCredentialOptions,\n );\n }\n\n if (managedIdentityClientId) {\n const managedIdentityClientOptions: ManagedIdentityCredentialClientIdOptions = {\n ...options,\n clientId: managedIdentityClientId,\n };\n\n return new ManagedIdentityCredential(managedIdentityClientOptions);\n }\n\n // We may be able to return a UnavailableCredential here, but that may be a breaking change\n return new ManagedIdentityCredential(options);\n}\n\n/**\n * Creates a {@link WorkloadIdentityCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nfunction createDefaultWorkloadIdentityCredential(\n options?: DefaultAzureCredentialOptions | DefaultAzureCredentialClientIdOptions,\n): TokenCredential {\n const managedIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.managedIdentityClientId ??\n process.env.AZURE_CLIENT_ID;\n const workloadIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.workloadIdentityClientId ??\n managedIdentityClientId;\n const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;\n const tenantId = options?.tenantId ?? process.env.AZURE_TENANT_ID;\n if (workloadFile && workloadIdentityClientId) {\n const workloadIdentityCredentialOptions: WorkloadIdentityCredentialOptions = {\n ...options,\n tenantId,\n clientId: workloadIdentityClientId,\n tokenFilePath: workloadFile,\n };\n return new WorkloadIdentityCredential(workloadIdentityCredentialOptions);\n }\n if (tenantId) {\n const workloadIdentityClientTenantOptions: WorkloadIdentityCredentialOptions = {\n ...options,\n tenantId,\n };\n return new WorkloadIdentityCredential(workloadIdentityClientTenantOptions);\n }\n\n // We may be able to return a UnavailableCredential here, but that may be a breaking change\n return new WorkloadIdentityCredential(options);\n}\n\n/**\n * Creates a {@link AzureDeveloperCliCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nfunction createDefaultAzureDeveloperCliCredential(\n options: DefaultAzureCredentialOptions = {},\n): TokenCredential {\n const processTimeoutInMs = options.processTimeoutInMs;\n return new AzureDeveloperCliCredential({ processTimeoutInMs, ...options });\n}\n\n/**\n * Creates a {@link AzureCliCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nfunction createDefaultAzureCliCredential(\n options: DefaultAzureCredentialOptions = {},\n): TokenCredential {\n const processTimeoutInMs = options.processTimeoutInMs;\n return new AzureCliCredential({ processTimeoutInMs, ...options });\n}\n\n/**\n * Creates a {@link AzurePowerShellCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nfunction createDefaultAzurePowershellCredential(\n options: DefaultAzureCredentialOptions = {},\n): TokenCredential {\n const processTimeoutInMs = options.processTimeoutInMs;\n return new AzurePowerShellCredential({ processTimeoutInMs, ...options });\n}\n\n/**\n * Creates an {@link EnvironmentCredential} from the provided options.\n * @param options - Options to configure the credential.\n *\n * @internal\n */\nexport function createEnvironmentCredential(\n options: DefaultAzureCredentialOptions = {},\n): TokenCredential {\n return new EnvironmentCredential(options);\n}\n\n/**\n * A no-op credential that logs the reason it was skipped if getToken is called.\n * @internal\n */\nexport class UnavailableDefaultCredential implements TokenCredential {\n credentialUnavailableErrorMessage: string;\n credentialName: string;\n\n constructor(credentialName: string, message: string) {\n this.credentialName = credentialName;\n this.credentialUnavailableErrorMessage = message;\n }\n\n getToken(): Promise<null> {\n logger.getToken.info(\n `Skipping ${this.credentialName}, reason: ${this.credentialUnavailableErrorMessage}`,\n );\n return Promise.resolve(null);\n }\n}\n\n/**\n * Provides a default {@link ChainedTokenCredential} configuration that works for most\n * applications that use Azure SDK client libraries. For more information, see\n * [DefaultAzureCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-defaultazurecredential-for-flexibility).\n *\n * The following credential types will be tried, in order:\n *\n * - {@link EnvironmentCredential}\n * - {@link WorkloadIdentityCredential}\n * - {@link ManagedIdentityCredential}\n * - {@link AzureCliCredential}\n * - {@link AzurePowerShellCredential}\n * - {@link AzureDeveloperCliCredential}\n *\n * Consult the documentation of these credential types for more information\n * on how they attempt authentication.\n */\nexport class DefaultAzureCredential extends ChainedTokenCredential {\n /**\n * Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialClientIdOptions}.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialClientIdOptions}.\n */\n constructor(options?: DefaultAzureCredentialClientIdOptions);\n\n /**\n * Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialResourceIdOptions}.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialResourceIdOptions}.\n */\n constructor(options?: DefaultAzureCredentialResourceIdOptions);\n\n /**\n * Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialOptions}.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialOptions}.\n */\n constructor(options?: DefaultAzureCredentialOptions);\n\n constructor(options?: DefaultAzureCredentialOptions) {\n const credentialFunctions = [\n createEnvironmentCredential,\n createDefaultWorkloadIdentityCredential,\n createDefaultManagedIdentityCredential,\n createDefaultAzureCliCredential,\n createDefaultAzurePowershellCredential,\n createDefaultAzureDeveloperCliCredential,\n ];\n\n // DefaultCredential constructors should not throw, instead throwing on getToken() which is handled by ChainedTokenCredential.\n\n // When adding new credentials to the default chain, consider:\n // 1. Making the constructor parameters required and explicit\n // 2. Validating any required parameters in the factory function\n // 3. Returning a UnavailableDefaultCredential from the factory function if a credential is unavailable for any reason\n const credentials: TokenCredential[] = credentialFunctions.map((createCredentialFn) => {\n try {\n return createCredentialFn(options);\n } catch (err: any) {\n logger.warning(\n `Skipped ${createCredentialFn.name} because of an error creating the credential: ${err}`,\n );\n return new UnavailableDefaultCredential(createCredentialFn.name, err.message);\n }\n });\n\n super(...credentials);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type {\n InteractiveBrowserCredentialInBrowserOptions,\n InteractiveBrowserCredentialNodeOptions,\n} from \"./interactiveBrowserCredentialOptions\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../util/tenantIdUtils\";\n\nimport type { AuthenticationRecord } from \"../msal/types\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport type { MsalClient, MsalClientOptions } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { DeveloperSignOnClientId } from \"../constants\";\n\nconst logger = credentialLogger(\"InteractiveBrowserCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID inside of the web browser\n * using the interactive login flow.\n */\nexport class InteractiveBrowserCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private msalClient: MsalClient;\n private disableAutomaticAuthentication?: boolean;\n private browserCustomizationOptions: InteractiveBrowserCredentialNodeOptions[\"browserCustomizationOptions\"];\n private loginHint?: string;\n\n /**\n * Creates an instance of InteractiveBrowserCredential with the details needed.\n *\n * This credential uses the [Authorization Code Flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow).\n * On Node.js, it will open a browser window while it listens for a redirect response from the authentication service.\n * On browsers, it authenticates via popups. The `loginStyle` optional parameter can be set to `redirect` to authenticate by redirecting the user to an Azure secure login page, which then will redirect the user back to the web application where the authentication started.\n *\n * For Node.js, if a `clientId` is provided, the Microsoft Entra application will need to be configured to have a \"Mobile and desktop applications\" redirect endpoint.\n * Follow our guide on [setting up Redirect URIs for Desktop apps that calls to web APIs](https://learn.microsoft.com/entra/identity-platform/scenario-desktop-app-registration#redirect-uris).\n *\n * @param options - Options for configuring the client which makes the authentication requests.\n */\n constructor(\n options: InteractiveBrowserCredentialNodeOptions | InteractiveBrowserCredentialInBrowserOptions,\n ) {\n this.tenantId = resolveTenantId(logger, options.tenantId, options.clientId);\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n const msalClientOptions: MsalClientOptions = {\n ...options,\n tokenCredentialOptions: options,\n logger,\n };\n const ibcNodeOptions = options as InteractiveBrowserCredentialNodeOptions;\n this.browserCustomizationOptions = ibcNodeOptions.browserCustomizationOptions;\n this.loginHint = ibcNodeOptions.loginHint;\n if (ibcNodeOptions?.brokerOptions?.enabled) {\n if (!ibcNodeOptions?.brokerOptions?.parentWindowHandle) {\n throw new Error(\n \"In order to do WAM authentication, `parentWindowHandle` under `brokerOptions` is a required parameter\",\n );\n } else {\n msalClientOptions.brokerOptions = {\n enabled: true,\n parentWindowHandle: ibcNodeOptions.brokerOptions.parentWindowHandle,\n legacyEnableMsaPassthrough: ibcNodeOptions.brokerOptions?.legacyEnableMsaPassthrough,\n useDefaultBrokerAccount: ibcNodeOptions.brokerOptions?.useDefaultBrokerAccount,\n };\n }\n }\n this.msalClient = createMsalClient(\n options.clientId ?? DeveloperSignOnClientId,\n this.tenantId,\n msalClientOptions,\n );\n this.disableAutomaticAuthentication = options?.disableAutomaticAuthentication;\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the user provided the option `disableAutomaticAuthentication`,\n * once the token can't be retrieved silently,\n * this method won't attempt to request user interaction to retrieve the token.\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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByInteractiveRequest(arrayScopes, {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n browserCustomizationOptions: this.browserCustomizationOptions,\n loginHint: this.loginHint,\n });\n },\n );\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the token can't be retrieved silently, this method will always generate a challenge for the user.\n *\n * On Node.js, this credential has [Proof Key for Code Exchange (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636) enabled by default.\n * PKCE is a security feature that mitigates authentication code interception attacks.\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 async authenticate(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AuthenticationRecord | undefined> {\n return tracingClient.withSpan(\n `${this.constructor.name}.authenticate`,\n options,\n async (newOptions) => {\n const arrayScopes = ensureScopes(scopes);\n await this.msalClient.getTokenByInteractiveRequest(arrayScopes, {\n ...newOptions,\n disableAutomaticAuthentication: false, // this method should always allow user interaction\n browserCustomizationOptions: this.browserCustomizationOptions,\n loginHint: this.loginHint,\n });\n return this.msalClient.getActiveAccount();\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../util/tenantIdUtils\";\nimport type {\n DeviceCodeCredentialOptions,\n DeviceCodeInfo,\n DeviceCodePromptCallback,\n} from \"./deviceCodeCredentialOptions\";\nimport type { AuthenticationRecord } from \"../msal/types\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { DeveloperSignOnClientId } from \"../constants\";\n\nconst logger = credentialLogger(\"DeviceCodeCredential\");\n\n/**\n * Method that logs the user code from the DeviceCodeCredential.\n * @param deviceCodeInfo - The device code.\n */\nexport function defaultDeviceCodePromptCallback(deviceCodeInfo: DeviceCodeInfo): void {\n console.log(deviceCodeInfo.message);\n}\n\n/**\n * Enables authentication to Microsoft Entra ID using a device code\n * that the user can enter into https://microsoft.com/devicelogin.\n */\nexport class DeviceCodeCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private disableAutomaticAuthentication?: boolean;\n private msalClient: MsalClient;\n private userPromptCallback: DeviceCodePromptCallback;\n\n /**\n * Creates an instance of DeviceCodeCredential with the details needed\n * to initiate the device code authorization flow with Microsoft Entra ID.\n *\n * A message will be logged, giving users a code that they can use to authenticate once they go to https://microsoft.com/devicelogin\n *\n * Developers can configure how this message is shown by passing a custom `userPromptCallback`:\n *\n * ```ts snippet:device_code_credential_example\n * import { DeviceCodeCredential } from \"@azure/identity\";\n *\n * const credential = new DeviceCodeCredential({\n * tenantId: process.env.AZURE_TENANT_ID,\n * clientId: process.env.AZURE_CLIENT_ID,\n * userPromptCallback: (info) => {\n * console.log(\"CUSTOMIZED PROMPT CALLBACK\", info.message);\n * },\n * });\n * ```\n *\n * @param options - Options for configuring the client which makes the authentication requests.\n */\n constructor(options?: DeviceCodeCredentialOptions) {\n this.tenantId = options?.tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n const clientId = options?.clientId ?? DeveloperSignOnClientId;\n const tenantId = resolveTenantId(logger, options?.tenantId, clientId);\n this.userPromptCallback = options?.userPromptCallback ?? defaultDeviceCodePromptCallback;\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: options || {},\n });\n this.disableAutomaticAuthentication = options?.disableAutomaticAuthentication;\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the user provided the option `disableAutomaticAuthentication`,\n * once the token can't be retrieved silently,\n * this method won't attempt to request user interaction to retrieve the token.\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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n });\n },\n );\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the token can't be retrieved silently, this method will always generate a challenge for the user.\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 async authenticate(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AuthenticationRecord | undefined> {\n return tracingClient.withSpan(\n `${this.constructor.name}.authenticate`,\n options,\n async (newOptions) => {\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n await this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, {\n ...newOptions,\n disableAutomaticAuthentication: false, // this method should always allow user interaction\n });\n return this.msalClient.getActiveAccount();\n },\n );\n }\n}\n","// 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\";\nimport { createHttpHeaders, createPipelineRequest } from \"@azure/core-rest-pipeline\";\n\nimport type { AzurePipelinesCredentialOptions } from \"./azurePipelinesCredentialOptions\";\nimport { ClientAssertionCredential } from \"./clientAssertionCredential\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport type { PipelineResponse } from \"@azure/core-rest-pipeline\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { credentialLogger } from \"../util/logging\";\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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport type { AuthorizationCodeCredentialOptions } from \"./authorizationCodeCredentialOptions\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\n\nconst logger = credentialLogger(\"AuthorizationCodeCredential\");\n\n/**\n * Enables authentication to Microsoft Entra ID using an authorization code\n * that was obtained through the authorization code flow, described in more detail\n * in the Microsoft Entra ID documentation:\n *\n * https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow\n */\nexport class AuthorizationCodeCredential implements TokenCredential {\n private msalClient: MsalClient;\n private disableAutomaticAuthentication?: boolean;\n private authorizationCode: string;\n private redirectUri: string;\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private clientSecret?: string;\n\n /**\n * Creates an instance of AuthorizationCodeCredential with the details needed\n * to request an access token using an authentication that was obtained\n * from Microsoft Entra ID.\n *\n * It is currently necessary for the user of this credential to initiate\n * the authorization code flow to obtain an authorization code to be used\n * with this credential. A full example of this flow is provided here:\n *\n * https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/v2/manual/authorizationCodeSample.ts\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID or name.\n * 'common' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration\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 options - Options for configuring the client which makes the access token request.\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n clientSecret: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions,\n );\n /**\n * Creates an instance of AuthorizationCodeCredential with the details needed\n * to request an access token using an authentication that was obtained\n * from Microsoft Entra ID.\n *\n * It is currently necessary for the user of this credential to initiate\n * the authorization code flow to obtain an authorization code to be used\n * with this credential. A full example of this flow is provided here:\n *\n * https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/v2/manual/authorizationCodeSample.ts\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID or name.\n * 'common' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\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 options - Options for configuring the client which makes the access token request.\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions,\n );\n /**\n * @hidden\n * @internal\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n clientSecretOrAuthorizationCode: string,\n authorizationCodeOrRedirectUri: string,\n redirectUriOrOptions: string | AuthorizationCodeCredentialOptions | undefined,\n options?: AuthorizationCodeCredentialOptions,\n ) {\n checkTenantId(logger, tenantId);\n this.clientSecret = clientSecretOrAuthorizationCode;\n\n if (typeof redirectUriOrOptions === \"string\") {\n // the clientId+clientSecret constructor\n this.authorizationCode = authorizationCodeOrRedirectUri;\n this.redirectUri = redirectUriOrOptions;\n // in this case, options are good as they come\n } else {\n // clientId only\n this.authorizationCode = clientSecretOrAuthorizationCode;\n this.redirectUri = authorizationCodeOrRedirectUri as string;\n this.clientSecret = undefined;\n options = redirectUriOrOptions as AuthorizationCodeCredentialOptions;\n }\n\n // TODO: Validate tenant if provided\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n );\n newOptions.tenantId = tenantId;\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalClient.getTokenByAuthorizationCode(\n arrayScopes,\n this.redirectUri,\n this.authorizationCode,\n this.clientSecret,\n {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n },\n );\n },\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport type {\n OnBehalfOfCredentialAssertionOptions,\n OnBehalfOfCredentialCertificateOptions,\n OnBehalfOfCredentialOptions,\n OnBehalfOfCredentialSecretOptions,\n} from \"./onBehalfOfCredentialOptions\";\nimport { credentialLogger, formatError } from \"../util/logging\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport type { CertificateParts } from \"../msal/types\";\nimport type { ClientCertificatePEMCertificatePath } from \"./clientCertificateCredential\";\nimport type { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport type { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\nimport { createHash } from \"node:crypto\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { readFile } from \"node:fs/promises\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst credentialName = \"OnBehalfOfCredential\";\nconst logger = credentialLogger(credentialName);\n\n/**\n * Enables authentication to Microsoft Entra ID using the [On Behalf Of flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow).\n */\nexport class OnBehalfOfCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalClient: MsalClient;\n private sendCertificateChain?: boolean;\n private certificatePath?: string;\n private clientSecret?: string;\n private userAssertionToken: string;\n private clientAssertion?: () => Promise<string>;\n\n /**\n * Creates an instance of the {@link OnBehalfOfCredential} with the details\n * needed to authenticate against Microsoft Entra ID with path to a PEM certificate,\n * and an user assertion.\n *\n * Example using the `KeyClient` from [\\@azure/keyvault-keys](https://www.npmjs.com/package/\\@azure/keyvault-keys):\n *\n * ```ts snippet:on_behalf_of_credential_pem_example\n * import { OnBehalfOfCredential } from \"@azure/identity\";\n * import { KeyClient } from \"@azure/keyvault-keys\";\n *\n * const tokenCredential = new OnBehalfOfCredential({\n * tenantId: \"tenant-id\",\n * clientId: \"client-id\",\n * certificatePath: \"/path/to/certificate.pem\",\n * userAssertionToken: \"access-token\",\n * });\n * const client = new KeyClient(\"vault-url\", tokenCredential);\n * await client.getKey(\"key-name\");\n * ```\n *\n * @param options - Optional parameters, generally common across credentials.\n */\n constructor(\n options: OnBehalfOfCredentialCertificateOptions &\n MultiTenantTokenCredentialOptions &\n CredentialPersistenceOptions,\n );\n /**\n * Creates an instance of the {@link OnBehalfOfCredential} with the details\n * needed to authenticate against Microsoft Entra ID with a client\n * secret and an user assertion.\n *\n * Example using the `KeyClient` from [\\@azure/keyvault-keys](https://www.npmjs.com/package/\\@azure/keyvault-keys):\n *\n * ```ts snippet:on_behalf_of_credential_secret_example\n * import { OnBehalfOfCredential } from \"@azure/identity\";\n * import { KeyClient } from \"@azure/keyvault-keys\";\n *\n * const tokenCredential = new OnBehalfOfCredential({\n * tenantId: \"tenant-id\",\n * clientId: \"client-id\",\n * clientSecret: \"client-secret\",\n * userAssertionToken: \"access-token\",\n * });\n * const client = new KeyClient(\"vault-url\", tokenCredential);\n * await client.getKey(\"key-name\");\n * ```\n *\n * @param options - Optional parameters, generally common across credentials.\n */\n constructor(\n options: OnBehalfOfCredentialSecretOptions &\n MultiTenantTokenCredentialOptions &\n CredentialPersistenceOptions,\n );\n\n /**\n * Creates an instance of the {@link OnBehalfOfCredential} with the details\n * needed to authenticate against Microsoft Entra ID with a client `getAssertion`\n * and an user assertion.\n *\n * Example using the `KeyClient` from [\\@azure/keyvault-keys](https://www.npmjs.com/package/\\@azure/keyvault-keys):\n *\n * ```ts snippet:on_behalf_of_credential_assertion_example\n * import { OnBehalfOfCredential } from \"@azure/identity\";\n * import { KeyClient } from \"@azure/keyvault-keys\";\n *\n * const tokenCredential = new OnBehalfOfCredential({\n * tenantId: \"tenant-id\",\n * clientId: \"client-id\",\n * getAssertion: () => {\n * return Promise.resolve(\"my-jwt\");\n * },\n * userAssertionToken: \"access-token\",\n * });\n * const client = new KeyClient(\"vault-url\", tokenCredential);\n * await client.getKey(\"key-name\");\n * ```\n *\n * @param options - Optional parameters, generally common across credentials.\n */\n constructor(\n options: OnBehalfOfCredentialAssertionOptions &\n MultiTenantTokenCredentialOptions &\n CredentialPersistenceOptions,\n );\n\n constructor(options: OnBehalfOfCredentialOptions) {\n const { clientSecret } = options as OnBehalfOfCredentialSecretOptions;\n const { certificatePath, sendCertificateChain } =\n options as OnBehalfOfCredentialCertificateOptions;\n const { getAssertion } = options as OnBehalfOfCredentialAssertionOptions;\n const {\n tenantId,\n clientId,\n userAssertionToken,\n additionallyAllowedTenants: additionallyAllowedTenantIds,\n } = options;\n if (!tenantId) {\n throw new CredentialUnavailableError(\n `${credentialName}: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n\n if (!clientId) {\n throw new CredentialUnavailableError(\n `${credentialName}: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n\n if (!clientSecret && !certificatePath && !getAssertion) {\n throw new CredentialUnavailableError(\n `${credentialName}: You must provide one of clientSecret, certificatePath, or a getAssertion callback but none were provided. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n\n if (!userAssertionToken) {\n throw new CredentialUnavailableError(\n `${credentialName}: userAssertionToken is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`,\n );\n }\n this.certificatePath = certificatePath;\n this.clientSecret = clientSecret;\n this.userAssertionToken = userAssertionToken;\n this.sendCertificateChain = sendCertificateChain;\n this.clientAssertion = getAssertion;\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n additionallyAllowedTenantIds,\n );\n\n this.msalClient = createMsalClient(clientId, this.tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: 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} 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 the underlying network requests.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = ensureScopes(scopes);\n if (this.certificatePath) {\n const clientCertificate = await this.buildClientCertificate(this.certificatePath);\n\n return this.msalClient.getTokenOnBehalfOf(\n arrayScopes,\n this.userAssertionToken,\n clientCertificate,\n newOptions,\n );\n } else if (this.clientSecret) {\n return this.msalClient.getTokenOnBehalfOf(\n arrayScopes,\n this.userAssertionToken,\n this.clientSecret,\n options,\n );\n } else if (this.clientAssertion) {\n return this.msalClient.getTokenOnBehalfOf(\n arrayScopes,\n this.userAssertionToken,\n this.clientAssertion,\n options,\n );\n } else {\n // this is an invalid scenario and is a bug, as the constructor should have thrown an error if neither clientSecret nor certificatePath nor clientAssertion were provided\n throw new Error(\n \"Expected either clientSecret or certificatePath or clientAssertion to be defined.\",\n );\n }\n });\n }\n\n private async buildClientCertificate(certificatePath: string): Promise<CertificateParts> {\n try {\n const parts = await this.parseCertificate({ certificatePath }, this.sendCertificateChain);\n return {\n thumbprint: parts.thumbprint,\n privateKey: parts.certificateContents,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n logger.info(formatError(\"\", error));\n throw error;\n }\n }\n\n private async parseCertificate(\n configuration: ClientCertificatePEMCertificatePath,\n sendCertificateChain?: boolean,\n ): Promise<Omit<CertificateParts, \"privateKey\"> & { certificateContents: string }> {\n const certificatePath = configuration.certificatePath;\n const certificateContents = await readFile(certificatePath, \"utf8\");\n const x5c = sendCertificateChain ? certificateContents : undefined;\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n const thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return {\n certificateContents,\n thumbprint,\n x5c,\n };\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { TokenCredential, TracingContext } from \"@azure/core-auth\";\nimport {\n bearerTokenAuthenticationPolicy,\n createEmptyPipeline,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\n\n/**\n * The options to configure the token provider.\n */\nexport interface GetBearerTokenProviderOptions {\n /** The abort signal to abort requests to get tokens */\n abortSignal?: AbortSignal;\n /** The tracing options for the requests to get tokens */\n tracingOptions?: {\n /**\n * Tracing Context for the current request to get a token.\n */\n tracingContext?: TracingContext;\n };\n}\n\n/**\n * Returns a callback that provides a bearer token.\n * For example, the bearer token can be used to authenticate a request as follows:\n * ```ts snippet:token_provider_example\n * import { DefaultAzureCredential, getBearerTokenProvider } from \"@azure/identity\";\n * import { createPipelineRequest } from \"@azure/core-rest-pipeline\";\n *\n * const credential = new DefaultAzureCredential();\n * const scope = \"https://cognitiveservices.azure.com/.default\";\n * const getAccessToken = getBearerTokenProvider(credential, scope);\n * const token = await getAccessToken();\n * // usage\n * const request = createPipelineRequest({ url: \"https://example.com\" });\n * request.headers.set(\"Authorization\", `Bearer ${token}`);\n * ```\n *\n * @param credential - The credential used to authenticate the request.\n * @param scopes - The scopes required for the bearer token.\n * @param options - Options to configure the token provider.\n * @returns a callback that provides a bearer token.\n */\nexport function getBearerTokenProvider(\n credential: TokenCredential,\n scopes: string | string[],\n options?: GetBearerTokenProviderOptions,\n): () => Promise<string> {\n const { abortSignal, tracingOptions } = options || {};\n const pipeline = createEmptyPipeline();\n pipeline.addPolicy(bearerTokenAuthenticationPolicy({ credential, scopes }));\n async function getRefreshedToken(): Promise<string> {\n // Create a pipeline with just the bearer token policy\n // and run a dummy request through it to get the token\n const res = await pipeline.sendRequest(\n {\n sendRequest: (request) =>\n Promise.resolve({\n request,\n status: 200,\n headers: request.headers,\n }),\n },\n createPipelineRequest({\n url: \"https://example.com\",\n abortSignal,\n tracingOptions,\n }),\n );\n const accessToken = res.headers.get(\"authorization\")?.split(\" \")[1];\n if (!accessToken) {\n throw new Error(\"Failed to get access token\");\n }\n return accessToken;\n }\n return getRefreshedToken;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport * from \"./plugins/consumer\";\n\nexport { IdentityPlugin } from \"./plugins/provider\";\n\nimport type { TokenCredential } from \"@azure/core-auth\";\nimport { DefaultAzureCredential } from \"./credentials/defaultAzureCredential\";\n\nexport {\n AuthenticationError,\n ErrorResponse,\n AggregateAuthenticationError,\n AuthenticationErrorName,\n AggregateAuthenticationErrorName,\n CredentialUnavailableError,\n CredentialUnavailableErrorName,\n AuthenticationRequiredError,\n AuthenticationRequiredErrorOptions,\n} from \"./errors\";\n\nexport { AuthenticationRecord } from \"./msal/types\";\nexport { serializeAuthenticationRecord, deserializeAuthenticationRecord } from \"./msal/utils\";\nexport { TokenCredentialOptions } from \"./tokenCredentialOptions\";\nexport { MultiTenantTokenCredentialOptions } from \"./credentials/multiTenantTokenCredentialOptions\";\nexport { AuthorityValidationOptions } from \"./credentials/authorityValidationOptions\";\n// TODO: Export again once we're ready to release this feature.\n// export { RegionalAuthority } from \"./regionalAuthority\";\n\nexport { BrokerAuthOptions } from \"./credentials/brokerAuthOptions\";\nexport {\n BrokerOptions,\n BrokerEnabledOptions,\n BrokerDisabledOptions,\n} from \"./msal/nodeFlows/brokerOptions\";\nexport { InteractiveCredentialOptions } from \"./credentials/interactiveCredentialOptions\";\n\nexport { ChainedTokenCredential } from \"./credentials/chainedTokenCredential\";\n\nexport { ClientSecretCredential } from \"./credentials/clientSecretCredential\";\nexport { ClientSecretCredentialOptions } from \"./credentials/clientSecretCredentialOptions\";\n\nexport { DefaultAzureCredential } from \"./credentials/defaultAzureCredential\";\nexport {\n DefaultAzureCredentialOptions,\n DefaultAzureCredentialClientIdOptions,\n DefaultAzureCredentialResourceIdOptions,\n} from \"./credentials/defaultAzureCredentialOptions\";\n\nexport { EnvironmentCredential } from \"./credentials/environmentCredential\";\nexport { EnvironmentCredentialOptions } from \"./credentials/environmentCredentialOptions\";\n\nexport {\n ClientCertificateCredential,\n ClientCertificateCredentialPEMConfiguration,\n ClientCertificatePEMCertificatePath,\n ClientCertificatePEMCertificate,\n} from \"./credentials/clientCertificateCredential\";\nexport { ClientCertificateCredentialOptions } from \"./credentials/clientCertificateCredentialOptions\";\nexport { ClientAssertionCredential } from \"./credentials/clientAssertionCredential\";\nexport { ClientAssertionCredentialOptions } from \"./credentials/clientAssertionCredentialOptions\";\nexport { CredentialPersistenceOptions } from \"./credentials/credentialPersistenceOptions\";\nexport { AzureCliCredential } from \"./credentials/azureCliCredential\";\nexport { AzureCliCredentialOptions } from \"./credentials/azureCliCredentialOptions\";\nexport { AzureDeveloperCliCredential } from \"./credentials/azureDeveloperCliCredential\";\nexport { AzureDeveloperCliCredentialOptions } from \"./credentials/azureDeveloperCliCredentialOptions\";\nexport { InteractiveBrowserCredential } from \"./credentials/interactiveBrowserCredential\";\nexport {\n InteractiveBrowserCredentialNodeOptions,\n InteractiveBrowserCredentialInBrowserOptions,\n BrowserLoginStyle,\n} from \"./credentials/interactiveBrowserCredentialOptions\";\nexport {\n ManagedIdentityCredential,\n ManagedIdentityCredentialClientIdOptions,\n ManagedIdentityCredentialResourceIdOptions,\n ManagedIdentityCredentialObjectIdOptions,\n} from \"./credentials/managedIdentityCredential\";\nexport { DeviceCodeCredential } from \"./credentials/deviceCodeCredential\";\nexport {\n DeviceCodePromptCallback,\n DeviceCodeInfo,\n} from \"./credentials/deviceCodeCredentialOptions\";\nexport { DeviceCodeCredentialOptions } from \"./credentials/deviceCodeCredentialOptions\";\nexport { AzurePipelinesCredential as AzurePipelinesCredential } from \"./credentials/azurePipelinesCredential\";\nexport { AzurePipelinesCredentialOptions as AzurePipelinesCredentialOptions } from \"./credentials/azurePipelinesCredentialOptions\";\nexport { AuthorizationCodeCredential } from \"./credentials/authorizationCodeCredential\";\nexport { AuthorizationCodeCredentialOptions } from \"./credentials/authorizationCodeCredentialOptions\";\nexport { AzurePowerShellCredential } from \"./credentials/azurePowerShellCredential\";\nexport { AzurePowerShellCredentialOptions } from \"./credentials/azurePowerShellCredentialOptions\";\nexport {\n OnBehalfOfCredentialOptions,\n OnBehalfOfCredentialSecretOptions,\n OnBehalfOfCredentialCertificateOptions,\n OnBehalfOfCredentialAssertionOptions,\n} from \"./credentials/onBehalfOfCredentialOptions\";\nexport { UsernamePasswordCredential } from \"./credentials/usernamePasswordCredential\";\nexport { UsernamePasswordCredentialOptions } from \"./credentials/usernamePasswordCredentialOptions\";\nexport { VisualStudioCodeCredential } from \"./credentials/visualStudioCodeCredential\";\nexport { VisualStudioCodeCredentialOptions } from \"./credentials/visualStudioCodeCredentialOptions\";\nexport { OnBehalfOfCredential } from \"./credentials/onBehalfOfCredential\";\nexport { WorkloadIdentityCredential } from \"./credentials/workloadIdentityCredential\";\nexport { WorkloadIdentityCredentialOptions } from \"./credentials/workloadIdentityCredentialOptions\";\nexport { BrowserCustomizationOptions } from \"./credentials/browserCustomizationOptions\";\nexport { TokenCachePersistenceOptions } from \"./msal/nodeFlows/tokenCachePersistenceOptions\";\n\nexport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-auth\";\nexport { logger } from \"./util/logging\";\n\nexport { AzureAuthorityHosts } from \"./constants\";\n\n/**\n * Returns a new instance of the {@link DefaultAzureCredential}.\n */\nexport function getDefaultAzureCredential(): TokenCredential {\n return new DefaultAzureCredential();\n}\n\nexport { getBearerTokenProvider, GetBearerTokenProviderOptions } from \"./tokenProvider\";\n"],"names":["AzureAuthorityHosts","logger","createClientLogger","createTracingClient","isNode","ServiceClient","createPipelineRequest","createHttpHeaders","isNodeLike","msalCommon","AbortError","msiName","isError","delay","retryPolicy","calculateRetryDelay","getLogLevel","msal","credentialName","readFile","ManagedIdentityApplication","childProcess","createPrivateKey","createHash","createEmptyPipeline","bearerTokenAuthenticationPolicy"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAEA;;AAEG;AACI,MAAM,WAAW,GAAG,OAAO;AAElC;;;AAGG;AACH;AACA;AACA;AACO,MAAM,uBAAuB,GAAG,sCAAsC;AAE7E;;;AAGG;AACI,MAAM,eAAe,GAAG,QAAQ;AAEvC;;AAEG;AACSA;AAAZ,CAAA,UAAY,mBAAmB,EAAA;AAC7B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