@azure/identity 4.14.0-beta.4 → 4.14.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/browser/constants.d.ts +1 -1
  2. package/dist/browser/constants.js +1 -1
  3. package/dist/browser/constants.js.map +1 -1
  4. package/dist/browser/credentials/clientCertificateCredentialModels.d.ts.map +1 -1
  5. package/dist/browser/credentials/clientCertificateCredentialModels.js.map +1 -1
  6. package/dist/commonjs/constants.d.ts +1 -1
  7. package/dist/commonjs/constants.js +1 -1
  8. package/dist/commonjs/constants.js.map +1 -1
  9. package/dist/commonjs/credentials/azureCliCredential.d.ts.map +1 -1
  10. package/dist/commonjs/credentials/azureCliCredential.js +19 -36
  11. package/dist/commonjs/credentials/azureCliCredential.js.map +3 -3
  12. package/dist/commonjs/credentials/azureDeveloperCliCredential.d.ts.map +1 -1
  13. package/dist/commonjs/credentials/azureDeveloperCliCredential.js +16 -40
  14. package/dist/commonjs/credentials/azureDeveloperCliCredential.js.map +3 -3
  15. package/dist/commonjs/credentials/azurePowerShellCredential.d.ts +10 -0
  16. package/dist/commonjs/credentials/azurePowerShellCredential.d.ts.map +1 -1
  17. package/dist/commonjs/credentials/azurePowerShellCredential.js +36 -11
  18. package/dist/commonjs/credentials/azurePowerShellCredential.js.map +2 -2
  19. package/dist/commonjs/credentials/clientCertificateCredentialModels.d.ts.map +1 -1
  20. package/dist/commonjs/credentials/clientCertificateCredentialModels.js.map +1 -1
  21. package/dist/commonjs/credentials/environmentCredential.d.ts.map +1 -1
  22. package/dist/commonjs/credentials/environmentCredential.js.map +2 -2
  23. package/dist/commonjs/msal/nodeFlows/msalPlugins.d.ts.map +1 -1
  24. package/dist/commonjs/msal/nodeFlows/msalPlugins.js.map +2 -2
  25. package/dist/commonjs/tsdoc-metadata.json +1 -1
  26. package/dist/commonjs/util/processUtils.d.ts +14 -3
  27. package/dist/commonjs/util/processUtils.d.ts.map +1 -1
  28. package/dist/commonjs/util/processUtils.js +35 -28
  29. package/dist/commonjs/util/processUtils.js.map +3 -3
  30. package/dist/esm/constants.d.ts +1 -1
  31. package/dist/esm/constants.js +1 -1
  32. package/dist/esm/constants.js.map +1 -1
  33. package/dist/esm/credentials/azureCliCredential.d.ts.map +1 -1
  34. package/dist/esm/credentials/azureCliCredential.js +21 -24
  35. package/dist/esm/credentials/azureCliCredential.js.map +1 -1
  36. package/dist/esm/credentials/azureDeveloperCliCredential.d.ts.map +1 -1
  37. package/dist/esm/credentials/azureDeveloperCliCredential.js +16 -24
  38. package/dist/esm/credentials/azureDeveloperCliCredential.js.map +1 -1
  39. package/dist/esm/credentials/azurePowerShellCredential.d.ts +10 -0
  40. package/dist/esm/credentials/azurePowerShellCredential.d.ts.map +1 -1
  41. package/dist/esm/credentials/azurePowerShellCredential.js +26 -6
  42. package/dist/esm/credentials/azurePowerShellCredential.js.map +1 -1
  43. package/dist/esm/credentials/clientCertificateCredentialModels.d.ts.map +1 -1
  44. package/dist/esm/credentials/clientCertificateCredentialModels.js.map +1 -1
  45. package/dist/esm/credentials/environmentCredential.d.ts.map +1 -1
  46. package/dist/esm/credentials/environmentCredential.js.map +1 -1
  47. package/dist/esm/msal/nodeFlows/msalPlugins.d.ts.map +1 -1
  48. package/dist/esm/msal/nodeFlows/msalPlugins.js.map +1 -1
  49. package/dist/esm/util/processUtils.d.ts +14 -3
  50. package/dist/esm/util/processUtils.d.ts.map +1 -1
  51. package/dist/esm/util/processUtils.js +36 -19
  52. package/dist/esm/util/processUtils.js.map +1 -1
  53. package/dist/workerd/constants.d.ts +1 -1
  54. package/dist/workerd/constants.js +1 -1
  55. package/dist/workerd/constants.js.map +1 -1
  56. package/dist/workerd/credentials/azureCliCredential.d.ts.map +1 -1
  57. package/dist/workerd/credentials/azureCliCredential.js +21 -24
  58. package/dist/workerd/credentials/azureCliCredential.js.map +1 -1
  59. package/dist/workerd/credentials/azureDeveloperCliCredential.d.ts.map +1 -1
  60. package/dist/workerd/credentials/azureDeveloperCliCredential.js +16 -24
  61. package/dist/workerd/credentials/azureDeveloperCliCredential.js.map +1 -1
  62. package/dist/workerd/credentials/azurePowerShellCredential.d.ts +10 -0
  63. package/dist/workerd/credentials/azurePowerShellCredential.d.ts.map +1 -1
  64. package/dist/workerd/credentials/azurePowerShellCredential.js +26 -6
  65. package/dist/workerd/credentials/azurePowerShellCredential.js.map +1 -1
  66. package/dist/workerd/credentials/clientCertificateCredentialModels.d.ts.map +1 -1
  67. package/dist/workerd/credentials/clientCertificateCredentialModels.js.map +1 -1
  68. package/dist/workerd/credentials/environmentCredential.d.ts.map +1 -1
  69. package/dist/workerd/credentials/environmentCredential.js.map +1 -1
  70. package/dist/workerd/msal/nodeFlows/msalPlugins.d.ts.map +1 -1
  71. package/dist/workerd/msal/nodeFlows/msalPlugins.js.map +1 -1
  72. package/dist/workerd/util/processUtils.d.ts +14 -3
  73. package/dist/workerd/util/processUtils.d.ts.map +1 -1
  74. package/dist/workerd/util/processUtils.js +36 -19
  75. package/dist/workerd/util/processUtils.js.map +1 -1
  76. package/package.json +13 -12
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/credentials/azurePowerShellCredential.ts"],
4
- "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils.js\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging.js\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils.js\";\n\nimport type { AzurePowerShellCredentialOptions } from \"./azurePowerShellCredentialOptions.js\";\nimport { CredentialUnavailableError } from \"../errors.js\";\nimport { processUtils } from \"../util/processUtils.js\";\nimport { tracingClient } from \"../util/tracing.js\";\nimport { uint8ArrayToString, stringToUint8Array } from \"@azure/core-util\";\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 claim:\n \"This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:\",\n troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`,\n};\n\n// PowerShell Azure User not logged in error check.\nconst isLoginError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(`(.*)${powerShellErrors.login}(.*)`);\n\n// Az Module not Installed in Azure PowerShell check.\nconst isNotInstalledError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(powerShellErrors.installed);\n\n/**\n * The PowerShell commands to be tried, in order.\n *\n * @internal\n */\nexport const commandStack = [formatCommand(\"pwsh\")];\n\nif (isWindows) {\n commandStack.push(formatCommand(\"powershell\"));\n}\n\n/**\n * This credential will use the currently logged-in user information from the\n * Azure PowerShell module. To do so, it will read the user access token and\n * expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}`\n */\nexport class AzurePowerShellCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzurePowerShellCredential}.\n *\n * To use this credential:\n * - Install the Azure Az PowerShell module with:\n * `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`.\n * - You have already logged in to Azure PowerShell using the command\n * `Connect-AzAccount` from the command line.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzurePowerShellCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Gets the access token from Azure PowerShell\n * @param resource - The resource to use when getting the token\n */\n private async getAzurePowerShellAccessToken(\n resource: string,\n tenantId?: string,\n timeout?: number,\n ): Promise<{ Token: string; ExpiresOn: string }> {\n // Clone the stack to avoid mutating it while iterating\n for (const powerShellCommand of [...commandStack]) {\n try {\n await runCommands([[powerShellCommand, \"/?\"]], timeout);\n } catch (e: any) {\n // Remove this credential from the original stack so that we don't try it again.\n commandStack.shift();\n continue;\n }\n\n const results = await runCommands([\n [\n 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' -and $m.Version -lt [version]'5.0.0'\n\n $params = @{\n ResourceUrl = \"${resource}\"\n }\n\n if ($tenantId.Length -gt 0) {\n $params[\"TenantId\"] = $tenantId\n }\n\n if ($useSecureString) {\n $params[\"AsSecureString\"] = $true\n }\n\n $token = Get-AzAccessToken @params\n\n $result = New-Object -TypeName PSObject\n $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn\n\n if ($token.Token -is [System.Security.SecureString]) {\n if ($PSVersionTable.PSVersion.Major -lt 7) {\n $ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($token.Token)\n try {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value ([System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr))\n }\n finally {\n [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)\n }\n }\n else {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value ($token.Token | ConvertFrom-SecureString -AsPlainText)\n }\n }\n else {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token\n }\n\n Write-Output (ConvertTo-Json $result)\n `,\n ],\n ]);\n\n const result = results[0];\n return parseJsonToken(result);\n }\n throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n\n const claimsValue = options.claims;\n if (claimsValue && claimsValue.trim()) {\n const encodedClaims = uint8ArrayToString(\n stringToUint8Array(claimsValue, \"utf-8\"),\n \"base64\",\n );\n let loginCmd = `Connect-AzAccount -ClaimsChallenge ${encodedClaims}`;\n\n const tenantIdFromOptions = options.tenantId;\n if (tenantIdFromOptions) {\n loginCmd += ` -Tenant ${tenantIdFromOptions}`;\n }\n const error = new CredentialUnavailableError(\n `${powerShellPublicErrorMessages.claim} ${loginCmd}`,\n );\n\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n try {\n ensureValidScopeForDevTimeCreds(scope, logger);\n logger.getToken.info(`Using the scope ${scope}`);\n const resource = getScopeResource(scope);\n const response = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.Token,\n expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n if (isNotInstalledError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);\n logger.getToken.info(formatError(scope, error));\n throw error;\n } else if (isLoginError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n const error = new CredentialUnavailableError(\n `${err}. ${powerShellPublicErrorMessages.troubleshoot}`,\n );\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n });\n }\n}\n\n/**\n *\n * @internal\n */\nexport async function parseJsonToken(\n result: string,\n): Promise<{ Token: string; ExpiresOn: string }> {\n const jsonRegex = /{[^{}]*}/g;\n const matches = result.match(jsonRegex);\n let resultWithoutToken = result;\n if (matches) {\n try {\n for (const item of matches) {\n try {\n const jsonContent = JSON.parse(item);\n if (jsonContent?.Token) {\n resultWithoutToken = resultWithoutToken.replace(item, \"\");\n if (resultWithoutToken) {\n logger.getToken.warning(resultWithoutToken);\n }\n return jsonContent;\n }\n } catch (e) {\n continue;\n }\n }\n } catch (e: any) {\n throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);\n }\n }\n throw new Error(`No access token found in the output. Received output: ${result}`);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,2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+C;AAC/C,QAAM,YAAY;AAClB,QAAM,UAAU,OAAO,MAAM,SAAS;AACtC,MAAI,qBAAqB;AACzB,MAAI,SAAS;AACX,QAAI;AACF,iBAAW,QAAQ,SAAS;AAC1B,YAAI;AACF,gBAAM,cAAc,KAAK,MAAM,IAAI;AACnC,cAAI,aAAa,OAAO;AACtB,iCAAqB,mBAAmB,QAAQ,MAAM,EAAE;AACxD,gBAAI,oBAAoB;AACtB,qBAAO,SAAS,QAAQ,kBAAkB;AAAA,YAC5C;AACA,mBAAO;AAAA,UACT;AAAA,QACF,SAAS,GAAG;AACV;AAAA,QACF;AAAA,MACF;AAAA,IACF,SAAS,GAAQ;AACf,YAAM,IAAI,MAAM,8DAA8D,MAAM,EAAE;AAAA,IACxF;AAAA,EACF;AACA,QAAM,IAAI,MAAM,yDAAyD,MAAM,EAAE;AACnF;",
4
+ "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils.js\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging.js\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils.js\";\n\nimport type { AzurePowerShellCredentialOptions } from \"./azurePowerShellCredentialOptions.js\";\nimport { CredentialUnavailableError } from \"../errors.js\";\nimport { processUtils } from \"../util/processUtils.js\";\nimport { tracingClient } from \"../util/tracing.js\";\nimport { uint8ArrayToString, stringToUint8Array } from \"@azure/core-util\";\n\nconst logger = credentialLogger(\"AzurePowerShellCredential\");\n\nconst isWindows = process.platform === \"win32\";\nconst powerShellResourceEnvironmentVariable = \"AZURE_IDENTITY_POWERSHELL_RESOURCE\";\nconst powerShellTenantEnvironmentVariable = \"AZURE_IDENTITY_POWERSHELL_TENANT_ID\";\nconst powerShellPrivateEnvironmentVariables = new Set(\n [powerShellResourceEnvironmentVariable, powerShellTenantEnvironmentVariable].map((name) =>\n name.toLowerCase(),\n ),\n);\n\n/**\n * Creates the child environment used to pass private values to PowerShell.\n *\n * @param resource - The resource passed to PowerShell.\n * @param tenantId - The optional tenant ID passed to PowerShell.\n * @param environment - The environment to copy.\n * @returns A child environment containing canonical private variable names.\n * @internal\n */\nexport function createPowerShellEnvironment(\n resource: string,\n tenantId: string | undefined,\n environment: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n const childEnvironment = Object.fromEntries(\n Object.entries(environment).filter(\n ([name]) => !powerShellPrivateEnvironmentVariables.has(name.toLowerCase()),\n ),\n );\n childEnvironment[powerShellResourceEnvironmentVariable] = resource;\n childEnvironment[powerShellTenantEnvironmentVariable] = tenantId ?? \"\";\n return childEnvironment;\n}\n\n/**\n * Returns a platform-appropriate command name by appending \".exe\" on Windows.\n *\n * @internal\n */\nexport function formatCommand(commandName: string): string {\n if (isWindows) {\n return `${commandName}.exe`;\n } else {\n return commandName;\n }\n}\n\n/**\n * Receives a list of commands to run, executes them, then returns the outputs.\n * If anything fails, an error is thrown.\n * @internal\n */\nasync function runCommands(\n commands: string[][],\n timeout?: number,\n env?: NodeJS.ProcessEnv,\n): Promise<string[]> {\n const results: string[] = [];\n\n for (const command of commands) {\n const [file, ...parameters] = command;\n const result = await processUtils.execFile(file, parameters, {\n encoding: \"utf8\",\n env,\n timeout,\n });\n\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Known PowerShell errors\n * @internal\n */\nexport const powerShellErrors = {\n login: \"Run Connect-AzAccount to login\",\n installed:\n \"The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory\",\n};\n\n/**\n * Messages to use when throwing in this credential.\n * @internal\n */\nexport const powerShellPublicErrorMessages = {\n login:\n \"Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.\",\n installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: \"Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force\".`,\n claim:\n \"This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:\",\n troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`,\n};\n\n// PowerShell Azure User not logged in error check.\nconst isLoginError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(`(.*)${powerShellErrors.login}(.*)`);\n\n// Az Module not Installed in Azure PowerShell check.\nconst isNotInstalledError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(powerShellErrors.installed);\n\n/**\n * The PowerShell commands to be tried, in order.\n *\n * @internal\n */\nexport const commandStack = [formatCommand(\"pwsh\")];\n\nif (isWindows) {\n commandStack.push(formatCommand(\"powershell\"));\n}\n\n/**\n * This credential will use the currently logged-in user information from the\n * Azure PowerShell module. To do so, it will read the user access token and\n * expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}`\n */\nexport class AzurePowerShellCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzurePowerShellCredential}.\n *\n * To use this credential:\n * - Install the Azure Az PowerShell module with:\n * `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`.\n * - You have already logged in to Azure PowerShell using the command\n * `Connect-AzAccount` from the command line.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzurePowerShellCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Gets the access token from Azure PowerShell\n * @param resource - The resource to use when getting the token\n */\n private async getAzurePowerShellAccessToken(\n resource: string,\n tenantId?: string,\n timeout?: number,\n ): Promise<{ Token: string; ExpiresOn: string }> {\n // Clone the stack to avoid mutating it while iterating\n for (const powerShellCommand of [...commandStack]) {\n try {\n await runCommands([[powerShellCommand, \"/?\"]], timeout);\n } catch (e: any) {\n // Remove this credential from the original stack so that we don't try it again.\n commandStack.shift();\n continue;\n }\n\n const results = await runCommands(\n [\n [\n powerShellCommand,\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `\n $tenantId = $env:${powerShellTenantEnvironmentVariable}\n $resource = $env:${powerShellResourceEnvironmentVariable}\n $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru\n $useSecureString = $m.Version -ge [version]'2.17.0' -and $m.Version -lt [version]'5.0.0'\n\n $params = @{\n ResourceUrl = $resource\n }\n\n if ($tenantId.Length -gt 0) {\n $params[\"TenantId\"] = $tenantId\n }\n\n if ($useSecureString) {\n $params[\"AsSecureString\"] = $true\n }\n\n $token = Get-AzAccessToken @params\n\n $result = New-Object -TypeName PSObject\n $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn\n\n if ($token.Token -is [System.Security.SecureString]) {\n if ($PSVersionTable.PSVersion.Major -lt 7) {\n $ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($token.Token)\n try {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value ([System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr))\n }\n finally {\n [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)\n }\n }\n else {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value ($token.Token | ConvertFrom-SecureString -AsPlainText)\n }\n }\n else {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token\n }\n\n Write-Output (ConvertTo-Json $result)\n `,\n ],\n ],\n timeout,\n createPowerShellEnvironment(resource, tenantId),\n );\n\n const result = results[0];\n return parseJsonToken(result);\n }\n throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n\n const claimsValue = options.claims;\n if (claimsValue && claimsValue.trim()) {\n const encodedClaims = uint8ArrayToString(\n stringToUint8Array(claimsValue, \"utf-8\"),\n \"base64\",\n );\n let loginCmd = `Connect-AzAccount -ClaimsChallenge ${encodedClaims}`;\n\n const tenantIdFromOptions = options.tenantId;\n if (tenantIdFromOptions) {\n loginCmd += ` -Tenant ${tenantIdFromOptions}`;\n }\n const error = new CredentialUnavailableError(\n `${powerShellPublicErrorMessages.claim} ${loginCmd}`,\n );\n\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n try {\n ensureValidScopeForDevTimeCreds(scope, logger);\n logger.getToken.info(`Using the scope ${scope}`);\n const resource = getScopeResource(scope);\n const response = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.Token,\n expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n if (isNotInstalledError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);\n logger.getToken.info(formatError(scope, error));\n throw error;\n } else if (isLoginError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n const error = new CredentialUnavailableError(\n `${err}. ${powerShellPublicErrorMessages.troubleshoot}`,\n );\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n });\n }\n}\n\n/**\n *\n * @internal\n */\nexport async function parseJsonToken(\n result: string,\n): Promise<{ Token: string; ExpiresOn: string }> {\n const jsonRegex = /{[^{}]*}/g;\n const matches = result.match(jsonRegex);\n let resultWithoutToken = result;\n if (matches) {\n try {\n for (const item of matches) {\n try {\n const jsonContent = JSON.parse(item);\n if (jsonContent?.Token) {\n resultWithoutToken = resultWithoutToken.replace(item, \"\");\n if (resultWithoutToken) {\n logger.getToken.warning(resultWithoutToken);\n }\n return jsonContent;\n }\n } catch (e) {\n continue;\n }\n }\n } catch (e: any) {\n throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);\n }\n }\n throw new Error(`No access token found in the output. Received output: ${result}`);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,2BAIO;AACP,qBAA6D;AAC7D,wBAAkE;AAGlE,oBAA2C;AAC3C,0BAA6B;AAC7B,qBAA8B;AAC9B,uBAAuD;AAEvD,MAAM,aAAS,iCAAiB,2BAA2B;AAE3D,MAAM,YAAY,QAAQ,aAAa;AACvC,MAAM,wCAAwC;AAC9C,MAAM,sCAAsC;AAC5C,MAAM,wCAAwC,IAAI;AAAA,EAChD,CAAC,uCAAuC,mCAAmC,EAAE;AAAA,IAAI,CAAC,SAChF,KAAK,YAAY;AAAA,EACnB;AACF;AAWO,SAAS,4BACd,UACA,UACA,cAAiC,QAAQ,KACtB;AACnB,QAAM,mBAAmB,OAAO;AAAA,IAC9B,OAAO,QAAQ,WAAW,EAAE;AAAA,MAC1B,CAAC,CAAC,IAAI,MAAM,CAAC,sCAAsC,IAAI,KAAK,YAAY,CAAC;AAAA,IAC3E;AAAA,EACF;AACA,mBAAiB,qCAAqC,IAAI;AAC1D,mBAAiB,mCAAmC,IAAI,YAAY;AACpE,SAAO;AACT;AAOO,SAAS,cAAc,aAA6B;AACzD,MAAI,WAAW;AACb,WAAO,GAAG,WAAW;AA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KAAK,MAAM,IAAI;AACnC,cAAI,aAAa,OAAO;AACtB,iCAAqB,mBAAmB,QAAQ,MAAM,EAAE;AACxD,gBAAI,oBAAoB;AACtB,qBAAO,SAAS,QAAQ,kBAAkB;AAAA,YAC5C;AACA,mBAAO;AAAA,UACT;AAAA,QACF,SAAS,GAAG;AACV;AAAA,QACF;AAAA,MACF;AAAA,IACF,SAAS,GAAQ;AACf,YAAM,IAAI,MAAM,8DAA8D,MAAM,EAAE;AAAA,IACxF;AAAA,EACF;AACA,QAAM,IAAI,MAAM,yDAAyD,MAAM,EAAE;AACnF;",
6
6
  "names": ["error"]
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"clientCertificateCredentialModels.d.ts","sourceRoot":"","sources":["../../../src/credentials/clientCertificateCredentialModels.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,WAAW,+BAA+B;IAC9C;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AACD;;GAEG;AACH,MAAM,WAAW,mCAAmC;IAClD;;OAEG;IACH,eAAe,EAAE,MAAM,CAAC;IAExB;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AACD;;GAEG;AACH,MAAM,MAAM,2CAA2C,GACnD,+BAA+B,GAC/B,mCAAmC,CAAC"}
1
+ {"version":3,"file":"clientCertificateCredentialModels.d.ts","sourceRoot":"","sources":["../../../src/credentials/clientCertificateCredentialModels.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,WAAW,+BAA+B;IAC9C;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AACD;;GAEG;AACH,MAAM,WAAW,mCAAmC;IAClD;;OAEG;IACH,eAAe,EAAE,MAAM,CAAC;IAExB;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AACD;;GAEG;AACH,MAAM,MAAM,2CAA2C,GACrD,+BAA+B,GAAG,mCAAmC,CAAC"}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/credentials/clientCertificateCredentialModels.ts"],
4
- "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\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 * Ensure that certificate is in PEM format and contains both the public and private keys.\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"],
4
+ "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\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 * Ensure that certificate is in PEM format and contains both the public and private keys.\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 | ClientCertificatePEMCertificatePath;\n"],
5
5
  "mappings": ";;;;;;;;;;;;;AAAA;AAAA;",
