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Token, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport { CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\nimport { ensureValidScope, getScopeResource } from \"../util/scopeUtils\";\nimport { processUtils } from \"../util/processUtils\";\nimport { AzurePowerShellCredentialOptions } from \"./azurePowerShellCredentialOptions\";\nimport { processMultiTenantRequest } from \"../util/validateMultiTenant\";\nimport { checkTenantId } from \"../util/checkTenantId\";\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[][]): Promise {\n const results: string[] = [];\n\n for (const command of commands) {\n const [file, ...parameters] = command;\n const result = (await processUtils.execFile(file, parameters, { encoding: \"utf8\" })) as string;\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Known PowerShell errors\n * @internal\n */\nexport const powerShellErrors = {\n login: \"Run Connect-AzAccount to login\",\n installed:\n \"The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory\",\n};\n\n/**\n * Messages to use when throwing in this credential.\n * @internal\n */\nexport const powerShellPublicErrorMessages = {\n login:\n \"Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.\",\n installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: \"Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force\".`,\n troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`,\n};\n\n// PowerShell Azure User not logged in error check.\nconst isLoginError = (err: Error) => err.message.match(`(.*)${powerShellErrors.login}(.*)`);\n\n// Az Module not Installed in Azure PowerShell check.\nconst isNotInstalledError = (err: Error) => 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\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 this.tenantId = options?.tenantId;\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 ): 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, \"/?\"]]);\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 let tenantSection = \"\";\n if (tenantId) {\n tenantSection = `-TenantId \"${tenantId}\"`;\n }\n\n const results = await runCommands([\n [\n powerShellCommand,\n \"-Command\",\n \"Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru\",\n ],\n [\n powerShellCommand,\n \"-Command\",\n `Get-AzAccessToken ${tenantSection} -ResourceUrl \"${resource}\" | ConvertTo-Json`,\n ],\n ]);\n\n const result = results[1];\n try {\n return JSON.parse(result);\n } catch (e: any) {\n throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);\n }\n }\n\n throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);\n }\n\n /**\n * Authenticates with Azure Active Directory 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 {\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n const tenantId = processMultiTenantRequest(this.tenantId, options);\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n ensureValidScope(scope, logger);\n logger.getToken.info(`Using the scope ${scope}`);\n const resource = getScopeResource(scope);\n\n try {\n const response = await this.getAzurePowerShellAccessToken(resource, tenantId);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.Token,\n expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),\n };\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"]}