MCPcopy Index your code
hub / github.com/ChinaSiro/claude-code-sourcemap / getAzurePowerShellAccessToken

Method getAzurePowerShellAccessToken

package/cli.js:392–420  ·  view source on GitHub ↗
(q,K,_)

Source from the content-addressed store, hash-verified

390 "AZURE_TENANT_ID",
391 "AZURE_CLIENT_ID",
392 "AZURE_FEDERATED_TOKEN_FILE". See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`;throw Od6.info(_),new x4(_)}return Od6.info("Invoking getToken() of Client Assertion Credential"),this.client.getToken(q,K)}async readFileContents(){if(this.cacheDate!==void 0&&Date.now()-this.cacheDate>=300000)this.azureFederatedTokenFileContent=void 0;if(!this.federatedTokenFilePath)throw new x4(`${_$6}: is unavailable. Invalid file path provided ${this.federatedTokenFilePath}.`);if(!this.azureFederatedTokenFileContent){let K=(await bQ9(this.federatedTokenFilePath,"utf8")).trim();if(!K)throw new x4(`${_$6}: is unavailable. No content on the file ${this.federatedTokenFilePath}.`);else this.azureFederatedTokenFileContent=K,this.cacheDate=Date.now()}return this.azureFederatedTokenFileContent}}var _$6="WorkloadIdentityCredential",xQ9,Od6;var fW8=y(()=>{yO();DW8();ZP();GP();xQ9=["AZURE_TENANT_ID","AZURE_CLIENT_ID","AZURE_FEDERATED_TOKEN_FILE"],Od6=T9(_$6)});var aVq="ManagedIdentityCredential - Token Exchange",IQ9,GZ1;var sVq=y(()=>{fW8();yO();IQ9=T9(aVq),GZ1={name:"tokenExchangeMsi",async isAvailable(q){let K=process.env,_=Boolean((q||K.AZURE_CLIENT_ID)&&K.AZURE_TENANT_ID&&process.env.AZURE_FEDERATED_TOKEN_FILE);if(!_)IQ9.info(`${aVq}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`);return _},async getToken(q,K={}){let{scopes:_,clientId:z}=q,Y={};return new Bn(Object.assign(Object.assign({clientId:z,tenantId:process.env.AZURE_TENANT_ID,tokenFilePath:process.env.AZURE_FEDERATED_TOKEN_FILE},Y),{disableInstanceDiscovery:!0})).getToken(_,K)}}});class B86{constructor(q,K){var _,z;this.msiRetryConfig={maxRetries:5,startDelayInMs:800,intervalIncrement:2};let Y;if(typeof q==="string")this.clientId=q,Y=K!==null&&K!==void 0?K:{};else this.clientId=q===null||q===void 0?void 0:q.clientId,Y=q!==null&&q!==void 0?q:{};this.resourceId=Y===null||Y===void 0?void 0:Y.resourceId,this.objectId=Y===null||Y===void 0?void 0:Y.objectId;let $=[{key:"clientId",value:this.clientId},{key:"resourceId",value:this.resourceId},{key:"objectId",value:this.objectId}].filter((O)=>O.value);if($.length>1)throw Error(`ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify({clientId:this.clientId,resourceId:this.resourceId,objectId:this.objectId})}`);if(Y.allowInsecureConnection=!0,((_=Y.retryOptions)===null||_===void 0?void 0:_.maxRetries)!==void 0)this.msiRetryConfig.maxRetries=Y.retryOptions.maxRetries;this.identityClient=new mg(Object.assign(Object.assign({},Y),{additionalPolicies:[{policy:VVq(this.msiRetryConfig),position:"perCall"}]})),this.managedIdentityApp=new ng({managedIdentityIdParams:{userAssignedClientId:this.clientId,userAssignedResourceId:this.resourceId,userAssignedObjectId:this.objectId},system:{disableInternalRetries:!0,networkClient:this.identityClient,loggerOptions:{logLevel:MW8(eM8()),piiLoggingEnabled:(z=Y.loggingOptions)===null||z===void 0?void 0:z.enableUnsafeSupportLogging,loggerCallback:JW8(aE)}}}),this.isAvailableIdentityClient=new mg(Object.assign(Object.assign({},Y),{retryOptions:{maxRetries:0}}));let A=this.managedIdentityApp.getManagedIdentitySource();if(A==="CloudShell"){if(this.clientId||this.resourceId||this.objectId)throw aE.warning(`CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify({clientId:this.clientId,resourceId:this.resourceId,objectId:this.objectId})}.`),new x4("ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters.")}if(A==="ServiceFabric"){if(this.clientId||this.resourceId||this.objectId)throw aE.warning(`Service Fabric detected with user-provided IDs - throwing. Received values: ${JSON.stringify({clientId:this.clientId,resourceId:this.resourceId,objectId:this.objectId})}.`),new x4(`ManagedIdentityCredential: ${O0q}`)}if(aE.info(`Using ${A} managed identity.`),$.length===1){let{key:O,value:w}=$[0];aE.info(`${A} with ${O}: ${w}`)}}async getToken(q,K={}){aE.getToken.info("Using the MSAL provider for Managed Identity.");let _=kU6(q);if(!_)throw new x4(`ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(q)}`);return xY.withSpan("ManagedIdentityCredential.getToken",K,async()=>{var z;try{let Y=await GZ1.isAvailable(this.clientId),$=this.managedIdentityApp.getManagedIdentitySource(),A=$==="DefaultToImds"||$==="Imds";if(aE.getToken.info(`MSAL Identity source: ${$}`),Y){aE.getToken.info("Using the token exchange managed identity.");let w=await GZ1.getToken({scopes:q,clientId:this.clientId,identityClient:this.identityClient,retryConfig:this.msiRetryConfig,resourceId:this.resourceId});if(w===null)throw new x4("Attempted to use the token exchange managed identity, but received a null response.");return w}else if(A){if(aE.getToken.info("Using the IMDS endpoint to probe for availability."),!await zZ1.isAvailable({scopes:q,clientId:this.clientId,getTokenOptions:K,identityClient:this.isAvailableIdentityClient,resourceId:this.resourceId}))throw new x4("Attempted to use the IMDS endpoint, but it is not available.")}aE.getToken.info("Calling into MSAL for managed identity token.");let O=await this.managedIdentityApp.acquireToken({resource:_});return this.ensureValidMsalToken(q,O,K),aE.getToken.info(AX(q)),{expiresOnTimestamp:O.expiresOn.getTime(),token:O.accessToken,refreshAfterTimestamp:(z=O.refreshOn)===null||z===void 0?void 0:z.getTime(),tokenType:"Bearer"}}catch(Y){if(aE.getToken.error(nz(q,Y)),Y.name==="AuthenticationRequiredError")throw Y;if(uQ9(Y))throw new x4(`ManagedIdentityCredential: Network unreachable. Message: ${Y.message}`,{cause:Y});throw new x4(`ManagedIdentityCredential: Authentication failed. Message ${Y.message}`,{cause:Y})}})}ensureValidMsalToken(q,K,_){let z=(Y)=>{return aE.getToken.info(Y),new BI({scopes:Array.isArray(q)?q:[q],getTokenOptions:_,message:Y})};if(!K)throw z("No response.");if(!K.expiresOn)throw z('Response had no "expiresOn" property.');if(!K.accessToken)throw z('Response had no "accessToken" property.')}}function uQ9(q){if(q.errorCode==="network_error")return!0;if(q.code==="ENETUNREACH"||q.code==="EHOSTUNREACH")return!0;if(q.statusCode===403||q.code===403){if(q.message.includes("unreachable"))return!0}return!1}var aE;var TZ1=y(()=>{nz6();HW8();NU6();ZP();XW8();NVq();yO();mf();yVq();sVq();aE=T9("ManagedIdentityCredential")});function sE(q){return Array.isArray(q)?q:[q]}function UZ6(q,K){if(!q.match(/^[0-9a-zA-Z-_.:/]+$/)){let _=Error("Invalid scope was specified by the user or calling client");throw K.getToken.info(nz(q,_)),_}}function ZW8(q){return q.replace(/\/.default$/,"")}var ig=y(()=>{yO()});function vZ1(q,K){if(!K.match(/^[0-9a-zA-Z-._ ]+$/)){let _=Error("Invalid subscription provided. You can locate your subscription by following the instructions listed here: https://learn.microsoft.com/azure/azure-portal/get-subscription-tenant-id.");throw q.info(nz("",_)),_}}var tVq=y(()=>{yO()});import mQ9 from"child_process";class wd6{constructor(q){if(q===null||q===void 0?void 0:q.tenantId)OX(vS,q===null||q===void 0?void 0:q.tenantId),this.tenantId=q===null||q===void 0?void 0:q.tenantId;if(q===null||q===void 0?void 0:q.subscription)vZ1(vS,q===null||q===void 0?void 0:q.subscription),this.subscription=q===null||q===void 0?void 0:q.subscription;this.additionallyAllowedTenantIds=fj(q===null||q===void 0?void 0:q.additionallyAllowedTenants),this.timeout=q===null||q===void 0?void 0:q.processTimeoutInMs}async getToken(q,K={}){let _=v2(this.tenantId,K,this.additionallyAllowedTenantIds);if(_)OX(vS,_);if(this.subscription)vZ1(vS,this.subscription);let z=typeof q==="string"?q:q[0];return vS.getToken.info(`Using the scope ${z}`),xY.withSpan(`${this.constructor.name}.getToken`,K,async()=>{var Y,$,A,O;try{UZ6(z,vS);let w=ZW8(z),j=await eVq.getAzureCliAccessToken(w,_,this.subscription,this.timeout),H=(Y=j.stderr)===null||Y===void 0?void 0:Y.match("(.*)az login --scope(.*)"),J=(($=j.stderr)===null||$===void 0?void 0:$.match("(.*)az login(.*)"))&&!H;if(((A=j.stderr)===null||A===void 0?void 0:A.match("az:(.*)not found"))||((O=j.stderr)===null||O===void 0?void 0:O.startsWith("'az' is not recognized"))){let X=new x4("Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'.");throw vS.getToken.info(nz(q,X)),X}if(J){let X=new x4("Please run 'az login' from a command prompt to authenticate before using this credential.");throw vS.getToken.info(nz(q,X)),X}try{let X=j.stdout,P=this.parseRawResponse(X);return vS.getToken.info(AX(q)),P}catch(X){if(j.stderr)throw new x4(j.stderr);throw X}}catch(w){let j=w.name==="CredentialUnavailableError"?w:new x4(w.message||"Unknown error while trying to retrieve the access token");throw vS.getToken.info(nz(q,j)),j}})}parseRawResponse(q){let K=JSON.parse(q),_=K.accessToken,z=Number.parseInt(K.expires_on,10)*1000;if(!isNaN(z))return vS.getToken.info("expires_on is available and is valid, using it"),{token:_,expiresOnTimestamp:z,tokenType:"Bearer"};if(z=new Date(K.expiresOn).getTime(),isNaN(z))throw new x4(`Unexpected response from Azure CLI when getting token. Expected "expiresOn" to be a RFC3339 date string. Got: "${K.expiresOn}"`);return{token:_,expiresOnTimestamp:z,tokenType:"Bearer"}}}var vS,eVq;var kZ1=y(()=>{GP();yO();ig();ZP();mf();tVq();vS=T9("AzureCliCredential"),eVq={getSafeWorkingDir(){if(process.platform==="win32"){let q=process.env.SystemRoot||process.env.SYSTEMROOT;if(!q)vS.getToken.warning("The SystemRoot environment variable is not set. This may cause issues when using the Azure CLI credential."),q="C:\\Windows";return q}else return"/bin"},async getAzureCliAccessToken(q,K,_,z){let Y=[],$=[];if(K)Y=["--tenant",K];if(_)$=["--subscription",`"${_}"`];return new Promise((A,O)=>{try{mQ9.execFile("az",["account","get-access-token","--output","json","--resource",q,...Y,...$],{cwd:eVq.getSafeWorkingDir(),shell:!0,timeout:z},(w,j,H)=>{A({stdout:j,stderr:H,error:w})})}catch(w){O(w)}})}}});import pQ9 from"child_process";class jd6{constructor(q){if(q===null||q===void 0?void 0:q.tenantId)OX(gn,q===null||q===void 0?void 0:q.tenantId),this.tenantId=q===null||q===void 0?void 0:q.tenantId;this.additionallyAllowedTenantIds=fj(q===null||q===void 0?void 0:q.additionallyAllowedTenants),this.timeout=q===null||q===void 0?void 0:q.processTimeoutInMs}async getToken(q,K={}){let _=v2(this.tenantId,K,this.additionallyAllowedTenantIds);if(_)OX(gn,_);let z;if(typeof q==="string")z=[q];else z=q;return gn.getToken.info(`Using the scopes ${q}`),xY.withSpan(`${this.constructor.name}.getToken`,K,async()=>{var Y,$,A,O;try{z.forEach((J)=>{UZ6(J,gn)});let w=await qNq.getAzdAccessToken(z,_,this.timeout),j=((Y=w.stderr)===null||Y===void 0?void 0:Y.match("not logged in, run `azd login` to login"))||(($=w.stderr)===null||$===void 0?void 0:$.match("not logged in, run `azd auth login` to login"));if(((A=w.stderr)===null||A===void 0?void 0:A.match("azd:(.*)not found"))||((O=w.stderr)===null||O===void 0?void 0:O.startsWith("'azd' is not recognized"))||w.error&&w.error.code==="ENOENT"){let J=new x4("Azure Developer CLI couldn't be found. To mitigate this issue, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.");throw gn.getToken.info(nz(q,J)),J}if(j){let J=new x4("Please run 'azd auth login' from a command prompt to authenticate before using this credential. For more information, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.");throw gn.getToken.info(nz(q,J)),J}try{let J=JSON.parse(w.stdout);return gn.getToken.info(AX(q)),{token:J.token,expiresOnTimestamp:new Date(J.expiresOn).getTime(),tokenType:"Bearer"}}catch(J){if(w.stderr)throw new x4(w.stderr);throw J}}catch(w){let j=w.name==="CredentialUnavailableError"?w:new x4(w.message||"Unknown error while trying to retrieve the access token");throw gn.getToken.info(nz(q,j)),j}})}}var gn,qNq;var VZ1=y(()=>{yO();ZP();GP();mf();ig();gn=T9("AzureDeveloperCliCredential"),qNq={getSafeWorkingDir(){if(process.platform==="win32"){let q=process.env.SystemRoot||process.env.SYSTEMROOT;if(!q)gn.getToken.warning("The SystemRoot environment variable is not set. This may cause issues when using the Azure Developer CLI credential."),q="C:\\Windows";return q}else return"/bin"},async getAzdAccessToken(q,K,_){let z=[];if(K)z=["--tenant-id",K];return new Promise((Y,$)=>{try{pQ9.execFile("azd",["auth","token","--output","json",...q.reduce((A,O)=>A.concat("--scope",O),[]),...z],{cwd:qNq.getSafeWorkingDir(),timeout:_},(A,O,w)=>{Y({stdout:O,stderr:w,error:A})})}catch(A){$(A)}})}}});import*as KNq from"child_process";var _Nq;var zNq=y(()=>{_Nq={execFile(q,K,_){return new Promise((z,Y)=>{KNq.execFile(q,K,_,($,A,O)=>{if(Buffer.isBuffer(A))A=A.toString("utf8");if(Buffer.isBuffer(O))O=O.toString("utf8");if(O||$)Y(O?Error(O):$);else z(A)})})}}});function ANq(q){if($Nq)return`${q}.exe`;else return q}async function YNq(q,K){let _=[];for(let z of q){let[Y,...$]=z,A=await _Nq.execFile(Y,$,{encoding:"utf8",timeout:K});_.push(A)}return _}class Hd6{constructor(q){if(q===null||q===void 0?void 0:q.tenantId)OX(Fn,q===null||q===void 0?void 0:q.tenantId),this.tenantId=q===null||q===void 0?void 0:q.tenantId;this.additionallyAllowedTenantIds=fj(q===null||q===void 0?void 0:q.additionallyAllowedTenants),this.timeout=q===null||q===void 0?void 0:q.processTimeoutInMs}async getAzurePowerShellAccessToken(q,K,_){for(let z of[...yZ1]){try{await YNq([[z,"/?"]],_)}catch(A){yZ1.shift();continue}let $=(await YNq([[z,"-NoProfile","-NonInteractive","-Command",`
393 $tenantId = "${K!==null&&K!==void 0?K:""}"
394 $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru
395 $useSecureString = $m.Version -ge [version]'2.17.0'
396
397 $params = @{
398 ResourceUrl = "${q}"
399 }
400
401 if ($tenantId.Length -gt 0) {
402 $params["TenantId"] = $tenantId
403 }
404
405 if ($useSecureString) {
406 $params["AsSecureString"] = $true
407 }
408
409 $token = Get-AzAccessToken @params
410
411 $result = New-Object -TypeName PSObject
412 $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn
413 if ($useSecureString) {
414 $result | Add-Member -MemberType NoteProperty -Name Token -Value (ConvertFrom-SecureString -AsPlainText $token.Token)
415 } else {
416 $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token
417 }
418
419 Write-Output (ConvertTo-Json $result)
420 `]]))[0];return FQ9($)}throw Error("Unable to execute PowerShell. Ensure that it is installed in your system")}async getToken(q,K={}){return xY.withSpan(`${this.constructor.name}.getToken`,K,async()=>{let _=v2(this.tenantId,K,this.additionallyAllowedTenantIds),z=typeof q==="string"?q:q[0];if(_)OX(Fn,_);try{UZ6(z,Fn),Fn.getToken.info(`Using the scope ${z}`);let Y=ZW8(z),$=await this.getAzurePowerShellAccessToken(Y,_,this.timeout);return Fn.getToken.info(AX(q)),{token:$.Token,expiresOnTimestamp:new Date($.ExpiresOn).getTime(),tokenType:"Bearer"}}catch(Y){if(gQ9(Y)){let A=new x4(NZ1.installed);throw Fn.getToken.info(nz(z,A)),A}else if(BQ9(Y)){let A=new x4(NZ1.login);throw Fn.getToken.info(nz(z,A)),A}let $=new x4(`${Y}. ${NZ1.troubleshoot}`);throw Fn.getToken.info(nz(z,$)),$}})}}async function FQ9(q){let K=/{[^{}]*}/g,_=q.match(K),z=q;if(_)try{for(let Y of _)try{let $=JSON.parse(Y);if($===null||$===void 0?void 0:$.Token){if(z=z.replace(Y,""),z)Fn.getToken.warning(z);return $}}catch($){continue}}catch(Y){throw Error(`Unable to parse the output of PowerShell. Received output: ${q}`)}throw Error(`No access token found in the output. Received output: ${q}`)}var Fn,$Nq,ONq,NZ1,BQ9=(q)=>q.message.match(`(.*)${ONq.login}(.*)`),gQ9=(q)=>q.message.match(ONq.installed),yZ1;var EZ1=y(()=>{GP();yO();ig();ZP();zNq();mf();Fn=T9("AzurePowerShellCredential"),$Nq=process.platform==="win32";ONq={login:"Run Connect-AzAccount to login",installed:"The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory"},NZ1={login:"Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.",installed:`The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: "Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force".`,troubleshoot:"To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot."},yZ1=[ANq("pwsh")];if($Nq)yZ1.push(ANq("powershell"))});class Jd6{constructor(...q){this._sources=[],this._sources=q}async getToken(q,K={}){let{token:_}=await this.getTokenInternal(q,K);return _}async getTokenInternal(q,K={}){let _=null,z,Y=[];return xY.withSpan("ChainedTokenCredential.getToken",K,async($)=>{for(let A=0;A<this._sources.length&&_===null;A++)try{_=await this._sources[A].getToken(q,$),z=this._sources[A]}catch(O){if(O.name==="CredentialUnavailableError"||O.name==="AuthenticationRequiredError")Y.push(O);else throw LZ1.getToken.info(nz(q,O)),O}if(!_&&Y.length>0){let A=new $U6(Y,"ChainedTokenCredential authentication failed.");throw LZ1.getToken.info(nz(q,A)),A}if(LZ1.getToken.info(`Result for ${z.constructor.name}: ${AX(q)}`),_===null)throw new x4("Failed to retrieve a valid token");return{token:_,successfulCredential:z}})}}var LZ1;var RZ1=y(()=>{ZP();yO();mf();LZ1=T9("ChainedTokenCredential")});import{createHash as wNq,createPrivateKey as UQ9}from"node:crypto";import{readFile as QQ9}from"node:fs/promises";class Xd6{constructor(q,K,_,z={}){if(!q||!K)throw Error(`${Md6}: tenantId and clientId are required parameters.`);this.tenantId=q,this.additionallyAllowedTenantIds=fj(z===null||z===void 0?void 0:z.additionallyAllowedTenants),this.sendCertificateChain=z.sendCertificateChain,this.certificateConfiguration=Object.assign({},typeof _==="string"?{certificatePath:_}:_);let Y=this.certificateConfiguration.certificate,$=this.certificateConfiguration.certificatePath;if(!this.certificateConfiguration||!(Y||$))throw Error(`${Md6}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);if(Y&&$)throw Error(`${Md6}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`);this.msalClient=AG(K,q,Object.assign(Object.assign({},z),{logger:jNq,tokenCredentialOptions:z}))}async getToken(q,K={}){return xY.withSpan(`${Md6}.getToken`,K,async(_)=>{_.tenantId=v2(this.tenantId,_,this.additionallyAllowedTenantIds,jNq);let z=Array.isArray(q)?q:[q],Y=await this.buildClientCertificate();return this.msalClient.getTokenByClientCertificate(z,Y,_)})}async buildClientCertificate(){var q;let K=await dQ9(this.certificateConfiguration,(q=this.sendCertificateChain)!==null&&q!==void 0?q:!1),_;if(this.certificateConfiguration.certificatePassword!==void 0)_=UQ9({key:K.certificateContents,passphrase:this.certificateConfiguration.certificatePassword,format:"pem"}).export({format:"pem",type:"pkcs8"}).toString();else _=K.certificateContents;return{thumbprint:K.thumbprint,thumbprintSha256:K.thumbprintSha256,privateKey:_,x5c:K.x5c}}}async function dQ9(q,K){let{certificate:_,certificatePath:z}=q,Y=_||await QQ9(z,"utf8"),$=K?Y:void 0,A=/(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g,O=[],w;do if(w=A.exec(Y),w)O.push(w[3]);while(w);if(O.length===0)throw Error("The file at the specified path does not contain a PEM-encoded certificate.");let j=wNq("sha1").update(Buffer.from(O[0],"base64")).digest("hex").toUpperCase(),H=wNq("sha256").update(Buffer.from(O[0],"base64")).digest("hex").toUpperCase();return{certificateContents:Y,thumbprintSha256:H,thumbprint:j,x5c:$}}var Md6="ClientCertificateCredential",jNq;var hZ1=y(()=>{pn();GP();yO();mf();jNq=T9(Md6)});class Pd6{constructor(q,K,_,z={}){if(!q)throw new x4("ClientSecretCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");if(!K)throw new x4("ClientSecretCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");if(!_)throw new x4("ClientSecretCredential: clientSecret is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.");this.clientSecret=_,this.tenantId=q,this.additionallyAllowedTenantIds=fj(z===null||z===void 0?void 0:z.additionallyAllowedTenants),this.msalClient=AG(K,q,Object.assign(Object.assign({},z),{logger:HNq,tokenCredentialOptions:z}))}async getToken(q,K={}){return xY.withSpan(`${this.constructor.name}.getToken`,K,async(_)=>{_.tenantId=v2(this.tenantId,_,this.additionallyAllowedTenantIds,HNq);let z=sE(q);return this.msalClient.getTokenByClientSecret(z,this.clientSecret,_)})}}var HNq;var SZ1=y(()=>{pn();GP();ZP();yO();ig();mf();HNq=T9("ClientSecretCredential")});class Wd6{constructor(q,K,_,z,Y={}){if(!q)throw new x4("UsernamePasswordCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");if(!K)throw new x4("UsernamePasswordCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");if(!_)throw new x4("UsernamePasswordCredential: username is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");if(!z)throw new x4("UsernamePasswordCredential: password is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.");this.tenantId=q,this.additionallyAllowedTenantIds=fj(Y===null||Y===void 0?void 0:Y.additionallyAllowedTenants),this.username=_,this.password=z,this.msalClient=AG(K,this.tenantId,Object.assign(Object.assign({},Y),{tokenCredentialOptions:Y!==null&&Y!==void 0?Y:{}}))}async getToken(q,K={}){return xY.withSpan(`${this.constructor.name}.getToken`,K,async(_)=>{_.tenantId=v2(this.tenantId,_,this.additionallyAllowedTenantIds,cQ9);let z=sE(q);return this.msalClient.getTokenByUsernamePassword(z,this.username,this.password,_)})}}var cQ9;var CZ1=y(()=>{pn();GP();ZP();yO();ig();mf();cQ9=T9("UsernamePasswordCredential")});function nQ9(){var q;return((q=process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS)!==null&&q!==void 0?q:"").split(";")}function iQ9(){var q;let K=((q=process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN)!==null&&q!==void 0?q:"").toLowerCase(),_=K==="true"||K==="1";return Un.verbose(`AZURE_CLIENT_SEND_CERTIFICATE_CHAIN: ${process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN}; sendCertificateChain: ${_}`),_}class Dd6{constructor(q){this._credential=void 0;let K=qX8(lQ9).assigned.join(", ");Un.info(`Found the following environment variables: ${K}`);let _=process.env.AZURE_TENANT_ID,z=process.env.AZURE_CLIENT_ID,Y=process.env.AZURE_CLIENT_SECRET,$=nQ9(),A=iQ9(),O=Object.assign(Object.assign({},q),{additionallyAllowedTenantIds:$,sendCertificateChain:A});if(_)OX(Un,_);if(_&&z&&Y){Un.info(`Invoking ClientSecretCredential with tenant ID: ${_}, clientId: ${z} and clientSecret: [REDACTED]`),this._credential=new Pd6(_,z,Y,O);return}let w=process.env.AZURE_CLIENT_CERTIFICATE_PATH,j=process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD;if(_&&z&&w){Un.info(`Invoking ClientCertificateCredential with tenant ID: ${_}, clientId: ${z} and certificatePath: ${w}`),this._credential=new Xd6(_,z,{certificatePath:w,certificatePassword:j},O);return}let H=process.env.AZURE_USERNAME,J=process.env.AZURE_PASSWORD;if(_&&z&&H&&J)Un.info(`Invoking UsernamePasswordCredential with tenant ID: ${_}, clientId: ${z} and username: ${H}`),Un.warning("Environment is configured to use username and password authentication. This authentication method is deprecated, as it doesn't support multifactor authentication (MFA). Use a more secure credential. For more details, see https://aka.ms/azsdk/identity/mfa."),this._credential=new Wd6(_,z,H,J,O)}async getToken(q,K={}){return xY.withSpan(`${GW8}.getToken`,K,async(_)=>{if(this._credential)try{let z=await this._credential.getToken(q,_);return Un.getToken.info(AX(q)),z}catch(z){let Y=new pI(400,{error:`${GW8} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,error_description:z.message.toString().split("More details:").join("")});throw Un.getToken.info(nz(q,Y)),Y}throw new x4(`${GW8} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`)})}}var lQ9,GW8="EnvironmentCredential",Un;var bZ1=y(()=>{ZP();yO();hZ1();SZ1();CZ1();GP();mf();lQ9=["AZURE_TENANT_ID","AZURE_CLIENT_ID","AZURE_CLIENT_SECRET","AZURE_CLIENT_CERTIFICATE_PATH","AZURE_CLIENT_CERTIFICATE_PASSWORD","AZURE_USERNAME","AZURE_PASSWORD","AZURE_ADDITIONALLY_ALLOWED_TENANTS","AZURE_CLIENT_SEND_CERTIFICATE_CHAIN"];Un=T9(GW8)});function rQ9(q={}){var K,_,z,Y;(K=q.retryOptions)!==null&&K!==void 0||(q.retryOptions={maxRetries:5,retryDelayInMs:800});let $=(_=q===null||q===void 0?void 0:q.managedIdentityClientId)!==null&&_!==void 0?_:process.env.AZURE_CLIENT_ID,A=(z=q===null||q===void 0?void 0:q.workloadIdentityClientId)!==null&&z!==void 0?z:$,O=q===null||q===void 0?void 0:q.managedIdentityResourceId,w=process.env.AZURE_FEDERATED_TOKEN_FILE,j=(Y=q===null||q===void 0?void 0:q.tenantId)!==null&&Y!==void 0?Y:process.env.AZURE_TENANT_ID;if(O){let H=Object.assign(Object.assign({},q),{resourceId:O});return new B86(H)}if(w&&A){let H=Object.assign(Object.assign({},q),{tenantId:j});return new B86(A,H)}if($){let H=Object.assign(Object.assign({},q),{clientId:$});return new B86(H)}return new B86(q)}function oQ9(q){var K,_,z;let Y=(K=q===null||q===void 0?void 0:q.managedIdentityClientId)!==null&&K!==void 0?K:process.env.AZURE_CLIENT_ID,$=(_=q===null||q===void 0?void 0:q.workloadIdentityClientId)!==null&&_!==void 0?_:Y,A=process.env.AZURE_FEDERATED_TOKEN_FILE,O=(z=q===null||q===void 0?void 0:q.tenantId)!==null&&z!==void 0?z:process.env.AZURE_TENANT_ID;if(A&&$){let w=Object.assign(Object.assign({},q),{tenantId:O,clientId:$,tokenFilePath:A});return new Bn(w)}if(O){let w=Object.assign(Object.assign({},q),{tenantId:O});return new Bn(w)}return new Bn(q)}function aQ9(q={}){let K=q.processTimeoutInMs;return new jd6(Object.assign({processTimeoutInMs:K},q))}function sQ9(q={}){let K=q.processTimeoutInMs;return new wd6(Object.assign({processTimeoutInMs:K},q))}function tQ9(q={}){let K=q.processTimeoutInMs;return new Hd6(Object.assign({processTimeoutInMs:K},q))}function eQ9(q={}){return new Dd6(q)}class JNq{constructor(q,K){this.credentialName=q,this.credentialUnavailableErrorMessage=K}getToken(){return xZ1.getToken.info(`Skipping ${this.credentialName}, reason: ${this.credentialUnavailableErrorMessage}`),Promise.resolve(null)}}var xZ1,fd6;var IZ1=y(()=>{TZ1();kZ1();VZ1();EZ1();RZ1();bZ1();fW8();yO();xZ1=T9("DefaultAzureCredential");fd6=class fd6 extends Jd6{constructor(q){let K=process.env.AZURE_TOKEN_CREDENTIALS?process.env.AZURE_TOKEN_CREDENTIALS.trim().toLowerCase():void 0,_=[sQ9,tQ9,aQ9],z=[eQ9,oQ9,rQ9],Y=[];if(K)switch(K){case"dev":Y=_;break;case"prod":Y=z;break;default:{let A=`Invalid value for AZURE_TOKEN_CREDENTIALS = ${process.env.AZURE_TOKEN_CREDENTIALS}. Valid values are 'prod' or 'dev'.`;throw xZ1.warning(A),Error(A)}}else Y=[...z,..._];let $=Y.map((A)=>{try{return A(q)}catch(O){return xZ1.warning(`Skipped ${A.name} because of an error creating the credential: ${O}`),new JNq(A.name,O.message)}});super(...$)}}});class mZ1{constructor(q){var K,_,z,Y,$;this.tenantId=s06(uZ1,q.tenantId,q.clientId),this.additionallyAllowedTenantIds=fj(q===null||q===void 0?void 0:q.additionallyAllowedTenants);let A=Object.assign(Object.assign({},q),{tokenCredentialOptions:q,logger:uZ1}),O=q;if(this.browserCustomizationOptions=O.browserCustomizationOptions,this.loginHint=O.loginHint,(K=O===null||O===void 0?void 0:O.brokerOptions)===null||K===void 0?void 0:K.enabled)if(!((_=O===null||O===void 0?void 0:O.brokerOptions)===null||_===void 0?void 0:_.parentWindowHandle))throw Error("In order to do WAM authentication, `parentWindowHandle` under `brokerOptions` is a required parameter");else A.brokerOptions={enabled:!0,parentWindowHandle:O.brokerOptions.parentWindowHandle,legacyEnableMsaPassthrough:(z=O.brokerOptions)===null||z===void 0?void 0:z.legacyEnableMsaPassthrough,useDefaultBrokerAccount:(Y=O.brokerOptions)===null||Y===void 0?void 0:Y.useDefaultBrokerAccount};this.msalClient=AG(($=q.clientId)!==null&&$!==void 0?$:lz6,this.tenantId,A),this.disableAutomaticAuthentication=q===null||q===void 0?void 0:q.disableAutomaticAuthentication}async getToken(q,K={}){return xY.withSpan(`${this.constructor.name}.getToken`,K,async(_)=>{_.tenantId=v2(this.tenantId,_,this.additionallyAllowedTenantIds,uZ1);let z=sE(q);return this.msalClient.getTokenByInteractiveRequest(z,Object.assign(Object.assign({},_),{disableAutomaticAuthentication:this.disableAutomaticAuthentication,browserCustomizationOptions:this.browserCustomizationOptions,loginHint:this.loginHint}))})}async authenticate(q,K={}){return xY.withSpan(`${this.constructor.name}.authenticate`,K,async(_)=>{let z=sE(q);return await this.msalClient.getTokenByInteractiveRequest(z,Object.assign(Object.assign({},_),{disableAutomaticAuthentication:!1,browserCustomizationOptions:this.browserCustomizationOptions,loginHint:this.loginHint})),this.msalClient.getActiveAccount()})}}var uZ1;var MNq=y(()=>{GP();yO();ig();mf();pn();Sg();uZ1=T9("InteractiveBrowserCredential")});function qd9(q){console.log(q.message)}class BZ1{constructor(q){var K,_;this.tenantId=q===null||q===void 0?void 0:q.tenantId,this.additionallyAllowedTenantIds=fj(q===null||q===void 0?void 0:q.additionallyAllowedTenants);let z=(K=q===null||q===void 0?void 0:q.clientId)!==null&&K!==void 0?K:lz6,Y=s06(pZ1,q===null||q===void 0?void 0:q.tenantId,z);this.userPromptCallback=(_=q===null||q===void 0?void 0:q.userPromptCallback)!==null&&_!==void 0?_:qd9,this.msalClient=AG(z,Y,Object.assign(Object.assign({},q),{logger:pZ1,tokenCredentialOptions:q||{}})),this.disableAutomaticAuthentication=q===null||q===void 0?void 0:q.disableAutomaticAuthentication}async getToken(q,K={}){return xY.withSpan(`${this.constructor.name}.getToken`,K,async(_)=>{_.tenantId=v2(this.tenantId,_,this.additionallyAllowedTenantIds,pZ1);let z=sE(q);return this.msalClient.getTokenByDeviceCode(z,this.userPromptCallback,Object.assign(Object.assign({},_),{disableAutomaticAuthentication:this.disableAutomaticAuthentication}))})}async authenticate(q,K={}){return xY.withSpan(`${this.constructor.name}.authenticate`,K,async(_)=>{let z=Array.isArray(q)?q:[q];return await this.msalClient.getTokenByDeviceCode(z,this.userPromptCallback,Object.assign(Object.assign({},_),{disableAutomaticAuthentication:!1})),this.msalClient.getActiveAccount()})}}var pZ1;var XNq=y(()=>{GP();yO();ig();mf();pn();Sg();pZ1=T9("DeviceCodeCredential")});class gZ1{constructor(q,K,_,z,Y={}){var $,A;if(!K)throw new x4(`${rI}: is unavailable. clientId is a required parameter.`);if(!q)throw new x4(`${rI}: is unavailable. tenantId is a required parameter.`);if(!_)throw new x4(`${rI}: is unavailable. serviceConnectionId is a required parameter.`);if(!z)throw new x4(`${rI}: is unavailable. systemAccessToken is a required parameter.`);if(Y.loggingOptions=Object.assign(Object.assign({},Y===null||Y===void 0?void 0:Y.loggingOptions),{additionalAllowedHeaderNames:[...(A=($=Y.loggingOptions)===null||$===void 0?void 0:$.additionalAllowedHeaderNames)!==null&&A!==void 0?A:[],"x-vss-e2eid","x-msedge-ref"]}),this.identityClient=new mg(Y),OX(kS,q),kS.info(`Invoking AzurePipelinesCredential with tenant ID: ${q}, client ID: ${K}, and service connection ID: ${_}`),!process.env.SYSTEM_OIDCREQUESTURI)throw new x4(`${rI}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- "SYSTEM_OIDCREQUESTURI"`);let O=`${process.env.SYSTEM_OIDCREQUESTURI}?api-version=${Kd9}&serviceConnectionId=${_}`;kS.info(`Invoking ClientAssertionCredential with tenant ID: ${q}, client ID: ${K} and service connection ID: ${_}`),this.clientAssertionCredential=new K$6(q,K,this.requestOidcToken.bind(this,O,z),Y)}async getToken(q,K){if(!this.clientAssertionCredential){let _=`${rI}: is unavailable. To use Federation Identity in Azure Pipelines, the following parameters are required -
421 tenantId,
422 clientId,
423 serviceConnectionId,

Callers 1

getTokenMethod · 0.95

Calls 3

YNqFunction · 0.85
FQ9Function · 0.85
shiftMethod · 0.45

Tested by

no test coverage detected