6
6
  "names": []
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"environmentCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/environmentCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAMtF,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAKtF;;;;;;GAMG;AACH,eAAO,MAAM,gCAAgC,UAU5C,CAAC;AAUF,wBAAgB,uBAAuB,IAAI,OAAO,CASjD;AAED;;GAEG;AACH,qBAAa,qBAAsB,YAAW,eAAe;IAC3D,OAAO,CAAC,WAAW,CAAC,CAGuB;IAC3C;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;gBACS,OAAO,CAAC,EAAE,4BAA4B;IA6DlD;;;;;OAKG;IACG,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,WAAW,CAAC;CAqB/F"}
1
+ {"version":3,"file":"environmentCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/environmentCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAMtF,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAKtF;;;;;;GAMG;AACH,eAAO,MAAM,gCAAgC,UAU5C,CAAC;AAUF,wBAAgB,uBAAuB,IAAI,OAAO,CASjD;AAED;;GAEG;AACH,qBAAa,qBAAsB,YAAW,eAAe;IAC3D,OAAO,CAAC,WAAW,CAAC,CAC4E;IAChG;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;gBACS,OAAO,CAAC,EAAE,4BAA4B;IA6DlD;;;;;OAKG;IACG,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,WAAW,CAAC;CAqB/F"}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/credentials/environmentCredential.ts"],
4
- "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../errors.js\";\nimport { credentialLogger, formatError, formatSuccess, processEnvVars } from \"../util/logging.js\";\n\nimport { ClientCertificateCredential } from \"#platform/credentials/clientCertificateCredential\";\nimport { ClientSecretCredential } from \"#platform/credentials/clientSecretCredential\";\nimport type { EnvironmentCredentialOptions } from \"./environmentCredentialOptions.js\";\nimport { UsernamePasswordCredential } from \"#platform/credentials/usernamePasswordCredential\";\nimport { checkTenantId } from \"../util/tenantIdUtils.js\";\nimport { tracingClient } from \"../util/tracing.js\";\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.\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 * Username and password authentication is deprecated, since it doesn't support multifactor authentication (MFA). See https://aka.ms/azsdk/identity/mfa for more details. Users can still provide environment variables for this authentication method:\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\n logger.warning(\n \"Environment is configured to use username and password authentication. This authentication method is deprecated, as it doesn't support multifactor authentication (MFA). Use a more secure credential. For more details, see https://aka.ms/azsdk/identity/mfa.\",\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"],
5
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,oBAAgE;AAChE,qBAA6E;AAE7E,yCAA4C;AAC5C,oCAAuC;AAEvC,wCAA2C;AAC3C,2BAA8B;AAC9B,qBAA8B;AASvB,MAAM,mCAAmC;AAAA,EAC9C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,gCAA0C;AACjD,QAAM,4BAA4B,QAAQ,IAAI,sCAAsC;AACpF,SAAO,0BAA0B,MAAM,GAAG;AAC5C;AAEA,MAAM,iBAAiB;AACvB,MAAM,aAAS,iCAAiB,cAAc;AAEvC,SAAS,0BAAmC;AACjD,QAAM,wBACJ,QAAQ,IAAI,uCAAuC,IACnD,YAAY;AACd,QAAM,SAAS,yBAAyB,UAAU,yBAAyB;AAC3E,SAAO;AAAA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AAA,QACL,uDAAuD,QAAQ,eAAe,QAAQ,kBAAkB,QAAQ;AAAA,MAClH;AAEA,aAAO;AAAA,QACL;AAAA,MACF;AACA,WAAK,cAAc,IAAI;AAAA,QACrB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,SAAS,QAA2B,UAA2B,CAAC,GAAyB;AAC7F,WAAO,6BAAc,SAAS,GAAG,cAAc,aAAa,SAAS,OAAO,eAAe;AACzF,UAAI,KAAK,aAAa;AACpB,YAAI;AACF,gBAAM,SAAS,MAAM,KAAK,YAAY,SAAS,QAAQ,UAAU;AACjE,iBAAO,SAAS,SAAK,8BAAc,MAAM,CAAC;AAC1C,iBAAO;AAAA,QACT,SAAS,KAAU;AACjB,gBAAM,sBAAsB,IAAI,kCAAoB,KAAK;AAAA,YACvD,OAAO,GAAG,cAAc;AAAA,YACxB,mBAAmB,IAAI,QAAQ,SAAS,EAAE,MAAM,eAAe,EAAE,KAAK,EAAE;AAAA,UAC1E,CAAC;AACD,iBAAO,SAAS,SAAK,4BAAY,QAAQ,mBAAmB,CAAC;AAC7D,gBAAM;AAAA,QACR;AAAA,MACF;AACA,YAAM,IAAI;AAAA,QACR,GAAG,cAAc;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
4
+ "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../errors.js\";\nimport { credentialLogger, formatError, formatSuccess, processEnvVars } from \"../util/logging.js\";\n\nimport { ClientCertificateCredential } from \"#platform/credentials/clientCertificateCredential\";\nimport { ClientSecretCredential } from \"#platform/credentials/clientSecretCredential\";\nimport type { EnvironmentCredentialOptions } from \"./environmentCredentialOptions.js\";\nimport { UsernamePasswordCredential } from \"#platform/credentials/usernamePasswordCredential\";\nimport { checkTenantId } from \"../util/tenantIdUtils.js\";\nimport { tracingClient } from \"../util/tracing.js\";\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.\n */\nexport class EnvironmentCredential implements TokenCredential {\n private _credential?:\n ClientSecretCredential | ClientCertificateCredential | 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 * Username and password authentication is deprecated, since it doesn't support multifactor authentication (MFA). See https://aka.ms/azsdk/identity/mfa for more details. Users can still provide environment variables for this authentication method:\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\n logger.warning(\n \"Environment is configured to use username and password authentication. This authentication method is deprecated, as it doesn't support multifactor authentication (MFA). Use a more secure credential. For more details, see https://aka.ms/azsdk/identity/mfa.\",\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"],
5
+ "mappings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AAE,MAAM,eAAe,EAAE,KAAK,EAAE;AAAA,UAC1E,CAAC;AACD,iBAAO,SAAS,SAAK,4BAAY,QAAQ,mBAAmB,CAAC;AAC7D,gBAAM;AAAA,QACR;AAAA,MACF;AACA,YAAM,IAAI;AAAA,QACR,GAAG,cAAc;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
6
6
  "names": []
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"msalPlugins.d.ts","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalPlugins.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAQlD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,KAAK,EACV,yBAAyB,EACzB,iCAAiC,EAClC,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAEtF;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,KAAK,EAAE;QACL;;WAEG;QACH,WAAW,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;QAC7C;;WAEG;QACH,cAAc,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;KACjD,CAAC;IACF;;OAEG;IACH,MAAM,EAAE;QACN;;;;WAIG;QACH,SAAS,EAAE,OAAO,CAAC;QACnB;;WAEG;QACH,oBAAoB,EAAE,OAAO,CAAC;QAC9B;;WAEG;QACH,kBAAkB,CAAC,EAAE,UAAU,CAAC;QAChC;;WAEG;QACH,kBAAkB,CAAC,EAAE,QAAQ,CAAC,mBAAmB,CAAC;QAClD;;WAEG;QACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;KACnC,CAAC;CACH;AAED;;;GAGG;AACH,eAAO,IAAI,mBAAmB,EAC1B,CAAC,CAAC,OAAO,CAAC,EAAE,4BAA4B,KAAK,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,CAAC;AAEF;;;;;;;GAOG;AACH,iBAAS,2BAA2B,CAAC,OAAO,EAAE,iBAAiB,GAAG,mBAAmB,CAqCpF;AAyDD;;GAEG;AACH,eAAO,MAAM,WAAW;;CAEvB,CAAC"}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/msal/nodeFlows/msalPlugins.ts"],
4
- "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type * as msalNode from \"@azure/msal-node\";\n\nimport {\n CACHE_CAE_SUFFIX,\n CACHE_NON_CAE_SUFFIX,\n DEFAULT_TOKEN_CACHE_NAME,\n} from \"../../constants.js\";\n\nimport type { MsalClientOptions } from \"./msalClient.js\";\nimport type {\n NativeBrokerPluginControl,\n VisualStudioCodeCredentialControl,\n} from \"../../plugins/provider.js\";\nimport type { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions.js\";\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\n/**\n * The current VSCode auth record path, undefined by default.\n * @internal\n */\nexport let vsCodeAuthRecordPath: string | undefined = undefined;\n\n/**\n * The current VSCode broker, undefined by default.\n * @internal\n */\nexport let vsCodeBrokerInfo:\n | {\n broker: msalNode.INativeBrokerPlugin;\n }\n | undefined = undefined;\n\nexport function hasNativeBroker(): boolean {\n return nativeBrokerInfo !== undefined;\n}\n\nexport function hasVSCodePlugin(): boolean {\n return vsCodeAuthRecordPath !== undefined && vsCodeBrokerInfo !== 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 * An object that allows setting the VSCode credential auth record path and broker.\n * @internal\n */\nexport const msalNodeFlowVSCodeCredentialControl: VisualStudioCodeCredentialControl = {\n setVSCodeAuthRecordPath(path: string): void {\n vsCodeAuthRecordPath = path;\n },\n setVSCodeBroker(broker: msalNode.INativeBrokerPlugin): void {\n vsCodeBrokerInfo = {\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 ...options.brokerOptions,\n isEnabled: options.brokerOptions?.enabled ?? false,\n enableMsaPassthrough: options.brokerOptions?.legacyEnableMsaPassthrough ?? false,\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 config.broker.nativeBrokerPlugin = getBrokerPlugin(options.isVSCodeCredential || false);\n }\n return config;\n}\n\n// Broker error message templates with variables for credential and package names\nconst brokerErrorTemplates = {\n missing: (credentialName: string, packageName: string, pluginVar: string) =>\n [\n `${credentialName} was requested, but no plugin was configured or no authentication record was found.`,\n `You must install the ${packageName} plugin package (npm install --save ${packageName})`,\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n `useIdentityPlugin(${pluginVar}) before using enableBroker.`,\n ].join(\" \"),\n unavailable: (credentialName: string, packageName: string) =>\n [\n `${credentialName} was requested, and the plugin is configured, but the broker is unavailable.`,\n `Ensure the ${credentialName} plugin is properly installed and configured.`,\n \"Check for missing native dependencies and ensure the package is properly installed.\",\n `See the README for prerequisites on installing and using ${packageName}.`,\n ].join(\" \"),\n};\n\n// Values for VSCode and native broker configurations for error message\nconst brokerConfig = {\n vsCode: {\n credentialName: \"Visual Studio Code Credential\",\n packageName: \"@azure/identity-vscode\",\n pluginVar: \"vsCodePlugin\",\n get brokerInfo() {\n return vsCodeBrokerInfo;\n },\n },\n native: {\n credentialName: \"Broker for WAM\",\n packageName: \"@azure/identity-broker\",\n pluginVar: \"nativeBrokerPlugin\",\n get brokerInfo() {\n return nativeBrokerInfo;\n },\n },\n} as const;\n\n/**\n * Set appropriate broker plugin based on whether VSCode or native broker is requested.\n * @param isVSCodePlugin - true for VSCode broker, false for native broker\n * @returns the broker plugin if available\n */\nfunction getBrokerPlugin(isVSCodePlugin: boolean): msalNode.INativeBrokerPlugin {\n const { credentialName, packageName, pluginVar, brokerInfo } =\n brokerConfig[isVSCodePlugin ? \"vsCode\" : \"native\"];\n if (brokerInfo === undefined) {\n throw new Error(brokerErrorTemplates.missing(credentialName, packageName, pluginVar));\n }\n if (brokerInfo.broker.isBrokerAvailable === false) {\n throw new Error(brokerErrorTemplates.unavailable(credentialName, packageName));\n }\n return brokerInfo.broker;\n}\n\n/**\n * Wraps generatePluginConfiguration as a writeable property for test stubbing purposes.\n */\nexport const msalPlugins = {\n generatePluginConfiguration,\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,uBAIO;AA2DA,IAAI,sBAEK;AAMT,MAAM,2BAA2B;AAAA,EACtC,eAAe,gBAAsE;AACnF,0BAAsB;AAAA,EACxB;AACF;AAMO,IAAI,mBAIK;AAMT,IAAI,uBAA2C;AAM/C,IAAI,mBAIK;AAET,SAAS,kBAA2B;AACzC,SAAO,qBAAqB;AAC9B;AAEO,SAAS,kBAA2B;AACzC,SAAO,yBAAyB,UAAa,qBAAqB;AACpE;AAMO,MAAM,kCAA6D;AAAA,EACxE,gBAAgB,QAAc;AAC5B,uBAAmB;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;AAMO,MAAM,sCAAyE;AAAA,EACpF,wBAAwB,MAAoB;AAC1C,2BAAuB;A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A,EACzE,EAAE,KAAK,GAAG;AACd;AAGA,MAAM,eAAe;AAAA,EACnB,QAAQ;AAAA,IACN,gBAAgB;AAAA,IAChB,aAAa;AAAA,IACb,WAAW;AAAA,IACX,IAAI,aAAa;AACf,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EACA,QAAQ;AAAA,IACN,gBAAgB;AAAA,IAChB,aAAa;AAAA,IACb,WAAW;AAAA,IACX,IAAI,aAAa;AACf,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAOA,SAAS,gBAAgB,gBAAuD;AAC9E,QAAM,EAAE,gBAAgB,aAAa,WAAW,WAAW,IACzD,aAAa,iBAAiB,WAAW,QAAQ;AACnD,MAAI,eAAe,QAAW;AAC5B,UAAM,IAAI,MAAM,qBAAqB,QAAQ,gBAAgB,aAAa,SAAS,CAAC;AAAA,EACtF;AACA,MAAI,WAAW,OAAO,sBAAsB,OAAO;AACjD,UAAM,IAAI,MAAM,qBAAqB,YAAY,gBAAgB,WAAW,CAAC;AAAA,EAC/E;AACA,SAAO,WAAW;AACpB;AAKO,MAAM,cAAc;AAAA,EACzB;AACF;",
4
+ "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type * as msalNode from \"@azure/msal-node\";\n\nimport {\n CACHE_CAE_SUFFIX,\n CACHE_NON_CAE_SUFFIX,\n DEFAULT_TOKEN_CACHE_NAME,\n} from \"../../constants.js\";\n\nimport type { MsalClientOptions } from \"./msalClient.js\";\nimport type {\n NativeBrokerPluginControl,\n VisualStudioCodeCredentialControl,\n} from \"../../plugins/provider.js\";\nimport type { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions.js\";\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>) | undefined =\n 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\n/**\n * The current VSCode auth record path, undefined by default.\n * @internal\n */\nexport let vsCodeAuthRecordPath: string | undefined = undefined;\n\n/**\n * The current VSCode broker, undefined by default.\n * @internal\n */\nexport let vsCodeBrokerInfo:\n | {\n broker: msalNode.INativeBrokerPlugin;\n }\n | undefined = undefined;\n\nexport function hasNativeBroker(): boolean {\n return nativeBrokerInfo !== undefined;\n}\n\nexport function hasVSCodePlugin(): boolean {\n return vsCodeAuthRecordPath !== undefined && vsCodeBrokerInfo !== 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 * An object that allows setting the VSCode credential auth record path and broker.\n * @internal\n */\nexport const msalNodeFlowVSCodeCredentialControl: VisualStudioCodeCredentialControl = {\n setVSCodeAuthRecordPath(path: string): void {\n vsCodeAuthRecordPath = path;\n },\n setVSCodeBroker(broker: msalNode.INativeBrokerPlugin): void {\n vsCodeBrokerInfo = {\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 ...options.brokerOptions,\n isEnabled: options.brokerOptions?.enabled ?? false,\n enableMsaPassthrough: options.brokerOptions?.legacyEnableMsaPassthrough ?? false,\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 config.broker.nativeBrokerPlugin = getBrokerPlugin(options.isVSCodeCredential || false);\n }\n return config;\n}\n\n// Broker error message templates with variables for credential and package names\nconst brokerErrorTemplates = {\n missing: (credentialName: string, packageName: string, pluginVar: string) =>\n [\n `${credentialName} was requested, but no plugin was configured or no authentication record was found.`,\n `You must install the ${packageName} plugin package (npm install --save ${packageName})`,\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n `useIdentityPlugin(${pluginVar}) before using enableBroker.`,\n ].join(\" \"),\n unavailable: (credentialName: string, packageName: string) =>\n [\n `${credentialName} was requested, and the plugin is configured, but the broker is unavailable.`,\n `Ensure the ${credentialName} plugin is properly installed and configured.`,\n \"Check for missing native dependencies and ensure the package is properly installed.\",\n `See the README for prerequisites on installing and using ${packageName}.`,\n ].join(\" \"),\n};\n\n// Values for VSCode and native broker configurations for error message\nconst brokerConfig = {\n vsCode: {\n credentialName: \"Visual Studio Code Credential\",\n packageName: \"@azure/identity-vscode\",\n pluginVar: \"vsCodePlugin\",\n get brokerInfo() {\n return vsCodeBrokerInfo;\n },\n },\n native: {\n credentialName: \"Broker for WAM\",\n packageName: \"@azure/identity-broker\",\n pluginVar: \"nativeBrokerPlugin\",\n get brokerInfo() {\n return nativeBrokerInfo;\n },\n },\n} as const;\n\n/**\n * Set appropriate broker plugin based on whether VSCode or native broker is requested.\n * @param isVSCodePlugin - true for VSCode broker, false for native broker\n * @returns the broker plugin if available\n */\nfunction getBrokerPlugin(isVSCodePlugin: boolean): msalNode.INativeBrokerPlugin {\n const { credentialName, packageName, pluginVar, brokerInfo } =\n brokerConfig[isVSCodePlugin ? \"vsCode\" : \"native\"];\n if (brokerInfo === undefined) {\n throw new Error(brokerErrorTemplates.missing(credentialName, packageName, pluginVar));\n }\n if (brokerInfo.broker.isBrokerAvailable === false) {\n throw new Error(brokerErrorTemplates.unavailable(credentialName, packageName));\n }\n return brokerInfo.broker;\n}\n\n/**\n * Wraps generatePluginConfiguration as a writeable property for test stubbing purposes.\n */\nexport const msalPlugins = {\n generatePluginConfiguration,\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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extractor",
8
- "packageVersion": "7.58.7"
8
+ "packageVersion": "7.58.12"
9
9
  }
