{"version":3,"file":"visualStudioCodeCredential.js","sourceRoot":"","sources":["../../../src/credentials/visualStudioCodeCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAExE,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE/E,MAAM,cAAc,GAAG,QAAQ,CAAC;AAChC,MAAM,oBAAoB,GAAG,sCAAsC,CAAC,CAAC,8CAA8C;AACnH,MAAM,MAAM,GAAG,gBAAgB,CAAC,4BAA4B,CAAC,CAAC;AAE9D,IAAI,eAAe,GAAuC,SAAS,CAAC;AAEpE,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,yBAAyB,CAAC,MAA8B;QACtD,eAAe,GAAG,MAAM,CAAC;IAC3B,CAAC;CACF,CAAC;AAEF,oEAAoE;AACpE,MAAM,oBAAoB,GAA2B;IACnD,IAAI,EAAE,mFAAmF;CAC1F,CAAC;AAEF,SAAS,sBAAsB,CAAC,QAAgB;IAC9C,8CAA8C;IAC9C,MAAM,sBAAsB,GAAG,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IAC9D,IAAI,sBAAsB,EAAE;QAC1B,MAAM,IAAI,0BAA0B,CAAC,sBAAsB,CAAC,CAAC;KAC9D;AACH,CAAC;AAID,MAAM,uBAAuB,GAAqC;IAChE,UAAU,EAAE,mBAAmB,CAAC,gBAAgB;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CAChE,QAAQ,EACR,oBAAoB,EACpB,WAAW,EACX,YAAY,EACZ,SAAS,CACV,CAAC;YAEF,IAAI,aAAa,EAAE;gBACjB,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;gBAC5C,OAAO,aAAa,CAAC,WAAW,CAAC;aAClC;iBAAM;gBACL,MAAM,KAAK,GAAG,IAAI,0BAA0B,CAC1C,0NAA0N,CAC3N,CAAC;gBACF,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;gBACjD,MAAM,KAAK,CAAC;aACb;SACF;aAAM;YACL,MAAM,KAAK,GAAG,IAAI,0BAA0B,CAC1C,8MAA8M,CAC/M,CAAC;YACF,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;YACjD,MAAM,KAAK,CAAC;SACb;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\n\nimport { AzureAuthorityHosts } from \"../constants\";\nimport { checkTenantId } from \"../util/checkTenantId\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\nimport { processMultiTenantRequest } from \"../util/validateMultiTenant\";\nimport { VSCodeCredentialFinder } from \"./visualStudioCodeCredentialPlugin\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\n\nconst CommonTenantId = \"common\";\nconst AzureAccountClientId = \"aebc6443-996d-45c2-90f0-388ff96faa56\"; // VSC: 'aebc6443-996d-45c2-90f0-388ff96faa56'\nconst logger = credentialLogger(\"VisualStudioCodeCredential\");\n\nlet findCredentials: VSCodeCredentialFinder | undefined = undefined;\n\nexport const vsCodeCredentialControl = {\n setVsCodeCredentialFinder(finder: VSCodeCredentialFinder): void {\n findCredentials = finder;\n },\n};\n\n// Map of unsupported Tenant IDs and the errors we will be throwing.\nconst unsupportedTenantIds: Record = {\n adfs: \"The VisualStudioCodeCredential does not support authentication with ADFS tenants.\",\n};\n\nfunction checkUnsupportedTenant(tenantId: string): void {\n // If the Tenant ID isn't supported, we throw.\n const unsupportedTenantError = unsupportedTenantIds[tenantId];\n if (unsupportedTenantError) {\n throw new CredentialUnavailableError(unsupportedTenantError);\n }\n}\n\ntype VSCodeCloudNames = \"AzureCloud\" | \"AzureChina\" | \"AzureGermanCloud\" | \"AzureUSGovernment\";\n\nconst mapVSCodeAuthorityHosts: Record = {\n AzureCloud: AzureAuthorityHosts.AzurePublicCloud,\n AzureChina: AzureAuthorityHosts.AzureChina,\n AzureGermanCloud: AzureAuthorityHosts.AzureGermany,\n AzureUSGovernment: AzureAuthorityHosts.AzureGovernment,\n};\n\n/**\n * Attempts to load a specific property from the VSCode configurations of the current OS.\n * If it fails at any point, returns undefined.\n */\nexport function getPropertyFromVSCode(property: string): string | undefined {\n const settingsPath = [\"User\", \"settings.json\"];\n // Eventually we can add more folders for more versions of VSCode.\n const vsCodeFolder = \"Code\";\n const homedir = os.homedir();\n\n function loadProperty(...pathSegments: string[]): string | undefined {\n const fullPath = path.join(...pathSegments, vsCodeFolder, ...settingsPath);\n const settings = JSON.parse(fs.readFileSync(fullPath, { encoding: \"utf8\" }));\n return settings[property];\n }\n\n try {\n let appData: string;\n switch (process.platform) {\n case \"win32\":\n appData = process.env.APPDATA!;\n return appData ? loadProperty(appData) : undefined;\n case \"darwin\":\n return loadProperty(homedir, \"Library\", \"Application Support\");\n case \"linux\":\n return loadProperty(homedir, \".config\");\n default:\n return;\n }\n } catch (e: any) {\n logger.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`);\n return;\n }\n}\n\n/**\n * Provides options to configure the Visual Studio Code credential.\n */\nexport interface VisualStudioCodeCredentialOptions extends TokenCredentialOptions {\n /**\n * Optionally pass in a Tenant ID to be used as part of the credential\n */\n tenantId?: string;\n}\n\n/**\n * Connects to Azure using the credential provided by the VSCode extension 'Azure Account'.\n * Once the user has logged in via the extension, this credential can share the same refresh token\n * that is cached by the extension.\n */\nexport class VisualStudioCodeCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private cloudName: VSCodeCloudNames;\n\n /**\n * Creates an instance of VisualStudioCodeCredential to use for automatically authenticating via VSCode.\n *\n * **Note**: `VisualStudioCodeCredential` is provided by a plugin package:\n * `@azure/identity-vscode`. If this package is not installed and registered\n * using the plugin API (`useIdentityPlugin`), then authentication using\n * `VisualStudioCodeCredential` will not be available.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: VisualStudioCodeCredentialOptions) {\n // We want to make sure we use the one assigned by the user on the VSCode settings.\n // Or just `AzureCloud` by default.\n this.cloudName = (getPropertyFromVSCode(\"azure.cloud\") || \"AzureCloud\") as VSCodeCloudNames;\n\n // Picking an authority host based on the cloud name.\n const authorityHost = mapVSCodeAuthorityHosts[this.cloudName];\n\n this.identityClient = new IdentityClient({\n authorityHost,\n ...options,\n });\n\n if (options && options.tenantId) {\n checkTenantId(logger, options.tenantId);\n this.tenantId = options.tenantId;\n } else {\n this.tenantId = CommonTenantId;\n }\n\n checkUnsupportedTenant(this.tenantId);\n }\n\n /**\n * Runs preparations for any further getToken request.\n */\n private async prepare(): Promise {\n // Attempts to load the tenant from the VSCode configuration file.\n const settingsTenant = getPropertyFromVSCode(\"azure.tenant\");\n if (settingsTenant) {\n this.tenantId = settingsTenant;\n }\n checkUnsupportedTenant(this.tenantId);\n }\n\n /**\n * The promise of the single preparation that will be executed at the first getToken request for an instance of this class.\n */\n private preparePromise: Promise | undefined;\n\n /**\n * Runs preparations for any further getToken, but only once.\n */\n private prepareOnce(): Promise | undefined {\n if (!this.preparePromise) {\n this.preparePromise = this.prepare();\n }\n return this.preparePromise;\n }\n\n /**\n * Returns the token found by searching VSCode's authentication cache or\n * returns null if no token could be found.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * `TokenCredential` implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise {\n await this.prepareOnce();\n\n const tenantId = processMultiTenantRequest(this.tenantId, options) || this.tenantId;\n\n if (findCredentials === undefined) {\n throw new CredentialUnavailableError(\n [\n \"No implementation of `VisualStudioCodeCredential` is available.\",\n \"You must install the identity-vscode plugin package (`npm install --save-dev @azure/identity-vscode`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(vsCodePlugin)` before creating a `VisualStudioCodeCredential`.\",\n ].join(\" \")\n );\n }\n\n let scopeString = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n\n // Check to make sure the scope we get back is a valid scope\n if (!scopeString.match(/^[0-9a-zA-Z-.:/]+$/)) {\n const error = new Error(\"Invalid scope was specified by the user or calling client\");\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n if (scopeString.indexOf(\"offline_access\") < 0) {\n scopeString += \" offline_access\";\n }\n\n // findCredentials returns an array similar to:\n // [\n // {\n // account: \"\",\n // password: \"\",\n // },\n // /* ... */\n // ]\n const credentials = await findCredentials();\n\n // If we can't find the credential based on the name, we'll pick the first one available.\n const { password: refreshToken } =\n credentials.find(({ account }) => account === this.cloudName) ?? credentials[0] ?? {};\n\n if (refreshToken) {\n const tokenResponse = await this.identityClient.refreshAccessToken(\n tenantId,\n AzureAccountClientId,\n scopeString,\n refreshToken,\n undefined\n );\n\n if (tokenResponse) {\n logger.getToken.info(formatSuccess(scopes));\n return tokenResponse.accessToken;\n } else {\n const error = new CredentialUnavailableError(\n \"Could not retrieve the token associated with Visual Studio Code. Have you connected using the 'Azure Account' extension recently? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n } else {\n const error = new CredentialUnavailableError(\n \"Could not retrieve the token associated with Visual Studio Code. Did you connect using the 'Azure Account' extension? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n }\n}\n"]}