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

Method getToken

package/cli.js:420–420  ·  view source on GitHub ↗
(q,K={})

Source from the content-addressed store, hash-verified

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

nothing calls this directly

Calls 1

getTokenInternalMethod · 0.95

Tested by

no test coverage detected