10
10
  ]
11
11
  }
@@ -1,13 +1,24 @@
1
- import childProcess from "node:child_process";
1
+ import { type ExecFileOptionsWithStringEncoding } from "@azure/core-process";
2
2
  /**
3
3
  * Easy to mock childProcess utils.
4
4
  * @internal
5
5
  */
6
6
  export declare const processUtils: {
7
7
  /**
8
- * Promisifying childProcess.execFile
8
+ * Executes a file and preserves output when the process exits nonzero.
9
+ *
9
10
  * @internal
10
11
  */
11
- execFile(file: string, params: string[], options?: childProcess.ExecFileOptionsWithStringEncoding): Promise<string | Buffer>;
12
+ execFileWithResult(file: string, params: string[], options: ExecFileOptionsWithStringEncoding): Promise<{
13
+ stdout: string;
14
+ stderr: string;
15
+ error: Error | null;
16
+ }>;
17
+ /**
18
+ * Executes a file and rejects when it writes to stderr or exits nonzero.
19
+ *
20
+ * @internal
21
+ */
22
+ execFile(file: string, params: string[], options: ExecFileOptionsWithStringEncoding): Promise<string>;
12
23
  };
13
24
  //# sourceMappingURL=processUtils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"processUtils.d.ts","sourceRoot":"","sources":["../../../src/util/processUtils.ts"],"names":[],"mappings":"AAGA,OAAO,YAAY,MAAM,oBAAoB,CAAC;AAE9C;;;GAGG;AACH,eAAO,MAAM,YAAY;IACvB;;;OAGG;mBAEK,MAAM,UACJ,MAAM,EAAE,YACN,YAAY,CAAC,iCAAiC,GACvD,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC;CAiB5B,CAAC"}
