@azure/identity 3.2.4 → 3.3.0

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.

Potentially problematic release.


This version of @azure/identity might be problematic. Click here for more details.

Files changed (39) hide show
  1. package/README.md +20 -56
  2. package/dist/index.js +82 -36
  3. package/dist/index.js.map +1 -1
  4. package/dist-esm/src/constants.js +3 -1
  5. package/dist-esm/src/constants.js.map +1 -1
  6. package/dist-esm/src/credentials/azureCliCredential.js +3 -3
  7. package/dist-esm/src/credentials/azureCliCredential.js.map +1 -1
  8. package/dist-esm/src/credentials/azurePowerShellCredential.js +4 -4
  9. package/dist-esm/src/credentials/azurePowerShellCredential.js.map +1 -1
  10. package/dist-esm/src/credentials/managedIdentityCredential/index.js +1 -0
  11. package/dist-esm/src/credentials/managedIdentityCredential/index.js.map +1 -1
  12. package/dist-esm/src/msal/browserFlows/msalAuthCode.js +2 -0
  13. package/dist-esm/src/msal/browserFlows/msalAuthCode.js.map +1 -1
  14. package/dist-esm/src/msal/browserFlows/msalBrowserCommon.js.map +1 -1
  15. package/dist-esm/src/msal/credentials.js.map +1 -1
  16. package/dist-esm/src/msal/nodeFlows/msalAuthorizationCode.js +6 -4
  17. package/dist-esm/src/msal/nodeFlows/msalAuthorizationCode.js.map +1 -1
  18. package/dist-esm/src/msal/nodeFlows/msalClientAssertion.js +1 -1
  19. package/dist-esm/src/msal/nodeFlows/msalClientAssertion.js.map +1 -1
  20. package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js +1 -1
  21. package/dist-esm/src/msal/nodeFlows/msalClientCertificate.js.map +1 -1
  22. package/dist-esm/src/msal/nodeFlows/msalClientSecret.js +1 -1
  23. package/dist-esm/src/msal/nodeFlows/msalClientSecret.js.map +1 -1
  24. package/dist-esm/src/msal/nodeFlows/msalDeviceCode.js +1 -1
  25. package/dist-esm/src/msal/nodeFlows/msalDeviceCode.js.map +1 -1
  26. package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js +57 -16
  27. package/dist-esm/src/msal/nodeFlows/msalNodeCommon.js.map +1 -1
  28. package/dist-esm/src/msal/nodeFlows/msalOnBehalfOf.js +1 -1
  29. package/dist-esm/src/msal/nodeFlows/msalOnBehalfOf.js.map +1 -1
  30. package/dist-esm/src/msal/nodeFlows/msalOpenBrowser.js +4 -4
  31. package/dist-esm/src/msal/nodeFlows/msalOpenBrowser.js.map +1 -1
  32. package/dist-esm/src/msal/nodeFlows/msalUsernamePassword.js +1 -1
  33. package/dist-esm/src/msal/nodeFlows/msalUsernamePassword.js.map +1 -1
  34. package/dist-esm/src/msal/types.js.map +1 -1
  35. package/dist-esm/src/tokenCredentialOptions.js.map +1 -1
  36. package/dist-esm/src/util/scopeUtils.js +1 -1
  37. package/dist-esm/src/util/scopeUtils.js.map +1 -1
  38. package/package.json +5 -5
  39. package/types/identity.d.ts +8 -1
@@ -97,7 +97,7 @@ export class MsalClientCertificate extends MsalNode {
97
97
  authority: options.authority,
98
98
  claims: options.claims,
99
99
  };
100
- const result = await this.confidentialApp.acquireTokenByClientCredential(clientCredReq);
100
+ const result = await this.getApp("confidential", options.enableCae).acquireTokenByClientCredential(clientCredReq);
101
101
  // Even though we're providing the same default in memory persistence cache that we use for DeviceCodeCredential,
102
102
  // The Client Credential flow does not return the account information from the authentication service,
103
103
  // so each time getToken gets called, we will have to acquire a new token through the service.
@@ -1 +1 @@
1
- {"version":3,"file":"msalClientCertificate.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalClientCertificate.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAOlC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAItD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,M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B,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,UAAyC,EAAE;QAE3C,IAAI;YACF,MAAM,aAAa,GAA4B;gBAC7C,MAAM;gBACN,aAAa,EAAE,OAAO,CAAC,aAAa;gBACpC,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;aACvB,CAAC;YACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAgB,CAAC,8BAA8B,CAAC,aAAa,CAAC,CAAC;YACzF,iHAAiH;YACjH,sGAAsG;YACtG,8FAA8F;YAC9F,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC;SACtE;QAAC,OAAO,GAAQ,EAAE;YACjB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;SAC9C;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n ClientCertificateCredentialPEMConfiguration,\n ClientCertificatePEMCertificate,\n ClientCertificatePEMCertificatePath,\n} from \"../../credentials/clientCertificateCredential\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { createHash, createPrivateKey } from \"crypto\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { ClientCredentialRequest } from \"@azure/msal-node\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { formatError } from \"../../util/logging\";\nimport { promisify } from \"util\";\nimport { readFile } from \"fs\";\n\nconst readFileAsync = promisify(readFile);\n\n/**\n * Options that can be passed to configure MSAL to handle client certificates.\n * @internal\n */\nexport interface MsalClientCertificateOptions extends MsalNodeOptions {\n /**\n * Location of the PEM certificate.\n */\n configuration: ClientCertificateCredentialPEMConfiguration;\n /**\n * Option to include x5c header for SubjectName and Issuer name authorization.\n * Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim\n */\n sendCertificateChain?: boolean;\n}\n\n/**\n * Parts of a certificate, as understood by MSAL.\n * @internal\n */\ninterface CertificateParts {\n /**\n * Hex encoded X.509 SHA-1 thumbprint of the certificate\n */\n thumbprint: string;\n /**\n * The PEM encoded private key (string should contain -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY-----\n */\n certificateContents: string;\n /**\n * x5c header.\n */\n x5c: string;\n}\n\n/**\n * Tries to asynchronously load a certificate from the given path.\n *\n * @param configuration - Either the PEM value or the path to the certificate.\n * @param sendCertificateChain - Option to include x5c header for SubjectName and Issuer name authorization.\n * @returns - The certificate parts, or `undefined` if the certificate could not be loaded.\n * @internal\n */\nexport async function parseCertificate(\n configuration: ClientCertificateCredentialPEMConfiguration,\n sendCertificateChain?: boolean\n): Promise<CertificateParts> {\n const certificateParts: Partial<CertificateParts> = {};\n\n const certificate: string | undefined = (configuration as ClientCertificatePEMCertificate)\n .certificate;\n const certificatePath: string | undefined = (configuration as ClientCertificatePEMCertificatePath)\n .certificatePath;\n certificateParts.certificateContents =\n certificate || (await readFileAsync(certificatePath!, \"utf8\"));\n if (sendCertificateChain) {\n certificateParts.x5c = certificateParts.certificateContents;\n }\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateParts.certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n certificateParts.thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return certificateParts as CertificateParts;\n}\n\n/**\n * MSAL client certificate client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.\n * @internal\n */\nexport class MsalClientCertificate extends MsalNode {\n private configuration: ClientCertificateCredentialPEMConfiguration;\n private sendCertificateChain?: boolean;\n\n constructor(options: MsalClientCertificateOptions) {\n super(options);\n this.requiresConfidential = true;\n this.configuration = options.configuration;\n this.sendCertificateChain = options.sendCertificateChain;\n }\n\n // Changing the MSAL configuration asynchronously\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n try {\n const parts = await parseCertificate(this.configuration, this.sendCertificateChain);\n\n let privateKey: string | undefined;\n if (this.configuration.certificatePassword !== undefined) {\n const privateKeyObject = createPrivateKey({\n key: parts.certificateContents,\n passphrase: this.configuration.certificatePassword,\n format: \"pem\",\n });\n\n privateKey = privateKeyObject\n .export({\n format: \"pem\",\n type: \"pkcs8\",\n })\n .toString();\n } else {\n privateKey = parts.certificateContents;\n }\n\n this.msalConfig.auth.clientCertificate = {\n thumbprint: parts.thumbprint,\n privateKey: privateKey,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n this.logger.info(formatError(\"\", error));\n throw error;\n }\n return super.init(options);\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const clientCredReq: ClientCredentialRequest = {\n scopes,\n correlationId: options.correlationId,\n azureRegion: this.azureRegion,\n authority: options.authority,\n claims: options.claims,\n };\n const result = await this.confidentialApp!.acquireTokenByClientCredential(clientCredReq);\n // Even though we're providing the same default in memory persistence cache that we use for DeviceCodeCredential,\n // The Client Credential flow does not return the account information from the authentication service,\n // so each time getToken gets called, we will have to acquire a new token through the service.\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"msalClientCertificate.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalClientCertificate.ts"],"names":[],"mappings":"AAAA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B,UAAU,EAAE,UAAU;gBACtB,GAAG,EAAE,KAAK,CAAC,GAAG;aACf,CAAC;SACH;QAAC,OAAO,KAAU,EAAE;YACnB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;YACzC,MAAM,KAAK,CAAC;SACb;QACD,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,UAAyC,EAAE;QAE3C,IAAI;YACF,MAAM,aAAa,GAA4B;gBAC7C,MAAM;gBACN,aAAa,EAAE,OAAO,CAAC,aAAa;gBACpC,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;aACvB,CAAC;YACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAC9B,cAAc,EACd,OAAO,CAAC,SAAS,CAClB,CAAC,8BAA8B,CAAC,aAAa,CAAC,CAAC;YAChD,iHAAiH;YACjH,sGAAsG;YACtG,8FAA8F;YAC9F,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC;SACtE;QAAC,OAAO,GAAQ,EAAE;YACjB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;SAC9C;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n ClientCertificateCredentialPEMConfiguration,\n ClientCertificatePEMCertificate,\n ClientCertificatePEMCertificatePath,\n} from \"../../credentials/clientCertificateCredential\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { createHash, createPrivateKey } from \"crypto\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { ClientCredentialRequest } from \"@azure/msal-node\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { formatError } from \"../../util/logging\";\nimport { promisify } from \"util\";\nimport { readFile } from \"fs\";\n\nconst readFileAsync = promisify(readFile);\n\n/**\n * Options that can be passed to configure MSAL to handle client certificates.\n * @internal\n */\nexport interface MsalClientCertificateOptions extends MsalNodeOptions {\n /**\n * Location of the PEM certificate.\n */\n configuration: ClientCertificateCredentialPEMConfiguration;\n /**\n * Option to include x5c header for SubjectName and Issuer name authorization.\n * Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim\n */\n sendCertificateChain?: boolean;\n}\n\n/**\n * Parts of a certificate, as understood by MSAL.\n * @internal\n */\ninterface CertificateParts {\n /**\n * Hex encoded X.509 SHA-1 thumbprint of the certificate\n */\n thumbprint: string;\n /**\n * The PEM encoded private key (string should contain -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY-----\n */\n certificateContents: string;\n /**\n * x5c header.\n */\n x5c: string;\n}\n\n/**\n * Tries to asynchronously load a certificate from the given path.\n *\n * @param configuration - Either the PEM value or the path to the certificate.\n * @param sendCertificateChain - Option to include x5c header for SubjectName and Issuer name authorization.\n * @returns - The certificate parts, or `undefined` if the certificate could not be loaded.\n * @internal\n */\nexport async function parseCertificate(\n configuration: ClientCertificateCredentialPEMConfiguration,\n sendCertificateChain?: boolean\n): Promise<CertificateParts> {\n const certificateParts: Partial<CertificateParts> = {};\n\n const certificate: string | undefined = (configuration as ClientCertificatePEMCertificate)\n .certificate;\n const certificatePath: string | undefined = (configuration as ClientCertificatePEMCertificatePath)\n .certificatePath;\n certificateParts.certificateContents =\n certificate || (await readFileAsync(certificatePath!, \"utf8\"));\n if (sendCertificateChain) {\n certificateParts.x5c = certificateParts.certificateContents;\n }\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateParts.certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n certificateParts.thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return certificateParts as CertificateParts;\n}\n\n/**\n * MSAL client certificate client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.\n * @internal\n */\nexport class MsalClientCertificate extends MsalNode {\n private configuration: ClientCertificateCredentialPEMConfiguration;\n private sendCertificateChain?: boolean;\n\n constructor(options: MsalClientCertificateOptions) {\n super(options);\n this.requiresConfidential = true;\n this.configuration = options.configuration;\n this.sendCertificateChain = options.sendCertificateChain;\n }\n\n // Changing the MSAL configuration asynchronously\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n try {\n const parts = await parseCertificate(this.configuration, this.sendCertificateChain);\n\n let privateKey: string | undefined;\n if (this.configuration.certificatePassword !== undefined) {\n const privateKeyObject = createPrivateKey({\n key: parts.certificateContents,\n passphrase: this.configuration.certificatePassword,\n format: \"pem\",\n });\n\n privateKey = privateKeyObject\n .export({\n format: \"pem\",\n type: \"pkcs8\",\n })\n .toString();\n } else {\n privateKey = parts.certificateContents;\n }\n\n this.msalConfig.auth.clientCertificate = {\n thumbprint: parts.thumbprint,\n privateKey: privateKey,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n this.logger.info(formatError(\"\", error));\n throw error;\n }\n return super.init(options);\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const clientCredReq: ClientCredentialRequest = {\n scopes,\n correlationId: options.correlationId,\n azureRegion: this.azureRegion,\n authority: options.authority,\n claims: options.claims,\n };\n const result = await this.getApp(\n \"confidential\",\n options.enableCae\n ).acquireTokenByClientCredential(clientCredReq);\n // Even though we're providing the same default in memory persistence cache that we use for DeviceCodeCredential,\n // The Client Credential flow does not return the account information from the authentication service,\n // so each time getToken gets called, we will have to acquire a new token through the service.\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n"]}
@@ -13,7 +13,7 @@ export class MsalClientSecret extends MsalNode {
13
13
  }
