@azure/identity-cache-persistence 1.1.2-alpha.20241112.1 → 1.1.2-alpha.20241114.2

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 (151) hide show
  1. package/dist/index.js.map +1 -1
  2. package/dist-esm/src/index.js.map +1 -0
  3. package/dist-esm/src/platforms.js.map +1 -0
  4. package/dist-esm/src/provider.js.map +1 -0
  5. package/package.json +3 -4
  6. package/dist-esm/identity/src/client/identityClient.js +0 -257
  7. package/dist-esm/identity/src/client/identityClient.js.map +0 -1
  8. package/dist-esm/identity/src/constants.js +0 -70
  9. package/dist-esm/identity/src/constants.js.map +0 -1
  10. package/dist-esm/identity/src/credentials/authorityValidationOptions.js +0 -4
  11. package/dist-esm/identity/src/credentials/authorityValidationOptions.js.map +0 -1
  12. package/dist-esm/identity/src/credentials/authorizationCodeCredential.js +0 -63
  13. package/dist-esm/identity/src/credentials/authorizationCodeCredential.js.map +0 -1
  14. package/dist-esm/identity/src/credentials/authorizationCodeCredentialOptions.js +0 -4
  15. package/dist-esm/identity/src/credentials/authorizationCodeCredentialOptions.js.map +0 -1
  16. package/dist-esm/identity/src/credentials/azureCliCredential.js +0 -194
  17. package/dist-esm/identity/src/credentials/azureCliCredential.js.map +0 -1
  18. package/dist-esm/identity/src/credentials/azureCliCredentialOptions.js +0 -4
  19. package/dist-esm/identity/src/credentials/azureCliCredentialOptions.js.map +0 -1
  20. package/dist-esm/identity/src/credentials/azureDeveloperCliCredential.js +0 -176
  21. package/dist-esm/identity/src/credentials/azureDeveloperCliCredential.js.map +0 -1
  22. package/dist-esm/identity/src/credentials/azureDeveloperCliCredentialOptions.js +0 -4
  23. package/dist-esm/identity/src/credentials/azureDeveloperCliCredentialOptions.js.map +0 -1
  24. package/dist-esm/identity/src/credentials/azurePipelinesCredential.js +0 -146
  25. package/dist-esm/identity/src/credentials/azurePipelinesCredential.js.map +0 -1
  26. package/dist-esm/identity/src/credentials/azurePipelinesCredentialOptions.js +0 -4
  27. package/dist-esm/identity/src/credentials/azurePipelinesCredentialOptions.js.map +0 -1
  28. package/dist-esm/identity/src/credentials/azurePowerShellCredential.js +0 -238
  29. package/dist-esm/identity/src/credentials/azurePowerShellCredential.js.map +0 -1
  30. package/dist-esm/identity/src/credentials/azurePowerShellCredentialOptions.js +0 -4
  31. package/dist-esm/identity/src/credentials/azurePowerShellCredentialOptions.js.map +0 -1
  32. package/dist-esm/identity/src/credentials/brokerAuthOptions.js +0 -2
  33. package/dist-esm/identity/src/credentials/brokerAuthOptions.js.map +0 -1
  34. package/dist-esm/identity/src/credentials/browserCustomizationOptions.js +0 -4
  35. package/dist-esm/identity/src/credentials/browserCustomizationOptions.js.map +0 -1
  36. package/dist-esm/identity/src/credentials/chainedTokenCredential.js +0 -95
  37. package/dist-esm/identity/src/credentials/chainedTokenCredential.js.map +0 -1
  38. package/dist-esm/identity/src/credentials/clientAssertionCredential.js +0 -58
  39. package/dist-esm/identity/src/credentials/clientAssertionCredential.js.map +0 -1
  40. package/dist-esm/identity/src/credentials/clientAssertionCredentialOptions.js +0 -4
  41. package/dist-esm/identity/src/credentials/clientAssertionCredentialOptions.js.map +0 -1
  42. package/dist-esm/identity/src/credentials/clientCertificateCredential.js +0 -126
  43. package/dist-esm/identity/src/credentials/clientCertificateCredential.js.map +0 -1
  44. package/dist-esm/identity/src/credentials/clientCertificateCredentialOptions.js +0 -4
  45. package/dist-esm/identity/src/credentials/clientCertificateCredentialOptions.js.map +0 -1
  46. package/dist-esm/identity/src/credentials/clientSecretCredential.js +0 -63
  47. package/dist-esm/identity/src/credentials/clientSecretCredential.js.map +0 -1
  48. package/dist-esm/identity/src/credentials/clientSecretCredentialOptions.js +0 -4
  49. package/dist-esm/identity/src/credentials/clientSecretCredentialOptions.js.map +0 -1
  50. package/dist-esm/identity/src/credentials/credentialPersistenceOptions.js +0 -4
  51. package/dist-esm/identity/src/credentials/credentialPersistenceOptions.js.map +0 -1
  52. package/dist-esm/identity/src/credentials/defaultAzureCredential.js +0 -164
  53. package/dist-esm/identity/src/credentials/defaultAzureCredential.js.map +0 -1
  54. package/dist-esm/identity/src/credentials/defaultAzureCredentialOptions.js +0 -4
  55. package/dist-esm/identity/src/credentials/defaultAzureCredentialOptions.js.map +0 -1
  56. package/dist-esm/identity/src/credentials/deviceCodeCredential.js +0 -96
  57. package/dist-esm/identity/src/credentials/deviceCodeCredential.js.map +0 -1
  58. package/dist-esm/identity/src/credentials/deviceCodeCredentialOptions.js +0 -4
  59. package/dist-esm/identity/src/credentials/deviceCodeCredentialOptions.js.map +0 -1
  60. package/dist-esm/identity/src/credentials/environmentCredential.js +0 -133
  61. package/dist-esm/identity/src/credentials/environmentCredential.js.map +0 -1
  62. package/dist-esm/identity/src/credentials/environmentCredentialOptions.js +0 -4
  63. package/dist-esm/identity/src/credentials/environmentCredentialOptions.js.map +0 -1
  64. package/dist-esm/identity/src/credentials/interactiveBrowserCredential.js +0 -96
  65. package/dist-esm/identity/src/credentials/interactiveBrowserCredential.js.map +0 -1
  66. package/dist-esm/identity/src/credentials/interactiveBrowserCredentialOptions.js +0 -4
  67. package/dist-esm/identity/src/credentials/interactiveBrowserCredentialOptions.js.map +0 -1
  68. package/dist-esm/identity/src/credentials/interactiveCredentialOptions.js +0 -4
  69. package/dist-esm/identity/src/credentials/interactiveCredentialOptions.js.map +0 -1
  70. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsMsi.js +0 -125
  71. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsMsi.js.map +0 -1
  72. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsRetryPolicy.js +0 -33
  73. package/dist-esm/identity/src/credentials/managedIdentityCredential/imdsRetryPolicy.js.map +0 -1
  74. package/dist-esm/identity/src/credentials/managedIdentityCredential/index.js +0 -220
  75. package/dist-esm/identity/src/credentials/managedIdentityCredential/index.js.map +0 -1
  76. package/dist-esm/identity/src/credentials/managedIdentityCredential/models.js +0 -4
  77. package/dist-esm/identity/src/credentials/managedIdentityCredential/models.js.map +0 -1
  78. package/dist-esm/identity/src/credentials/managedIdentityCredential/tokenExchangeMsi.js +0 -37
  79. package/dist-esm/identity/src/credentials/managedIdentityCredential/tokenExchangeMsi.js.map +0 -1
  80. package/dist-esm/identity/src/credentials/managedIdentityCredential/utils.js +0 -77
  81. package/dist-esm/identity/src/credentials/managedIdentityCredential/utils.js.map +0 -1
  82. package/dist-esm/identity/src/credentials/multiTenantTokenCredentialOptions.js +0 -4
  83. package/dist-esm/identity/src/credentials/multiTenantTokenCredentialOptions.js.map +0 -1
  84. package/dist-esm/identity/src/credentials/onBehalfOfCredential.js +0 -119
  85. package/dist-esm/identity/src/credentials/onBehalfOfCredential.js.map +0 -1
  86. package/dist-esm/identity/src/credentials/onBehalfOfCredentialOptions.js +0 -4
  87. package/dist-esm/identity/src/credentials/onBehalfOfCredentialOptions.js.map +0 -1
  88. package/dist-esm/identity/src/credentials/usernamePasswordCredential.js +0 -70
  89. package/dist-esm/identity/src/credentials/usernamePasswordCredential.js.map +0 -1
  90. package/dist-esm/identity/src/credentials/usernamePasswordCredentialOptions.js +0 -4
  91. package/dist-esm/identity/src/credentials/usernamePasswordCredentialOptions.js.map +0 -1
  92. package/dist-esm/identity/src/credentials/visualStudioCodeCredential.js +0 -195
  93. package/dist-esm/identity/src/credentials/visualStudioCodeCredential.js.map +0 -1
  94. package/dist-esm/identity/src/credentials/visualStudioCodeCredentialOptions.js +0 -4
  95. package/dist-esm/identity/src/credentials/visualStudioCodeCredentialOptions.js.map +0 -1
  96. package/dist-esm/identity/src/credentials/visualStudioCodeCredentialPlugin.js +0 -4
  97. package/dist-esm/identity/src/credentials/visualStudioCodeCredentialPlugin.js.map +0 -1
  98. package/dist-esm/identity/src/credentials/workloadIdentityCredential.js +0 -119
  99. package/dist-esm/identity/src/credentials/workloadIdentityCredential.js.map +0 -1
  100. package/dist-esm/identity/src/credentials/workloadIdentityCredentialOptions.js +0 -4
  101. package/dist-esm/identity/src/credentials/workloadIdentityCredentialOptions.js.map +0 -1
  102. package/dist-esm/identity/src/errors.js +0 -123
  103. package/dist-esm/identity/src/errors.js.map +0 -1
  104. package/dist-esm/identity/src/index.js +0 -34
  105. package/dist-esm/identity/src/index.js.map +0 -1
  106. package/dist-esm/identity/src/msal/msal.js +0 -5
  107. package/dist-esm/identity/src/msal/msal.js.map +0 -1
  108. package/dist-esm/identity/src/msal/nodeFlows/brokerOptions.js +0 -2
  109. package/dist-esm/identity/src/msal/nodeFlows/brokerOptions.js.map +0 -1
  110. package/dist-esm/identity/src/msal/nodeFlows/msalClient.js +0 -511
  111. package/dist-esm/identity/src/msal/nodeFlows/msalClient.js.map +0 -1
  112. package/dist-esm/identity/src/msal/nodeFlows/msalPlugins.js +0 -87
  113. package/dist-esm/identity/src/msal/nodeFlows/msalPlugins.js.map +0 -1
  114. package/dist-esm/identity/src/msal/nodeFlows/tokenCachePersistenceOptions.js +0 -4
  115. package/dist-esm/identity/src/msal/nodeFlows/tokenCachePersistenceOptions.js.map +0 -1
  116. package/dist-esm/identity/src/msal/types.js +0 -4
  117. package/dist-esm/identity/src/msal/types.js.map +0 -1
  118. package/dist-esm/identity/src/msal/utils.js +0 -232
  119. package/dist-esm/identity/src/msal/utils.js.map +0 -1
  120. package/dist-esm/identity/src/plugins/consumer.js +0 -43
  121. package/dist-esm/identity/src/plugins/consumer.js.map +0 -1
  122. package/dist-esm/identity/src/plugins/provider.js +0 -4
  123. package/dist-esm/identity/src/plugins/provider.js.map +0 -1
  124. package/dist-esm/identity/src/regionalAuthority.js +0 -140
  125. package/dist-esm/identity/src/regionalAuthority.js.map +0 -1
  126. package/dist-esm/identity/src/tokenCredentialOptions.js +0 -4
  127. package/dist-esm/identity/src/tokenCredentialOptions.js.map +0 -1
  128. package/dist-esm/identity/src/tokenProvider.js +0 -55
  129. package/dist-esm/identity/src/tokenProvider.js.map +0 -1
  130. package/dist-esm/identity/src/util/identityTokenEndpoint.js +0 -11
  131. package/dist-esm/identity/src/util/identityTokenEndpoint.js.map +0 -1
  132. package/dist-esm/identity/src/util/logging.js +0 -94
  133. package/dist-esm/identity/src/util/logging.js.map +0 -1
  134. package/dist-esm/identity/src/util/processMultiTenantRequest.js +0 -35
  135. package/dist-esm/identity/src/util/processMultiTenantRequest.js.map +0 -1
  136. package/dist-esm/identity/src/util/processUtils.js +0 -32
  137. package/dist-esm/identity/src/util/processUtils.js.map +0 -1
  138. package/dist-esm/identity/src/util/scopeUtils.js +0 -29
  139. package/dist-esm/identity/src/util/scopeUtils.js.map +0 -1
  140. package/dist-esm/identity/src/util/subscriptionUtils.js +0 -14
  141. package/dist-esm/identity/src/util/subscriptionUtils.js.map +0 -1
  142. package/dist-esm/identity/src/util/tenantIdUtils.js +0 -44
  143. package/dist-esm/identity/src/util/tenantIdUtils.js.map +0 -1
  144. package/dist-esm/identity/src/util/tracing.js +0 -14
  145. package/dist-esm/identity/src/util/tracing.js.map +0 -1
  146. package/dist-esm/identity-cache-persistence/src/index.js.map +0 -1
  147. package/dist-esm/identity-cache-persistence/src/platforms.js.map +0 -1
  148. package/dist-esm/identity-cache-persistence/src/provider.js.map +0 -1
  149. /package/dist-esm/{identity-cache-persistence/src → src}/index.js +0 -0
  150. /package/dist-esm/{identity-cache-persistence/src → src}/platforms.js +0 -0
  151. /package/dist-esm/{identity-cache-persistence/src → src}/provider.js +0 -0