1
+ {"version":3,"file":"processUtils.d.ts","sourceRoot":"","sources":["../../../src/util/processUtils.ts"],"names":[],"mappings":"AAGA,OAAO,EAGL,KAAK,iCAAiC,EACvC,MAAM,qBAAqB,CAAC;AAS7B;;;GAGG;AACH,eAAO,MAAM,YAAY;IACvB;;;;OAIG;6BAEK,MAAM,UACJ,MAAM,EAAE,WACP,iCAAiC,GACzC,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAA;KAAE,CAAC;IAgBnE;;;;OAIG;mBAEK,MAAM,UACJ,MAAM,EAAE,WACP,iCAAiC,GACzC,OAAO,CAAC,MAAM,CAAC;CAOnB,CAAC"}
@@ -1,8 +1,6 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
5
  var __export = (target, all) => {
8
6
  for (var name in all)
@@ -16,42 +14,51 @@ var __copyProps = (to, from, except, desc) => {
16
14
  }
17
15
  return to;
18
16
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
17
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
18
  var processUtils_exports = {};
29
19
  __export(processUtils_exports, {
30
20
  processUtils: () => processUtils
31
21
  });
32
22
  module.exports = __toCommonJS(processUtils_exports);
33
- var import_node_child_process = __toESM(require("node:child_process"));
23
+ var import_core_process = require("@azure/core-process");
24
+ function outputToString(output) {
25
+ if (output === void 0) {
26
+ return "";
27
+ }
28
+ return Buffer.isBuffer(output) ? output.toString("utf8") : output;
29
+ }
34
30
  const processUtils = {
35
31
  /**
36
- * Promisifying childProcess.execFile
32
+ * Executes a file and preserves output when the process exits nonzero.
33
+ *
34
+ * @internal
35
+ */
36
+ async execFileWithResult(file, params, options) {
37
+ try {
38
+ const result = await (0, import_core_process.execFile)(file, params, options);
39
+ return { ...result, error: null };
40
+ } catch (error) {
41
+ if ((0, import_core_process.isProcessError)(error)) {
42
+ return {
43
+ stdout: outputToString(error.stdout),
44
+ stderr: outputToString(error.stderr),
45
+ error
46
+ };
47
+ }
48
+ throw error;
49
+ }
50
+ },
51
+ /**
52
+ * Executes a file and rejects when it writes to stderr or exits nonzero.
53
+ *
37
54
  * @internal
38
55
  */
39
- execFile(file, params, options) {
40
- return new Promise((resolve, reject) => {
41
- import_node_child_process.default.execFile(file, params, options, (error, stdout, stderr) => {
42
- if (Buffer.isBuffer(stdout)) {
43
- stdout = stdout.toString("utf8");
44
- }
45
- if (Buffer.isBuffer(stderr)) {
46
- stderr = stderr.toString("utf8");
47
- }
48
- if (stderr || error) {
49
- reject(stderr ? new Error(stderr) : error);
50
- } else {
51
- resolve(stdout);
52
- }
53
- });
54
- });
56
+ async execFile(file, params, options) {
57
+ const { stdout, stderr, error } = await processUtils.execFileWithResult(file, params, options);
58
+ if (stderr || error) {
59
+ throw stderr ? new Error(stderr) : error;
60
+ }
61
+ return stdout;
55
62
  }
56
63
  };
57
64
  // Annotate the CommonJS export names for ESM import in node:
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/util/processUtils.ts"],
4
- "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport childProcess from \"node: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"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,gCAAyB;AAMlB,MAAM,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA,EAK1B,SACE,MACA,QACA,SAC0B;AAC1B,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,gCAAAA,QAAa,SAAS,MAAM,QAAQ,SAAS,CAAC,OAAO,QAAQ,WAAW;AACtE,YAAI,OAAO,SAAS,MAAM,GAAG;AAC3B,mBAAS,OAAO,SAAS,MAAM;AAAA,QACjC;AACA,YAAI,OAAO,SAAS,MAAM,GAAG;AAC3B,mBAAS,OAAO,SAAS,MAAM;AAAA,QACjC;AACA,YAAI,UAAU,OAAO;AACnB,iBAAO,SAAS,IAAI,MAAM,MAAM,IAAI,KAAK;AAAA,QAC3C,OAAO;AACL,kBAAQ,MAAM;AAAA,QAChB;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;",
6
- "names": ["childProcess"]
4
+ "sourcesContent": ["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport {\n execFile,\n isProcessError,\n type ExecFileOptionsWithStringEncoding,\n} from \"@azure/core-process\";\n\nfunction outputToString(output: string | Buffer | undefined): string {\n if (output === undefined) {\n return \"\";\n }\n return Buffer.isBuffer(output) ? output.toString(\"utf8\") : output;\n}\n\n/**\n * Easy to mock childProcess utils.\n * @internal\n */\nexport const processUtils = {\n /**\n * Executes a file and preserves output when the process exits nonzero.\n *\n * @internal\n */\n async execFileWithResult(\n file: string,\n params: string[],\n options: ExecFileOptionsWithStringEncoding,\n ): Promise<{ stdout: string; stderr: string; error: Error | null }> {\n try {\n const result = await execFile(file, params, options);\n return { ...result, error: null };\n } catch (error: unknown) {\n if (isProcessError(error)) {\n return {\n stdout: outputToString(error.stdout),\n stderr: outputToString(error.stderr),\n error,\n };\n }\n throw error;\n }\n },\n\n /**\n * Executes a file and rejects when it writes to stderr or exits nonzero.\n *\n * @internal\n */\n async execFile(\n file: string,\n params: string[],\n options: ExecFileOptionsWithStringEncoding,\n ): Promise<string> {\n const { stdout, stderr, error } = await processUtils.execFileWithResult(file, params, options);\n if (stderr || error) {\n throw stderr ? new Error(stderr) : error;\n }\n return stdout;\n },\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,0BAIO;AAEP,SAAS,eAAe,QAA6C;AACnE,MAAI,WAAW,QAAW;AACxB,WAAO;AAAA,EACT;AACA,SAAO,OAAO,SAAS,MAAM,IAAI,OAAO,SAAS,MAAM,IAAI;AAC7D;AAMO,MAAM,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM1B,MAAM,mBACJ,MACA,QACA,SACkE;AAClE,QAAI;AACF,YAAM,SAAS,UAAM,8BAAS,MAAM,QAAQ,OAAO;AACnD,aAAO,EAAE,GAAG,QAAQ,OAAO,KAAK;AAAA,IAClC,SAAS,OAAgB;AACvB,cAAI,oCAAe,KAAK,GAAG;AACzB,eAAO;AAAA,UACL,QAAQ,eAAe,MAAM,MAAM;AAAA,UACnC,QAAQ,eAAe,MAAM,MAAM;AAAA,UACnC;AAAA,QACF;AAAA,MACF;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,SACJ,MACA,QACA,SACiB;AACjB,UAAM,EAAE,QAAQ,QAAQ,MAAM,IAAI,MAAM,aAAa,mBAAmB,MAAM,QAAQ,OAAO;AAC7F,QAAI,UAAU,OAAO;AACnB,YAAM,SAAS,IAAI,MAAM,MAAM,IAAI;AAAA,IACrC;AACA,WAAO;AAAA,EACT;AACF;",
6
+ "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Current version of the `@azure/identity` package.
3
3
  */
4
- export declare const SDK_VERSION = "4.14.0-beta.4";
4
+ export declare const SDK_VERSION = "4.14.0-beta.5";
5
5
  /**
6
6
  * The default client ID for authentication
7
7
  * @internal
@@ -3,7 +3,7 @@
3
3
  /**
4
4
  * Current version of the `@azure/identity` package.
5
5
  */
6
- export const SDK_VERSION = `4.14.0-beta.4`;
6
+ export const SDK_VERSION = `4.14.0-beta.5`;
7
7
  /**
8
8
  * The default client ID for authentication
9
9
  * @internal
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC;AAE3C;;;GAGG;AACH,2EAA2E;AAC3E,6CAA6C;AAC7C,uGAAuG;AACvG,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AAExC;;GAEG;AACH,MAAM,CAAN,IAAY,mBAoBX;AApBD,WAAY,mBAAmB;IAC7B;;OAEG;IACH,oEAA6C,CAAA;IAC7C;;;;;SAKK;IACL,wEAAiD,CAAA;IACjD;;OAEG;IACH,2EAAoD,CAAA;IACpD;;OAEG;IACH,6EAAsD,CAAA;AACxD,CAAC,EApBW,mBAAmB,KAAnB,mBAAmB,QAoB9B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,mBAAmB,CAAC,gBAAgB,CAAC;AAEzE;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AAE5D;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAa,CAAC,GAAG,CAAC,CAAC;AAE3C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAEtC;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,YAAY,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Current version of the `@azure/identity` package.\n */\nexport const SDK_VERSION = `4.14.0-beta.4`;\n\n/**\n * The default client ID for authentication\n * @internal\n */\n// TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n// Developer Sign On application is available\n// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9\nexport const DeveloperSignOnClientId = \"04b07795-8ddb-461a-bbee-02f9e1bf7b46\";\n\n/**\n * The default tenant for authentication\n * @internal\n */\nexport const DefaultTenantId = \"common\";\n\n/**\n * A list of known Azure authority hosts\n */\nexport enum AzureAuthorityHosts {\n /**\n * China-based Azure Authority Host\n */\n AzureChina = \"https://login.chinacloudapi.cn\",\n /**\n * Germany-based Azure Authority Host\n *\n * @deprecated Microsoft Cloud Germany was closed on October 29th, 2021.\n *\n * */\n AzureGermany = \"https://login.microsoftonline.de\",\n /**\n * US Government Azure Authority Host\n */\n AzureGovernment = \"https://login.microsoftonline.us\",\n /**\n * Public Cloud Azure Authority Host\n */\n AzurePublicCloud = \"https://login.microsoftonline.com\",\n}\n\n/**\n * @internal\n * The default authority host.\n */\nexport const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;\n\n/**\n * @internal\n * The default environment host for Azure Public Cloud\n */\nexport const DefaultAuthority = \"login.microsoftonline.com\";\n\n/**\n * @internal\n * Allow acquiring tokens for any tenant for multi-tentant auth.\n */\nexport const ALL_TENANTS: string[] = [\"*\"];\n\n/**\n * @internal\n */\nexport const CACHE_CAE_SUFFIX = \"cae\";\n\n/**\n * @internal\n */\nexport const CACHE_NON_CAE_SUFFIX = \"nocae\";\n\n/**\n * @internal\n *\n * The default name for the cache persistence plugin.\n * Matches the constant defined in the cache persistence package.\n */\nexport const DEFAULT_TOKEN_CACHE_NAME = \"msal.cache\";\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC;AAE3C;;;GAGG;AACH,2EAA2E;AAC3E,6CAA6C;AAC7C,uGAAuG;AACvG,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AAExC;;GAEG;AACH,MAAM,CAAN,IAAY,mBAoBX;AApBD,WAAY,mBAAmB;IAC7B;;OAEG;IACH,oEAA6C,CAAA;IAC7C;;;;;SAKK;IACL,wEAAiD,CAAA;IACjD;;OAEG;IACH,2EAAoD,CAAA;IACpD;;OAEG;IACH,6EAAsD,CAAA;AACxD,CAAC,EApBW,mBAAmB,KAAnB,mBAAmB,QAoB9B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,mBAAmB,CAAC,gBAAgB,CAAC;AAEzE;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AAE5D;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAa,CAAC,GAAG,CAAC,CAAC;AAE3C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAEtC;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,YAAY,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Current version of the `@azure/identity` package.\n */\nexport const SDK_VERSION = `4.14.0-beta.5`;\n\n/**\n * The default client ID for authentication\n * @internal\n */\n// TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n// Developer Sign On application is available\n// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9\nexport const DeveloperSignOnClientId = \"04b07795-8ddb-461a-bbee-02f9e1bf7b46\";\n\n/**\n * The default tenant for authentication\n * @internal\n */\nexport const DefaultTenantId = \"common\";\n\n/**\n * A list of known Azure authority hosts\n */\nexport enum AzureAuthorityHosts {\n /**\n * China-based Azure Authority Host\n */\n AzureChina = \"https://login.chinacloudapi.cn\",\n /**\n * Germany-based Azure Authority Host\n *\n * @deprecated Microsoft Cloud Germany was closed on October 29th, 2021.\n *\n * */\n AzureGermany = \"https://login.microsoftonline.de\",\n /**\n * US Government Azure Authority Host\n */\n AzureGovernment = \"https://login.microsoftonline.us\",\n /**\n * Public Cloud Azure Authority Host\n */\n AzurePublicCloud = \"https://login.microsoftonline.com\",\n}\n\n/**\n * @internal\n * The default authority host.\n */\nexport const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;\n\n/**\n * @internal\n * The default environment host for Azure Public Cloud\n */\nexport const DefaultAuthority = \"login.microsoftonline.com\";\n\n/**\n * @internal\n * Allow acquiring tokens for any tenant for multi-tentant auth.\n */\nexport const ALL_TENANTS: string[] = [\"*\"];\n\n/**\n * @internal\n */\nexport const CACHE_CAE_SUFFIX = \"cae\";\n\n/**\n * @internal\n */\nexport const CACHE_NON_CAE_SUFFIX = \"nocae\";\n\n/**\n * @internal\n *\n * The default name for the cache persistence plugin.\n * Matches the constant defined in the cache persistence package.\n */\nexport const DEFAULT_TOKEN_CACHE_NAME = \"msal.cache\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"azureCliCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/azureCliCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAStF,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAShF;;;GAGG;AACH,eAAO,MAAM,2BAA2B;;;;;;CAUvC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,sBAAsB;IACjC;;OAEG;yBACkB,MAAM;IAgB3B;;;;OAIG;qCAES,MAAM,aACL,MAAM,iBACF,MAAM,YACX,MAAM,GACf,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAA;KAAE,CAAC;CAmCpE,CAAC;AAEF;;;;;GAKG;AACH,qBAAa,kBAAmB,YAAW,eAAe;IACxD,OAAO,CAAC,QAAQ,CAAC,CAAS;IAC1B,OAAO,CAAC,4BAA4B,CAAW;IAC/C,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,YAAY,CAAC,CAAS;IAE9B;;;;;;;OAOG;gBACS,OAAO,CAAC,EAAE,yBAAyB;IAe/C;;;;;;;OAOG;IACU,QAAQ,CACnB,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EACzB,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,WAAW,CAAC;IAiFvB;;;;;;;;;OASG;IACH,OAAO,CAAC,gBAAgB;CA+BzB"}
1
+ {"version":3,"file":"azureCliCredential.d.ts","sourceRoot":"","sources":["../../../src/credentials/azureCliCredential.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAStF,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAUhF;;;GAGG;AACH,eAAO,MAAM,2BAA2B;;;;;;CAUvC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,sBAAsB;IACjC;;OAEG;yBACkB,MAAM;IAgB3B;;;;OAIG;qCAES,MAAM,aACL,MAAM,iBACF,MAAM,YACX,MAAM,GACf,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAA;KAAE,CAAC;CA0BpE,CAAC;AAEF;;;;;GAKG;AACH,qBAAa,kBAAmB,YAAW,eAAe;IACxD,OAAO,CAAC,QAAQ,CAAC,CAAS;IAC1B,OAAO,CAAC,4BAA4B,CAAW;IAC/C,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,YAAY,CAAC,CAAS;IAE9B;;;;;;;OAOG;gBACS,OAAO,CAAC,EAAE,yBAAyB;IAe/C;;;;;;;OAOG;IACU,QAAQ,CACnB,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EACzB,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,WAAW,CAAC;IAmFvB;;;;;;;;;OASG;IACH,OAAO,CAAC,gBAAgB;CA+BzB"}
@@ -4,10 +4,11 @@ import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTen
4
4
  import { credentialLogger, formatError, formatSuccess } from "../util/logging.js";
5
5
  import { ensureValidScopeForDevTimeCreds, getScopeResource } from "../util/scopeUtils.js";
6
6
  import { CredentialUnavailableError } from "../errors.js";
7
- import child_process from "child_process";
8
7
  import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util";
9
8
  import { tracingClient } from "../util/tracing.js";
10
9
  import { checkSubscription } from "../util/subscriptionUtils.js";
10
+ import { processUtils } from "../util/processUtils.js";
11
+ import { isProcessError } from "@azure/core-process";
11
12
  const logger = credentialLogger("AzureCliCredential");
12
13
  /**
13
14
  * Messages to use when throwing in this credential.
@@ -53,29 +54,23 @@ export const cliCredentialInternals = {
53
54
  tenantSection = ["--tenant", tenantId];
54
55
  }
55
56
  if (subscription) {
56
- // Add quotes around the subscription to handle subscriptions with spaces
57
- subscriptionSection = ["--subscription", `"${subscription}"`];
57
+ subscriptionSection = ["--subscription", subscription];
58
58
  }
59
- return new Promise((resolve, reject) => {
60
- try {
61
- const args = [
62
- "account",
63
- "get-access-token",
64
- "--output",
65
- "json",
66
- "--resource",
67
- resource,
68
- ...tenantSection,
69
- ...subscriptionSection,
70
- ];
71
- const command = ["az", ...args].join(" ");
72
- child_process.exec(command, { cwd: cliCredentialInternals.getSafeWorkingDir(), timeout }, (error, stdout, stderr) => {
73
- resolve({ stdout: stdout, stderr: stderr, error });
74
- });
75
- }
76
- catch (err) {
77
- reject(err);
78
- }
59
+ const args = [
60
+ "account",
61
+ "get-access-token",
62
+ "--output",
63
+ "json",
64
+ "--resource",
65
+ resource,
66
+ ...tenantSection,
67
+ ...subscriptionSection,
68
+ ];
69
+ return processUtils.execFileWithResult("az", args, {
70
+ allowWindowsBatchFiles: true,
71
+ cwd: cliCredentialInternals.getSafeWorkingDir(),
72
+ encoding: "utf8",
73
+ timeout,
79
74
  });
80
75
  },
81
76
  };
@@ -147,7 +142,9 @@ export class AzureCliCredential {
147
142
  const obj = await cliCredentialInternals.getAzureCliAccessToken(resource, tenantId, this.subscription, this.timeout);
148
143
  const specificScope = obj.stderr?.match("(.*)az login --scope(.*)");
149
144
  const isLoginError = obj.stderr?.match("(.*)az login(.*)") && !specificScope;
150
- const isNotInstallError = obj.stderr?.match("az:(.*)not found") || obj.stderr?.startsWith("'az' is not recognized");
145
+ const isNotInstallError = obj.stderr?.match("az:(.*)not found") ||
146
+ obj.stderr?.startsWith("'az' is not recognized") ||
147
+ (obj.error && isProcessError(obj.error) && obj.error.code === "ENOENT");
151
148
  if (isNotInstallError) {
152
149
  const error = new CredentialUnavailableError(azureCliPublicErrorMessages.notInstalled);
153
150
  logger.getToken.info(formatError(scopes, error));
@@ -1 +1 @@
1
- {"version":3,"file":"azureCliCredential.js","sourceRoot":"","sources":["../../../src/credentials/azureCliCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EACL,aAAa,EACb,yBAAyB,EACzB,mCAAmC,GACpC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,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AAQ,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAC9C,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,CAAC;QACnC,8EAA8E;QAC9E,8BAA8B;QAC9B,IAAI,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,UAAU,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC;QACzE,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,CAAC;YAC/B,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,gDAAgD,CAAC,CAAC;YACvE,OAAO;gBACL,KAAK;gBACL,kBAAkB;gBAClB,SAAS,EAAE,QAAQ;aACpB,CAAC;QACJ,CAAC;QAED,2DAA2D;QAC3D,kBAAkB,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,CAAC;QAE5D,qCAAqC;QACrC,IAAI,KAAK,CAAC,kBAAkB,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,0BAA0B,CAClC,GAAG,2BAA2B,CAAC,kBAAkB,KAAK,QAAQ,CAAC,SAAS,GAAG,CAC5E,CAAC;QACJ,CAAC;QAED,OAAO;YACL,KAAK;YACL,kBAAkB;YAClB,SAAS,EAAE,QAAQ;SACpB,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils.js\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging.js\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils.js\";\n\nimport type { AzureCliCredentialOptions } from \"./azureCliCredentialOptions.js\";\nimport { CredentialUnavailableError } from \"../errors.js\";\nimport child_process from \"child_process\";\nimport { uint8ArrayToString, stringToUint8Array } from \"@azure/core-util\";\nimport { tracingClient } from \"../util/tracing.js\";\nimport { checkSubscription } from \"../util/subscriptionUtils.js\";\n\nconst logger = credentialLogger(\"AzureCliCredential\");\n\n/**\n * Messages to use when throwing in this credential.\n * @internal\n */\nexport const azureCliPublicErrorMessages = {\n claim:\n \"This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:\",\n notInstalled:\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 login:\n \"Please run 'az login' from a command prompt to authenticate before using this credential.\",\n unknown: \"Unknown error while trying to retrieve the access token\",\n unexpectedResponse:\n 'Unexpected response from Azure CLI when getting token. Expected \"expiresOn\" to be a RFC3339 date string. Got:',\n};\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 let systemRoot = process.env.SystemRoot || process.env[\"SYSTEMROOT\"];\n if (!systemRoot) {\n logger.getToken.warning(\n \"The SystemRoot environment variable is not set. This may cause issues when using the Azure CLI credential.\",\n );\n\n systemRoot = \"C:\\\\Windows\";\n }\n return 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 const args = [\n \"account\",\n \"get-access-token\",\n \"--output\",\n \"json\",\n \"--resource\",\n resource,\n ...tenantSection,\n ...subscriptionSection,\n ];\n const command = [\"az\", ...args].join(\" \");\n child_process.exec(\n command,\n { cwd: cliCredentialInternals.getSafeWorkingDir(), 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\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 scope = typeof scopes === \"string\" ? scopes : scopes[0];\n const claimsValue = options.claims;\n if (claimsValue && claimsValue.trim()) {\n const encodedClaims = uint8ArrayToString(stringToUint8Array(claimsValue, \"utf-8\"), \"base64\");\n let loginCmd = `az login --claims-challenge ${encodedClaims} --scope ${scope}`;\n\n const tenantIdFromOptions = options.tenantId;\n if (tenantIdFromOptions) {\n loginCmd += ` --tenant ${tenantIdFromOptions}`;\n }\n\n const error = new CredentialUnavailableError(\n `${azureCliPublicErrorMessages.claim} ${loginCmd}`,\n );\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n if (this.subscription) {\n checkSubscription(logger, this.subscription);\n }\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(azureCliPublicErrorMessages.notInstalled);\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n if (isLoginError) {\n const error = new CredentialUnavailableError(azureCliPublicErrorMessages.login);\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 || azureCliPublicErrorMessages.unknown,\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 `${azureCliPublicErrorMessages.unexpectedResponse} \"${response.expiresOn}\"`,\n );\n }\n\n return {\n token,\n expiresOnTimestamp,\n tokenType: \"Bearer\",\n };\n }\n}\n"]}
1
+ {"version":3,"file":"azureCliCredential.js","sourceRoot":"","sources":["../../../src/credentials/azureCliCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EACL,aAAa,EACb,yBAAyB,EACzB,mCAAmC,GACpC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,+BAA+B,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG1F,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,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,kBAAkB,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,0BAA0B,CAClC,GAAG,2BAA2B,CAAC,kBAAkB,KAAK,QAAQ,CAAC,SAAS,GAAG,CAC5E,CAAC;QACJ,CAAC;QAED,OAAO;YACL,KAAK;YACL,kBAAkB;YAClB,SAAS,EAAE,QAAQ;SACpB,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils.js\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging.js\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils.js\";\n\nimport type { AzureCliCredentialOptions } from \"./azureCliCredentialOptions.js\";\nimport { CredentialUnavailableError } from \"../errors.js\";\nimport { uint8ArrayToString, stringToUint8Array } from \"@azure/core-util\";\nimport { tracingClient } from \"../util/tracing.js\";\nimport { checkSubscription } from \"../util/subscriptionUtils.js\";\nimport { processUtils } from \"../util/processUtils.js\";\nimport { isProcessError } from \"@azure/core-process\";\n\nconst logger = credentialLogger(\"AzureCliCredential\");\n\n/**\n * Messages to use when throwing in this credential.\n * @internal\n */\nexport const azureCliPublicErrorMessages = {\n claim:\n \"This credential doesn't support claims challenges. To authenticate with the required claims, please run the following command:\",\n notInstalled:\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 login:\n \"Please run 'az login' from a command prompt to authenticate before using this credential.\",\n unknown: \"Unknown error while trying to retrieve the access token\",\n unexpectedResponse:\n 'Unexpected response from Azure CLI when getting token. Expected \"expiresOn\" to be a RFC3339 date string. Got:',\n};\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 let systemRoot = process.env.SystemRoot || process.env[\"SYSTEMROOT\"];\n if (!systemRoot) {\n logger.getToken.warning(\n \"The SystemRoot environment variable is not set. This may cause issues when using the Azure CLI credential.\",\n );\n\n systemRoot = \"C:\\\\Windows\";\n }\n return 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 subscriptionSection = [\"--subscription\", subscription];\n }\n const args = [\n \"account\",\n \"get-access-token\",\n \"--output\",\n \"json\",\n \"--resource\",\n resource,\n ...tenantSection,\n ...subscriptionSection,\n ];\n return processUtils.execFileWithResult(\"az\", args, {\n allowWindowsBatchFiles: true,\n cwd: cliCredentialInternals.getSafeWorkingDir(),\n encoding: \"utf8\",\n timeout,\n });\n },\n};\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 scope = typeof scopes === \"string\" ? scopes : scopes[0];\n const claimsValue = options.claims;\n if (claimsValue && claimsValue.trim()) {\n const encodedClaims = uint8ArrayToString(stringToUint8Array(claimsValue, \"utf-8\"), \"base64\");\n let loginCmd = `az login --claims-challenge ${encodedClaims} --scope ${scope}`;\n\n const tenantIdFromOptions = options.tenantId;\n if (tenantIdFromOptions) {\n loginCmd += ` --tenant ${tenantIdFromOptions}`;\n }\n\n const error = new CredentialUnavailableError(\n `${azureCliPublicErrorMessages.claim} ${loginCmd}`,\n );\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n if (this.subscription) {\n checkSubscription(logger, this.subscription);\n }\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\") ||\n obj.stderr?.startsWith(\"'az' is not recognized\") ||\n (obj.error && isProcessError(obj.error) && obj.error.code === \"ENOENT\");\n\n if (isNotInstallError) {\n const error = new CredentialUnavailableError(azureCliPublicErrorMessages.notInstalled);\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n if (isLoginError) {\n const error = new CredentialUnavailableError(azureCliPublicErrorMessages.login);\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 || azureCliPublicErrorMessages.unknown,\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 `${azureCliPublicErrorMessages.unexpectedResponse} \"${response.expiresOn}\"`,\n );\n }\n\n return {\n token,\n expiresOnTimestamp,\n tokenType: \"Bearer\",\n };\n }\n}\n"]}