@azure/msal-node
Advanced tools
Comparing version 1.10.0 to 1.11.0
@@ -10,2 +10,3 @@ import { LoggerOptions, INetworkModule, ProtocolMode, ICachePlugin, AzureCloudOptions, ApplicationTelemetry } from "@azure/msal-common"; | ||
* - protocolMode - Enum that represents the protocol that msal follows. Used for configuring proper endpoints. | ||
* - skipAuthorityMetadataCache - A flag to choose whether to use or not use the local metadata cache during authority initialization. Defaults to false. | ||
* @public | ||
@@ -29,2 +30,3 @@ */ | ||
azureCloudOptions?: AzureCloudOptions; | ||
skipAuthorityMetadataCache?: boolean; | ||
}; | ||
@@ -31,0 +33,0 @@ /** |
@@ -1,2 +0,2 @@ | ||
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t,r=require("@azure/msal-common"),n=e(require("http")),i=e(require("https")),o=require("uuid"),s=e(require("crypto")),a=require("jsonwebtoken");!function(e){e.GET="get",e.POST="post"}(t||(t={}));const c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";var l;!function(e){e[e.acquireTokenSilent=62]="acquireTokenSilent",e[e.acquireTokenByUsernamePassword=371]="acquireTokenByUsernamePassword",e[e.acquireTokenByDeviceCode=671]="acquireTokenByDeviceCode",e[e.acquireTokenByClientCredential=771]="acquireTokenByClientCredential",e[e.acquireTokenByCode=871]="acquireTokenByCode",e[e.acquireTokenByRefreshToken=872]="acquireTokenByRefreshToken"}(l||(l={}));class h{async sendGetRequestAsync(e,r){return null!=r&&r.proxyUrl?u(e,t.GET,r):d(e,t.GET,r)}async sendPostRequestAsync(e,r,n){return null!=r&&r.proxyUrl?u(e,t.POST,r,n):d(e,t.POST,r,n)}}const u=(e,r,i,o)=>{const s=(null==i?void 0:i.headers)||{},a=new URL((null==i?void 0:i.proxyUrl)||""),c=new URL(e),l={host:a.hostname,port:a.port,method:"CONNECT",path:c.hostname,headers:s};o&&(l.timeout=o);let h="";if(r===t.POST){const e=(null==i?void 0:i.body)||"";h=`Content-Type: application/x-www-form-urlencoded\r\nContent-Length: ${e.length}\r\n\r\n`+e}const u=`${r.toUpperCase()} ${c.href} HTTP/1.1\r\nHost: ${c.host}\r\nConnection: close\r\n`+h+"\r\n";return new Promise((e,t)=>{const r=n.request(l);l.timeout&&r.on("timeout",()=>{r.destroy(),t(new Error("Request time out"))}),r.end(),r.on("connect",(n,i)=>{const o=(null==n?void 0:n.statusCode)||500;(o<200||o>299)&&(r.destroy(),i.destroy(),t(new Error("HTTP status code "+o))),l.timeout&&(i.setTimeout(l.timeout),i.on("timeout",()=>{r.destroy(),i.destroy(),t(new Error("Request time out"))})),i.write(u);const s=[];i.on("data",e=>{s.push(e)}),i.on("end",()=>{const n=Buffer.concat([...s]).toString().split("\r\n"),o=parseInt(n[0].split(" ")[1]),a=n[n.length-1],c=n.slice(1,n.length-2),l=new Map;c.forEach(e=>{const t=e.split(new RegExp(/:\s(.*)/s)),r=t[0];let n=t[1];try{const e=JSON.parse(n);e&&"object"==typeof e&&(n=e)}catch(e){}l.set(r,n)});const h={headers:Object.fromEntries(l),body:JSON.parse(a),status:o};(o<200||o>299)&&"authorization_pending"!==h.body.error&&(r.destroy(),i.destroy(),t(new Error("HTTP status code "+o))),e(h)}),i.on("error",e=>{r.destroy(),i.destroy(),t(new Error(e.toString()))})}),r.on("error",e=>{r.destroy(),t(new Error(e.toString()))})})},d=(e,r,n,o)=>{const s=r===t.POST,a=(null==n?void 0:n.body)||"",c={method:r,headers:(null==n?void 0:n.headers)||{}};return o&&(c.timeout=o),s&&(c.headers={...c.headers,"Content-Length":a.length}),new Promise((t,r)=>{const n=i.request(e,c);o&&n.on("timeout",()=>{n.destroy(),r(new Error("Request time out"))}),s&&n.write(a),n.end(),n.on("response",e=>{const i=e.headers,o=e.statusCode,s=[];e.on("data",e=>{s.push(e)}),e.on("end",()=>{const e=Buffer.concat([...s]).toString(),a={headers:i,body:JSON.parse(e),status:o};(o<200||o>299)&&"authorization_pending"!==a.body.error&&(n.destroy(),r(new Error("HTTP status code "+o))),t(a)})}),n.on("error",e=>{n.destroy(),r(new Error(e.toString()))})})},g={clientId:r.Constants.EMPTY_STRING,authority:r.Constants.DEFAULT_AUTHORITY,clientSecret:r.Constants.EMPTY_STRING,clientAssertion:r.Constants.EMPTY_STRING,clientCertificate:{thumbprint:r.Constants.EMPTY_STRING,privateKey:r.Constants.EMPTY_STRING,x5c:r.Constants.EMPTY_STRING},knownAuthorities:[],cloudDiscoveryMetadata:r.Constants.EMPTY_STRING,authorityMetadata:r.Constants.EMPTY_STRING,clientCapabilities:[],protocolMode:r.ProtocolMode.AAD,azureCloudOptions:{azureCloudInstance:r.AzureCloudInstance.None,tenant:r.Constants.EMPTY_STRING}},p={},y={loggerOptions:{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:r.LogLevel.Info},networkClient:class{static getNetworkClient(){return new h}}.getNetworkClient(),proxyUrl:r.Constants.EMPTY_STRING},m={application:{appName:r.Constants.EMPTY_STRING,appVersion:r.Constants.EMPTY_STRING}};function f({auth:e,cache:t,system:r,telemetry:n}){return{auth:{...g,...e},cache:{...p,...t},system:{...y,...r},telemetry:{...m,...n}}}class C{generateGuid(){return o.v4()}isGuid(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}}class T{static base64Encode(e,t){return Buffer.from(e,t).toString("base64")}static base64EncodeUrl(e,t){return T.base64Encode(e,t).replace(/=/g,r.Constants.EMPTY_STRING).replace(/\+/g,"-").replace(/\//g,"_")}static base64Decode(e){return Buffer.from(e,"base64").toString("utf8")}static base64DecodeUrl(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";return T.base64Decode(t)}}class A{sha256(e){return s.createHash("sha256").update(e).digest()}}class k{constructor(){this.hashUtils=new A}async generatePkceCodes(){const e=this.generateCodeVerifier();return{verifier:e,challenge:this.generateCodeChallengeFromVerifier(e)}}generateCodeVerifier(){const e=[],t=256-256%c.length;for(;e.length<=32;){const r=s.randomBytes(1)[0];r>=t||e.push(c[r%c.length])}const n=e.join(r.Constants.EMPTY_STRING);return T.base64EncodeUrl(n)}generateCodeChallengeFromVerifier(e){return T.base64EncodeUrl(this.hashUtils.sha256(e).toString("base64"),"base64")}}class I{constructor(){this.pkceGenerator=new k,this.guidGenerator=new C,this.hashUtils=new A}createNewGuid(){return this.guidGenerator.generateGuid()}base64Encode(e){return T.base64Encode(e)}base64Decode(e){return T.base64Decode(e)}generatePkceCodes(){return this.pkceGenerator.generatePkceCodes()}getPublicKeyThumbprint(){throw new Error("Method not implemented.")}removeTokenBindingKey(){throw new Error("Method not implemented.")}clearKeystore(){throw new Error("Method not implemented.")}signJwt(){throw new Error("Method not implemented.")}async hashString(e){return T.base64EncodeUrl(this.hashUtils.sha256(e).toString("base64"),"base64")}}class E{static deserializeJSONBlob(e){return r.StringUtils.isEmpty(e)?{}:JSON.parse(e)}static deserializeAccounts(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={homeAccountId:i.home_account_id,environment:i.environment,realm:i.realm,localAccountId:i.local_account_id,username:i.username,authorityType:i.authority_type,name:i.name,clientInfo:i.client_info,lastModificationTime:i.last_modification_time,lastModificationApp:i.last_modification_app},s=new r.AccountEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeIdTokens(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={homeAccountId:i.home_account_id,environment:i.environment,credentialType:i.credential_type,clientId:i.client_id,secret:i.secret,realm:i.realm},s=new r.IdTokenEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeAccessTokens(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={homeAccountId:i.home_account_id,environment:i.environment,credentialType:i.credential_type,clientId:i.client_id,secret:i.secret,realm:i.realm,target:i.target,cachedAt:i.cached_at,expiresOn:i.expires_on,extendedExpiresOn:i.extended_expires_on,refreshOn:i.refresh_on,keyId:i.key_id,tokenType:i.token_type,requestedClaims:i.requestedClaims,requestedClaimsHash:i.requestedClaimsHash},s=new r.AccessTokenEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeRefreshTokens(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={homeAccountId:i.home_account_id,environment:i.environment,credentialType:i.credential_type,clientId:i.client_id,secret:i.secret,familyId:i.family_id,target:i.target,realm:i.realm},s=new r.RefreshTokenEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeAppMetadata(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={clientId:i.client_id,environment:i.environment,familyId:i.family_id},s=new r.AppMetadataEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeAllCache(e){return{accounts:e.Account?this.deserializeAccounts(e.Account):{},idTokens:e.IdToken?this.deserializeIdTokens(e.IdToken):{},accessTokens:e.AccessToken?this.deserializeAccessTokens(e.AccessToken):{},refreshTokens:e.RefreshToken?this.deserializeRefreshTokens(e.RefreshToken):{},appMetadata:e.AppMetadata?this.deserializeAppMetadata(e.AppMetadata):{}}}}class b{static serializeJSONBlob(e){return JSON.stringify(e)}static serializeAccounts(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,realm:n.realm,local_account_id:n.localAccountId,username:n.username,authority_type:n.authorityType,name:n.name,client_info:n.clientInfo,last_modification_time:n.lastModificationTime,last_modification_app:n.lastModificationApp}})),t}static serializeIdTokens(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,credential_type:n.credentialType,client_id:n.clientId,secret:n.secret,realm:n.realm}})),t}static serializeAccessTokens(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,credential_type:n.credentialType,client_id:n.clientId,secret:n.secret,realm:n.realm,target:n.target,cached_at:n.cachedAt,expires_on:n.expiresOn,extended_expires_on:n.extendedExpiresOn,refresh_on:n.refreshOn,key_id:n.keyId,token_type:n.tokenType,requestedClaims:n.requestedClaims,requestedClaimsHash:n.requestedClaimsHash}})),t}static serializeRefreshTokens(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,credential_type:n.credentialType,client_id:n.clientId,secret:n.secret,family_id:n.familyId,target:n.target,realm:n.realm}})),t}static serializeAppMetadata(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={client_id:n.clientId,environment:n.environment,family_id:n.familyId}})),t}static serializeAllCache(e){return{Account:this.serializeAccounts(e.accounts),IdToken:this.serializeIdTokens(e.idTokens),AccessToken:this.serializeAccessTokens(e.accessTokens),RefreshToken:this.serializeRefreshTokens(e.refreshTokens),AppMetadata:this.serializeAppMetadata(e.appMetadata)}}}class w extends r.CacheManager{constructor(e,t,r){super(t,r),this.cache={},this.changeEmitters=[],this.logger=e}registerChangeEmitter(e){this.changeEmitters.push(e)}emitChange(){this.changeEmitters.forEach(e=>e.call(null))}cacheToInMemoryCache(e){const t={accounts:{},idTokens:{},accessTokens:{},refreshTokens:{},appMetadata:{}};for(const n in e)if(e[n]instanceof r.AccountEntity)t.accounts[n]=e[n];else if(e[n]instanceof r.IdTokenEntity)t.idTokens[n]=e[n];else if(e[n]instanceof r.AccessTokenEntity)t.accessTokens[n]=e[n];else if(e[n]instanceof r.RefreshTokenEntity)t.refreshTokens[n]=e[n];else{if(!(e[n]instanceof r.AppMetadataEntity))continue;t.appMetadata[n]=e[n]}return t}inMemoryCacheToCache(e){let t=this.getCache();return t={...t,...e.accounts,...e.idTokens,...e.accessTokens,...e.refreshTokens,...e.appMetadata},t}getInMemoryCache(){return this.logger.trace("Getting in-memory cache"),this.cacheToInMemoryCache(this.getCache())}setInMemoryCache(e){this.logger.trace("Setting in-memory cache");const t=this.inMemoryCacheToCache(e);this.setCache(t),this.emitChange()}getCache(){return this.logger.trace("Getting cache key-value store"),this.cache}setCache(e){this.logger.trace("Setting cache key value store"),this.cache=e,this.emitChange()}getItem(e){return this.logger.tracePii("Item key: "+e),this.getCache()[e]}setItem(e,t){this.logger.tracePii("Item key: "+e);const r=this.getCache();r[e]=t,this.setCache(r)}getAccount(e){const t=this.getItem(e);return r.AccountEntity.isAccountEntity(t)?t:null}setAccount(e){const t=e.generateAccountKey();this.setItem(t,e)}getIdTokenCredential(e){const t=this.getItem(e);return r.IdTokenEntity.isIdTokenEntity(t)?t:null}setIdTokenCredential(e){const t=e.generateCredentialKey();this.setItem(t,e)}getAccessTokenCredential(e){const t=this.getItem(e);return r.AccessTokenEntity.isAccessTokenEntity(t)?t:null}setAccessTokenCredential(e){const t=e.generateCredentialKey();this.setItem(t,e)}getRefreshTokenCredential(e){const t=this.getItem(e);return r.RefreshTokenEntity.isRefreshTokenEntity(t)?t:null}setRefreshTokenCredential(e){const t=e.generateCredentialKey();this.setItem(t,e)}getAppMetadata(e){const t=this.getItem(e);return r.AppMetadataEntity.isAppMetadataEntity(e,t)?t:null}setAppMetadata(e){const t=e.generateAppMetadataKey();this.setItem(t,e)}getServerTelemetry(e){const t=this.getItem(e);return t&&r.ServerTelemetryEntity.isServerTelemetryEntity(e,t)?t:null}setServerTelemetry(e,t){this.setItem(e,t)}getAuthorityMetadata(e){const t=this.getItem(e);return t&&r.AuthorityMetadataEntity.isAuthorityMetadataEntity(e,t)?t:null}getAuthorityMetadataKeys(){return this.getKeys().filter(e=>this.isAuthorityMetadata(e))}setAuthorityMetadata(e,t){this.setItem(e,t)}getThrottlingCache(e){const t=this.getItem(e);return t&&r.ThrottlingEntity.isThrottlingEntity(e,t)?t:null}setThrottlingCache(e,t){this.setItem(e,t)}removeItem(e){this.logger.tracePii("Item key: "+e);let t=!1;const r=this.getCache();return r[e]&&(delete r[e],t=!0),t&&(this.setCache(r),this.emitChange()),t}containsKey(e){return this.getKeys().includes(e)}getKeys(){this.logger.trace("Retrieving all cache keys");const e=this.getCache();return[...Object.keys(e)]}async clear(){this.logger.trace("Clearing cache entries created by MSAL"),this.getKeys().forEach(e=>{this.removeItem(e)}),this.emitChange()}static generateInMemoryCache(e){return E.deserializeAllCache(E.deserializeJSONBlob(e))}static generateJsonCache(e){return b.serializeAllCache(e)}updateCredentialCacheKey(e,t){const r=t.generateCredentialKey();if(e!==r){const n=this.getItem(e);if(n)return this.removeItem(e),this.setItem(r,n),this.logger.verbose(`Updated an outdated ${t.credentialType} cache key`),r;this.logger.error(`Attempted to update an outdated ${t.credentialType} cache key but no item matching the outdated key was found in storage`)}return e}}const v={},M={},S={},R={},O={};class _{constructor(e,t,r){this.cacheHasChanged=!1,this.storage=e,this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this)),r&&(this.persistence=r),this.logger=t}hasChanged(){return this.cacheHasChanged}serialize(){this.logger.trace("Serializing in-memory cache");let e=b.serializeAllCache(this.storage.getInMemoryCache());return r.StringUtils.isEmpty(this.cacheSnapshot)?this.logger.trace("No cache snapshot to merge"):(this.logger.trace("Reading cache snapshot from disk"),e=this.mergeState(JSON.parse(this.cacheSnapshot),e)),this.cacheHasChanged=!1,JSON.stringify(e)}deserialize(e){if(this.logger.trace("Deserializing JSON to in-memory cache"),this.cacheSnapshot=e,r.StringUtils.isEmpty(this.cacheSnapshot))this.logger.trace("No cache snapshot to deserialize");else{this.logger.trace("Reading cache snapshot from disk");const e=E.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));this.storage.setInMemoryCache(e)}}getKVStore(){return this.storage.getCache()}async getAllAccounts(){let e;this.logger.trace("getAllAccounts called");try{return this.persistence&&(e=new r.TokenCacheContext(this,!1),await this.persistence.beforeCacheAccess(e)),this.storage.getAllAccounts()}finally{this.persistence&&e&&await this.persistence.afterCacheAccess(e)}}async getAccountByHomeId(e){const t=await this.getAllAccounts();return!r.StringUtils.isEmpty(e)&&t&&t.length&&t.filter(t=>t.homeAccountId===e)[0]||null}async getAccountByLocalId(e){const t=await this.getAllAccounts();return!r.StringUtils.isEmpty(e)&&t&&t.length&&t.filter(t=>t.localAccountId===e)[0]||null}async removeAccount(e){let t;this.logger.trace("removeAccount called");try{this.persistence&&(t=new r.TokenCacheContext(this,!0),await this.persistence.beforeCacheAccess(t)),await this.storage.removeAccount(r.AccountEntity.generateAccountCacheKey(e))}finally{this.persistence&&t&&await this.persistence.afterCacheAccess(t)}}handleChangeEvent(){this.cacheHasChanged=!0}mergeState(e,t){this.logger.trace("Merging in-memory cache with cache snapshot");const r=this.mergeRemovals(e,t);return this.mergeUpdates(r,t)}mergeUpdates(e,t){return Object.keys(t).forEach(r=>{const n=t[r];if(e.hasOwnProperty(r)){const t=null!==n,i="object"==typeof n,o=!Array.isArray(n),s=null!=e[r];t&&i&&o&&s?this.mergeUpdates(e[r],n):e[r]=n}else null!==n&&(e[r]=n)}),e}mergeRemovals(e,t){this.logger.trace("Remove updated entries in cache");const r=e.Account?this.mergeRemovalsDict(e.Account,t.Account):e.Account,n=e.AccessToken?this.mergeRemovalsDict(e.AccessToken,t.AccessToken):e.AccessToken,i=e.RefreshToken?this.mergeRemovalsDict(e.RefreshToken,t.RefreshToken):e.RefreshToken,o=e.IdToken?this.mergeRemovalsDict(e.IdToken,t.IdToken):e.IdToken,s=e.AppMetadata?this.mergeRemovalsDict(e.AppMetadata,t.AppMetadata):e.AppMetadata;return{...e,Account:r,AccessToken:n,RefreshToken:i,IdToken:o,AppMetadata:s}}mergeRemovalsDict(e,t){const r={...e};return Object.keys(e).forEach(e=>{t&&t.hasOwnProperty(e)||delete r[e]}),r}overlayDefaults(e){return this.logger.trace("Overlaying input cache with the default cache"),{Account:{...v,...e.Account},IdToken:{...M,...e.IdToken},AccessToken:{...S,...e.AccessToken},RefreshToken:{...R,...e.RefreshToken},AppMetadata:{...O,...e.AppMetadata}}}}class P{constructor(e){this.config=f(e),this.cryptoProvider=new I,this.logger=new r.Logger(this.config.system.loggerOptions,"@azure/msal-node","1.10.0"),this.storage=new w(this.logger,this.config.auth.clientId,this.cryptoProvider),this.tokenCache=new _(this.storage,this.logger,this.config.cache.cachePlugin)}async getAuthCodeUrl(e){this.logger.info("getAuthCodeUrl called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e),responseMode:e.responseMode||r.ResponseMode.QUERY,authenticationScheme:r.AuthenticationScheme.BEARER},n=await this.buildOauthClientConfiguration(t.authority,t.correlationId,void 0,void 0,e.azureCloudOptions),i=new r.AuthorizationCodeClient(n);return this.logger.verbose("Auth code client created",t.correlationId),i.getAuthCodeUrl(t)}async acquireTokenByCode(e,t){this.logger.info("acquireTokenByCode called",e.correlationId);const n={...e,...await this.initializeBaseRequest(e),authenticationScheme:r.AuthenticationScheme.BEARER},i=this.initializeServerTelemetryManager(l.acquireTokenByCode,n.correlationId);try{const o=await this.buildOauthClientConfiguration(n.authority,n.correlationId,i,void 0,e.azureCloudOptions),s=new r.AuthorizationCodeClient(o);return this.logger.verbose("Auth code client created",n.correlationId),s.acquireToken(n,t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(n.correlationId),i.cacheFailedRequest(e),e}}async acquireTokenByRefreshToken(e){this.logger.info("acquireTokenByRefreshToken called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e),authenticationScheme:r.AuthenticationScheme.BEARER},n=this.initializeServerTelemetryManager(l.acquireTokenByRefreshToken,t.correlationId);try{const i=await this.buildOauthClientConfiguration(t.authority,t.correlationId,n,void 0,e.azureCloudOptions),o=new r.RefreshTokenClient(i);return this.logger.verbose("Refresh token client created",t.correlationId),o.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),n.cacheFailedRequest(e),e}}async acquireTokenSilent(e){const t={...e,...await this.initializeBaseRequest(e),forceRefresh:e.forceRefresh||!1},n=this.initializeServerTelemetryManager(l.acquireTokenSilent,t.correlationId,t.forceRefresh);try{const i=await this.buildOauthClientConfiguration(t.authority,t.correlationId,n,void 0,e.azureCloudOptions),o=new r.SilentFlowClient(i);return this.logger.verbose("Silent flow client created",t.correlationId),o.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),n.cacheFailedRequest(e),e}}async acquireTokenByUsernamePassword(e){this.logger.info("acquireTokenByUsernamePassword called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e)},n=this.initializeServerTelemetryManager(l.acquireTokenByUsernamePassword,t.correlationId);try{const i=await this.buildOauthClientConfiguration(t.authority,t.correlationId,n,void 0,e.azureCloudOptions),o=new r.UsernamePasswordClient(i);return this.logger.verbose("Username password client created",t.correlationId),o.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),n.cacheFailedRequest(e),e}}getTokenCache(){return this.logger.info("getTokenCache called"),this.tokenCache}getLogger(){return this.logger}setLogger(e){this.logger=e}async buildOauthClientConfiguration(e,t,n,i,o){this.logger.verbose("buildOauthClientConfiguration called",t);const s=o||this.config.auth.azureCloudOptions;this.logger.verbose("building oauth client configuration with the authority: "+e,t);const a=await this.createAuthority(e,i,t,s);return null==n||n.updateRegionDiscoveryMetadata(a.regionDiscoveryMetadata),{authOptions:{clientId:this.config.auth.clientId,authority:a,clientCapabilities:this.config.auth.clientCapabilities},systemOptions:{proxyUrl:this.config.system.proxyUrl},loggerOptions:{logLevel:this.config.system.loggerOptions.logLevel,loggerCallback:this.config.system.loggerOptions.loggerCallback,piiLoggingEnabled:this.config.system.loggerOptions.piiLoggingEnabled,correlationId:t},cryptoInterface:this.cryptoProvider,networkInterface:this.config.system.networkClient,storageInterface:this.storage,serverTelemetryManager:n,clientCredentials:{clientSecret:this.clientSecret,clientAssertion:this.clientAssertion?this.getClientAssertion(a):void 0},libraryInfo:{sku:"msal.js.node",version:"1.10.0",cpu:process.arch||r.Constants.EMPTY_STRING,os:process.platform||r.Constants.EMPTY_STRING},telemetry:this.config.telemetry,persistencePlugin:this.config.cache.cachePlugin,serializableCache:this.tokenCache}}getClientAssertion(e){return{assertion:this.clientAssertion.getJwt(this.cryptoProvider,this.config.auth.clientId,e.tokenEndpoint),assertionType:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"}}async initializeBaseRequest(e){return this.logger.verbose("initializeRequestScopes called",e.correlationId),e.authenticationScheme&&e.authenticationScheme===r.AuthenticationScheme.POP&&this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request",e.correlationId),e.authenticationScheme=r.AuthenticationScheme.BEARER,e.claims&&!r.StringUtils.isEmpty(e.claims)&&(e.requestedClaimsHash=await this.cryptoProvider.hashString(e.claims)),{...e,scopes:[...e&&e.scopes||[],...r.OIDC_DEFAULT_SCOPES],correlationId:e&&e.correlationId||this.cryptoProvider.createNewGuid(),authority:e.authority||this.config.auth.authority}}initializeServerTelemetryManager(e,t,n){return new r.ServerTelemetryManager({clientId:this.config.auth.clientId,correlationId:t,apiId:e,forceRefresh:n||!1},this.storage)}async createAuthority(e,t,n,i){this.logger.verbose("createAuthority called",n);const o=r.Authority.generateAuthority(e,i),s={protocolMode:this.config.auth.protocolMode,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,azureRegionConfiguration:t};return await r.AuthorityFactory.createDiscoveredInstance(o,this.config.system.networkClient,this.storage,s,this.config.system.proxyUrl)}clearCache(){this.storage.clear()}}class q{static fromAssertion(e){const t=new q;return t.jwt=e,t}static fromCertificate(e,t,r){const n=new q;return n.privateKey=t,n.thumbprint=e,r&&(n.publicCertificate=this.parseCertificate(r)),n}getJwt(e,t,n){if(this.privateKey&&this.thumbprint)return this.jwt&&!this.isExpired()&&t===this.issuer&&n===this.jwtAudience?this.jwt:this.createJwt(e,t,n);if(this.jwt)return this.jwt;throw r.ClientAuthError.createInvalidAssertionError()}createJwt(e,t,n){this.issuer=t,this.jwtAudience=n;const i=r.TimeUtils.nowSeconds();this.expirationTime=i+600;const o={alg:"RS256",x5t:T.base64EncodeUrl(this.thumbprint,"hex")};this.publicCertificate&&Object.assign(o,{x5c:this.publicCertificate});const s={aud:this.jwtAudience,exp:this.expirationTime,iss:this.issuer,sub:this.issuer,nbf:i,jti:e.createNewGuid()};return this.jwt=a.sign(s,this.privateKey,{header:o}),this.jwt}isExpired(){return this.expirationTime<r.TimeUtils.nowSeconds()}static parseCertificate(e){const t=/-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs,n=[];let i;for(;null!==(i=t.exec(e));)n.push(i[1].replace(/\r*\n/g,r.Constants.EMPTY_STRING));return n}}Object.defineProperty(exports,"AuthError",{enumerable:!0,get:function(){return r.AuthError}}),Object.defineProperty(exports,"AuthErrorMessage",{enumerable:!0,get:function(){return r.AuthErrorMessage}}),Object.defineProperty(exports,"AzureCloudInstance",{enumerable:!0,get:function(){return r.AzureCloudInstance}}),Object.defineProperty(exports,"ClientAuthError",{enumerable:!0,get:function(){return r.ClientAuthError}}),Object.defineProperty(exports,"ClientAuthErrorMessage",{enumerable:!0,get:function(){return r.ClientAuthErrorMessage}}),Object.defineProperty(exports,"ClientConfigurationError",{enumerable:!0,get:function(){return r.ClientConfigurationError}}),Object.defineProperty(exports,"ClientConfigurationErrorMessage",{enumerable:!0,get:function(){return r.ClientConfigurationErrorMessage}}),Object.defineProperty(exports,"InteractionRequiredAuthError",{enumerable:!0,get:function(){return r.InteractionRequiredAuthError}}),Object.defineProperty(exports,"InteractionRequiredAuthErrorMessage",{enumerable:!0,get:function(){return r.InteractionRequiredAuthErrorMessage}}),Object.defineProperty(exports,"LogLevel",{enumerable:!0,get:function(){return r.LogLevel}}),Object.defineProperty(exports,"Logger",{enumerable:!0,get:function(){return r.Logger}}),Object.defineProperty(exports,"PromptValue",{enumerable:!0,get:function(){return r.PromptValue}}),Object.defineProperty(exports,"ProtocolMode",{enumerable:!0,get:function(){return r.ProtocolMode}}),Object.defineProperty(exports,"ResponseMode",{enumerable:!0,get:function(){return r.ResponseMode}}),Object.defineProperty(exports,"ServerError",{enumerable:!0,get:function(){return r.ServerError}}),Object.defineProperty(exports,"TokenCacheContext",{enumerable:!0,get:function(){return r.TokenCacheContext}}),exports.ClientApplication=P,exports.ClientAssertion=q,exports.ConfidentialClientApplication=class extends P{constructor(e){super(e),this.setClientCredential(this.config)}async acquireTokenByClientCredential(e){let t;this.logger.info("acquireTokenByClientCredential called",e.correlationId),e.clientAssertion&&(t={assertion:e.clientAssertion,assertionType:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"});const n={...e,...await this.initializeBaseRequest(e),clientAssertion:t},i={azureRegion:n.azureRegion,environmentRegion:process.env.REGION_NAME},o=this.initializeServerTelemetryManager(l.acquireTokenByClientCredential,n.correlationId,n.skipCache);try{const t=await this.buildOauthClientConfiguration(n.authority,n.correlationId,o,i,e.azureCloudOptions),s=new r.ClientCredentialClient(t);return this.logger.verbose("Client credential client created",n.correlationId),s.acquireToken(n)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(n.correlationId),o.cacheFailedRequest(e),e}}async acquireTokenOnBehalfOf(e){this.logger.info("acquireTokenOnBehalfOf called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e)};try{const n=await this.buildOauthClientConfiguration(t.authority,t.correlationId,void 0,void 0,e.azureCloudOptions),i=new r.OnBehalfOfClient(n);return this.logger.verbose("On behalf of client created",t.correlationId),i.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),e}}setClientCredential(e){const t=!r.StringUtils.isEmpty(e.auth.clientSecret),n=!r.StringUtils.isEmpty(e.auth.clientAssertion),i=e.auth.clientCertificate||{thumbprint:r.Constants.EMPTY_STRING,privateKey:r.Constants.EMPTY_STRING},o=!r.StringUtils.isEmpty(i.thumbprint)||!r.StringUtils.isEmpty(i.privateKey);if(t&&n||n&&o||t&&o)throw r.ClientAuthError.createInvalidCredentialError();if(e.auth.clientSecret)this.clientSecret=e.auth.clientSecret;else if(e.auth.clientAssertion)this.clientAssertion=q.fromAssertion(e.auth.clientAssertion);else{if(!o)throw r.ClientAuthError.createInvalidCredentialError();var s;this.clientAssertion=q.fromCertificate(i.thumbprint,i.privateKey,null==(s=e.auth.clientCertificate)?void 0:s.x5c)}}},exports.CryptoProvider=I,exports.DistributedCachePlugin=class{constructor(e,t){this.client=e,this.partitionManager=t}async beforeCacheAccess(e){const t=await this.partitionManager.getKey(),r=await this.client.get(t);e.tokenCache.deserialize(r)}async afterCacheAccess(e){if(e.cacheHasChanged){const t=e.tokenCache.getKVStore(),n=Object.values(t).filter(e=>r.AccountEntity.isAccountEntity(e));if(n.length>0){const t=n[0],r=await this.partitionManager.extractKey(t);await this.client.set(r,e.tokenCache.serialize())}}}},exports.NodeStorage=w,exports.PublicClientApplication=class extends P{constructor(e){super(e)}async acquireTokenByDeviceCode(e){this.logger.info("acquireTokenByDeviceCode called",e.correlationId);const t=Object.assign(e,await this.initializeBaseRequest(e)),n=this.initializeServerTelemetryManager(l.acquireTokenByDeviceCode,t.correlationId);try{const i=await this.buildOauthClientConfiguration(t.authority,t.correlationId,n,void 0,e.azureCloudOptions),o=new r.DeviceCodeClient(i);return this.logger.verbose("Device code client created",t.correlationId),o.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),n.cacheFailedRequest(e),e}}},exports.TokenCache=_,exports.buildAppConfiguration=f,exports.version="1.10.0"; | ||
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t,r=require("@azure/msal-common"),n=e(require("http")),i=e(require("https")),o=require("uuid"),s=e(require("crypto")),a=require("jsonwebtoken");!function(e){e.GET="get",e.POST="post"}(t||(t={}));const c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";var l;!function(e){e[e.acquireTokenSilent=62]="acquireTokenSilent",e[e.acquireTokenByUsernamePassword=371]="acquireTokenByUsernamePassword",e[e.acquireTokenByDeviceCode=671]="acquireTokenByDeviceCode",e[e.acquireTokenByClientCredential=771]="acquireTokenByClientCredential",e[e.acquireTokenByCode=871]="acquireTokenByCode",e[e.acquireTokenByRefreshToken=872]="acquireTokenByRefreshToken"}(l||(l={}));class h{async sendGetRequestAsync(e,r){return null!=r&&r.proxyUrl?u(e,t.GET,r):d(e,t.GET,r)}async sendPostRequestAsync(e,r,n){return null!=r&&r.proxyUrl?u(e,t.POST,r,n):d(e,t.POST,r,n)}}const u=(e,r,i,o)=>{const s=(null==i?void 0:i.headers)||{},a=new URL((null==i?void 0:i.proxyUrl)||""),c=new URL(e),l={host:a.hostname,port:a.port,method:"CONNECT",path:c.hostname,headers:s};o&&(l.timeout=o);let h="";if(r===t.POST){const e=(null==i?void 0:i.body)||"";h=`Content-Type: application/x-www-form-urlencoded\r\nContent-Length: ${e.length}\r\n\r\n`+e}const u=`${r.toUpperCase()} ${c.href} HTTP/1.1\r\nHost: ${c.host}\r\nConnection: close\r\n`+h+"\r\n";return new Promise((e,t)=>{const r=n.request(l);l.timeout&&r.on("timeout",()=>{r.destroy(),t(new Error("Request time out"))}),r.end(),r.on("connect",(n,i)=>{const o=(null==n?void 0:n.statusCode)||500;(o<200||o>299)&&(r.destroy(),i.destroy(),t(new Error("HTTP status code "+o))),l.timeout&&(i.setTimeout(l.timeout),i.on("timeout",()=>{r.destroy(),i.destroy(),t(new Error("Request time out"))})),i.write(u);const s=[];i.on("data",e=>{s.push(e)}),i.on("end",()=>{const n=Buffer.concat([...s]).toString().split("\r\n"),o=parseInt(n[0].split(" ")[1]),a=n[n.length-1],c=n.slice(1,n.length-2),l=new Map;c.forEach(e=>{const t=e.split(new RegExp(/:\s(.*)/s)),r=t[0];let n=t[1];try{const e=JSON.parse(n);e&&"object"==typeof e&&(n=e)}catch(e){}l.set(r,n)});const h={headers:Object.fromEntries(l),body:JSON.parse(a),status:o};(o<200||o>299)&&"authorization_pending"!==h.body.error&&(r.destroy(),i.destroy(),t(new Error("HTTP status code "+o))),e(h)}),i.on("error",e=>{r.destroy(),i.destroy(),t(new Error(e.toString()))})}),r.on("error",e=>{r.destroy(),t(new Error(e.toString()))})})},d=(e,r,n,o)=>{const s=r===t.POST,a=(null==n?void 0:n.body)||"",c={method:r,headers:(null==n?void 0:n.headers)||{}};return o&&(c.timeout=o),s&&(c.headers={...c.headers,"Content-Length":a.length}),new Promise((t,r)=>{const n=i.request(e,c);o&&n.on("timeout",()=>{n.destroy(),r(new Error("Request time out"))}),s&&n.write(a),n.end(),n.on("response",e=>{const i=e.headers,o=e.statusCode,s=[];e.on("data",e=>{s.push(e)}),e.on("end",()=>{const e=Buffer.concat([...s]).toString(),a={headers:i,body:JSON.parse(e),status:o};(o<200||o>299)&&"authorization_pending"!==a.body.error&&(n.destroy(),r(new Error("HTTP status code "+o))),t(a)})}),n.on("error",e=>{n.destroy(),r(new Error(e.toString()))})})},g={clientId:r.Constants.EMPTY_STRING,authority:r.Constants.DEFAULT_AUTHORITY,clientSecret:r.Constants.EMPTY_STRING,clientAssertion:r.Constants.EMPTY_STRING,clientCertificate:{thumbprint:r.Constants.EMPTY_STRING,privateKey:r.Constants.EMPTY_STRING,x5c:r.Constants.EMPTY_STRING},knownAuthorities:[],cloudDiscoveryMetadata:r.Constants.EMPTY_STRING,authorityMetadata:r.Constants.EMPTY_STRING,clientCapabilities:[],protocolMode:r.ProtocolMode.AAD,azureCloudOptions:{azureCloudInstance:r.AzureCloudInstance.None,tenant:r.Constants.EMPTY_STRING},skipAuthorityMetadataCache:!1},p={},y={loggerOptions:{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:r.LogLevel.Info},networkClient:class{static getNetworkClient(){return new h}}.getNetworkClient(),proxyUrl:r.Constants.EMPTY_STRING},m={application:{appName:r.Constants.EMPTY_STRING,appVersion:r.Constants.EMPTY_STRING}};function f({auth:e,cache:t,system:r,telemetry:n}){return{auth:{...g,...e},cache:{...p,...t},system:{...y,...r},telemetry:{...m,...n}}}class C{generateGuid(){return o.v4()}isGuid(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}}class T{static base64Encode(e,t){return Buffer.from(e,t).toString("base64")}static base64EncodeUrl(e,t){return T.base64Encode(e,t).replace(/=/g,r.Constants.EMPTY_STRING).replace(/\+/g,"-").replace(/\//g,"_")}static base64Decode(e){return Buffer.from(e,"base64").toString("utf8")}static base64DecodeUrl(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";return T.base64Decode(t)}}class A{sha256(e){return s.createHash("sha256").update(e).digest()}}class k{constructor(){this.hashUtils=new A}async generatePkceCodes(){const e=this.generateCodeVerifier();return{verifier:e,challenge:this.generateCodeChallengeFromVerifier(e)}}generateCodeVerifier(){const e=[],t=256-256%c.length;for(;e.length<=32;){const r=s.randomBytes(1)[0];r>=t||e.push(c[r%c.length])}const n=e.join(r.Constants.EMPTY_STRING);return T.base64EncodeUrl(n)}generateCodeChallengeFromVerifier(e){return T.base64EncodeUrl(this.hashUtils.sha256(e).toString("base64"),"base64")}}class I{constructor(){this.pkceGenerator=new k,this.guidGenerator=new C,this.hashUtils=new A}createNewGuid(){return this.guidGenerator.generateGuid()}base64Encode(e){return T.base64Encode(e)}base64Decode(e){return T.base64Decode(e)}generatePkceCodes(){return this.pkceGenerator.generatePkceCodes()}getPublicKeyThumbprint(){throw new Error("Method not implemented.")}removeTokenBindingKey(){throw new Error("Method not implemented.")}clearKeystore(){throw new Error("Method not implemented.")}signJwt(){throw new Error("Method not implemented.")}async hashString(e){return T.base64EncodeUrl(this.hashUtils.sha256(e).toString("base64"),"base64")}}class E{static deserializeJSONBlob(e){return r.StringUtils.isEmpty(e)?{}:JSON.parse(e)}static deserializeAccounts(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={homeAccountId:i.home_account_id,environment:i.environment,realm:i.realm,localAccountId:i.local_account_id,username:i.username,authorityType:i.authority_type,name:i.name,clientInfo:i.client_info,lastModificationTime:i.last_modification_time,lastModificationApp:i.last_modification_app},s=new r.AccountEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeIdTokens(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={homeAccountId:i.home_account_id,environment:i.environment,credentialType:i.credential_type,clientId:i.client_id,secret:i.secret,realm:i.realm},s=new r.IdTokenEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeAccessTokens(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={homeAccountId:i.home_account_id,environment:i.environment,credentialType:i.credential_type,clientId:i.client_id,secret:i.secret,realm:i.realm,target:i.target,cachedAt:i.cached_at,expiresOn:i.expires_on,extendedExpiresOn:i.extended_expires_on,refreshOn:i.refresh_on,keyId:i.key_id,tokenType:i.token_type,requestedClaims:i.requestedClaims,requestedClaimsHash:i.requestedClaimsHash},s=new r.AccessTokenEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeRefreshTokens(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={homeAccountId:i.home_account_id,environment:i.environment,credentialType:i.credential_type,clientId:i.client_id,secret:i.secret,familyId:i.family_id,target:i.target,realm:i.realm},s=new r.RefreshTokenEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeAppMetadata(e){const t={};return e&&Object.keys(e).map((function(n){const i=e[n],o={clientId:i.client_id,environment:i.environment,familyId:i.family_id},s=new r.AppMetadataEntity;r.CacheManager.toObject(s,o),t[n]=s})),t}static deserializeAllCache(e){return{accounts:e.Account?this.deserializeAccounts(e.Account):{},idTokens:e.IdToken?this.deserializeIdTokens(e.IdToken):{},accessTokens:e.AccessToken?this.deserializeAccessTokens(e.AccessToken):{},refreshTokens:e.RefreshToken?this.deserializeRefreshTokens(e.RefreshToken):{},appMetadata:e.AppMetadata?this.deserializeAppMetadata(e.AppMetadata):{}}}}class b{static serializeJSONBlob(e){return JSON.stringify(e)}static serializeAccounts(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,realm:n.realm,local_account_id:n.localAccountId,username:n.username,authority_type:n.authorityType,name:n.name,client_info:n.clientInfo,last_modification_time:n.lastModificationTime,last_modification_app:n.lastModificationApp}})),t}static serializeIdTokens(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,credential_type:n.credentialType,client_id:n.clientId,secret:n.secret,realm:n.realm}})),t}static serializeAccessTokens(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,credential_type:n.credentialType,client_id:n.clientId,secret:n.secret,realm:n.realm,target:n.target,cached_at:n.cachedAt,expires_on:n.expiresOn,extended_expires_on:n.extendedExpiresOn,refresh_on:n.refreshOn,key_id:n.keyId,token_type:n.tokenType,requestedClaims:n.requestedClaims,requestedClaimsHash:n.requestedClaimsHash}})),t}static serializeRefreshTokens(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={home_account_id:n.homeAccountId,environment:n.environment,credential_type:n.credentialType,client_id:n.clientId,secret:n.secret,family_id:n.familyId,target:n.target,realm:n.realm}})),t}static serializeAppMetadata(e){const t={};return Object.keys(e).map((function(r){const n=e[r];t[r]={client_id:n.clientId,environment:n.environment,family_id:n.familyId}})),t}static serializeAllCache(e){return{Account:this.serializeAccounts(e.accounts),IdToken:this.serializeIdTokens(e.idTokens),AccessToken:this.serializeAccessTokens(e.accessTokens),RefreshToken:this.serializeRefreshTokens(e.refreshTokens),AppMetadata:this.serializeAppMetadata(e.appMetadata)}}}class w extends r.CacheManager{constructor(e,t,r){super(t,r),this.cache={},this.changeEmitters=[],this.logger=e}registerChangeEmitter(e){this.changeEmitters.push(e)}emitChange(){this.changeEmitters.forEach(e=>e.call(null))}cacheToInMemoryCache(e){const t={accounts:{},idTokens:{},accessTokens:{},refreshTokens:{},appMetadata:{}};for(const n in e)if(e[n]instanceof r.AccountEntity)t.accounts[n]=e[n];else if(e[n]instanceof r.IdTokenEntity)t.idTokens[n]=e[n];else if(e[n]instanceof r.AccessTokenEntity)t.accessTokens[n]=e[n];else if(e[n]instanceof r.RefreshTokenEntity)t.refreshTokens[n]=e[n];else{if(!(e[n]instanceof r.AppMetadataEntity))continue;t.appMetadata[n]=e[n]}return t}inMemoryCacheToCache(e){let t=this.getCache();return t={...t,...e.accounts,...e.idTokens,...e.accessTokens,...e.refreshTokens,...e.appMetadata},t}getInMemoryCache(){return this.logger.trace("Getting in-memory cache"),this.cacheToInMemoryCache(this.getCache())}setInMemoryCache(e){this.logger.trace("Setting in-memory cache");const t=this.inMemoryCacheToCache(e);this.setCache(t),this.emitChange()}getCache(){return this.logger.trace("Getting cache key-value store"),this.cache}setCache(e){this.logger.trace("Setting cache key value store"),this.cache=e,this.emitChange()}getItem(e){return this.logger.tracePii("Item key: "+e),this.getCache()[e]}setItem(e,t){this.logger.tracePii("Item key: "+e);const r=this.getCache();r[e]=t,this.setCache(r)}getAccount(e){const t=this.getItem(e);return r.AccountEntity.isAccountEntity(t)?t:null}setAccount(e){const t=e.generateAccountKey();this.setItem(t,e)}getIdTokenCredential(e){const t=this.getItem(e);return r.IdTokenEntity.isIdTokenEntity(t)?t:null}setIdTokenCredential(e){const t=e.generateCredentialKey();this.setItem(t,e)}getAccessTokenCredential(e){const t=this.getItem(e);return r.AccessTokenEntity.isAccessTokenEntity(t)?t:null}setAccessTokenCredential(e){const t=e.generateCredentialKey();this.setItem(t,e)}getRefreshTokenCredential(e){const t=this.getItem(e);return r.RefreshTokenEntity.isRefreshTokenEntity(t)?t:null}setRefreshTokenCredential(e){const t=e.generateCredentialKey();this.setItem(t,e)}getAppMetadata(e){const t=this.getItem(e);return r.AppMetadataEntity.isAppMetadataEntity(e,t)?t:null}setAppMetadata(e){const t=e.generateAppMetadataKey();this.setItem(t,e)}getServerTelemetry(e){const t=this.getItem(e);return t&&r.ServerTelemetryEntity.isServerTelemetryEntity(e,t)?t:null}setServerTelemetry(e,t){this.setItem(e,t)}getAuthorityMetadata(e){const t=this.getItem(e);return t&&r.AuthorityMetadataEntity.isAuthorityMetadataEntity(e,t)?t:null}getAuthorityMetadataKeys(){return this.getKeys().filter(e=>this.isAuthorityMetadata(e))}setAuthorityMetadata(e,t){this.setItem(e,t)}getThrottlingCache(e){const t=this.getItem(e);return t&&r.ThrottlingEntity.isThrottlingEntity(e,t)?t:null}setThrottlingCache(e,t){this.setItem(e,t)}removeItem(e){this.logger.tracePii("Item key: "+e);let t=!1;const r=this.getCache();return r[e]&&(delete r[e],t=!0),t&&(this.setCache(r),this.emitChange()),t}containsKey(e){return this.getKeys().includes(e)}getKeys(){this.logger.trace("Retrieving all cache keys");const e=this.getCache();return[...Object.keys(e)]}async clear(){this.logger.trace("Clearing cache entries created by MSAL"),this.getKeys().forEach(e=>{this.removeItem(e)}),this.emitChange()}static generateInMemoryCache(e){return E.deserializeAllCache(E.deserializeJSONBlob(e))}static generateJsonCache(e){return b.serializeAllCache(e)}updateCredentialCacheKey(e,t){const r=t.generateCredentialKey();if(e!==r){const n=this.getItem(e);if(n)return this.removeItem(e),this.setItem(r,n),this.logger.verbose(`Updated an outdated ${t.credentialType} cache key`),r;this.logger.error(`Attempted to update an outdated ${t.credentialType} cache key but no item matching the outdated key was found in storage`)}return e}}const v={},M={},S={},R={},O={};class _{constructor(e,t,r){this.cacheHasChanged=!1,this.storage=e,this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this)),r&&(this.persistence=r),this.logger=t}hasChanged(){return this.cacheHasChanged}serialize(){this.logger.trace("Serializing in-memory cache");let e=b.serializeAllCache(this.storage.getInMemoryCache());return r.StringUtils.isEmpty(this.cacheSnapshot)?this.logger.trace("No cache snapshot to merge"):(this.logger.trace("Reading cache snapshot from disk"),e=this.mergeState(JSON.parse(this.cacheSnapshot),e)),this.cacheHasChanged=!1,JSON.stringify(e)}deserialize(e){if(this.logger.trace("Deserializing JSON to in-memory cache"),this.cacheSnapshot=e,r.StringUtils.isEmpty(this.cacheSnapshot))this.logger.trace("No cache snapshot to deserialize");else{this.logger.trace("Reading cache snapshot from disk");const e=E.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));this.storage.setInMemoryCache(e)}}getKVStore(){return this.storage.getCache()}async getAllAccounts(){let e;this.logger.trace("getAllAccounts called");try{return this.persistence&&(e=new r.TokenCacheContext(this,!1),await this.persistence.beforeCacheAccess(e)),this.storage.getAllAccounts()}finally{this.persistence&&e&&await this.persistence.afterCacheAccess(e)}}async getAccountByHomeId(e){const t=await this.getAllAccounts();return!r.StringUtils.isEmpty(e)&&t&&t.length&&t.filter(t=>t.homeAccountId===e)[0]||null}async getAccountByLocalId(e){const t=await this.getAllAccounts();return!r.StringUtils.isEmpty(e)&&t&&t.length&&t.filter(t=>t.localAccountId===e)[0]||null}async removeAccount(e){let t;this.logger.trace("removeAccount called");try{this.persistence&&(t=new r.TokenCacheContext(this,!0),await this.persistence.beforeCacheAccess(t)),await this.storage.removeAccount(r.AccountEntity.generateAccountCacheKey(e))}finally{this.persistence&&t&&await this.persistence.afterCacheAccess(t)}}handleChangeEvent(){this.cacheHasChanged=!0}mergeState(e,t){this.logger.trace("Merging in-memory cache with cache snapshot");const r=this.mergeRemovals(e,t);return this.mergeUpdates(r,t)}mergeUpdates(e,t){return Object.keys(t).forEach(r=>{const n=t[r];if(e.hasOwnProperty(r)){const t=null!==n,i="object"==typeof n,o=!Array.isArray(n),s=null!=e[r];t&&i&&o&&s?this.mergeUpdates(e[r],n):e[r]=n}else null!==n&&(e[r]=n)}),e}mergeRemovals(e,t){this.logger.trace("Remove updated entries in cache");const r=e.Account?this.mergeRemovalsDict(e.Account,t.Account):e.Account,n=e.AccessToken?this.mergeRemovalsDict(e.AccessToken,t.AccessToken):e.AccessToken,i=e.RefreshToken?this.mergeRemovalsDict(e.RefreshToken,t.RefreshToken):e.RefreshToken,o=e.IdToken?this.mergeRemovalsDict(e.IdToken,t.IdToken):e.IdToken,s=e.AppMetadata?this.mergeRemovalsDict(e.AppMetadata,t.AppMetadata):e.AppMetadata;return{...e,Account:r,AccessToken:n,RefreshToken:i,IdToken:o,AppMetadata:s}}mergeRemovalsDict(e,t){const r={...e};return Object.keys(e).forEach(e=>{t&&t.hasOwnProperty(e)||delete r[e]}),r}overlayDefaults(e){return this.logger.trace("Overlaying input cache with the default cache"),{Account:{...v,...e.Account},IdToken:{...M,...e.IdToken},AccessToken:{...S,...e.AccessToken},RefreshToken:{...R,...e.RefreshToken},AppMetadata:{...O,...e.AppMetadata}}}}class P{constructor(e){this.config=f(e),this.cryptoProvider=new I,this.logger=new r.Logger(this.config.system.loggerOptions,"@azure/msal-node","1.11.0"),this.storage=new w(this.logger,this.config.auth.clientId,this.cryptoProvider),this.tokenCache=new _(this.storage,this.logger,this.config.cache.cachePlugin)}async getAuthCodeUrl(e){this.logger.info("getAuthCodeUrl called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e),responseMode:e.responseMode||r.ResponseMode.QUERY,authenticationScheme:r.AuthenticationScheme.BEARER},n=await this.buildOauthClientConfiguration(t.authority,t.correlationId,void 0,void 0,e.azureCloudOptions),i=new r.AuthorizationCodeClient(n);return this.logger.verbose("Auth code client created",t.correlationId),i.getAuthCodeUrl(t)}async acquireTokenByCode(e,t){this.logger.info("acquireTokenByCode called",e.correlationId);const n={...e,...await this.initializeBaseRequest(e),authenticationScheme:r.AuthenticationScheme.BEARER},i=this.initializeServerTelemetryManager(l.acquireTokenByCode,n.correlationId);try{const o=await this.buildOauthClientConfiguration(n.authority,n.correlationId,i,void 0,e.azureCloudOptions),s=new r.AuthorizationCodeClient(o);return this.logger.verbose("Auth code client created",n.correlationId),s.acquireToken(n,t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(n.correlationId),i.cacheFailedRequest(e),e}}async acquireTokenByRefreshToken(e){this.logger.info("acquireTokenByRefreshToken called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e),authenticationScheme:r.AuthenticationScheme.BEARER},n=this.initializeServerTelemetryManager(l.acquireTokenByRefreshToken,t.correlationId);try{const i=await this.buildOauthClientConfiguration(t.authority,t.correlationId,n,void 0,e.azureCloudOptions),o=new r.RefreshTokenClient(i);return this.logger.verbose("Refresh token client created",t.correlationId),o.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),n.cacheFailedRequest(e),e}}async acquireTokenSilent(e){const t={...e,...await this.initializeBaseRequest(e),forceRefresh:e.forceRefresh||!1},n=this.initializeServerTelemetryManager(l.acquireTokenSilent,t.correlationId,t.forceRefresh);try{const i=await this.buildOauthClientConfiguration(t.authority,t.correlationId,n,void 0,e.azureCloudOptions),o=new r.SilentFlowClient(i);return this.logger.verbose("Silent flow client created",t.correlationId),o.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),n.cacheFailedRequest(e),e}}async acquireTokenByUsernamePassword(e){this.logger.info("acquireTokenByUsernamePassword called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e)},n=this.initializeServerTelemetryManager(l.acquireTokenByUsernamePassword,t.correlationId);try{const i=await this.buildOauthClientConfiguration(t.authority,t.correlationId,n,void 0,e.azureCloudOptions),o=new r.UsernamePasswordClient(i);return this.logger.verbose("Username password client created",t.correlationId),o.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),n.cacheFailedRequest(e),e}}getTokenCache(){return this.logger.info("getTokenCache called"),this.tokenCache}getLogger(){return this.logger}setLogger(e){this.logger=e}async buildOauthClientConfiguration(e,t,n,i,o){this.logger.verbose("buildOauthClientConfiguration called",t);const s=o||this.config.auth.azureCloudOptions;this.logger.verbose("building oauth client configuration with the authority: "+e,t);const a=await this.createAuthority(e,i,t,s);return null==n||n.updateRegionDiscoveryMetadata(a.regionDiscoveryMetadata),{authOptions:{clientId:this.config.auth.clientId,authority:a,clientCapabilities:this.config.auth.clientCapabilities},systemOptions:{proxyUrl:this.config.system.proxyUrl},loggerOptions:{logLevel:this.config.system.loggerOptions.logLevel,loggerCallback:this.config.system.loggerOptions.loggerCallback,piiLoggingEnabled:this.config.system.loggerOptions.piiLoggingEnabled,correlationId:t},cryptoInterface:this.cryptoProvider,networkInterface:this.config.system.networkClient,storageInterface:this.storage,serverTelemetryManager:n,clientCredentials:{clientSecret:this.clientSecret,clientAssertion:this.clientAssertion?this.getClientAssertion(a):void 0},libraryInfo:{sku:"msal.js.node",version:"1.11.0",cpu:process.arch||r.Constants.EMPTY_STRING,os:process.platform||r.Constants.EMPTY_STRING},telemetry:this.config.telemetry,persistencePlugin:this.config.cache.cachePlugin,serializableCache:this.tokenCache}}getClientAssertion(e){return{assertion:this.clientAssertion.getJwt(this.cryptoProvider,this.config.auth.clientId,e.tokenEndpoint),assertionType:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"}}async initializeBaseRequest(e){return this.logger.verbose("initializeRequestScopes called",e.correlationId),e.authenticationScheme&&e.authenticationScheme===r.AuthenticationScheme.POP&&this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request",e.correlationId),e.authenticationScheme=r.AuthenticationScheme.BEARER,e.claims&&!r.StringUtils.isEmpty(e.claims)&&(e.requestedClaimsHash=await this.cryptoProvider.hashString(e.claims)),{...e,scopes:[...e&&e.scopes||[],...r.OIDC_DEFAULT_SCOPES],correlationId:e&&e.correlationId||this.cryptoProvider.createNewGuid(),authority:e.authority||this.config.auth.authority}}initializeServerTelemetryManager(e,t,n){return new r.ServerTelemetryManager({clientId:this.config.auth.clientId,correlationId:t,apiId:e,forceRefresh:n||!1},this.storage)}async createAuthority(e,t,n,i){this.logger.verbose("createAuthority called",n);const o=r.Authority.generateAuthority(e,i),s={protocolMode:this.config.auth.protocolMode,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,azureRegionConfiguration:t,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache};return await r.AuthorityFactory.createDiscoveredInstance(o,this.config.system.networkClient,this.storage,s,this.config.system.proxyUrl)}clearCache(){this.storage.clear()}}class q{static fromAssertion(e){const t=new q;return t.jwt=e,t}static fromCertificate(e,t,r){const n=new q;return n.privateKey=t,n.thumbprint=e,r&&(n.publicCertificate=this.parseCertificate(r)),n}getJwt(e,t,n){if(this.privateKey&&this.thumbprint)return this.jwt&&!this.isExpired()&&t===this.issuer&&n===this.jwtAudience?this.jwt:this.createJwt(e,t,n);if(this.jwt)return this.jwt;throw r.ClientAuthError.createInvalidAssertionError()}createJwt(e,t,n){this.issuer=t,this.jwtAudience=n;const i=r.TimeUtils.nowSeconds();this.expirationTime=i+600;const o={alg:"RS256",x5t:T.base64EncodeUrl(this.thumbprint,"hex")};this.publicCertificate&&Object.assign(o,{x5c:this.publicCertificate});const s={aud:this.jwtAudience,exp:this.expirationTime,iss:this.issuer,sub:this.issuer,nbf:i,jti:e.createNewGuid()};return this.jwt=a.sign(s,this.privateKey,{header:o}),this.jwt}isExpired(){return this.expirationTime<r.TimeUtils.nowSeconds()}static parseCertificate(e){const t=/-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs,n=[];let i;for(;null!==(i=t.exec(e));)n.push(i[1].replace(/\r*\n/g,r.Constants.EMPTY_STRING));return n}}Object.defineProperty(exports,"AuthError",{enumerable:!0,get:function(){return r.AuthError}}),Object.defineProperty(exports,"AuthErrorMessage",{enumerable:!0,get:function(){return r.AuthErrorMessage}}),Object.defineProperty(exports,"AzureCloudInstance",{enumerable:!0,get:function(){return r.AzureCloudInstance}}),Object.defineProperty(exports,"ClientAuthError",{enumerable:!0,get:function(){return r.ClientAuthError}}),Object.defineProperty(exports,"ClientAuthErrorMessage",{enumerable:!0,get:function(){return r.ClientAuthErrorMessage}}),Object.defineProperty(exports,"ClientConfigurationError",{enumerable:!0,get:function(){return r.ClientConfigurationError}}),Object.defineProperty(exports,"ClientConfigurationErrorMessage",{enumerable:!0,get:function(){return r.ClientConfigurationErrorMessage}}),Object.defineProperty(exports,"InteractionRequiredAuthError",{enumerable:!0,get:function(){return r.InteractionRequiredAuthError}}),Object.defineProperty(exports,"InteractionRequiredAuthErrorMessage",{enumerable:!0,get:function(){return r.InteractionRequiredAuthErrorMessage}}),Object.defineProperty(exports,"LogLevel",{enumerable:!0,get:function(){return r.LogLevel}}),Object.defineProperty(exports,"Logger",{enumerable:!0,get:function(){return r.Logger}}),Object.defineProperty(exports,"PromptValue",{enumerable:!0,get:function(){return r.PromptValue}}),Object.defineProperty(exports,"ProtocolMode",{enumerable:!0,get:function(){return r.ProtocolMode}}),Object.defineProperty(exports,"ResponseMode",{enumerable:!0,get:function(){return r.ResponseMode}}),Object.defineProperty(exports,"ServerError",{enumerable:!0,get:function(){return r.ServerError}}),Object.defineProperty(exports,"TokenCacheContext",{enumerable:!0,get:function(){return r.TokenCacheContext}}),exports.ClientApplication=P,exports.ClientAssertion=q,exports.ConfidentialClientApplication=class extends P{constructor(e){super(e),this.setClientCredential(this.config)}async acquireTokenByClientCredential(e){let t;this.logger.info("acquireTokenByClientCredential called",e.correlationId),e.clientAssertion&&(t={assertion:e.clientAssertion,assertionType:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"});const n={...e,...await this.initializeBaseRequest(e),clientAssertion:t},i={azureRegion:n.azureRegion,environmentRegion:process.env.REGION_NAME},o=this.initializeServerTelemetryManager(l.acquireTokenByClientCredential,n.correlationId,n.skipCache);try{const t=await this.buildOauthClientConfiguration(n.authority,n.correlationId,o,i,e.azureCloudOptions),s=new r.ClientCredentialClient(t);return this.logger.verbose("Client credential client created",n.correlationId),s.acquireToken(n)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(n.correlationId),o.cacheFailedRequest(e),e}}async acquireTokenOnBehalfOf(e){this.logger.info("acquireTokenOnBehalfOf called",e.correlationId);const t={...e,...await this.initializeBaseRequest(e)};try{const n=await this.buildOauthClientConfiguration(t.authority,t.correlationId,void 0,void 0,e.azureCloudOptions),i=new r.OnBehalfOfClient(n);return this.logger.verbose("On behalf of client created",t.correlationId),i.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),e}}setClientCredential(e){const t=!r.StringUtils.isEmpty(e.auth.clientSecret),n=!r.StringUtils.isEmpty(e.auth.clientAssertion),i=e.auth.clientCertificate||{thumbprint:r.Constants.EMPTY_STRING,privateKey:r.Constants.EMPTY_STRING},o=!r.StringUtils.isEmpty(i.thumbprint)||!r.StringUtils.isEmpty(i.privateKey);if(t&&n||n&&o||t&&o)throw r.ClientAuthError.createInvalidCredentialError();if(e.auth.clientSecret)this.clientSecret=e.auth.clientSecret;else if(e.auth.clientAssertion)this.clientAssertion=q.fromAssertion(e.auth.clientAssertion);else{if(!o)throw r.ClientAuthError.createInvalidCredentialError();var s;this.clientAssertion=q.fromCertificate(i.thumbprint,i.privateKey,null==(s=e.auth.clientCertificate)?void 0:s.x5c)}}},exports.CryptoProvider=I,exports.DistributedCachePlugin=class{constructor(e,t){this.client=e,this.partitionManager=t}async beforeCacheAccess(e){const t=await this.partitionManager.getKey(),r=await this.client.get(t);e.tokenCache.deserialize(r)}async afterCacheAccess(e){if(e.cacheHasChanged){const t=e.tokenCache.getKVStore(),n=Object.values(t).filter(e=>r.AccountEntity.isAccountEntity(e));if(n.length>0){const t=n[0],r=await this.partitionManager.extractKey(t);await this.client.set(r,e.tokenCache.serialize())}}}},exports.NodeStorage=w,exports.PublicClientApplication=class extends P{constructor(e){super(e)}async acquireTokenByDeviceCode(e){this.logger.info("acquireTokenByDeviceCode called",e.correlationId);const t=Object.assign(e,await this.initializeBaseRequest(e)),n=this.initializeServerTelemetryManager(l.acquireTokenByDeviceCode,t.correlationId);try{const i=await this.buildOauthClientConfiguration(t.authority,t.correlationId,n,void 0,e.azureCloudOptions),o=new r.DeviceCodeClient(i);return this.logger.verbose("Device code client created",t.correlationId),o.acquireToken(t)}catch(e){throw e instanceof r.AuthError&&e.setCorrelationId(t.correlationId),n.cacheFailedRequest(e),e}}},exports.TokenCache=_,exports.buildAppConfiguration=f,exports.version="1.11.0"; | ||
//# sourceMappingURL=msal-node.cjs.production.min.js.map |
export declare const name = "@azure/msal-node"; | ||
export declare const version = "1.10.0"; | ||
export declare const version = "1.11.0"; | ||
//# sourceMappingURL=packageMetadata.d.ts.map |
{ | ||
"name": "@azure/msal-node", | ||
"version": "1.10.0", | ||
"version": "1.11.0", | ||
"author": { | ||
@@ -42,3 +42,2 @@ "name": "Microsoft", | ||
}, | ||
"peerDependencies": {}, | ||
"beachball": { | ||
@@ -59,6 +58,7 @@ "disallowedChangeTypes": [ | ||
"tslib": "^1.10.0", | ||
"typescript": "^3.8.3" | ||
"typescript": "^3.8.3", | ||
"yargs": "^17.3.1" | ||
}, | ||
"dependencies": { | ||
"@azure/msal-common": "^7.0.0", | ||
"@azure/msal-common": "^7.1.0", | ||
"jsonwebtoken": "^8.5.1", | ||
@@ -65,0 +65,0 @@ "uuid": "^8.3.0" |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
773703
5704
10
Updated@azure/msal-common@^7.1.0