@@ -1,4 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- export {};
4
- //# sourceMappingURL=azurePipelinesCredentialOptions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"azurePipelinesCredentialOptions.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/azurePipelinesCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport type { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport type { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Optional parameters for the {@link AzurePipelinesCredential} class.\n */\nexport interface AzurePipelinesCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n CredentialPersistenceOptions,\n AuthorityValidationOptions {}\n"]}
@@ -1,238 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import { __awaiter } from "tslib";
4
- import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
5
- import { credentialLogger, formatError, formatSuccess } from "../util/logging";
6
- import { ensureValidScopeForDevTimeCreds, getScopeResource } from "../util/scopeUtils";
7
- import { CredentialUnavailableError } from "../errors";
8
- import { processUtils } from "../util/processUtils";
9
- import { tracingClient } from "../util/tracing";
10
- const logger = credentialLogger("AzurePowerShellCredential");
11
- const isWindows = process.platform === "win32";
12
- /**
13
- * Returns a platform-appropriate command name by appending ".exe" on Windows.
14
- *
15
- * @internal
16
- */
17
- export function formatCommand(commandName) {
18
- if (isWindows) {
19
- return `${commandName}.exe`;
20
- }
21
- else {
22
- return commandName;
23
- }
24
- }
25
- /**
26
- * Receives a list of commands to run, executes them, then returns the outputs.
27
- * If anything fails, an error is thrown.
28
- * @internal
29
- */
30
- function runCommands(commands, timeout) {
31
- return __awaiter(this, void 0, void 0, function* () {
32
- const results = [];
33
- for (const command of commands) {
34
- const [file, ...parameters] = command;
35
- const result = (yield processUtils.execFile(file, parameters, {
36
- encoding: "utf8",
37
- timeout,
38
- }));
39
- results.push(result);
40
- }
41
- return results;
42
- });
43
- }
44
- /**
45
- * Known PowerShell errors
46
- * @internal
47
- */
48
- export const powerShellErrors = {
49
- login: "Run Connect-AzAccount to login",
50
- installed: "The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory",
51
- };
52
- /**
53
- * Messages to use when throwing in this credential.
54
- * @internal
55
- */
56
- export const powerShellPublicErrorMessages = {
57
- login: "Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.",
58
- 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".`,
59
- troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`,
60
- };
61
- // PowerShell Azure User not logged in error check.
62
- const isLoginError = (err) => err.message.match(`(.*)${powerShellErrors.login}(.*)`);
63
- // Az Module not Installed in Azure PowerShell check.
64
- const isNotInstalledError = (err) => err.message.match(powerShellErrors.installed);
65
- /**
66
- * The PowerShell commands to be tried, in order.
67
- *
68
- * @internal
69
- */
70
- export const commandStack = [formatCommand("pwsh")];
71
- if (isWindows) {
72
- commandStack.push(formatCommand("powershell"));
73
- }
74
- /**
75
- * This credential will use the currently logged-in user information from the
76
- * Azure PowerShell module. To do so, it will read the user access token and
77
- * expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}`
78
- */
79
- export class AzurePowerShellCredential {
80
- /**
81
- * Creates an instance of the {@link AzurePowerShellCredential}.
82
- *
83
- * To use this credential:
84
- * - Install the Azure Az PowerShell module with:
85
- * `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`.
86
- * - You have already logged in to Azure PowerShell using the command
87
- * `Connect-AzAccount` from the command line.
88
- *
89
- * @param options - Options, to optionally allow multi-tenant requests.
90
- */
91
- constructor(options) {
92
- if (options === null || options === void 0 ? void 0 : options.tenantId) {
93
- checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId);
94
- this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId;
95
- }
96
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
97
- this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs;
98
- }
99
- /**
100
- * Gets the access token from Azure PowerShell
101
- * @param resource - The resource to use when getting the token
102
- */
103
- getAzurePowerShellAccessToken(resource, tenantId, timeout) {
104
- return __awaiter(this, void 0, void 0, function* () {
105
- // Clone the stack to avoid mutating it while iterating
106
- for (const powerShellCommand of [...commandStack]) {
107
- try {
108
- yield runCommands([[powerShellCommand, "/?"]], timeout);
109
- }
110
- catch (e) {
111
- // Remove this credential from the original stack so that we don't try it again.
112
- commandStack.shift();
113
- continue;
114
- }
115
- const results = yield runCommands([
116
- [
117
- powerShellCommand,
118
- "-NoProfile",
119
- "-NonInteractive",
120
- "-Command",
121
- `
122
- $tenantId = "${tenantId !== null && tenantId !== void 0 ? tenantId : ""}"
123
- $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru
124
- $useSecureString = $m.Version -ge [version]'2.17.0'
125
-
126
- $params = @{
127
- ResourceUrl = "${resource}"
128
- }
129
-
130
- if ($tenantId.Length -gt 0) {
131
- $params["TenantId"] = $tenantId
132
- }
133
-
134
- if ($useSecureString) {
135
- $params["AsSecureString"] = $true
136
- }
137
-
138
- $token = Get-AzAccessToken @params
139
-
140
- $result = New-Object -TypeName PSObject
141
- $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn
142
- if ($useSecureString) {
143
- $result | Add-Member -MemberType NoteProperty -Name Token -Value (ConvertFrom-SecureString -AsPlainText $token.Token)
144
- } else {
145
- $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token
146
- }
147
-
148
- Write-Output (ConvertTo-Json $result)
149
- `,
150
- ],
151
- ]);
152
- const result = results[0];
153
- return parseJsonToken(result);
154
- }
155
- throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);
156
- });
157
- }
158
- /**
159
- * Authenticates with Microsoft Entra ID and returns an access token if successful.
160
- * If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown.
161
- *
162
- * @param scopes - The list of scopes for which the token will have access.
163
- * @param options - The options used to configure any requests this TokenCredential implementation might make.
164
- */
165
- getToken(scopes_1) {
166
- return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
167
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, () => __awaiter(this, void 0, void 0, function* () {
168
- const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds);
169
- const scope = typeof scopes === "string" ? scopes : scopes[0];
170
- if (tenantId) {
171
- checkTenantId(logger, tenantId);
172
- }
173
- try {
174
- ensureValidScopeForDevTimeCreds(scope, logger);
175
- logger.getToken.info(`Using the scope ${scope}`);
176
- const resource = getScopeResource(scope);
177
- const response = yield this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout);
178
- logger.getToken.info(formatSuccess(scopes));
179
- return {
180
- token: response.Token,
181
- expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),
182
- tokenType: "Bearer",
183
- };
184
- }
185
- catch (err) {
186
- if (isNotInstalledError(err)) {
187
- const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);
188
- logger.getToken.info(formatError(scope, error));
189
- throw error;
190
- }
191
- else if (isLoginError(err)) {
192
- const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);
193
- logger.getToken.info(formatError(scope, error));
194
- throw error;
195
- }
196
- const error = new CredentialUnavailableError(`${err}. ${powerShellPublicErrorMessages.troubleshoot}`);
197
- logger.getToken.info(formatError(scope, error));
198
- throw error;
199
- }
200
- }));
201
- });
202
- }
203
- }
204
- /**
205
- *
206
- * @internal
207
- */
208
- export function parseJsonToken(result) {
209
- return __awaiter(this, void 0, void 0, function* () {
210
- const jsonRegex = /{[^{}]*}/g;
211
- const matches = result.match(jsonRegex);
212
- let resultWithoutToken = result;
213
- if (matches) {
214
- try {
215
- for (const item of matches) {
216
- try {
217
- const jsonContent = JSON.parse(item);
218
- if (jsonContent === null || jsonContent === void 0 ? void 0 : jsonContent.Token) {
219
- resultWithoutToken = resultWithoutToken.replace(item, "");
220
- if (resultWithoutToken) {
221
- logger.getToken.warning(resultWithoutToken);
222
- }
223
- return jsonContent;
224
- }
225
- }
226
- catch (e) {
227
- continue;
228
- }
229
- }
230
- }
231
- catch (e) {
232
- throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);
233
- }
234
- }
235
- throw new Error(`No access token found in the output. Received output: ${result}`);
236
- });
237
- }
238
- //# sourceMappingURL=azurePowerShellCredential.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"azurePowerShellCredential.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/azurePowerShellCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAGlC,OAAO,EACL,aAAa,EACb,yBAAyB,EACzB,mCAAmC,GACpC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,+BAA+B,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGvF,OAAO,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D,MAAM,SAAS,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;AAE/C;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,WAAmB;IAC/C,IAAI,SAAS,EAAE,CAAC;QACd,OAAO,GAAG,WAAW,MAAM,CAAC;IAC9B,CAAC;SAAM,CAAC;QACN,OAAO,WAAW,CAAC;IACrB,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,SAAe,WAAW,CAAC,QAAoB,EAAE,OAAgB;;QAC/D,MAAM,OAAO,GAAa,EAAE,CAAC;QAE7B,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC/B,MAAM,CAAC,IAAI,EAAE,GAAG,UAAU,CAAC,GAAG,OAAO,CAAC;YACtC,MAAM,MAAM,GAAG,CAAC,MA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OAAO,CAAC,EAAE,CAAC;wBACX,SAAS;oBACX,CAAC;gBACH,CAAC;YACH,CAAC;YAAC,OAAO,CAAM,EAAE,CAAC;gBAChB,MAAM,IAAI,KAAK,CAAC,8DAA8D,MAAM,EAAE,CAAC,CAAC;YAC1F,CAAC;QACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,yDAAyD,MAAM,EAAE,CAAC,CAAC;IACrF,CAAC;CAAA","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\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils\";\n\nimport type { AzurePowerShellCredentialOptions } from \"./azurePowerShellCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { processUtils } from \"../util/processUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"AzurePowerShellCredential\");\n\nconst isWindows = process.platform === \"win32\";\n\n/**\n * Returns a platform-appropriate command name by appending \".exe\" on Windows.\n *\n * @internal\n */\nexport function formatCommand(commandName: string): string {\n if (isWindows) {\n return `${commandName}.exe`;\n } else {\n return commandName;\n }\n}\n\n/**\n * Receives a list of commands to run, executes them, then returns the outputs.\n * If anything fails, an error is thrown.\n * @internal\n */\nasync function runCommands(commands: string[][], timeout?: number): Promise<string[]> {\n const results: string[] = [];\n\n for (const command of commands) {\n const [file, ...parameters] = command;\n const result = (await processUtils.execFile(file, parameters, {\n encoding: \"utf8\",\n timeout,\n })) as string;\n\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Known PowerShell errors\n * @internal\n */\nexport const powerShellErrors = {\n login: \"Run Connect-AzAccount to login\",\n installed:\n \"The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory\",\n};\n\n/**\n * Messages to use when throwing in this credential.\n * @internal\n */\nexport const powerShellPublicErrorMessages = {\n login:\n \"Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.\",\n installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: \"Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force\".`,\n troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`,\n};\n\n// PowerShell Azure User not logged in error check.\nconst isLoginError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(`(.*)${powerShellErrors.login}(.*)`);\n\n// Az Module not Installed in Azure PowerShell check.\nconst isNotInstalledError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(powerShellErrors.installed);\n\n/**\n * The PowerShell commands to be tried, in order.\n *\n * @internal\n */\nexport const commandStack = [formatCommand(\"pwsh\")];\n\nif (isWindows) {\n commandStack.push(formatCommand(\"powershell\"));\n}\n\n/**\n * This credential will use the currently logged-in user information from the\n * Azure PowerShell module. To do so, it will read the user access token and\n * expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}`\n */\nexport class AzurePowerShellCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzurePowerShellCredential}.\n *\n * To use this credential:\n * - Install the Azure Az PowerShell module with:\n * `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`.\n * - You have already logged in to Azure PowerShell using the command\n * `Connect-AzAccount` from the command line.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzurePowerShellCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Gets the access token from Azure PowerShell\n * @param resource - The resource to use when getting the token\n */\n private async getAzurePowerShellAccessToken(\n resource: string,\n tenantId?: string,\n timeout?: number,\n ): Promise<{ Token: string; ExpiresOn: string }> {\n // Clone the stack to avoid mutating it while iterating\n for (const powerShellCommand of [...commandStack]) {\n try {\n await runCommands([[powerShellCommand, \"/?\"]], timeout);\n } catch (e: any) {\n // Remove this credential from the original stack so that we don't try it again.\n commandStack.shift();\n continue;\n }\n\n const results = await runCommands([\n [\n powerShellCommand,\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `\n $tenantId = \"${tenantId ?? \"\"}\"\n $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru\n $useSecureString = $m.Version -ge [version]'2.17.0'\n\n $params = @{\n ResourceUrl = \"${resource}\"\n }\n\n if ($tenantId.Length -gt 0) {\n $params[\"TenantId\"] = $tenantId\n }\n\n if ($useSecureString) {\n $params[\"AsSecureString\"] = $true\n }\n\n $token = Get-AzAccessToken @params\n\n $result = New-Object -TypeName PSObject\n $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn\n if ($useSecureString) {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value (ConvertFrom-SecureString -AsPlainText $token.Token)\n } else {\n $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token\n }\n\n Write-Output (ConvertTo-Json $result)\n `,\n ],\n ]);\n\n const result = results[0];\n return parseJsonToken(result);\n }\n throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<AccessToken> {\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n );\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n try {\n ensureValidScopeForDevTimeCreds(scope, logger);\n logger.getToken.info(`Using the scope ${scope}`);\n const resource = getScopeResource(scope);\n const response = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.Token,\n expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),\n tokenType: \"Bearer\",\n } as AccessToken;\n } catch (err: any) {\n if (isNotInstalledError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);\n logger.getToken.info(formatError(scope, error));\n throw error;\n } else if (isLoginError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n const error = new CredentialUnavailableError(\n `${err}. ${powerShellPublicErrorMessages.troubleshoot}`,\n );\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n });\n }\n}\n\n/**\n *\n * @internal\n */\nexport async function parseJsonToken(\n result: string,\n): Promise<{ Token: string; ExpiresOn: string }> {\n const jsonRegex = /{[^{}]*}/g;\n const matches = result.match(jsonRegex);\n let resultWithoutToken = result;\n if (matches) {\n try {\n for (const item of matches) {\n try {\n const jsonContent = JSON.parse(item);\n if (jsonContent?.Token) {\n resultWithoutToken = resultWithoutToken.replace(item, \"\");\n if (resultWithoutToken) {\n logger.getToken.warning(resultWithoutToken);\n }\n return jsonContent;\n }\n } catch (e) {\n continue;\n }\n }\n } catch (e: any) {\n throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);\n }\n }\n throw new Error(`No access token found in the output. Received output: ${result}`);\n}\n"]}
@@ -1,4 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- export {};
4
- //# sourceMappingURL=azurePowerShellCredentialOptions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"azurePowerShellCredentialOptions.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/azurePowerShellCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Options for the {@link AzurePowerShellCredential}\n */\nexport interface AzurePowerShellCredentialOptions extends MultiTenantTokenCredentialOptions {\n /**\n * Allows specifying a tenant ID\n */\n tenantId?: string;\n /**\n * Process timeout configurable for making token requests, provided in milliseconds\n */\n processTimeoutInMs?: number;\n}\n"]}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=brokerAuthOptions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"brokerAuthOptions.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/brokerAuthOptions.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport type { BrokerOptions } from \"../msal/nodeFlows/brokerOptions\";\n\n/**\n * Configuration options for InteractiveBrowserCredential\n * to support WAM Broker Authentication.\n */\n\nexport interface BrokerAuthOptions {\n /**\n * Options to allow broker authentication when using InteractiveBrowserCredential\n *\n */\n brokerOptions?: BrokerOptions;\n}\n"]}
@@ -1,4 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- export {};
4
- //# sourceMappingURL=browserCustomizationOptions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"browserCustomizationOptions.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/browserCustomizationOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Shared configuration options for browser customization\n */\nexport interface BrowserCustomizationOptions {\n /**\n * Shared configuration options for browser customization\n */\n browserCustomizationOptions?: {\n /**\n * Format for error messages for display in browser\n */\n errorMessage?: string;\n /**\n * Format for success messages for display in browser\n */\n successMessage?: string;\n };\n}\n"]}
@@ -1,95 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import { __awaiter } from "tslib";
4
- import { AggregateAuthenticationError, CredentialUnavailableError } from "../errors";
5
- import { credentialLogger, formatError, formatSuccess } from "../util/logging";
6
- import { tracingClient } from "../util/tracing";
7
- /**
8
- * @internal
9
- */
10
- export const logger = credentialLogger("ChainedTokenCredential");
11
- /**
12
- * Enables multiple `TokenCredential` implementations to be tried in order until
13
- * one of the getToken methods returns an access token. For more information, see
14
- * [ChainedTokenCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-chainedtokencredential-for-granularity).
15
- */
16
- export class ChainedTokenCredential {
17
- /**
18
- * Creates an instance of ChainedTokenCredential using the given credentials.
19
- *
20
- * @param sources - `TokenCredential` implementations to be tried in order.
21
- *
22
- * Example usage:
23
- * ```ts snippet:chained_token_credential_example
24
- * import { ClientSecretCredential, ChainedTokenCredential } from "@azure/identity";
25
- *
26
- * const tenantId = "<tenant-id>";
27
- * const clientId = "<client-id>";
28
- * const clientSecret = "<client-secret>";
29
- * const anotherClientId = "<another-client-id>";
30
- * const anotherSecret = "<another-client-secret>";
31
- * const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
32
- * const secondCredential = new ClientSecretCredential(tenantId, anotherClientId, anotherSecret);
33
- * const credentialChain = new ChainedTokenCredential(firstCredential, secondCredential);
34
- * ```
35
- */
36
- constructor(...sources) {
37
- this._sources = [];
38
- this._sources = sources;
39
- }
40
- /**
41
- * Returns the first access token returned by one of the chained
42
- * `TokenCredential` implementations. Throws an {@link AggregateAuthenticationError}
43
- * when one or more credentials throws an {@link AuthenticationError} and
44
- * no credentials have returned an access token.
45
- *
46
- * This method is called automatically by Azure SDK client libraries. You may call this method
47
- * directly, but you must also handle token caching and token refreshing.
48
- *
49
- * @param scopes - The list of scopes for which the token will have access.
50
- * @param options - The options used to configure any requests this
51
- * `TokenCredential` implementation might make.
52
- */
53
- getToken(scopes_1) {
54
- return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
55
- const { token } = yield this.getTokenInternal(scopes, options);
56
- return token;
57
- });
58
- }
59
- getTokenInternal(scopes_1) {
60
- return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
61
- let token = null;
62
- let successfulCredential;
63
- const errors = [];
64
- return tracingClient.withSpan("ChainedTokenCredential.getToken", options, (updatedOptions) => __awaiter(this, void 0, void 0, function* () {
65
- for (let i = 0; i < this._sources.length && token === null; i++) {
66
- try {
67
- token = yield this._sources[i].getToken(scopes, updatedOptions);
68
- successfulCredential = this._sources[i];
69
- }
70
- catch (err) {
71
- if (err.name === "CredentialUnavailableError" ||
72
- err.name === "AuthenticationRequiredError") {
73
- errors.push(err);
74
- }
75
- else {
76
- logger.getToken.info(formatError(scopes, err));
77
- throw err;
78
- }
79
- }
80
- }
81
- if (!token && errors.length > 0) {
82
- const err = new AggregateAuthenticationError(errors, "ChainedTokenCredential authentication failed.");
83
- logger.getToken.info(formatError(scopes, err));
84
- throw err;
85
- }
86
- logger.getToken.info(`Result for ${successfulCredential.constructor.name}: ${formatSuccess(scopes)}`);
87
- if (token === null) {
88
- throw new CredentialUnavailableError("Failed to retrieve a valid token");
89
- }
90
- return { token, successfulCredential };
91
- }));
92
- });
93
- }
94
- }
95
- //# sourceMappingURL=chainedTokenCredential.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"chainedTokenCredential.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/chainedTokenCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAGlC,OAAO,EAAE,4BAA4B,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AACrF,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE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C1C,CAAC;4BACD,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;wBACnB,CAAC;6BAAM,CAAC;4BACN,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;4BAC/C,MAAM,GAAG,CAAC;wBACZ,CAAC;oBACH,CAAC;gBACH,CAAC;gBAED,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBAChC,MAAM,GAAG,GAAG,IAAI,4BAA4B,CAC1C,MAAM,EACN,+CAA+C,CAChD,CAAC;oBACF,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;oBAC/C,MAAM,GAAG,CAAC;gBACZ,CAAC;gBAED,MAAM,CAAC,QAAQ,CAAC,IAAI,CAClB,cAAc,oBAAoB,CAAC,WAAW,CAAC,IAAI,KAAK,aAAa,CAAC,MAAM,CAAC,EAAE,CAChF,CAAC;gBAEF,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;oBACnB,MAAM,IAAI,0BAA0B,CAAC,kCAAkC,CAAC,CAAC;gBAC3E,CAAC;gBACD,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC;YACzC,CAAC,CAAA,CACF,CAAC;QACJ,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AggregateAuthenticationError, CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\n\n/**\n * @internal\n */\nexport const logger = credentialLogger(\"ChainedTokenCredential\");\n\n/**\n * Enables multiple `TokenCredential` implementations to be tried in order until\n * one of the getToken methods returns an access token. For more information, see\n * [ChainedTokenCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-chainedtokencredential-for-granularity).\n */\nexport class ChainedTokenCredential implements TokenCredential {\n private _sources: TokenCredential[] = [];\n\n /**\n * Creates an instance of ChainedTokenCredential using the given credentials.\n *\n * @param sources - `TokenCredential` implementations to be tried in order.\n *\n * Example usage:\n * ```ts snippet:chained_token_credential_example\n * import { ClientSecretCredential, ChainedTokenCredential } from \"@azure/identity\";\n *\n * const tenantId = \"<tenant-id>\";\n * const clientId = \"<client-id>\";\n * const clientSecret = \"<client-secret>\";\n * const anotherClientId = \"<another-client-id>\";\n * const anotherSecret = \"<another-client-secret>\";\n * const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);\n * const secondCredential = new ClientSecretCredential(tenantId, anotherClientId, anotherSecret);\n * const credentialChain = new ChainedTokenCredential(firstCredential, secondCredential);\n * ```\n */\n constructor(...sources: TokenCredential[]) {\n this._sources = sources;\n }\n\n /**\n * Returns the first access token returned by one of the chained\n * `TokenCredential` implementations. Throws an {@link AggregateAuthenticationError}\n * when one or more credentials throws an {@link AuthenticationError} and\n * no credentials have returned an access token.\n *\n * This method is called automatically by Azure SDK client libraries. You may call this method\n * directly, but you must also handle token caching and token refreshing.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * `TokenCredential` implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n const { token } = await this.getTokenInternal(scopes, options);\n return token;\n }\n\n private async getTokenInternal(\n scopes: string | string[],\n options: GetTokenOptions = {},\n ): Promise<{ token: AccessToken; successfulCredential: TokenCredential }> {\n let token: AccessToken | null = null;\n let successfulCredential: TokenCredential;\n const errors: Error[] = [];\n\n return tracingClient.withSpan(\n \"ChainedTokenCredential.getToken\",\n options,\n async (updatedOptions) => {\n for (let i = 0; i < this._sources.length && token === null; i++) {\n try {\n token = await this._sources[i].getToken(scopes, updatedOptions);\n successfulCredential = this._sources[i];\n } catch (err: any) {\n if (\n err.name === \"CredentialUnavailableError\" ||\n err.name === \"AuthenticationRequiredError\"\n ) {\n errors.push(err);\n } else {\n logger.getToken.info(formatError(scopes, err));\n throw err;\n }\n }\n }\n\n if (!token && errors.length > 0) {\n const err = new AggregateAuthenticationError(\n errors,\n \"ChainedTokenCredential authentication failed.\",\n );\n logger.getToken.info(formatError(scopes, err));\n throw err;\n }\n\n logger.getToken.info(\n `Result for ${successfulCredential.constructor.name}: ${formatSuccess(scopes)}`,\n );\n\n if (token === null) {\n throw new CredentialUnavailableError(\"Failed to retrieve a valid token\");\n }\n return { token, successfulCredential };\n },\n );\n }\n}\n"]}
@@ -1,58 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import { __awaiter } from "tslib";
4
- import { createMsalClient } from "../msal/nodeFlows/msalClient";
5
- import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
6
- import { CredentialUnavailableError } from "../errors";
7
- import { credentialLogger } from "../util/logging";
8
- import { tracingClient } from "../util/tracing";
9
- const logger = credentialLogger("ClientAssertionCredential");
10
- /**
11
- * Authenticates a service principal with a JWT assertion.
12
- */
13
- export class ClientAssertionCredential {
14
- /**
15
- * Creates an instance of the ClientAssertionCredential with the details
16
- * needed to authenticate against Microsoft Entra ID with a client
17
- * assertion provided by the developer through the `getAssertion` function parameter.
18
- *
19
- * @param tenantId - The Microsoft Entra tenant (directory) ID.
20
- * @param clientId - The client (application) ID of an App Registration in the tenant.
21
- * @param getAssertion - A function that retrieves the assertion for the credential to use.
22
- * @param options - Options for configuring the client which makes the authentication request.
23
- */
24
- constructor(tenantId, clientId, getAssertion, options = {}) {
25
- if (!tenantId) {
26
- throw new CredentialUnavailableError("ClientAssertionCredential: tenantId is a required parameter.");
27
- }
28
- if (!clientId) {
29
- throw new CredentialUnavailableError("ClientAssertionCredential: clientId is a required parameter.");
30
- }
31
- if (!getAssertion) {
32
- throw new CredentialUnavailableError("ClientAssertionCredential: clientAssertion is a required parameter.");
33
- }
34
- this.tenantId = tenantId;
35
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
36
- this.options = options;
37
- this.getAssertion = getAssertion;
38
- this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: this.options }));
39
- }
40
- /**
41
- * Authenticates with Microsoft Entra ID and returns an access token if successful.
42
- * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
43
- *
44
- * @param scopes - The list of scopes for which the token will have access.
45
- * @param options - The options used to configure any requests this
46
- * TokenCredential implementation might make.
47
- */
48
- getToken(scopes_1) {
49
- return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
50
- return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, (newOptions) => __awaiter(this, void 0, void 0, function* () {
51
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger);
52
- const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
53
- return this.msalClient.getTokenByClientAssertion(arrayScopes, this.getAssertion, newOptions);
54
- }));
55
- });
56
- }
57
- }
58
- //# sourceMappingURL=clientAssertionCredential.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"clientAssertionCredential.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/clientAssertionCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAIlC,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EACL,yBAAyB,EACzB,mCAAmC,GACpC,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,MAAM,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;AAE7D;;G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,CAAC;gBAC9D,OAAO,IAAI,CAAC,UAAU,CAAC,yBAAyB,CAC9C,WAAW,EACX,IAAI,CAAC,YAAY,EACjB,UAAU,CACX,CAAC;YACJ,CAAC,CAAA,CACF,CAAC;QACJ,CAAC;KAAA;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type { MsalClient } from \"../msal/nodeFlows/msalClient\";\nimport { createMsalClient } from \"../msal/nodeFlows/msalClient\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\n\nimport type { ClientAssertionCredentialOptions } from \"./clientAssertionCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"ClientAssertionCredential\");\n\n/**\n * Authenticates a service principal with a JWT assertion.\n */\nexport class ClientAssertionCredential implements TokenCredential {\n private msalClient: MsalClient;\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private getAssertion: () => Promise<string>;\n private options: ClientAssertionCredentialOptions;\n\n /**\n * Creates an instance of the ClientAssertionCredential with the details\n * needed to authenticate against Microsoft Entra ID with a client\n * assertion provided by the developer through the `getAssertion` function parameter.\n *\n * @param tenantId - The Microsoft Entra tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param getAssertion - A function that retrieves the assertion for the credential to use.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n getAssertion: () => Promise<string>,\n options: ClientAssertionCredentialOptions = {},\n ) {\n if (!tenantId) {\n throw new CredentialUnavailableError(\n \"ClientAssertionCredential: tenantId is a required parameter.\",\n );\n }\n\n if (!clientId) {\n throw new CredentialUnavailableError(\n \"ClientAssertionCredential: clientId is a required parameter.\",\n );\n }\n\n if (!getAssertion) {\n throw new CredentialUnavailableError(\n \"ClientAssertionCredential: clientAssertion is a required parameter.\",\n );\n }\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants,\n );\n\n this.options = options;\n this.getAssertion = getAssertion;\n this.msalClient = createMsalClient(clientId, tenantId, {\n ...options,\n logger,\n tokenCredentialOptions: this.options,\n });\n }\n\n /**\n * Authenticates with Microsoft Entra ID and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger,\n );\n\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n return this.msalClient.getTokenByClientAssertion(\n arrayScopes,\n this.getAssertion,\n newOptions,\n );\n },\n );\n }\n}\n"]}
@@ -1,4 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- export {};
4
- //# sourceMappingURL=clientAssertionCredentialOptions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"clientAssertionCredentialOptions.js","sourceRoot":"","sources":["../../../../../identity/src/credentials/clientAssertionCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AuthorityValidationOptions } from \"./authorityValidationOptions\";\nimport type { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport type { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\n\n/**\n * Options for the {@link ClientAssertionCredential}\n */\nexport interface ClientAssertionCredentialOptions\n extends MultiTenantTokenCredentialOptions,\n CredentialPersistenceOptions,\n AuthorityValidationOptions {}\n"]}
@@ -1,126 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import { __awaiter } from "tslib";
4
- import { createMsalClient } from "../msal/nodeFlows/msalClient";
5
- import { createHash, createPrivateKey } from "crypto";
6
- import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils";
7
- import { credentialLogger } from "../util/logging";
8
- import { readFile } from "fs/promises";
9
- import { tracingClient } from "../util/tracing";
10
- const credentialName = "ClientCertificateCredential";
11
- const logger = credentialLogger(credentialName);
12
- /**
13
- * Enables authentication to Microsoft Entra ID using a PEM-encoded
14
- * certificate that is assigned to an App Registration. More information
15
- * on how to configure certificate authentication can be found here:
16
- *
17
- * https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad
18
- *
19
- */
20
- export class ClientCertificateCredential {
21
- constructor(tenantId, clientId, certificatePathOrConfiguration, options = {}) {
22
- if (!tenantId || !clientId) {
23
- throw new Error(`${credentialName}: tenantId and clientId are required parameters.`);
24
- }
25
- this.tenantId = tenantId;
26
- this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants);
27
- this.sendCertificateChain = options.sendCertificateChain;
28
- this.certificateConfiguration = Object.assign({}, (typeof certificatePathOrConfiguration === "string"
29
- ? {
30
- certificatePath: certificatePathOrConfiguration,
31
- }
32
- : certificatePathOrConfiguration));
33
- const certificate = this.certificateConfiguration.certificate;
34
- const certificatePath = this.certificateConfiguration.certificatePath;
35
- if (!this.certificateConfiguration || !(certificate || certificatePath)) {
36
- throw new Error(`${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
37
- }
38
- if (certificate && certificatePath) {
39
- throw new Error(`${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);
40
- }
41
- this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options }));
42
- }
43
- /**
44
- * Authenticates with Microsoft Entra ID and returns an access token if successful.
45
- * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.
46
- *
47
- * @param scopes - The list of scopes for which the token will have access.
48
- * @param options - The options used to configure any requests this
49
- * TokenCredential implementation might make.
50
- */
51
- getToken(scopes_1) {
52
- return __awaiter(this, arguments, void 0, function* (scopes, options = {}) {
53
- return tracingClient.withSpan(`${credentialName}.getToken`, options, (newOptions) => __awaiter(this, void 0, void 0, function* () {
54
- newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger);
55
- const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];
56
- const certificate = yield this.buildClientCertificate();
57
- return this.msalClient.getTokenByClientCertificate(arrayScopes, certificate, newOptions);
58
- }));
59
- });
60
- }
61
- buildClientCertificate() {
62
- return __awaiter(this, void 0, void 0, function* () {
63
- var _a;
64
- const parts = yield parseCertificate(this.certificateConfiguration, (_a = this.sendCertificateChain) !== null && _a !== void 0 ? _a : false);
65
- let privateKey;
66
- if (this.certificateConfiguration.certificatePassword !== undefined) {
67
- privateKey = createPrivateKey({
68
- key: parts.certificateContents,
69
- passphrase: this.certificateConfiguration.certificatePassword,
70
- format: "pem",
71
- })
72
- .export({
73
- format: "pem",
74
- type: "pkcs8",
75
- })
76
- .toString();
77
- }
78
- else {
79
- privateKey = parts.certificateContents;
80
- }
81
- return {
82
- thumbprint: parts.thumbprint,
83
- privateKey,
84
- x5c: parts.x5c,
85
- };
86
- });
87
- }
88
- }
89
- /**
90
- * Parses a certificate into its relevant parts
91
- *
92
- * @param certificateConfiguration - The certificate contents or path to the certificate
93
- * @param sendCertificateChain - true if the entire certificate chain should be sent for SNI, false otherwise
94
- * @returns The parsed certificate parts and the certificate contents
95
- */
96
- export function parseCertificate(certificateConfiguration, sendCertificateChain) {
97
- return __awaiter(this, void 0, void 0, function* () {
98
- const certificate = certificateConfiguration.certificate;
99
- const certificatePath = certificateConfiguration.certificatePath;
100
- const certificateContents = certificate || (yield readFile(certificatePath, "utf8"));
101
- const x5c = sendCertificateChain ? certificateContents : undefined;
102
- const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g;
103
- const publicKeys = [];
104
- // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c
105
- let match;
106
- do {
107
- match = certificatePattern.exec(certificateContents);
108
- if (match) {
109
- publicKeys.push(match[3]);
110
- }
111
- } while (match);
112
- if (publicKeys.length === 0) {
113
- throw new Error("The file at the specified path does not contain a PEM-encoded certificate.");
114
- }
115
- const thumbprint = createHash("sha1")
116
- .update(Buffer.from(publicKeys[0], "base64"))
117
- .digest("hex")
118
- .toUpperCase();
119
- return {
120
- certificateContents,
121
- thumbprint,
122
- x5c,
123
- };
124
- });
125
- }
126
- //# sourceMappingURL=clientCertificateCredential.js.map