14
14
  async doGetToken(scopes, options = {}) {
15
15
  try {
16
- const result = await this.confidentialApp.acquireTokenByClientCredential({
16
+ const result = await this.getApp("confidential", options.enableCae).acquireTokenByClientCredential({
17
17
  scopes,
18
18
  correlationId: options.correlationId,
19
19
  azureRegion: this.azureRegion,
@@ -1 +1 @@
1
- {"version":3,"file":"msalClientSecret.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalClientSecret.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAe7D;;;GAGG;AACH,MAAM,OAAO,gBAAiB,SAAQ,QAAQ;IAC5C,YAAY,OAAgC;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC;QACjC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3D,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,UAAyC,EAAE;QAE3C,IAAI;YACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAgB,CAAC,8BAA8B,CAAC;gBACxE,MAAM;gBACN,aAAa,EAAE,OAAO,CAAC,aAAa;gBACpC,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;aACvB,CAAC,CAAC;YACH,yDAAyD;YACzD,8FAA8F;YAC9F,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC;SACtE;QAAC,OAAO,GAAQ,EAAE;YACjB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;SAC9C;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\n\n/**\n * Options that can be passed to configure MSAL to handle client secrets.\n * @internal\n */\nexport interface MsalClientSecretOptions extends MsalNodeOptions {\n /**\n * A client secret that was generated for the App Registration.\n */\n clientSecret: string;\n}\n\n/**\n * MSAL client secret client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.\n * @internal\n */\nexport class MsalClientSecret extends MsalNode {\n constructor(options: MsalClientSecretOptions) {\n super(options);\n this.requiresConfidential = true;\n this.msalConfig.auth.clientSecret = options.clientSecret;\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const result = await this.confidentialApp!.acquireTokenByClientCredential({\n scopes,\n correlationId: options.correlationId,\n azureRegion: this.azureRegion,\n authority: options.authority,\n claims: options.claims,\n });\n // The Client Credential flow does not return an account,\n // so each time getToken gets called, we will have to acquire a new token through the service.\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"msalClientSecret.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalClientSecret.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAe7D;;;GAGG;AACH,MAAM,OAAO,gBAAiB,SAAQ,QAAQ;IAC5C,YAAY,OAAgC;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC;QACjC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3D,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,UAAyC,EAAE;QAE3C,IAAI;YACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAC9B,cAAc,EACd,OAAO,CAAC,SAAS,CAClB,CAAC,8BAA8B,CAAC;gBAC/B,MAAM;gBACN,aAAa,EAAE,OAAO,CAAC,aAAa;gBACpC,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;aACvB,CAAC,CAAC;YACH,yDAAyD;YACzD,8FAA8F;YAC9F,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC;SACtE;QAAC,OAAO,GAAQ,EAAE;YACjB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;SAC9C;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\n\n/**\n * Options that can be passed to configure MSAL to handle client secrets.\n * @internal\n */\nexport interface MsalClientSecretOptions extends MsalNodeOptions {\n /**\n * A client secret that was generated for the App Registration.\n */\n clientSecret: string;\n}\n\n/**\n * MSAL client secret client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.\n * @internal\n */\nexport class MsalClientSecret extends MsalNode {\n constructor(options: MsalClientSecretOptions) {\n super(options);\n this.requiresConfidential = true;\n this.msalConfig.auth.clientSecret = options.clientSecret;\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const result = await this.getApp(\n \"confidential\",\n options.enableCae\n ).acquireTokenByClientCredential({\n scopes,\n correlationId: options.correlationId,\n azureRegion: this.azureRegion,\n authority: options.authority,\n claims: options.claims,\n });\n // The Client Credential flow does not return an account,\n // so each time getToken gets called, we will have to acquire a new token through the service.\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n"]}
@@ -20,7 +20,7 @@ export class MsalDeviceCode extends MsalNode {
20
20
  authority: options === null || options === void 0 ? void 0 : options.authority,
21
21
  claims: options === null || options === void 0 ? void 0 : options.claims,
22
22
  };
23
- const promise = this.publicApp.acquireTokenByDeviceCode(requestOptions);
23
+ const promise = this.getApp("public", options === null || options === void 0 ? void 0 : options.enableCae).acquireTokenByDeviceCode(requestOptions);
24
24
  const deviceResponse = await this.withCancellation(promise, options === null || options === void 0 ? void 0 : options.abortSignal, () => {
25
25
  requestOptions.cancel = true;
26
26
  });
@@ -1 +1 @@
1
- {"version":3,"file":"msalDeviceCode.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalDeviceCode.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAa7D;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,QAAQ;IAG1C,YAAY,OAA8B;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IACvD,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,OAAuC;QAEvC,IAAI;YACF,MAAM,cAAc,GAA+B;gBACjD,kBAAkB,EAAE,IAAI,CAAC,kBAAkB;gBAC3C,MAAM;gBACN,MAAM,EAAE,KAAK;gBACb,aAAa,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,aAAa;gBACrC,SAAS,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS;gBAC7B,MAAM,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM;aACxB,CAAC;YACF,MAAM,OAAO,GAAG,IAAI,CAAC,SAAU,CAAC,wBAAwB,CAAC,cAAc,CAAC,CAAC;YACzE,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,WAAW,EAAE,GAAG,EAAE;gBACrF,cAAc,CAAC,MAAM,GAAG,IAAI,CAAC;YAC/B,CAAC,CAAC,CAAC;YACH,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,cAAc,IAAI,SAAS,CAAC,CAAC;SAC9E;QAAC,OAAO,KAAU,EAAE;YACnB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;SAChD;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through device codes.\n * @internal\n */\nexport interface MsalDeviceCodeOptions extends MsalNodeOptions {\n userPromptCallback: DeviceCodePromptCallback;\n}\n\n/**\n * MSAL device code client. Calls to the MSAL's public application's `acquireTokenByDeviceCode` during `doGetToken`.\n * @internal\n */\nexport class MsalDeviceCode extends MsalNode {\n private userPromptCallback: DeviceCodePromptCallback;\n\n constructor(options: MsalDeviceCodeOptions) {\n super(options);\n this.userPromptCallback = options.userPromptCallback;\n }\n\n protected async doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n try {\n const requestOptions: msalNode.DeviceCodeRequest = {\n deviceCodeCallback: this.userPromptCallback,\n scopes,\n cancel: false,\n correlationId: options?.correlationId,\n authority: options?.authority,\n claims: options?.claims,\n };\n const promise = this.publicApp!.acquireTokenByDeviceCode(requestOptions);\n const deviceResponse = await this.withCancellation(promise, options?.abortSignal, () => {\n requestOptions.cancel = true;\n });\n return this.handleResult(scopes, this.clientId, deviceResponse || undefined);\n } catch (error: any) {\n throw this.handleError(scopes, error, options);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"msalDeviceCode.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalDeviceCode.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAa7D;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,QAAQ;IAG1C,YAAY,OAA8B;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IACvD,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,OAAuC;QAEvC,IAAI;YACF,MAAM,cAAc,GAA+B;gBACjD,kBAAkB,EAAE,IAAI,CAAC,kBAAkB;gBAC3C,MAAM;gBACN,MAAM,EAAE,KAAK;gBACb,aAAa,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,aAAa;gBACrC,SAAS,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS;gBAC7B,MAAM,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM;aACxB,CAAC;YACF,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,CAAC,CAAC,wBAAwB,CAChF,cAAc,CACf,CAAC;YACF,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,WAAW,EAAE,GAAG,EAAE;gBACrF,cAAc,CAAC,MAAM,GAAG,IAAI,CAAC;YAC/B,CAAC,CAAC,CAAC;YACH,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,cAAc,IAAI,SAAS,CAAC,CAAC;SAC9E;QAAC,OAAO,KAAU,EAAE;YACnB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;SAChD;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through device codes.\n * @internal\n */\nexport interface MsalDeviceCodeOptions extends MsalNodeOptions {\n userPromptCallback: DeviceCodePromptCallback;\n}\n\n/**\n * MSAL device code client. Calls to the MSAL's public application's `acquireTokenByDeviceCode` during `doGetToken`.\n * @internal\n */\nexport class MsalDeviceCode extends MsalNode {\n private userPromptCallback: DeviceCodePromptCallback;\n\n constructor(options: MsalDeviceCodeOptions) {\n super(options);\n this.userPromptCallback = options.userPromptCallback;\n }\n\n protected async doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n try {\n const requestOptions: msalNode.DeviceCodeRequest = {\n deviceCodeCallback: this.userPromptCallback,\n scopes,\n cancel: false,\n correlationId: options?.correlationId,\n authority: options?.authority,\n claims: options?.claims,\n };\n const promise = this.getApp(\"public\", options?.enableCae).acquireTokenByDeviceCode(\n requestOptions\n );\n const deviceResponse = await this.withCancellation(promise, options?.abortSignal, () => {\n requestOptions.cancel = true;\n });\n return this.handleResult(scopes, this.clientId, deviceResponse || undefined);\n } catch (error: any) {\n throw this.handleError(scopes, error, options);\n }\n }\n}\n"]}
@@ -5,7 +5,7 @@ import { getLogLevel } from "@azure/logger";
5
5
  import { MsalBaseUtilities, defaultLoggerCallback, getAuthority, getKnownAuthorities, msalToPublic, publicToMsal, getMSALLogLevel, } from "../utils";
6
6
  import { processMultiTenantRequest, resolveAddionallyAllowedTenantIds, resolveTenantId, } from "../../util/tenantIdUtils";
7
7
  import { AuthenticationRequiredError } from "../../errors";
8
- import { DeveloperSignOnClientId } from "../../constants";
8
+ import { CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX, DeveloperSignOnClientId } from "../../constants";
9
9
  import { IdentityClient } from "../../client/identityClient";
10
10
  import { RegionalAuthority } from "../../regionalAuthority";
11
11
  /**
@@ -35,6 +35,12 @@ export class MsalNode extends MsalBaseUtilities {
35
35
  constructor(options) {
36
36
  var _a, _b, _c, _d;
37
37
  super(options);
38
+ // protected publicApp: msalNode.PublicClientApplication | undefined;
39
+ // protected publicAppCae: msalNode.PublicClientApplication | undefined;
40
+ // protected confidentialApp: msalNode.ConfidentialClientApplication | undefined;
41
+ // protected confidentialAppCae: msalNode.ConfidentialClientApplication | undefined;
42
+ this.app = {};
43
+ this.caeApp = {};
38
44
  this.requiresConfidential = false;
39
45
  this.msalConfig = this.defaultNodeMsalConfig(options);
40
46
  this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
@@ -45,7 +51,10 @@ export class MsalNode extends MsalBaseUtilities {
45
51
  }
46
52
  // If persistence has been configured
47
53
  if (persistenceProvider !== undefined && ((_b = options.tokenCachePersistenceOptions) === null || _b === void 0 ? void 0 : _b.enabled)) {
48
- this.createCachePlugin = () => persistenceProvider(options.tokenCachePersistenceOptions);
54
+ const nonCaeOptions = Object.assign({ name: `${options.tokenCachePersistenceOptions.name}.${CACHE_NON_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions);
55
+ const caeOptions = Object.assign({ name: `${options.tokenCachePersistenceOptions.name}.${CACHE_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions);
56
+ this.createCachePlugin = () => persistenceProvider(nonCaeOptions);
57
+ this.createCachePluginCae = () => persistenceProvider(caeOptions);
49
58
  }
50
59
  else if ((_c = options.tokenCachePersistenceOptions) === null || _c === void 0 ? void 0 : _c.enabled) {
51
60
  throw new Error([
@@ -64,15 +73,13 @@ export class MsalNode extends MsalBaseUtilities {
64
73
  * Generates a MSAL configuration that generally works for Node.js
65
74
  */
66
75
  defaultNodeMsalConfig(options) {
76
+ var _a;
67
77
  const clientId = options.clientId || DeveloperSignOnClientId;
68
78
  const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);
69
79
  this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;
70
80
  const authority = getAuthority(tenantId, this.authorityHost);
71
81
  this.identityClient = new IdentityClient(Object.assign(Object.assign({}, options.tokenCredentialOptions), { authorityHost: authority, loggingOptions: options.loggingOptions }));
72
- let clientCapabilities = ["cp1"];
73
- if (process.env.AZURE_IDENTITY_DISABLE_CP1) {
74
- clientCapabilities = [];
75
- }
82
+ const clientCapabilities = [];
76
83
  return {
77
84
  auth: {
78
85
  clientId,
@@ -86,10 +93,26 @@ export class MsalNode extends MsalBaseUtilities {
86
93
  loggerOptions: {
87
94
  loggerCallback: defaultLoggerCallback(options.logger),
88
95
  logLevel: getMSALLogLevel(getLogLevel()),
96
+ piiLoggingEnabled: (_a = options.loggingOptions) === null || _a === void 0 ? void 0 : _a.enableUnsafeSupportLogging,
89
97
  },
90
98
  },
91
99
  };
92
100
  }
101
+ getApp(appType, enableCae) {
102
+ const app = enableCae ? this.caeApp : this.app;
103
+ if (appType === "publicFirst") {
104
+ return (app.public || app.confidential);
105
+ }
106
+ else if (appType === "confidentialFirst") {
107
+ return (app.confidential || app.public);
108
+ }
109
+ else if (appType === "confidential") {
110
+ return app.confidential;
111
+ }
112
+ else {
113
+ return app.public;
114
+ }
115
+ }
93
116
  /**
94
117
  * Prepares the MSAL applications.
95
118
  */
@@ -101,15 +124,29 @@ export class MsalNode extends MsalBaseUtilities {
101
124
  this.identityClient.abortRequests(options.correlationId);
102
125
  });
103
126
  }
104
- if (this.publicApp || this.confidentialApp) {
127
+ const app = (options === null || options === void 0 ? void 0 : options.enableCae) ? this.caeApp : this.app;
128
+ if (options === null || options === void 0 ? void 0 : options.enableCae) {
129
+ this.msalConfig.auth.clientCapabilities = ["cp1"];
130
+ }
131
+ if (app.public || app.confidential) {
105
132
  return;
106
133
  }
134
+ if ((options === null || options === void 0 ? void 0 : options.enableCae) && this.createCachePluginCae !== undefined) {
135
+ this.msalConfig.cache = {
136
+ cachePlugin: await this.createCachePluginCae(),
137
+ };
138
+ }
107
139
  if (this.createCachePlugin !== undefined) {
108
140
  this.msalConfig.cache = {
109
141
  cachePlugin: await this.createCachePlugin(),
110
142
  };
111
143
  }
112
- this.publicApp = new msalNode.PublicClientApplication(this.msalConfig);
144
+ if (options === null || options === void 0 ? void 0 : options.enableCae) {
145
+ this.caeApp.public = new msalNode.PublicClientApplication(this.msalConfig);
146
+ }
147
+ else {
148
+ this.app.public = new msalNode.PublicClientApplication(this.msalConfig);
149
+ }
113
150
  if (this.getAssertion) {
114
151
  this.msalConfig.auth.clientAssertion = await this.getAssertion();
115
152
  }
@@ -117,7 +154,12 @@ export class MsalNode extends MsalBaseUtilities {
117
154
  if (this.msalConfig.auth.clientSecret ||
118
155
  this.msalConfig.auth.clientAssertion ||
119
156
  this.msalConfig.auth.clientCertificate) {
120
- this.confidentialApp = new msalNode.ConfidentialClientApplication(this.msalConfig);
157
+ if (options === null || options === void 0 ? void 0 : options.enableCae) {
158
+ this.caeApp.confidential = new msalNode.ConfidentialClientApplication(this.msalConfig);
159
+ }
160
+ else {
161
+ this.app.confidential = new msalNode.ConfidentialClientApplication(this.msalConfig);
162
+ }
121
163
  }
122
164
  else {
123
165
  if (this.requiresConfidential) {
@@ -145,12 +187,11 @@ export class MsalNode extends MsalBaseUtilities {
145
187
  /**
146
188
  * Returns the existing account, attempts to load the account from MSAL.
147
189
  */
148
- async getActiveAccount() {
149
- var _a, _b, _c;
190
+ async getActiveAccount(enableCae = false) {
150
191
  if (this.account) {
151
192
  return this.account;
152
193
  }
153
- const cache = (_b = (_a = this.confidentialApp) === null || _a === void 0 ? void 0 : _a.getTokenCache()) !== null && _b !== void 0 ? _b : (_c = this.publicApp) === null || _c === void 0 ? void 0 : _c.getTokenCache();
194
+ const cache = this.getApp("confidentialFirst", enableCae).getTokenCache();
154
195
  const accountsByTenant = await (cache === null || cache === void 0 ? void 0 : cache.getAllAccounts());
155
196
  if (!accountsByTenant) {
156
197
  return;
@@ -174,7 +215,7 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
174
215
  */
175
216
  async getTokenSilent(scopes, options) {
176
217
  var _a, _b, _c;
177
- await this.getActiveAccount();
218
+ await this.getActiveAccount(options === null || options === void 0 ? void 0 : options.enableCae);
178
219
  if (!this.account) {
179
220
  throw new AuthenticationRequiredError({
180
221
  scopes,
@@ -196,10 +237,10 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
196
237
  * The following code to retrieve all accounts is done as a workaround in an attempt to force the
197
238
  * refresh of the token cache with the token and the account passed in through the
198
239
  * `authenticationRecord` parameter. See issue - https://github.com/Azure/azure-sdk-for-js/issues/24349#issuecomment-1496715651
199
- * This workaround serves as a workoaround for silent authentication not happening when authenticationRecord is passed.
240
+ * This workaround serves as a workaround for silent authentication not happening when authenticationRecord is passed.
200
241
  */
201
- await ((_a = (this.publicApp || this.confidentialApp)) === null || _a === void 0 ? void 0 : _a.getTokenCache().getAllAccounts());
202
- const response = (_c = (await ((_b = this.confidentialApp) === null || _b === void 0 ? void 0 : _b.acquireTokenSilent(silentRequest)))) !== null && _c !== void 0 ? _c : (await this.publicApp.acquireTokenSilent(silentRequest));
242
+ await ((_a = this.getApp("publicFirst", options === null || options === void 0 ? void 0 : options.enableCae)) === null || _a === void 0 ? void 0 : _a.getTokenCache().getAllAccounts());
243
+ const response = (_c = (await ((_b = this.getApp("confidential", options === null || options === void 0 ? void 0 : options.enableCae)) === null || _b === void 0 ? void 0 : _b.acquireTokenSilent(silentRequest)))) !== null && _c !== void 0 ? _c : (await this.getApp("public", options === null || options === void 0 ? void 0 : options.enableCae).acquireTokenSilent(silentRequest));
203
244
  return this.handleResult(scopes, this.clientId, response || undefined);
204
245
  }
205
246
  catch (err) {
@@ -1 +1 @@
1
- {"version":3,"file":"msalNodeCommon.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalNodeCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EACrB,YAAY,EACZ,mBAAmB,EACnB,YAAY,EACZ,YAAY,EACZ,eAAe,GAChB,MAAM,UAAU,CAAC;AAElB,OAAO,EACL,yBAAyB,EACzB,iCAAiC,EACjC,eAAe,GAChB,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAG7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAwB5D;;;GAGG;AACH,IAAI,mBAAmB,GAEP,SAAS,CAAC;AAE1B;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAw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msalCommon from \"@azure/msal-common\";\nimport * as msalNode from \"@azure/msal-node\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { getLogLevel } from \"@azure/logger\";\nimport {\n MsalBaseUtilities,\n defaultLoggerCallback,\n getAuthority,\n getKnownAuthorities,\n msalToPublic,\n publicToMsal,\n getMSALLogLevel,\n} from \"../utils\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport {\n processMultiTenantRequest,\n resolveAddionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../../util/tenantIdUtils\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationRecord } from \"../types\";\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\nimport { MultiTenantTokenCredentialOptions } from \"../../credentials/multiTenantTokenCredentialOptions\";\nimport { RegionalAuthority } from \"../../regionalAuthority\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types for Node.\n * @internal\n */\nexport interface MsalNodeOptions extends MsalFlowOptions {\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n tokenCredentialOptions: MultiTenantTokenCredentialOptions;\n /**\n * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n * If the property is not specified, uses a non-regional authority endpoint.\n */\n regionalAuthority?: string;\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n loggingOptions?: LogPolicyOptions & {\n allowLoggingAccountIdentifiers?: boolean;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nlet persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalCommon.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 * MSAL partial base client for Node.js.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalNode extends MsalBaseUtilities implements MsalFlow {\n protected publicApp: msalNode.PublicClientApplication | undefined;\n protected confidentialApp: msalNode.ConfidentialClientApplication | undefined;\n protected msalConfig: msalNode.Configuration;\n protected clientId: string;\n protected tenantId: string;\n protected additionallyAllowedTenantIds: string[];\n protected authorityHost?: string;\n protected identityClient?: IdentityClient;\n protected requiresConfidential: boolean = false;\n protected azureRegion?: string;\n protected createCachePlugin: (() => Promise<msalCommon.ICachePlugin>) | undefined;\n\n /**\n * MSAL currently caches the tokens depending on the claims used to retrieve them.\n * In cases like CAE, in which we use claims to update the tokens, trying to retrieve the token without the claims will yield the original token.\n * To ensure we always get the latest token, we have to keep track of the claims.\n */\n private cachedClaims: string | undefined;\n\n protected getAssertion: (() => Promise<string>) | undefined;\n constructor(options: MsalNodeOptions) {\n super(options);\n this.msalConfig = this.defaultNodeMsalConfig(options);\n this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n this.additionallyAllowedTenantIds = resolveAddionallyAllowedTenantIds(\n options?.tokenCredentialOptions?.additionallyAllowedTenants\n );\n this.clientId = this.msalConfig.auth.clientId;\n if (options?.getAssertion) {\n this.getAssertion = options.getAssertion;\n }\n\n // If persistence has been configured\n if (persistenceProvider !== undefined && options.tokenCachePersistenceOptions?.enabled) {\n this.createCachePlugin = () => persistenceProvider!(options.tokenCachePersistenceOptions);\n } else if (options.tokenCachePersistenceOptions?.enabled) {\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 this.azureRegion = options.regionalAuthority ?? process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n if (this.azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n this.azureRegion = \"AUTO_DISCOVER\";\n }\n }\n\n /**\n * Generates a MSAL configuration that generally works for Node.js\n */\n protected defaultNodeMsalConfig(options: MsalNodeOptions): msalNode.Configuration {\n const clientId = options.clientId || DeveloperSignOnClientId;\n const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n\n this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;\n const authority = getAuthority(tenantId, this.authorityHost);\n\n this.identityClient = new IdentityClient({\n ...options.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: options.loggingOptions,\n });\n\n let clientCapabilities: string[] = [\"cp1\"];\n if (process.env.AZURE_IDENTITY_DISABLE_CP1) {\n clientCapabilities = [];\n }\n\n return {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(\n tenantId,\n authority,\n options.disableInstanceDiscovery\n ),\n clientCapabilities,\n },\n // Cache is defined in this.prepare();\n system: {\n networkClient: this.identityClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger),\n logLevel: getMSALLogLevel(getLogLevel()),\n },\n },\n };\n }\n\n /**\n * Prepares the MSAL applications.\n */\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n // This will abort any pending request in the IdentityClient,\n // based on the received or generated correlationId\n this.identityClient!.abortRequests(options.correlationId);\n });\n }\n\n if (this.publicApp || this.confidentialApp) {\n return;\n }\n\n if (this.createCachePlugin !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePlugin(),\n };\n }\n\n this.publicApp = new msalNode.PublicClientApplication(this.msalConfig);\n if (this.getAssertion) {\n this.msalConfig.auth.clientAssertion = await this.getAssertion();\n }\n // The confidential client requires either a secret, assertion or certificate.\n if (\n this.msalConfig.auth.clientSecret ||\n this.msalConfig.auth.clientAssertion ||\n this.msalConfig.auth.clientCertificate\n ) {\n this.confidentialApp = new msalNode.ConfidentialClientApplication(this.msalConfig);\n } else {\n if (this.requiresConfidential) {\n throw new Error(\n \"Unable to generate the MSAL confidential client. Missing either the client's secret, certificate or assertion.\"\n );\n }\n }\n }\n\n /**\n * Allows the cancellation of a MSAL request.\n */\n protected withCancellation(\n promise: Promise<msalCommon.AuthenticationResult | null>,\n abortSignal?: AbortSignalLike,\n onCancel?: () => void\n ): Promise<msalCommon.AuthenticationResult | null> {\n return new Promise((resolve, reject) => {\n promise\n .then((msalToken) => {\n return resolve(msalToken!);\n })\n .catch(reject);\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n onCancel?.();\n });\n }\n });\n }\n\n /**\n * Returns the existing account, attempts to load the account from MSAL.\n */\n async getActiveAccount(): Promise<AuthenticationRecord | undefined> {\n if (this.account) {\n return this.account;\n }\n const cache = this.confidentialApp?.getTokenCache() ?? this.publicApp?.getTokenCache();\n const accountsByTenant = await cache?.getAllAccounts();\n\n if (!accountsByTenant) {\n return;\n }\n\n if (accountsByTenant.length === 1) {\n this.account = msalToPublic(this.clientId, accountsByTenant[0]);\n } else {\n this.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n return;\n }\n\n return this.account;\n }\n\n /**\n * Attempts to retrieve a token from cache.\n */\n async getTokenSilent(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n await this.getActiveAccount();\n if (!this.account) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const silentRequest: msalNode.SilentFlowRequest = {\n // To be able to re-use the account, the Token Cache must also have been provided.\n account: publicToMsal(this.account),\n correlationId: options?.correlationId,\n scopes,\n authority: options?.authority,\n claims: options?.claims,\n };\n\n try {\n this.logger.info(\"Attempting to acquire token silently\");\n /**\n * The following code to retrieve all accounts is done as a workaround in an attempt to force the\n * refresh of the token cache with the token and the account passed in through the\n * `authenticationRecord` parameter. See issue - https://github.com/Azure/azure-sdk-for-js/issues/24349#issuecomment-1496715651\n * This workaround serves as a workoaround for silent authentication not happening when authenticationRecord is passed.\n */\n await (this.publicApp || this.confidentialApp)?.getTokenCache().getAllAccounts();\n\n const response =\n (await this.confidentialApp?.acquireTokenSilent(silentRequest)) ??\n (await this.publicApp!.acquireTokenSilent(silentRequest));\n return this.handleResult(scopes, this.clientId, response || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n protected abstract doGetToken(scopes: string[], options?: GetTokenOptions): Promise<AccessToken>;\n\n /**\n * Wrapper around each MSAL flow get token operation: doGetToken.\n * If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId =\n processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds) ||\n this.tenantId;\n\n options.authority = getAuthority(tenantId, this.authorityHost);\n\n options.correlationId = options?.correlationId || this.generateUuid();\n await this.init(options);\n\n try {\n // MSAL now caches tokens based on their claims,\n // so now one has to keep track fo claims in order to retrieve the newer tokens from acquireTokenSilent\n // This update happened on PR: https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/4533\n const optionsClaims = (options as any).claims;\n if (optionsClaims) {\n this.cachedClaims = optionsClaims;\n }\n if (this.cachedClaims && !optionsClaims) {\n (options as any).claims = this.cachedClaims;\n }\n // We don't return the promise since we want to catch errors right here.\n return await this.getTokenSilent(scopes, options);\n } catch (err: any) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (options?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n this.logger.info(`Silent authentication failed, falling back to interactive method.`);\n return this.doGetToken(scopes, options);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"msalNodeCommon.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalNodeCommon.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EACrB,YAAY,EACZ,mBAAmB,EACnB,YAAY,EACZ,YAAY,EACZ,eAAe,GAChB,MAAM,UAAU,CAAC;AAElB,OAAO,EACL,yBAAyB,EACzB,iCAAiC,EACjC,eAAe,GAChB,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAE3D,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAClG,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAG7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AA+B5D;;;GAGG;AACH,IAAI,mBAAmB,GAEP,SAAS,CAAC;AAE1B;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,cAAc,CAAC,cAA8D;QAC3E,mBAAmB,GAAG,cAAc,CAAC;IACvC,CAAC;CACF,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,OA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CAAC,YAAY,IAAI,CAAC,aAAa,EAAE;gBACtC,OAAe,CAAC,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC;aAC7C;YACD,wEAAwE;YACxE,OAAO,MAAM,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;SACnD;QAAC,OAAO,GAAQ,EAAE;YACjB,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B,EAAE;gBAC9C,MAAM,GAAG,CAAC;aACX;YACD,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,8BAA8B,EAAE;gBAC3C,MAAM,IAAI,2BAA2B,CAAC;oBACpC,MAAM;oBACN,eAAe,EAAE,OAAO;oBACxB,OAAO,EACL,uFAAuF;iBAC1F,CAAC,CAAC;aACJ;YACD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,mEAAmE,CAAC,CAAC;YACtF,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;SACzC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalCommon from \"@azure/msal-common\";\nimport * as msalNode from \"@azure/msal-node\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { getLogLevel } from \"@azure/logger\";\nimport {\n MsalBaseUtilities,\n defaultLoggerCallback,\n getAuthority,\n getKnownAuthorities,\n msalToPublic,\n publicToMsal,\n getMSALLogLevel,\n} from \"../utils\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport {\n processMultiTenantRequest,\n resolveAddionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../../util/tenantIdUtils\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AppType, AuthenticationRecord } from \"../types\";\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX, DeveloperSignOnClientId } from \"../../constants\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\nimport { MultiTenantTokenCredentialOptions } from \"../../credentials/multiTenantTokenCredentialOptions\";\nimport { RegionalAuthority } from \"../../regionalAuthority\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types for Node.\n * @internal\n */\nexport interface MsalNodeOptions extends MsalFlowOptions {\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n tokenCredentialOptions: MultiTenantTokenCredentialOptions;\n /**\n * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n * If the property is not specified, uses a non-regional authority endpoint.\n */\n regionalAuthority?: string;\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: LogPolicyOptions & {\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n allowLoggingAccountIdentifiers?: boolean;\n /**\n * Allows logging personally identifiable information for customer support.\n */\n enableUnsafeSupportLogging?: boolean;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nlet persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalCommon.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 * MSAL partial base client for Node.js.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalNode extends MsalBaseUtilities implements MsalFlow {\n // protected publicApp: msalNode.PublicClientApplication | undefined;\n // protected publicAppCae: msalNode.PublicClientApplication | undefined;\n // protected confidentialApp: msalNode.ConfidentialClientApplication | undefined;\n // protected confidentialAppCae: msalNode.ConfidentialClientApplication | undefined;\n private app: {\n public?: msalNode.PublicClientApplication;\n confidential?: msalNode.ConfidentialClientApplication;\n } = {};\n private caeApp: {\n public?: msalNode.PublicClientApplication;\n confidential?: msalNode.ConfidentialClientApplication;\n } = {};\n protected msalConfig: msalNode.Configuration;\n protected clientId: string;\n protected tenantId: string;\n protected additionallyAllowedTenantIds: string[];\n protected authorityHost?: string;\n protected identityClient?: IdentityClient;\n protected requiresConfidential: boolean = false;\n protected azureRegion?: string;\n protected createCachePlugin: (() => Promise<msalCommon.ICachePlugin>) | undefined;\n protected createCachePluginCae: (() => Promise<msalCommon.ICachePlugin>) | undefined;\n\n /**\n * MSAL currently caches the tokens depending on the claims used to retrieve them.\n * In cases like CAE, in which we use claims to update the tokens, trying to retrieve the token without the claims will yield the original token.\n * To ensure we always get the latest token, we have to keep track of the claims.\n */\n private cachedClaims: string | undefined;\n\n protected getAssertion: (() => Promise<string>) | undefined;\n constructor(options: MsalNodeOptions) {\n super(options);\n this.msalConfig = this.defaultNodeMsalConfig(options);\n this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n this.additionallyAllowedTenantIds = resolveAddionallyAllowedTenantIds(\n options?.tokenCredentialOptions?.additionallyAllowedTenants\n );\n this.clientId = this.msalConfig.auth.clientId;\n if (options?.getAssertion) {\n this.getAssertion = options.getAssertion;\n }\n\n // If persistence has been configured\n if (persistenceProvider !== undefined && options.tokenCachePersistenceOptions?.enabled) {\n const nonCaeOptions = {\n name: `${options.tokenCachePersistenceOptions.name}.${CACHE_NON_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n };\n const caeOptions = {\n name: `${options.tokenCachePersistenceOptions.name}.${CACHE_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n };\n this.createCachePlugin = () => persistenceProvider!(nonCaeOptions);\n this.createCachePluginCae = () => persistenceProvider!(caeOptions);\n } else if (options.tokenCachePersistenceOptions?.enabled) {\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 this.azureRegion = options.regionalAuthority ?? process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n if (this.azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n this.azureRegion = \"AUTO_DISCOVER\";\n }\n }\n\n /**\n * Generates a MSAL configuration that generally works for Node.js\n */\n protected defaultNodeMsalConfig(options: MsalNodeOptions): msalNode.Configuration {\n const clientId = options.clientId || DeveloperSignOnClientId;\n const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n\n this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;\n const authority = getAuthority(tenantId, this.authorityHost);\n\n this.identityClient = new IdentityClient({\n ...options.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: options.loggingOptions,\n });\n\n const clientCapabilities: string[] = [];\n\n return {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(\n tenantId,\n authority,\n options.disableInstanceDiscovery\n ),\n clientCapabilities,\n },\n // Cache is defined in this.prepare();\n system: {\n networkClient: this.identityClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n }\n protected getApp(\n appType: \"publicFirst\" | \"confidentialFirst\",\n enableCae?: boolean\n ): msalNode.ConfidentialClientApplication | msalNode.PublicClientApplication;\n protected getApp(appType: \"public\", enableCae?: boolean): msalNode.PublicClientApplication;\n\n protected getApp(\n appType: \"confidential\",\n enableCae?: boolean\n ): msalNode.ConfidentialClientApplication;\n\n protected getApp(\n appType: AppType,\n enableCae?: boolean\n ): msalNode.ConfidentialClientApplication | msalNode.PublicClientApplication {\n const app = enableCae ? this.caeApp : this.app;\n if (appType === \"publicFirst\") {\n return (app.public || app.confidential)!;\n } else if (appType === \"confidentialFirst\") {\n return (app.confidential || app.public)!;\n } else if (appType === \"confidential\") {\n return app.confidential!;\n } else {\n return app.public!;\n }\n }\n\n /**\n * Prepares the MSAL applications.\n */\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n // This will abort any pending request in the IdentityClient,\n // based on the received or generated correlationId\n this.identityClient!.abortRequests(options.correlationId);\n });\n }\n\n const app = options?.enableCae ? this.caeApp : this.app;\n if (options?.enableCae) {\n this.msalConfig.auth.clientCapabilities = [\"cp1\"];\n }\n if (app.public || app.confidential) {\n return;\n }\n if (options?.enableCae && this.createCachePluginCae !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePluginCae(),\n };\n }\n if (this.createCachePlugin !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePlugin(),\n };\n }\n\n if (options?.enableCae) {\n this.caeApp.public = new msalNode.PublicClientApplication(this.msalConfig);\n } else {\n this.app.public = new msalNode.PublicClientApplication(this.msalConfig);\n }\n\n if (this.getAssertion) {\n this.msalConfig.auth.clientAssertion = await this.getAssertion();\n }\n // The confidential client requires either a secret, assertion or certificate.\n if (\n this.msalConfig.auth.clientSecret ||\n this.msalConfig.auth.clientAssertion ||\n this.msalConfig.auth.clientCertificate\n ) {\n if (options?.enableCae) {\n this.caeApp.confidential = new msalNode.ConfidentialClientApplication(this.msalConfig);\n } else {\n this.app.confidential = new msalNode.ConfidentialClientApplication(this.msalConfig);\n }\n } else {\n if (this.requiresConfidential) {\n throw new Error(\n \"Unable to generate the MSAL confidential client. Missing either the client's secret, certificate or assertion.\"\n );\n }\n }\n }\n\n /**\n * Allows the cancellation of a MSAL request.\n */\n protected withCancellation(\n promise: Promise<msalCommon.AuthenticationResult | null>,\n abortSignal?: AbortSignalLike,\n onCancel?: () => void\n ): Promise<msalCommon.AuthenticationResult | null> {\n return new Promise((resolve, reject) => {\n promise\n .then((msalToken) => {\n return resolve(msalToken!);\n })\n .catch(reject);\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n onCancel?.();\n });\n }\n });\n }\n\n /**\n * Returns the existing account, attempts to load the account from MSAL.\n */\n async getActiveAccount(enableCae = false): Promise<AuthenticationRecord | undefined> {\n if (this.account) {\n return this.account;\n }\n const cache = this.getApp(\"confidentialFirst\", enableCae).getTokenCache();\n const accountsByTenant = await cache?.getAllAccounts();\n\n if (!accountsByTenant) {\n return;\n }\n\n if (accountsByTenant.length === 1) {\n this.account = msalToPublic(this.clientId, accountsByTenant[0]);\n } else {\n this.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n return;\n }\n\n return this.account;\n }\n\n /**\n * Attempts to retrieve a token from cache.\n */\n async getTokenSilent(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n await this.getActiveAccount(options?.enableCae);\n if (!this.account) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const silentRequest: msalNode.SilentFlowRequest = {\n // To be able to re-use the account, the Token Cache must also have been provided.\n account: publicToMsal(this.account),\n correlationId: options?.correlationId,\n scopes,\n authority: options?.authority,\n claims: options?.claims,\n };\n\n try {\n this.logger.info(\"Attempting to acquire token silently\");\n /**\n * The following code to retrieve all accounts is done as a workaround in an attempt to force the\n * refresh of the token cache with the token and the account passed in through the\n * `authenticationRecord` parameter. See issue - https://github.com/Azure/azure-sdk-for-js/issues/24349#issuecomment-1496715651\n * This workaround serves as a workaround for silent authentication not happening when authenticationRecord is passed.\n */\n await this.getApp(\"publicFirst\", options?.enableCae)?.getTokenCache().getAllAccounts();\n const response =\n (await this.getApp(\"confidential\", options?.enableCae)?.acquireTokenSilent(\n silentRequest\n )) ?? (await this.getApp(\"public\", options?.enableCae).acquireTokenSilent(silentRequest));\n return this.handleResult(scopes, this.clientId, response || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n protected abstract doGetToken(scopes: string[], options?: GetTokenOptions): Promise<AccessToken>;\n\n /**\n * Wrapper around each MSAL flow get token operation: doGetToken.\n * If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId =\n processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds) ||\n this.tenantId;\n\n options.authority = getAuthority(tenantId, this.authorityHost);\n\n options.correlationId = options?.correlationId || this.generateUuid();\n await this.init(options);\n\n try {\n // MSAL now caches tokens based on their claims,\n // so now one has to keep track fo claims in order to retrieve the newer tokens from acquireTokenSilent\n // This update happened on PR: https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/4533\n const optionsClaims = (options as any).claims;\n if (optionsClaims) {\n this.cachedClaims = optionsClaims;\n }\n if (this.cachedClaims && !optionsClaims) {\n (options as any).claims = this.cachedClaims;\n }\n // We don't return the promise since we want to catch errors right here.\n return await this.getTokenSilent(scopes, options);\n } catch (err: any) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (options?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n this.logger.info(`Silent authentication failed, falling back to interactive method.`);\n return this.doGetToken(scopes, options);\n }\n }\n}\n"]}
@@ -40,7 +40,7 @@ export class MsalOnBehalfOf extends MsalNode {
40
40
  }
41
41
  async doGetToken(scopes, options = {}) {
42
42
  try {
43
- const result = await this.confidentialApp.acquireTokenOnBehalfOf({
43
+ const result = await this.getApp("confidential", options.enableCae).acquireTokenOnBehalfOf({
44
44
  scopes,
45
45
  correlationId: options.correlationId,
46
46
  authority: options.authority,
@@ -1 +1 @@
1
- {"version":3,"file":"msalOnBehalfOf.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalOnBehalfOf.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAG7D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AA0B3D;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,QAAQ;IAM1C,YAAY,OAA8B;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;QACzD,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC;QACjC,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACrD,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QAC/C,IAAI,CAAC,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,CAAC;QACzD,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3C,CAAC;IAED,iDAAiD;IACjD,KAAK,CAAC,IAAI,CAAC,OAAuC;QAChD,IAAI,IAAI,CAAC,eAAe,EAAE;YACxB,IAAI;gBACF,MAAM,KAAK,GAAG,MAAM,gBAAgB,CAClC,EAAE,eAAe,EAAE,IAAI,CAAC,eAAe,EAAE,EACzC,IAAI,CAAC,oBAAoB,CAC1B,CAAC;gBACF,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,iBAAiB,GAAG;oBACvC,UAAU,EAAE,KAAK,CAAC,UAAU;oBAC5B,UAAU,EAAE,KAAK,CAAC,mBAAmB;oBACrC,GAAG,EAAE,KAAK,CAAC,GAAG;iBACf,CAAC;aACH;YAAC,OAAO,KAAU,EAAE;gBACnB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;gBACzC,MAAM,KAAK,CAAC;aACb;SACF;aAAM;YACL,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;SACvD;QACD,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,UAAyC,EAAE;QAE3C,IAAI;YACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAgB,CAAC,sBAAsB,CAAC;gBAChE,MAAM;gBACN,aAAa,EAAE,OAAO,CAAC,aAAa;gBACpC,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;gBACtB,YAAY,EAAE,IAAI,CAAC,kBAAkB;aACtC,CAAC,CAAC;YACH,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC;SACtE;QAAC,OAAO,GAAQ,EAAE;YACjB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;SAC9C;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { formatError } from \"../../util/logging\";\nimport { parseCertificate } from \"./msalClientCertificate\";\n\n/**\n * Options that can be passed to configure MSAL to handle On-Behalf-Of authentication requests.\n * @internal\n */\nexport interface MsalOnBehalfOfOptions extends MsalNodeOptions {\n /**\n * A client secret that was generated for the App Registration.\n */\n clientSecret?: string;\n /**\n * Location of the PEM certificate.\n */\n certificatePath?: string;\n /**\n * Option to include x5c header for SubjectName and Issuer name authorization.\n * Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim\n */\n sendCertificateChain?: boolean;\n /**\n * The user assertion for the On-Behalf-Of flow.\n */\n userAssertionToken: string;\n}\n\n/**\n * MSAL on behalf of flow. Calls to MSAL's confidential application's `acquireTokenOnBehalfOf` during `doGetToken`.\n * @internal\n */\nexport class MsalOnBehalfOf extends MsalNode {\n private userAssertionToken: string;\n private certificatePath?: string;\n private sendCertificateChain?: boolean;\n private clientSecret?: string;\n\n constructor(options: MsalOnBehalfOfOptions) {\n super(options);\n this.logger.info(\"Initialized MSAL's On-Behalf-Of flow\");\n this.requiresConfidential = true;\n this.userAssertionToken = options.userAssertionToken;\n this.certificatePath = options.certificatePath;\n this.sendCertificateChain = options.sendCertificateChain;\n this.clientSecret = options.clientSecret;\n }\n\n // Changing the MSAL configuration asynchronously\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (this.certificatePath) {\n try {\n const parts = await parseCertificate(\n { certificatePath: this.certificatePath },\n this.sendCertificateChain\n );\n this.msalConfig.auth.clientCertificate = {\n thumbprint: parts.thumbprint,\n privateKey: parts.certificateContents,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n this.logger.info(formatError(\"\", error));\n throw error;\n }\n } else {\n this.msalConfig.auth.clientSecret = this.clientSecret;\n }\n return super.init(options);\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const result = await this.confidentialApp!.acquireTokenOnBehalfOf({\n scopes,\n correlationId: options.correlationId,\n authority: options.authority,\n claims: options.claims,\n oboAssertion: this.userAssertionToken,\n });\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"msalOnBehalfOf.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalOnBehalfOf.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAG7D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AA0B3D;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,QAAQ;IAM1C,YAAY,OAA8B;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;QACzD,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC;QACjC,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACrD,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QAC/C,IAAI,CAAC,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,CAAC;QACzD,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3C,CAAC;IAED,iDAAiD;IACjD,KAAK,CAAC,IAAI,CAAC,OAAuC;QAChD,IAAI,IAAI,CAAC,eAAe,EAAE;YACxB,IAAI;gBACF,MAAM,KAAK,GAAG,MAAM,gBAAgB,CAClC,EAAE,eAAe,EAAE,IAAI,CAAC,eAAe,EAAE,EACzC,IAAI,CAAC,oBAAoB,CAC1B,CAAC;gBACF,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,iBAAiB,GAAG;oBACvC,UAAU,EAAE,KAAK,CAAC,UAAU;oBAC5B,UAAU,EAAE,KAAK,CAAC,mBAAmB;oBACrC,GAAG,EAAE,KAAK,CAAC,GAAG;iBACf,CAAC;aACH;YAAC,OAAO,KAAU,EAAE;gBACnB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;gBACzC,MAAM,KAAK,CAAC;aACb;SACF;aAAM;YACL,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;SACvD;QACD,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,UAAyC,EAAE;QAE3C,IAAI;YACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,sBAAsB,CAAC;gBACzF,MAAM;gBACN,aAAa,EAAE,OAAO,CAAC,aAAa;gBACpC,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;gBACtB,YAAY,EAAE,IAAI,CAAC,kBAAkB;aACtC,CAAC,CAAC;YACH,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC;SACtE;QAAC,OAAO,GAAQ,EAAE;YACjB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;SAC9C;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { formatError } from \"../../util/logging\";\nimport { parseCertificate } from \"./msalClientCertificate\";\n\n/**\n * Options that can be passed to configure MSAL to handle On-Behalf-Of authentication requests.\n * @internal\n */\nexport interface MsalOnBehalfOfOptions extends MsalNodeOptions {\n /**\n * A client secret that was generated for the App Registration.\n */\n clientSecret?: string;\n /**\n * Location of the PEM certificate.\n */\n certificatePath?: string;\n /**\n * Option to include x5c header for SubjectName and Issuer name authorization.\n * Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim\n */\n sendCertificateChain?: boolean;\n /**\n * The user assertion for the On-Behalf-Of flow.\n */\n userAssertionToken: string;\n}\n\n/**\n * MSAL on behalf of flow. Calls to MSAL's confidential application's `acquireTokenOnBehalfOf` during `doGetToken`.\n * @internal\n */\nexport class MsalOnBehalfOf extends MsalNode {\n private userAssertionToken: string;\n private certificatePath?: string;\n private sendCertificateChain?: boolean;\n private clientSecret?: string;\n\n constructor(options: MsalOnBehalfOfOptions) {\n super(options);\n this.logger.info(\"Initialized MSAL's On-Behalf-Of flow\");\n this.requiresConfidential = true;\n this.userAssertionToken = options.userAssertionToken;\n this.certificatePath = options.certificatePath;\n this.sendCertificateChain = options.sendCertificateChain;\n this.clientSecret = options.clientSecret;\n }\n\n // Changing the MSAL configuration asynchronously\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (this.certificatePath) {\n try {\n const parts = await parseCertificate(\n { certificatePath: this.certificatePath },\n this.sendCertificateChain\n );\n this.msalConfig.auth.clientCertificate = {\n thumbprint: parts.thumbprint,\n privateKey: parts.certificateContents,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n this.logger.info(formatError(\"\", error));\n throw error;\n }\n } else {\n this.msalConfig.auth.clientSecret = this.clientSecret;\n }\n return super.init(options);\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const result = await this.getApp(\"confidential\", options.enableCae).acquireTokenOnBehalfOf({\n scopes,\n correlationId: options.correlationId,\n authority: options.authority,\n claims: options.claims,\n oboAssertion: this.userAssertionToken,\n });\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n"]}
@@ -33,8 +33,8 @@ export class MsalOpenBrowser extends MsalNode {
33
33
  }
34
34
  this.hostname = url.hostname;
35
35
  }
36
- async acquireTokenByCode(request) {
37
- return this.publicApp.acquireTokenByCode(request);
36
+ async acquireTokenByCode(request, enableCae) {
37
+ return this.getApp("public", enableCae).acquireTokenByCode(request);
38
38
  }
39
39
  doGetToken(scopes, options) {
40
40
  return new Promise((resolve, reject) => {
@@ -60,7 +60,7 @@ export class MsalOpenBrowser extends MsalNode {
60
60
  authority: options === null || options === void 0 ? void 0 : options.authority,
61
61
  codeVerifier: (_a = this.pkceCodes) === null || _a === void 0 ? void 0 : _a.verifier,
62
62
  };
63
- this.acquireTokenByCode(tokenRequest)
63
+ this.acquireTokenByCode(tokenRequest, options === null || options === void 0 ? void 0 : options.enableCae)
64
64
  .then((authResponse) => {
65
65
  if (authResponse === null || authResponse === void 0 ? void 0 : authResponse.account) {
66
66
  this.account = msalToPublic(this.clientId, authResponse.account);
@@ -156,7 +156,7 @@ export class MsalOpenBrowser extends MsalNode {
156
156
  codeChallenge: this.pkceCodes.challenge,
157
157
  codeChallengeMethod: "S256", // Use SHA256 Algorithm
158
158
  };
159
- const response = await this.publicApp.getAuthCodeUrl(authCodeUrlParameters);
159
+ const response = await this.getApp("public", options === null || options === void 0 ? void 0 : options.enableCae).getAuthCodeUrl(authCodeUrlParameters);
160
160
  try {
161
161
  // A new instance on macOS only which allows it to not hang, does not fix the issue on linux
162
162
  await interactiveBrowserMockable.open(response, { wait: true, newInstance: true });
@@ -1 +1 @@
1
- {"version":3,"file":"msalOpenBrowser.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalOpenBrowser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGlF,OAAO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AA4F;YAC5F,MAAM,0BAA0B,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;SACpF;QAAC,OAAO,CAAM,EAAE;YACf,MAAM,IAAI,0BAA0B,CAClC,yEAAyE,CAAC,CAAC,OAAO,EAAE,CACrF,CAAC;SACH;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { CredentialUnavailableError } from \"../../errors\";\nimport { Socket } from \"net\";\nimport http from \"http\";\nimport { msalToPublic } from \"../utils\";\nimport open from \"open\";\nimport stoppable from \"stoppable\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through opening a browser window.\n * @internal\n */\nexport interface MsalOpenBrowserOptions extends MsalNodeOptions {\n redirectUri: string;\n loginHint?: string;\n}\n\n/**\n * A call to open(), but mockable\n * @internal\n */\nexport const interactiveBrowserMockable = {\n open,\n};\n\n/**\n * This MSAL client sets up a web server to listen for redirect callbacks, then calls to the MSAL's public application's `acquireTokenByDeviceCode` during `doGetToken`\n * to trigger the authentication flow, and then respond based on the values obtained from the redirect callback\n * @internal\n */\nexport class MsalOpenBrowser extends MsalNode {\n private redirectUri: string;\n private port: number;\n private hostname: string;\n private loginHint?: string;\n\n constructor(options: MsalOpenBrowserOptions) {\n super(options);\n this.logger = credentialLogger(\"Node.js MSAL Open Browser\");\n this.redirectUri = options.redirectUri;\n this.loginHint = options.loginHint;\n\n const url = new URL(this.redirectUri);\n this.port = parseInt(url.port);\n if (isNaN(this.port)) {\n this.port = 80;\n }\n this.hostname = url.hostname;\n }\n\n private async acquireTokenByCode(\n request: msalNode.AuthorizationCodeRequest\n ): Promise<msalNode.AuthenticationResult | null> {\n return this.publicApp!.acquireTokenByCode(request);\n }\n\n protected doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n return new Promise<AccessToken>((resolve, reject) => {\n const socketToDestroy: Socket[] = [];\n\n const requestListener = (req: http.IncomingMessage, res: http.ServerResponse): void => {\n if (!req.url) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n let url: URL;\n try {\n url = new URL(req.url, this.redirectUri);\n } catch (e: any) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n const tokenRequest: msalNode.AuthorizationCodeRequest = {\n code: url.searchParams.get(\"code\")!,\n redirectUri: this.redirectUri,\n scopes: scopes,\n authority: options?.authority,\n codeVerifier: this.pkceCodes?.verifier,\n };\n\n this.acquireTokenByCode(tokenRequest)\n .then((authResponse) => {\n if (authResponse?.account) {\n this.account = msalToPublic(this.clientId, authResponse.account);\n }\n const successMessage = `Authentication Complete. You can close the browser and return to the application.`;\n if (authResponse && authResponse.expiresOn) {\n const expiresOnTimestamp = authResponse?.expiresOn.valueOf();\n res.writeHead(200);\n res.end(successMessage);\n this.logger.getToken.info(formatSuccess(scopes));\n\n resolve({\n expiresOnTimestamp,\n token: authResponse.accessToken,\n });\n } else {\n const errorMessage = formatError(\n scopes,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n this.logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n }\n cleanup();\n return;\n })\n .catch(() => {\n const errorMessage = formatError(\n scopes,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n this.logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n cleanup();\n });\n };\n\n const app = http.createServer(requestListener);\n const server = stoppable(app);\n\n const listen = app.listen(this.port, this.hostname, () =>\n this.logger.info(`InteractiveBrowserCredential listening on port ${this.port}!`)\n );\n\n function cleanup(): void {\n if (listen) {\n listen.close();\n }\n\n for (const socket of socketToDestroy) {\n socket.destroy();\n }\n\n if (server) {\n server.close();\n server.stop();\n }\n }\n\n app.on(\"connection\", (socket) => socketToDestroy.push(socket));\n\n app.on(\"error\", (err) => {\n cleanup();\n const code = (err as any).code;\n if (code === \"EACCES\" || code === \"EADDRINUSE\") {\n reject(\n new CredentialUnavailableError(\n [\n `InteractiveBrowserCredential: Access denied to port ${this.port}.`,\n `Try sending a redirect URI with a different port, as follows:`,\n '`new InteractiveBrowserCredential({ redirectUri: \"http://localhost:1337\" })`',\n ].join(\" \")\n )\n );\n } else {\n reject(\n new CredentialUnavailableError(\n `InteractiveBrowserCredential: Failed to start the necessary web server. Error: ${err.message}`\n )\n );\n }\n });\n\n app.on(\"listening\", () => {\n const openPromise = this.openAuthCodeUrl(scopes, options);\n\n const abortSignal = options?.abortSignal;\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n cleanup();\n reject(new Error(\"Aborted\"));\n });\n }\n\n openPromise.catch((e) => {\n cleanup();\n reject(e);\n });\n });\n });\n }\n\n private pkceCodes?: {\n verifier: string;\n challenge: string;\n };\n\n private async openAuthCodeUrl(\n scopeArray: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<void> {\n // Initialize CryptoProvider instance\n const cryptoProvider = new msalNode.CryptoProvider();\n // Generate PKCE Codes before starting the authorization flow\n this.pkceCodes = await cryptoProvider.generatePkceCodes();\n\n const authCodeUrlParameters: msalNode.AuthorizationUrlRequest = {\n scopes: scopeArray,\n correlationId: options?.correlationId,\n redirectUri: this.redirectUri,\n authority: options?.authority,\n claims: options?.claims,\n loginHint: this.loginHint,\n codeChallenge: this.pkceCodes.challenge,\n codeChallengeMethod: \"S256\", // Use SHA256 Algorithm\n };\n\n const response = await this.publicApp!.getAuthCodeUrl(authCodeUrlParameters);\n\n try {\n // A new instance on macOS only which allows it to not hang, does not fix the issue on linux\n await interactiveBrowserMockable.open(response, { wait: true, newInstance: true });\n } catch (e: any) {\n throw new CredentialUnavailableError(\n `InteractiveBrowserCredential: Could not open a browser window. Error: ${e.message}`\n );\n }\n }\n}\n"]}
1
+ {"version":3,"file":"msalOpenBrowser.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalOpenBrowser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGlF,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAE1D,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,SAAS,MAAM,WAAW,CAAC;AAWlC;;;GAGG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,IAAI;CACL,CAAC;AAEF;;;;GAIG;AACH,MAAM,OAAO,eAAgB,SAAQ,QAAQ;IAM3C,YAAY,OAA+B;QACzC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,gBAAgB,CAAC,2BAA2B,CAAC,CAAC;QAC5D,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QAEnC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACtC,IA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AuC;QAEvC,qCAAqC;QACrC,MAAM,cAAc,GAAG,IAAI,QAAQ,CAAC,cAAc,EAAE,CAAC;QACrD,6DAA6D;QAC7D,IAAI,CAAC,SAAS,GAAG,MAAM,cAAc,CAAC,iBAAiB,EAAE,CAAC;QAE1D,MAAM,qBAAqB,GAAqC;YAC9D,MAAM,EAAE,UAAU;YAClB,aAAa,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,aAAa;YACrC,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,SAAS,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS;YAC7B,MAAM,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM;YACvB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,aAAa,EAAE,IAAI,CAAC,SAAS,CAAC,SAAS;YACvC,mBAAmB,EAAE,MAAM,EAAE,uBAAuB;SACrD,CAAC;QACF,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,CAAC,CAAC,cAAc,CAC7E,qBAAqB,CACtB,CAAC;QACF,IAAI;YACF,4FAA4F;YAC5F,MAAM,0BAA0B,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;SACpF;QAAC,OAAO,CAAM,EAAE;YACf,MAAM,IAAI,0BAA0B,CAClC,yEAAyE,CAAC,CAAC,OAAO,EAAE,CACrF,CAAC;SACH;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { CredentialUnavailableError } from \"../../errors\";\nimport { Socket } from \"net\";\nimport http from \"http\";\nimport { msalToPublic } from \"../utils\";\nimport open from \"open\";\nimport stoppable from \"stoppable\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through opening a browser window.\n * @internal\n */\nexport interface MsalOpenBrowserOptions extends MsalNodeOptions {\n redirectUri: string;\n loginHint?: string;\n}\n\n/**\n * A call to open(), but mockable\n * @internal\n */\nexport const interactiveBrowserMockable = {\n open,\n};\n\n/**\n * This MSAL client sets up a web server to listen for redirect callbacks, then calls to the MSAL's public application's `acquireTokenByDeviceCode` during `doGetToken`\n * to trigger the authentication flow, and then respond based on the values obtained from the redirect callback\n * @internal\n */\nexport class MsalOpenBrowser extends MsalNode {\n private redirectUri: string;\n private port: number;\n private hostname: string;\n private loginHint?: string;\n\n constructor(options: MsalOpenBrowserOptions) {\n super(options);\n this.logger = credentialLogger(\"Node.js MSAL Open Browser\");\n this.redirectUri = options.redirectUri;\n this.loginHint = options.loginHint;\n\n const url = new URL(this.redirectUri);\n this.port = parseInt(url.port);\n if (isNaN(this.port)) {\n this.port = 80;\n }\n this.hostname = url.hostname;\n }\n\n private async acquireTokenByCode(\n request: msalNode.AuthorizationCodeRequest,\n enableCae?: boolean\n ): Promise<msalNode.AuthenticationResult | null> {\n return this.getApp(\"public\", enableCae).acquireTokenByCode(request);\n }\n\n protected doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n return new Promise<AccessToken>((resolve, reject) => {\n const socketToDestroy: Socket[] = [];\n\n const requestListener = (req: http.IncomingMessage, res: http.ServerResponse): void => {\n if (!req.url) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n let url: URL;\n try {\n url = new URL(req.url, this.redirectUri);\n } catch (e: any) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n const tokenRequest: msalNode.AuthorizationCodeRequest = {\n code: url.searchParams.get(\"code\")!,\n redirectUri: this.redirectUri,\n scopes: scopes,\n authority: options?.authority,\n codeVerifier: this.pkceCodes?.verifier,\n };\n\n this.acquireTokenByCode(tokenRequest, options?.enableCae)\n .then((authResponse) => {\n if (authResponse?.account) {\n this.account = msalToPublic(this.clientId, authResponse.account);\n }\n const successMessage = `Authentication Complete. You can close the browser and return to the application.`;\n if (authResponse && authResponse.expiresOn) {\n const expiresOnTimestamp = authResponse?.expiresOn.valueOf();\n res.writeHead(200);\n res.end(successMessage);\n this.logger.getToken.info(formatSuccess(scopes));\n\n resolve({\n expiresOnTimestamp,\n token: authResponse.accessToken,\n });\n } else {\n const errorMessage = formatError(\n scopes,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n this.logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n }\n cleanup();\n return;\n })\n .catch(() => {\n const errorMessage = formatError(\n scopes,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n this.logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n cleanup();\n });\n };\n\n const app = http.createServer(requestListener);\n const server = stoppable(app);\n\n const listen = app.listen(this.port, this.hostname, () =>\n this.logger.info(`InteractiveBrowserCredential listening on port ${this.port}!`)\n );\n\n function cleanup(): void {\n if (listen) {\n listen.close();\n }\n\n for (const socket of socketToDestroy) {\n socket.destroy();\n }\n\n if (server) {\n server.close();\n server.stop();\n }\n }\n\n app.on(\"connection\", (socket) => socketToDestroy.push(socket));\n\n app.on(\"error\", (err) => {\n cleanup();\n const code = (err as any).code;\n if (code === \"EACCES\" || code === \"EADDRINUSE\") {\n reject(\n new CredentialUnavailableError(\n [\n `InteractiveBrowserCredential: Access denied to port ${this.port}.`,\n `Try sending a redirect URI with a different port, as follows:`,\n '`new InteractiveBrowserCredential({ redirectUri: \"http://localhost:1337\" })`',\n ].join(\" \")\n )\n );\n } else {\n reject(\n new CredentialUnavailableError(\n `InteractiveBrowserCredential: Failed to start the necessary web server. Error: ${err.message}`\n )\n );\n }\n });\n\n app.on(\"listening\", () => {\n const openPromise = this.openAuthCodeUrl(scopes, options);\n\n const abortSignal = options?.abortSignal;\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n cleanup();\n reject(new Error(\"Aborted\"));\n });\n }\n\n openPromise.catch((e) => {\n cleanup();\n reject(e);\n });\n });\n });\n }\n\n private pkceCodes?: {\n verifier: string;\n challenge: string;\n };\n\n private async openAuthCodeUrl(\n scopeArray: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<void> {\n // Initialize CryptoProvider instance\n const cryptoProvider = new msalNode.CryptoProvider();\n // Generate PKCE Codes before starting the authorization flow\n this.pkceCodes = await cryptoProvider.generatePkceCodes();\n\n const authCodeUrlParameters: msalNode.AuthorizationUrlRequest = {\n scopes: scopeArray,\n correlationId: options?.correlationId,\n redirectUri: this.redirectUri,\n authority: options?.authority,\n claims: options?.claims,\n loginHint: this.loginHint,\n codeChallenge: this.pkceCodes.challenge,\n codeChallengeMethod: \"S256\", // Use SHA256 Algorithm\n };\n const response = await this.getApp(\"public\", options?.enableCae).getAuthCodeUrl(\n authCodeUrlParameters\n );\n try {\n // A new instance on macOS only which allows it to not hang, does not fix the issue on linux\n await interactiveBrowserMockable.open(response, { wait: true, newInstance: true });\n } catch (e: any) {\n throw new CredentialUnavailableError(\n `InteractiveBrowserCredential: Could not open a browser window. Error: ${e.message}`\n );\n }\n }\n}\n"]}
@@ -21,7 +21,7 @@ export class MsalUsernamePassword extends MsalNode {
21
21
  authority: options === null || options === void 0 ? void 0 : options.authority,
22
22
  claims: options === null || options === void 0 ? void 0 : options.claims,
23
23
  };
24
- const result = await this.publicApp.acquireTokenByUsernamePassword(requestOptions);
24
+ const result = await this.getApp("public", options === null || options === void 0 ? void 0 : options.enableCae).acquireTokenByUsernamePassword(requestOptions);
25
25
  return this.handleResult(scopes, this.clientId, result || undefined);
26
26
  }
27
27
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"msalUsernamePassword.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalUsernamePassword.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAa7D;;;GAGG;AACH,MAAM,OAAO,oBAAqB,SAAQ,QAAQ;IAIhD,YAAY,OAAoC;QAC9C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IACnC,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,OAAuC;QAEvC,IAAI;YACF,MAAM,cAAc,GAAqC;gBACvD,MAAM;gBACN,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,aAAa,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,aAAa;gBACrC,SAAS,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS;gBAC7B,MAAM,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM;aACxB,CAAC;YACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAU,CAAC,8BAA8B,CAAC,cAAc,CAAC,CAAC;YACpF,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC;SACtE;QAAC,OAAO,KAAU,EAAE;YACnB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;SAChD;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through username and password.\n * @internal\n */\nexport interface MsalUsernamePasswordOptions extends MsalNodeOptions {\n username: string;\n password: string;\n}\n\n/**\n * MSAL username and password client. Calls to the MSAL's public application's `acquireTokenByUsernamePassword` during `doGetToken`.\n * @internal\n */\nexport class MsalUsernamePassword extends MsalNode {\n private username: string;\n private password: string;\n\n constructor(options: MsalUsernamePasswordOptions) {\n super(options);\n this.username = options.username;\n this.password = options.password;\n }\n\n protected async doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n try {\n const requestOptions: msalNode.UsernamePasswordRequest = {\n scopes,\n username: this.username,\n password: this.password,\n correlationId: options?.correlationId,\n authority: options?.authority,\n claims: options?.claims,\n };\n const result = await this.publicApp!.acquireTokenByUsernamePassword(requestOptions);\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (error: any) {\n throw this.handleError(scopes, error, options);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"msalUsernamePassword.js","sourceRoot":"","sources":["../../../../src/msal/nodeFlows/msalUsernamePassword.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AAa7D;;;GAGG;AACH,MAAM,OAAO,oBAAqB,SAAQ,QAAQ;IAIhD,YAAY,OAAoC;QAC9C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IACnC,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,MAAgB,EAChB,OAAuC;QAEvC,IAAI;YACF,MAAM,cAAc,GAAqC;gBACvD,MAAM;gBACN,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,aAAa,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,aAAa;gBACrC,SAAS,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS;gBAC7B,MAAM,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM;aACxB,CAAC;YACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,CAAC,CAAC,8BAA8B,CAC3F,cAAc,CACf,CAAC;YACF,OAAO,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC;SACtE;QAAC,OAAO,KAAU,EAAE;YACnB,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;SAChD;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through username and password.\n * @internal\n */\nexport interface MsalUsernamePasswordOptions extends MsalNodeOptions {\n username: string;\n password: string;\n}\n\n/**\n * MSAL username and password client. Calls to the MSAL's public application's `acquireTokenByUsernamePassword` during `doGetToken`.\n * @internal\n */\nexport class MsalUsernamePassword extends MsalNode {\n private username: string;\n private password: string;\n\n constructor(options: MsalUsernamePasswordOptions) {\n super(options);\n this.username = options.username;\n this.password = options.password;\n }\n\n protected async doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n try {\n const requestOptions: msalNode.UsernamePasswordRequest = {\n scopes,\n username: this.username,\n password: this.password,\n correlationId: options?.correlationId,\n authority: options?.authority,\n claims: options?.claims,\n };\n const result = await this.getApp(\"public\", options?.enableCae).acquireTokenByUsernamePassword(\n requestOptions\n );\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (error: any) {\n throw this.handleError(scopes, error, options);\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/msal/types.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * The shape we use return the token (and the expiration date).\n * @internal\n */\nexport interface MsalToken {\n accessToken?: string;\n expiresOn: Date | null;\n}\n\n/**\n * Internal representation of MSAL's Account information.\n * Helps us to disambiguate the MSAL classes accross environments.\n * @internal\n */\nexport interface MsalAccountInfo {\n homeAccountId: string;\n environment?: string;\n tenantId: string;\n username: string;\n localAccountId: string;\n name?: string;\n // Leaving idTokenClaims as object since that's how MSAL has this assigned.\n /* eslint-disable-next-line @typescript-eslint/ban-types */\n idTokenClaims?: object;\n}\n\n/**\n * Represents the common properties of any of the MSAL responses.\n * @internal\n */\nexport interface MsalResult {\n authority?: string;\n account: MsalAccountInfo | null;\n accessToken: string;\n expiresOn: Date | null;\n}\n\n/**\n * The record to use to find the cached tokens in the cache.\n */\nexport interface AuthenticationRecord {\n /**\n * The associated authority, if used.\n */\n authority: string;\n /**\n * The home account Id.\n */\n homeAccountId: string;\n /**\n * The associated client ID.\n */\n clientId: string;\n /**\n * The associated tenant ID.\n */\n tenantId: string;\n /**\n * The username of the logged in account.\n */\n username: string;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/msal/types.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * @internal\n */\nexport type AppType = \"public\" | \"confidential\" | \"publicFirst\" | \"confidentialFirst\";\n\n/**\n * The shape we use return the token (and the expiration date).\n * @internal\n */\nexport interface MsalToken {\n accessToken?: string;\n expiresOn: Date | null;\n}\n\n/**\n * Internal representation of MSAL's Account information.\n * Helps us to disambiguate the MSAL classes accross environments.\n * @internal\n */\nexport interface MsalAccountInfo {\n homeAccountId: string;\n environment?: string;\n tenantId: string;\n username: string;\n localAccountId: string;\n name?: string;\n // Leaving idTokenClaims as object since that's how MSAL has this assigned.\n /* eslint-disable-next-line @typescript-eslint/ban-types */\n idTokenClaims?: object;\n}\n\n/**\n * Represents the common properties of any of the MSAL responses.\n * @internal\n */\nexport interface MsalResult {\n authority?: string;\n account: MsalAccountInfo | null;\n accessToken: string;\n expiresOn: Date | null;\n}\n\n/**\n * The record to use to find the cached tokens in the cache.\n */\nexport interface AuthenticationRecord {\n /**\n * The associated authority, if used.\n */\n authority: string;\n /**\n * The home account Id.\n */\n homeAccountId: string;\n /**\n * The associated client ID.\n */\n clientId: string;\n /**\n * The associated tenant ID.\n */\n tenantId: string;\n /**\n * The username of the logged in account.\n */\n username: string;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tokenCredentialOptions.js","sourceRoot":"","sources":["../../src/tokenCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CommonClientOptions } from \"@azure/core-client\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\n\n/**\n * Provides options to configure how the Identity library makes authentication\n * requests to Azure Active Directory.\n */\nexport interface TokenCredentialOptions extends CommonClientOptions {\n /**\n * The authority host to use for authentication requests.\n * Possible values are available through {@link AzureAuthorityHosts}.\n * The default is \"https://login.microsoftonline.com\".\n */\n authorityHost?: string;\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n loggingOptions?: LogPolicyOptions & {\n allowLoggingAccountIdentifiers?: boolean;\n };\n}\n"]}
1
+ {"version":3,"file":"tokenCredentialOptions.js","sourceRoot":"","sources":["../../src/tokenCredentialOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CommonClientOptions } from \"@azure/core-client\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\n\n/**\n * Provides options to configure how the Identity library makes authentication\n * requests to Azure Active Directory.\n */\nexport interface TokenCredentialOptions extends CommonClientOptions {\n /**\n * The authority host to use for authentication requests.\n * Possible values are available through {@link AzureAuthorityHosts}.\n * The default is \"https://login.microsoftonline.com\".\n */\n authorityHost?: string;\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: LogPolicyOptions & {\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n allowLoggingAccountIdentifiers?: boolean;\n /**\n * Allows logging personally identifiable information for customer support.\n */\n enableUnsafeSupportLogging?: boolean;\n };\n}\n"]}
@@ -12,7 +12,7 @@ export function ensureScopes(scopes) {
12
12
  * Throws if the received scope is not valid.
13
13
  * @internal
14
14
  */
15
- export function ensureValidScope(scope, logger) {
15
+ export function ensureValidScopeForDevTimeCreds(scope, logger) {
16
16
  if (!scope.match(/^[0-9a-zA-Z-.:/]+$/)) {
17
17
  const error = new Error("Invalid scope was specified by the user or calling client");
18
18
  logger.getToken.info(formatError(scope, error));