reject(newError(`Error connecting to proxy. Http status code: ${response.statusCode}. Http status message: ${(response==null?void0:response.statusMessage)||"Unknown"}`));
}
if(tunnelRequestOptions.timeout){
socket.setTimeout(tunnelRequestOptions.timeout);
socket.on("timeout",()=>{
request.destroy();
socket.destroy();
reject(newError("Request time out"));
});
}// make a request over an HTTP tunnel
socket.write(outgoingRequestString);
constdata=[];
socket.on("data",chunk=>{
data.push(chunk);
});
socket.on("end",()=>{
// combine all received buffer streams into one buffer, and then into a string
constdataString=Buffer.concat([...data]).toString();// separate each line into it's own entry in an arry
constdataStringArray=dataString.split("\r\n");// the first entry will contain the statusCode and statusMessage
consthttpStatusCode=parseInt(dataStringArray[0].split("")[1]);// remove "HTTP/1.1" and the status code to get the status message
conststatusMessage=dataStringArray[0].split("").slice(2).join("");// the last entry will contain the body
constbody=dataStringArray[dataStringArray.length-1];// everything in between the first and last entries are the headers
constheadersArray=dataStringArray.slice(1,dataStringArray.length-2);// build an object out of all the headers
constentries=newMap();
headersArray.forEach(header=>{
/**
* the header might look like "Content-Length: 1531", but that is just a string
* it needs to be converted to a key/value pair
* split the string at the first instance of ":"
* there may be more than one ":" if the value of the header is supposed to be a JSON object
if((httpStatusCode<HttpStatus.SUCCESS_RANGE_START||httpStatusCode>HttpStatus.SUCCESS_RANGE_END)&&// do not destroy the request for the device code flow
error_description:`${errorDescriptionHelper} error occured.\nHttp status code: ${statusCode}\nHttp status message: ${statusMessage||"Unknown"}\nHeaders: ${JSON.stringify(headers)}`
};
}
returnparsedBody;
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This class implements MSAL node's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and
* implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
* @public
*/
classCryptoProvider{
constructor(){
// Browser crypto needs to be validated first before any other classes can be set.
this.pkceGenerator=newPkceGenerator();
this.guidGenerator=newGuidGenerator();
this.hashUtils=newHashUtils();
}
/**
* Creates a new random GUID - used to populate state and nonce.
* @returns string (GUID)
*/
createNewGuid(){
returnthis.guidGenerator.generateGuid();
}
/**
* Encodes input string to base64.
* @param input - string to be encoded
*/
base64Encode(input){
returnEncodingUtils.base64Encode(input);
}
/**
* Decodes input string from base64.
* @param input - string to be decoded
*/
base64Decode(input){
returnEncodingUtils.base64Decode(input);
}
/**
* Generates PKCE codes used in Authorization Code Flow.
*/
generatePkceCodes(){
returnthis.pkceGenerator.generatePkceCodes();
}
/**
* Generates a keypair, stores it and returns a thumbprint - not yet implemented for node
*/
getPublicKeyThumbprint(){
thrownewError("Method not implemented.");
}
/**
* Removes cryptographic keypair from key store matching the keyId passed in
* @param kid
*/
removeTokenBindingKey(){
thrownewError("Method not implemented.");
}
/**
* Removes all cryptographic keys from Keystore
*/
clearKeystore(){
thrownewError("Method not implemented.");
}
/**
* Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node
this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`);
returnupdatedCacheKey;
}else{
this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`);
}
}
returncurrentCacheKey;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
constuserAzureCloudOptions=azureCloudOptions?azureCloudOptions:this.config.auth.azureCloudOptions;// using null assertion operator as we ensure that all config values have default values in buildConfiguration()
this.logger.verbose(`building oauth client configuration with the authority: ${authority}`,requestCorrelationId);
* Generates a request with the default scopes & generates a correlationId.
* @param authRequest - BaseAuthRequest for initialization
*/
asyncinitializeBaseRequest(authRequest){
this.logger.verbose("initializeRequestScopes called",authRequest.correlationId);// Default authenticationScheme to Bearer, log that POP isn't supported yet
this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request",authRequest.correlationId);
}
authRequest.authenticationScheme=msalCommon.AuthenticationScheme.BEARER;// Set requested claims hash if claims were requested
this.logger.verbose("createAuthority called",requestCorrelationId);// build authority string based on auth params - azureCloudInstance is prioritized if provided
* Important attributes in the Configuration object for auth are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.
* - authority: the authority URL for your application.
*
* AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
* - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered
* its own authority. You will have to set the all of the knownAuthorities at the time of the client application
* construction.
*
* ADFS authorities are of the form https://\{instance\}/adfs.
*/
constructor(configuration){
super(configuration);
}
/**
* Acquires a token from the authority using OAuth2.0 device code flow.
* This flow is designed for devices that do not have access to a browser or have input constraints.
* The authorization server issues a DeviceCode object with a verification code, an end-user code,
* and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be
* instructed to use another device to navigate to the verification URI to input credentials.
* Since the client cannot receive incoming requests, it polls the authorization server repeatedly
* until the end-user completes input of credentials.
* Constructor for the ConfidentialClientApplication
*
* Required attributes in the Configuration object are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal
* - authority: the authority URL for your application.
* - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.
*
* In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
* If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* In Azure B2C, authority is of the form https://\{instance\}/tfp/\{tenant\}/\{policyName\}/
* Full B2C functionality will be available in this library in future versions.
*
* @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance
*/
constructor(configuration){
super(configuration);
this.setClientCredential(this.config);
this.appTokenProvider=undefined;
}
/**
* This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and
* is meant for Azure SDK to enhance Managed Identity support.
*
* @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source.
*/
SetAppTokenProvider(provider){
this.appTokenProvider=provider;
}
/**
* Acquires tokens from the authority for the application (not for an end user).
*/
asyncacquireTokenByClientCredential(request){
this.logger.info("acquireTokenByClientCredential called",request.correlationId);// If there is a client assertion present in the request, it overrides the one present in the client configuration
letclientAssertion;
if(request.clientAssertion){
clientAssertion={
assertion:request.clientAssertion,
assertionType:Constants.JWT_BEARER_ASSERTION_TYPE
};
}
constbaseRequest=awaitthis.initializeBaseRequest(request);// valid base request should not contain oidc scopes in this grant type
{"version":3,"file":"msal-node.cjs.development.js","sources":["../src/utils/Constants.ts","../src/utils/NetworkUtils.ts","../src/network/HttpClient.ts","../src/config/Configuration.ts","../src/crypto/GuidGenerator.ts","../src/utils/EncodingUtils.ts","../src/crypto/HashUtils.ts","../src/crypto/PkceGenerator.ts","../src/crypto/CryptoProvider.ts","../src/cache/serializer/Deserializer.ts","../src/cache/serializer/Serializer.ts","../src/cache/NodeStorage.ts","../src/cache/TokenCache.ts","../src/packageMetadata.ts","../src/error/NodeAuthError.ts","../src/client/ClientApplication.ts","../src/network/LoopbackClient.ts","../src/client/PublicClientApplication.ts","../src/client/ClientAssertion.ts","../src/client/ConfidentialClientApplication.ts","../src/cache/distributed/DistributedCachePlugin.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * http methods\n */\nexport enum HttpMethod {\n GET = \"get\",\n POST = \"post\",\n}\n\nexport enum HttpStatus {\n SUCCESS_RANGE_START = 200,\n SUCCESS_RANGE_END = 299,\n REDIRECT = 302,\n CLIENT_ERROR_RANGE_START = 400,\n CLIENT_ERROR_RANGE_END = 499,\n SERVER_ERROR_RANGE_START = 500,\n SERVER_ERROR_RANGE_END = 599\n}\n\nexport enum ProxyStatus {\n SUCCESS_RANGE_START = 200,\n SUCCESS_RANGE_END = 299,\n SERVER_ERROR = 500\n}\n\n/**\n * Constants used for region discovery\n */\nexport const REGION_ENVIRONMENT_VARIABLE = \"REGION_NAME\";\n\n/**\n * Constant used for PKCE\n */\nexport const RANDOM_OCTET_SIZE = 32;\n\n/**\n * Constants used in PKCE\n */\nexport const Hash = {\n SHA256: \"sha256\",\n};\n\n/**\n * Constants for encoding schemes\n */\nexport const CharSet = {\n CV_CHARSET:\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~\",\n};\n\n/**\n * Cache Constants\n */\nexport const CACHE = {\n FILE_CACHE: \"fileCache\",\n EXTENSION_LIB: \"extenstion_library\",\n};\n\n/**\n * Constants\n */\nexport const Constants = {\n MSAL_SKU: \"msal.js.node\",\n JWT_BEARER_ASSERTION_TYPE: \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n AUTHORIZATION_PENDING: \"authorization_pending\",\n HTTP_PROTOCOL: \"http://\",\n LOCALHOST: \"localhost\"\n};\n\n/**\n * API Codes for Telemetry purposes.\n * Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs\n * 0-99 Silent Flow\n * 600-699 Device Code Flow\n * 800-899 Auth Code Flow\n */\nexport enum ApiId {\n acquireTokenSilent = 62,\n acquireTokenByUsernamePassword = 371,\n acquireTokenByDeviceCode = 671,\n acquireTokenByClientCredential = 771,\n acquireTokenByCode = 871,\n acquireTokenByRefreshToken = 872\n}\n\n/**\n * JWT constants\n */\nexport const JwtConstants = {\n ALGORITHM: \"alg\",\n RSA_256: \"RS256\",\n X5T: \"x5t\", \n X5C: \"x5c\",\n AUDIENCE: \"aud\",\n EXPIRATION_TIME: \"exp\",\n ISSUER: \"iss\",\n SUBJECT: \"sub\",\n NOT_BEFORE: \"nbf\",\n JWT_ID: \"jti\",\n};\n\nexport const LOOPBACK_SERVER_CONSTANTS = {\n INTERVAL_MS: 100,\n TIMEOUT_MS: 5000\n};\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NetworkResponse } from \"@azure/msal-common\";\n\nexport class NetworkUtils {\n static getNetworkResponse<T>(headers: Record<string, string>, body: T, statusCode: number): NetworkResponse<T> {\n return {\n headers: headers,\n body: body,\n status: statusCode,\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n INetworkModule,\n NetworkRequestOptions,\n NetworkResponse\n} from \"@azure/msal-common\";\nimport { HttpMethod, Constants, HttpStatus, ProxyStatus } from \"../utils/Constants\";\nimport { NetworkUtils } from \"../utils/NetworkUtils\";\nimport http from \"http\";\nimport https from \"https\";\n\n/**\n * This class implements the API for network requests.\n */\nexport class HttpClient implements INetworkModule {\n\n /**\n * Http Get request\n * @param url\n * @param options\n */\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n ): Promise<NetworkResponse<T>> {\n if (options?.proxyUrl) {\n return networkRequestViaProxy(url, HttpMethod.GET, options);\n } else {\n return networkRequestViaHttps(url, HttpMethod.GET, options);\n }\n }\n\n /**\n * Http Post request\n * @param url\n * @param options\n */\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n cancellationToken?: number,\n ): Promise<NetworkResponse<T>> {\n if (options?.proxyUrl) {\n return networkRequestViaProxy(url, HttpMethod.POST, options, cancellationToken);\n } else {\n return networkRequestViaHttps(url, HttpMethod.POST, options, cancellationToken);\n }\n }\n}\n\nconst networkRequestViaProxy = <T>(\n url: string,\n httpMethod: string,\n options: NetworkRequestOptions,\n timeout?: number,\n): Promise<NetworkResponse<T>> => {\n const headers = options?.headers || {} as Record<string, string>;\n const proxyUrl = new URL(options?.proxyUrl || \"\");\n const destinationUrl = new URL(url);\n\n // \"method: connect\" must be used to establish a connection to the proxy\n const tunnelRequestOptions: https.RequestOptions = {\n host: proxyUrl.hostname,\n port: proxyUrl.port,\n method: \"CONNECT\",\n path: destinationUrl.hostname,\n headers: headers,\n };\n\n if (timeout) {\n tunnelRequestOptions.timeout = timeout;\n }\n\n // compose a request string for the socket\n let postRequestStringContent: string = \"\";\n if (httpMethod === HttpMethod.POST) {\n const body = options?.body || \"\";\n postRequestStringContent =\n \"Content-Type: application/x-www-form-urlencoded\\r\\n\" +\n `Content-Length: ${body.length}\\r\\n` +\n `\\r\\n${body}`;\n }\n const outgoingRequestString = `${httpMethod.toUpperCase()} ${destinationUrl.href} HTTP/1.1\\r\\n` +\n `Host: ${destinationUrl.host}\\r\\n` +\n \"Connection: close\\r\\n\" +\n postRequestStringContent +\n \"\\r\\n\";\n\n return new Promise<NetworkResponse<T>>(((resolve, reject) => {\n const request = http.request(tunnelRequestOptions);\n\n if (tunnelRequestOptions.timeout) {\n request.on(\"timeout\", () => {\n request.destroy();\n reject(new Error(\"Request time out\"));\n });\n }\n\n request.end();\n\n // establish connection to the proxy\n request.on(\"connect\", (response, socket) => {\n const proxyStatusCode = response?.statusCode || ProxyStatus.SERVER_ERROR;\n if ((proxyStatusCode < ProxyStatus.SUCCESS_RANGE_START) || (proxyStatusCode > ProxyStatus.SUCCESS_RANGE_END)) {\n request.destroy();\n socket.destroy();\n reject(new Error(`Error connecting to proxy. Http status code: ${response.statusCode}. Http status message: ${response?.statusMessage || \"Unknown\"}`));\n }\n if (tunnelRequestOptions.timeout) {\n socket.setTimeout(tunnelRequestOptions.timeout);\n socket.on(\"timeout\", () => {\n request.destroy();\n socket.destroy();\n reject(new Error(\"Request time out\"));\n });\n }\n\n // make a request over an HTTP tunnel\n socket.write(outgoingRequestString);\n\n const data: Buffer[] = [];\n socket.on(\"data\", (chunk) => {\n data.push(chunk);\n });\n\n socket.on(\"end\", () => {\n // combine all received buffer streams into one buffer, and then into a string\n const dataString = Buffer.concat([...data]).toString();\n\n // separate each line into it's own entry in an arry\n const dataStringArray = dataString.split(\"\\r\\n\");\n // the first entry will contain the statusCode and statusMessage\n const httpStatusCode = parseInt(dataStringArray[0].split(\" \")[1]);\n // remove \"HTTP/1.1\" and the status code to get the status message\n const statusMessage = dataStringArray[0].split(\" \").slice(2).join(\" \");\n // the last entry will contain the body\n const body = dataStringArray[dataStringArray.length - 1];\n\n // everything in between the first and last entries are the headers\n const headersArray = dataStringArray.slice(1, dataStringArray.length - 2);\n\n // build an object out of all the headers\n const entries = new Map();\n headersArray.forEach((header) => {\n /**\n * the header might look like \"Content-Length: 1531\", but that is just a string\n * it needs to be converted to a key/value pair\n * split the string at the first instance of \":\"\n * there may be more than one \":\" if the value of the header is supposed to be a JSON object\n */\n const headerKeyValue = header.split(new RegExp(/:\\s(.*)/s));\n const headerKey = headerKeyValue[0];\n let headerValue = headerKeyValue[1];\n\n // check if the value of the header is supposed to be a JSON object\n try {\n const object = JSON.parse(headerValue);\n\n // if it is, then convert it from a string to a JSON object\n if (object && (typeof object === \"object\")) {\n headerValue = object;\n }\n } catch (e) {\n // otherwise, leave it as a string\n }\n\n entries.set(headerKey, headerValue);\n });\n const headers = Object.fromEntries(entries);\n\n const parsedHeaders = headers as Record<string, string>;\n const networkResponse = NetworkUtils.getNetworkResponse(\n parsedHeaders,\n parseBody(httpStatusCode, statusMessage, parsedHeaders, body) as T,\n httpStatusCode\n );\n\n if (((httpStatusCode < HttpStatus.SUCCESS_RANGE_START) || (httpStatusCode > HttpStatus.SUCCESS_RANGE_END)) &&\n // do not destroy the request for the device code flow\n networkResponse.body[\"error\"] !== Constants.AUTHORIZATION_PENDING) {\n request.destroy();\n }\n resolve(networkResponse);\n });\n\n socket.on(\"error\", (chunk) => {\n request.destroy();\n socket.destroy();\n reject(new Error(chunk.toString()));\n });\n });\n\n request.on(\"error\", (chunk) => {\n request.destroy();\n reject(new Error(chunk.toString()));\n });\n }));\n};\n\nconst networkRequestViaHttps = <T>(\n url: string,\n httpMethod: string,\n options?: NetworkRequestOptions,\n timeout?: number,\n): Promise<NetworkResponse<T>> => {\n const isPostRequest = httpMethod === HttpMethod.POST;\n const body: string = options?.body || \"\";\n\n const emptyHeaders: Record<string, string> = {};\n const customOptions: https.RequestOptions = {\n method: httpMethod,\n headers: options?.headers || emptyHeaders,\n };\n\n if (timeout) {\n customOptions.timeout = timeout;\n }\n\n if (isPostRequest) {\n // needed for post request to work\n customOptions.headers = {\n ...customOptions.headers,\n \"Content-Length\": body.length,\n };\n }\n\n return new Promise<NetworkResponse<T>>((resolve, reject) => {\n const request = https.request(url, customOptions);\n\n if (timeout) {\n request.on(\"timeout\", () => {\n request.destroy();\n reject(new Error(\"Request time out\"));\n });\n }\n\n if (isPostRequest) {\n request.write(body);\n }\n\n request.end();\n\n request.on(\"response\", (response) => {\n const headers = response.headers;\n const statusCode = response.statusCode as number;\n const statusMessage = response.statusMessage;\n\n const data: Buffer[] = [];\n response.on(\"data\", (chunk) => {\n data.push(chunk);\n });\n\n response.on(\"end\", () => {\n // combine all received buffer streams into one buffer, and then into a string\n const body = Buffer.concat([...data]).toString();\n\n const parsedHeaders = headers as Record<string, string>;\n const networkResponse = NetworkUtils.getNetworkResponse(\n parsedHeaders,\n parseBody(statusCode, statusMessage, parsedHeaders, body) as T,\n statusCode\n );\n\n if (((statusCode < HttpStatus.SUCCESS_RANGE_START) || (statusCode > HttpStatus.SUCCESS_RANGE_END)) &&\n // do not destroy the request for the device code flow\n networkResponse.body[\"error\"] !== Constants.AUTHORIZATION_PENDING) {\n request.destroy();\n }\n resolve(networkResponse);\n });\n });\n\n request.on(\"error\", (chunk) => {\n request.destroy();\n reject(new Error(chunk.toString()));\n });\n });\n};\n\n/**\n * Check if extra parsing is needed on the repsonse from the server\n * @param statusCode {number} the status code of the response from the server\n * @param statusMessage {string | undefined} the status message of the response from the server\n * @param headers {Record<string, string>} the headers of the response from the server\n * @param body {string} the body from the response of the server\n * @returns {Object} JSON parsed body or error object\n */\nconst parseBody = (statusCode: number, statusMessage: string | undefined, headers: Record<string, string>, body: string) => {\n /*\n * Informational responses (100 – 199)\n * Successful responses (200 – 299)\n * Redirection messages (300 – 399)\n * Client error responses (400 – 499)\n * Server error responses (500 – 599)\n */\n \n let parsedBody;\n try {\n parsedBody = JSON.parse(body);\n } catch (error) {\n let errorType;\n let errorDescriptionHelper;\n if ((statusCode >= HttpStatus.CLIENT_ERROR_RANGE_START) && (statusCode <= HttpStatus.CLIENT_ERROR_RANGE_END)) {\n errorType = \"client_error\";\n errorDescriptionHelper = \"A client\";\n } else if ((statusCode >= HttpStatus.SERVER_ERROR_RANGE_START) && (statusCode <= HttpStatus.SERVER_ERROR_RANGE_END)) {\n errorType = \"server_error\";\n errorDescriptionHelper = \"A server\";\n } else {\n errorType = \"unknown_error\";\n errorDescriptionHelper = \"An unknown\";\n }\n\n parsedBody = {\n error: errorType,\n error_description: `${errorDescriptionHelper} error occured.\\nHttp status code: ${statusCode}\\nHttp status message: ${statusMessage || \"Unknown\"}\\nHeaders: ${JSON.stringify(headers)}`\n };\n }\n\n return parsedBody;\n};\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n LoggerOptions,\n INetworkModule,\n LogLevel,\n ProtocolMode,\n ICachePlugin,\n Constants,\n AzureCloudInstance,\n AzureCloudOptions,\n ApplicationTelemetry\n} from \"@azure/msal-common\";\nimport { HttpClient } from \"../network/HttpClient\";\n\n/**\n * - clientId - Client id of the application.\n * - authority - Url of the authority. If no value is set, defaults to https://login.microsoftonline.com/common.\n * - knownAuthorities - Needed for Azure B2C and ADFS. All authorities that will be used in the client application. Only the host of the authority should be passed in.\n * - clientSecret - Secret string that the application uses when requesting a token. Only used in confidential client applications. Can be created in the Azure app registration portal.\n * - clientAssertion - Assertion string that the application uses when requesting a token. Only used in confidential client applications. Assertion should be of type urn:ietf:params:oauth:client-assertion-type:jwt-bearer.\n * - clientCertificate - Certificate that the application uses when requesting a token. Only used in confidential client applications. Requires hex encoded X.509 SHA-1 thumbprint of the certificiate, and the PEM encoded private key (string should contain -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- )\n * - protocolMode - Enum that represents the protocol that msal follows. Used for configuring proper endpoints.\n * - skipAuthorityMetadataCache - A flag to choose whether to use or not use the local metadata cache during authority initialization. Defaults to false.\n * @public\n */\nexport type NodeAuthOptions = {\n clientId: string;\n authority?: string;\n clientSecret?: string;\n clientAssertion?: string;\n clientCertificate?: {\n thumbprint: string,\n privateKey: string,\n x5c?: string\n };\n knownAuthorities?: Array<string>;\n cloudDiscoveryMetadata?: string;\n authorityMetadata?: string;\n clientCapabilities?: Array<string>;\n protocolMode?: ProtocolMode;\n azureCloudOptions?: AzureCloudOptions;\n skipAuthorityMetadataCache?: boolean;\n};\n\n/**\n * Use this to configure the below cache configuration options:\n *\n * - cachePlugin - Plugin for reading and writing token cache to disk.\n * @public\n */\nexport type CacheOptions = {\n cachePlugin?: ICachePlugin;\n};\n\n/**\n * Type for configuring logger and http client options\n *\n * - logger - Used to initialize the Logger object; TODO: Expand on logger details or link to the documentation on logger\n * - networkClient - Http client used for all http get and post calls. Defaults to using MSAL's default http client.\n * @public\n */\nexport type NodeSystemOptions = {\n loggerOptions?: LoggerOptions;\n networkClient?: INetworkModule;\n proxyUrl?: string;\n};\n\nexport type NodeTelemetryOptions = {\n application?: ApplicationTelemetry;\n};\n\n/**\n * Use the configuration object to configure MSAL and initialize the client application object\n *\n * - auth: this is where you configure auth elements like clientID, authority used for authenticating against the Microsoft Identity Platform\n * - cache: this is where you configure cache location\n * - system: this is where you can configure the network client, logger\n * @public\n */\nexport type Configuration = {\n auth: NodeAuthOptions;\n cache?: CacheOptions;\n system?: NodeSystemOptions;\n telemetry?: NodeTelemetryOptions;\n};\n\nconst DEFAULT_AUTH_OPTIONS: Required<NodeAuthOptions> = {\n clientId: Constants.EMPTY_STRING,\n authority: Constants.DEFAULT_AUTHORITY,\n clientSecret: Constants.EMPTY_STRING,\n clientAssertion: Constants.EMPTY_STRING,\n clientCertificate: {\n thumbprint: Constants.EMPTY_STRING,\n privateKey: Constants.EMPTY_STRING,\n x5c: Constants.EMPTY_STRING\n },\n knownAuthorities: [],\n cloudDiscoveryMetadata: Constants.EMPTY_STRING,\n authorityMetadata: Constants.EMPTY_STRING,\n clientCapabilities: [],\n protocolMode: ProtocolMode.AAD,\n azureCloudOptions: {\n azureCloudInstance: AzureCloudInstance.None,\n tenant: Constants.EMPTY_STRING\n },\n skipAuthorityMetadataCache: false,\n};\n\nconst DEFAULT_CACHE_OPTIONS: CacheOptions = {};\n\nconst DEFAULT_LOGGER_OPTIONS: LoggerOptions = {\n loggerCallback: (): void => {\n // allow users to not set logger call back\n },\n piiLoggingEnabled: false,\n logLevel: LogLevel.Info,\n};\n\nconst DEFAULT_SYSTEM_OPTIONS: Required<NodeSystemOptions> = {\n loggerOptions: DEFAULT_LOGGER_OPTIONS,\n networkClient: new HttpClient(),\n proxyUrl: Constants.EMPTY_STRING,\n};\n\nconst DEFAULT_TELEMETRY_OPTIONS: Required<NodeTelemetryOptions> = {\n application: {\n appName: Constants.EMPTY_STRING,\n appVersion: Constants.EMPTY_STRING\n }\n};\n\nexport type NodeConfiguration = {\n auth: Required<NodeAuthOptions>;\n cache: CacheOptions;\n system: Required<NodeSystemOptions>;\n telemetry: Required<NodeTelemetryOptions>;\n};\n\n/**\n * Sets the default options when not explicitly configured from app developer\n *\n * @param auth - Authentication options\n * @param cache - Cache options\n * @param system - System options\n * @param telemetry - Telemetry options\n *\n * @returns Configuration\n * @public\n */\nexport function buildAppConfiguration({\n auth,\n cache,\n system,\n telemetry\n}: Configuration): NodeConfiguration {\n\n return {\n auth: { ...DEFAULT_AUTH_OPTIONS, ...auth },\n cache: { ...DEFAULT_CACHE_OPTIONS, ...cache },\n system: { ...DEFAULT_SYSTEM_OPTIONS, ...system },\n telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry }\n };\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IGuidGenerator } from \"@azure/msal-common\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nexport class GuidGenerator implements IGuidGenerator {\n /**\n *\n * RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers.\n * uuidv4 generates guids from cryprtographically-string random\n */\n generateGuid(): string {\n return uuidv4();\n }\n\n /**\n * verifies if a string is GUID\n * @param guid\n */\n isGuid(guid: string): boolean {\n const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return regexGuid.test(guid);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants } from \"@azure/msal-common\";\n\nexport class EncodingUtils {\n /**\n * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.\n * 'base64': Base64 encoding.\n *\n * @param str text\n */\n static base64Encode(str: string, encoding?: BufferEncoding): string {\n return Buffer.from(str, encoding).toString(\"base64\");\n }\n\n /**\n * encode a URL\n * @param str\n */\n static base64EncodeUrl(str: string, encoding?: BufferEncoding): string {\n return EncodingUtils.base64Encode(str, encoding)\n .replace(/=/g, Constants.EMPTY_STRING)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\");\n }\n\n /**\n * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.\n * 'base64': Base64 encoding.\n *\n * @param base64Str Base64 encoded text\n */\n static base64Decode(base64Str: string): string {\n return Buffer.from(base64Str, \"base64\").toString(\"utf8\");\n }\n\n /**\n * @param base64Str Base64 encoded Url\n */\n static base64DecodeUrl(base64Str: string): string {\n let str = base64Str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (str.length % 4) {\n str += \"=\";\n }\n return EncodingUtils.base64Decode(str);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Hash } from \"../utils/Constants\";\nimport crypto from \"crypto\";\n\nexport class HashUtils {\n /**\n * generate 'SHA256' hash\n * @param buffer\n */\n sha256(buffer: string): Buffer {\n return crypto\n .createHash(Hash.SHA256)\n .update(buffer)\n .digest();\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants, PkceCodes } from \"@azure/msal-common\";\nimport { CharSet, RANDOM_OCTET_SIZE } from \"../utils/Constants\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\nimport { HashUtils } from \"./HashUtils\";\nimport crypto from \"crypto\";\n\n/**\n * https://tools.ietf.org/html/rfc7636#page-8\n */\nexport class PkceGenerator {\n private hashUtils: HashUtils;\n\n constructor() {\n this.hashUtils = new HashUtils();\n }\n /**\n * generates the codeVerfier and the challenge from the codeVerfier\n * reference: https://tools.ietf.org/html/rfc7636#section-4.1 and https://tools.ietf.org/html/rfc7636#section-4.2\n */\n async generatePkceCodes(): Promise<PkceCodes> {\n const verifier = this.generateCodeVerifier();\n const challenge = this.generateCodeChallengeFromVerifier(verifier);\n return { verifier, challenge };\n }\n\n /**\n * generates the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.1\n */\n private generateCodeVerifier(): string {\n const charArr = [];\n const maxNumber = 256 - (256 % CharSet.CV_CHARSET.length);\n while (charArr.length <= RANDOM_OCTET_SIZE) {\n const byte = crypto.randomBytes(1)[0];\n if (byte >= maxNumber) {\n /* \n * Ignore this number to maintain randomness.\n * Including it would result in an unequal distribution of characters after doing the modulo\n */\n continue;\n }\n const index = byte % CharSet.CV_CHARSET.length;\n charArr.push(CharSet.CV_CHARSET[index]);\n }\n const verifier: string = charArr.join(Constants.EMPTY_STRING);\n return EncodingUtils.base64EncodeUrl(verifier);\n }\n\n /**\n * generate the challenge from the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.2\n * @param codeVerifier\n */\n private generateCodeChallengeFromVerifier(codeVerifier: string): string {\n return EncodingUtils.base64EncodeUrl(\n this.hashUtils.sha256(codeVerifier).toString(\"base64\"), \n \"base64\" \n );\n }\n\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ICrypto, PkceCodes } from \"@azure/msal-common\";\nimport { GuidGenerator } from \"./GuidGenerator\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\nimport { PkceGenerator } from \"./PkceGenerator\";\nimport { HashUtils } from \"./HashUtils\";\n\n/**\n * This class implements MSAL node's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and\n * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).\n * @public\n */\nexport class CryptoProvider implements ICrypto {\n private pkceGenerator: PkceGenerator;\n private guidGenerator: GuidGenerator;\n private hashUtils: HashUtils;\n\n constructor() {\n // Browser crypto needs to be validated first before any other classes can be set.\n this.pkceGenerator = new PkceGenerator();\n this.guidGenerator = new GuidGenerator();\n this.hashUtils = new HashUtils();\n }\n\n /**\n * Creates a new random GUID - used to populate state and nonce.\n * @returns string (GUID)\n */\n createNewGuid(): string {\n return this.guidGenerator.generateGuid();\n }\n\n /**\n * Encodes input string to base64.\n * @param input - string to be encoded\n */\n base64Encode(input: string): string {\n return EncodingUtils.base64Encode(input);\n }\n\n /**\n * Decodes input string from base64.\n * @param input - string to be decoded\n */\n base64Decode(input: string): string {\n return EncodingUtils.base64Decode(input);\n }\n\n /**\n * Generates PKCE codes used in Authorization Code Flow.\n */\n generatePkceCodes(): Promise<PkceCodes> {\n return this.pkceGenerator.generatePkceCodes();\n }\n\n /**\n * Generates a keypair, stores it and returns a thumbprint - not yet implemented for node\n */\n getPublicKeyThumbprint(): Promise<string> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Removes cryptographic keypair from key store matching the keyId passed in\n * @param kid \n */\n removeTokenBindingKey(): Promise<boolean> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Removes all cryptographic keys from Keystore\n */\n clearKeystore(): Promise<boolean> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node\n */\n signJwt(): Promise<string> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Returns the SHA-256 hash of an input string\n */\n async hashString(plainText: string): Promise<string> {\n return EncodingUtils.base64EncodeUrl(\n this.hashUtils.sha256(plainText).toString(\"base64\"), \n \"base64\" \n );\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { StringUtils, AccountCache, IdTokenCache, AccessTokenCache, RefreshTokenCache, AppMetadataCache, AccountEntity, IdTokenEntity, AccessTokenEntity, RefreshTokenEntity, AppMetadataEntity, CacheManager } from \"@azure/msal-common\";\nimport { JsonCache, InMemoryCache, SerializedAccountEntity, SerializedIdTokenEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedAppMetadataEntity } from \"./SerializerTypes\";\n\n/**\n * This class deserializes cache entities read from the file into in memory object types defined internally\n */\nexport class Deserializer {\n /**\n * Parse the JSON blob in memory and deserialize the content\n * @param cachedJson\n */\n static deserializeJSONBlob(jsonFile: string): JsonCache {\n const deserializedCache = StringUtils.isEmpty(jsonFile)\n ? {}\n : JSON.parse(jsonFile);\n return deserializedCache;\n }\n\n /**\n * Deserializes accounts to AccountEntity objects\n * @param accounts\n */\n static deserializeAccounts(accounts: Record<string, SerializedAccountEntity>): AccountCache {\n const accountObjects: AccountCache = {};\n if (accounts) {\n Object.keys(accounts).map(function (key) {\n const serializedAcc = accounts[key];\n const mappedAcc = {\n homeAccountId: serializedAcc.home_account_id,\n environment: serializedAcc.environment,\n realm: serializedAcc.realm,\n localAccountId: serializedAcc.local_account_id,\n username: serializedAcc.username,\n authorityType: serializedAcc.authority_type,\n name: serializedAcc.name,\n clientInfo: serializedAcc.client_info,\n lastModificationTime: serializedAcc.last_modification_time,\n lastModificationApp: serializedAcc.last_modification_app,\n };\n const account: AccountEntity = new AccountEntity();\n CacheManager.toObject(account, mappedAcc);\n accountObjects[key] = account;\n });\n }\n\n return accountObjects;\n }\n\n /**\n * Deserializes id tokens to IdTokenEntity objects\n * @param idTokens\n */\n static deserializeIdTokens(idTokens: Record<string, SerializedIdTokenEntity>): IdTokenCache {\n const idObjects: IdTokenCache = {};\n if (idTokens) {\n Object.keys(idTokens).map(function (key) {\n const serializedIdT = idTokens[key];\n const mappedIdT = {\n homeAccountId: serializedIdT.home_account_id,\n environment: serializedIdT.environment,\n credentialType: serializedIdT.credential_type,\n clientId: serializedIdT.client_id,\n secret: serializedIdT.secret,\n realm: serializedIdT.realm,\n };\n const idToken: IdTokenEntity = new IdTokenEntity();\n CacheManager.toObject(idToken, mappedIdT);\n idObjects[key] = idToken;\n });\n }\n return idObjects;\n }\n\n /**\n * Deserializes access tokens to AccessTokenEntity objects\n * @param accessTokens\n */\n static deserializeAccessTokens(accessTokens: Record<string, SerializedAccessTokenEntity>): AccessTokenCache {\n const atObjects: AccessTokenCache = {};\n if (accessTokens) {\n Object.keys(accessTokens).map(function (key) {\n const serializedAT = accessTokens[key];\n const mappedAT = {\n homeAccountId: serializedAT.home_account_id,\n environment: serializedAT.environment,\n credentialType: serializedAT.credential_type,\n clientId: serializedAT.client_id,\n secret: serializedAT.secret,\n realm: serializedAT.realm,\n target: serializedAT.target,\n cachedAt: serializedAT.cached_at,\n expiresOn: serializedAT.expires_on,\n extendedExpiresOn: serializedAT.extended_expires_on,\n refreshOn: serializedAT.refresh_on,\n keyId: serializedAT.key_id,\n tokenType: serializedAT.token_type,\n requestedClaims: serializedAT.requestedClaims,\n requestedClaimsHash: serializedAT.requestedClaimsHash,\n userAssertionHash: serializedAT.userAssertionHash,\n };\n const accessToken: AccessTokenEntity = new AccessTokenEntity();\n CacheManager.toObject(accessToken, mappedAT);\n atObjects[key] = accessToken;\n });\n }\n\n return atObjects;\n }\n\n /**\n * Deserializes refresh tokens to RefreshTokenEntity objects\n * @param refreshTokens\n */\n static deserializeRefreshTokens(refreshTokens: Record<string, SerializedRefreshTokenEntity>): RefreshTokenCache {\n const rtObjects: RefreshTokenCache = {};\n if (refreshTokens) {\n Object.keys(refreshTokens).map(function (key) {\n const serializedRT = refreshTokens[key];\n const mappedRT = {\n homeAccountId: serializedRT.home_account_id,\n environment: serializedRT.environment,\n credentialType: serializedRT.credential_type,\n clientId: serializedRT.client_id,\n secret: serializedRT.secret,\n familyId: serializedRT.family_id,\n target: serializedRT.target,\n realm: serializedRT.realm,\n };\n const refreshToken: RefreshTokenEntity = new RefreshTokenEntity();\n CacheManager.toObject(refreshToken, mappedRT);\n rtObjects[key] = refreshToken;\n });\n }\n\n return rtObjects;\n }\n\n /**\n * Deserializes appMetadata to AppMetaData objects\n * @param appMetadata\n */\n static deserializeAppMetadata(appMetadata: Record<string, SerializedAppMetadataEntity>): AppMetadataCache {\n const appMetadataObjects: AppMetadataCache = {};\n if (appMetadata) {\n Object.keys(appMetadata).map(function (key) {\n const serializedAmdt = appMetadata[key];\n const mappedAmd = {\n clientId: serializedAmdt.client_id,\n environment: serializedAmdt.environment,\n familyId: serializedAmdt.family_id,\n };\n const amd: AppMetadataEntity = new AppMetadataEntity();\n CacheManager.toObject(amd, mappedAmd);\n appMetadataObjects[key] = amd;\n });\n }\n\n return appMetadataObjects;\n }\n\n /**\n * Deserialize an inMemory Cache\n * @param jsonCache\n */\n static deserializeAllCache(jsonCache: JsonCache): InMemoryCache {\n return {\n accounts: jsonCache.Account\n ? this.deserializeAccounts(jsonCache.Account)\n : {},\n idTokens: jsonCache.IdToken\n ? this.deserializeIdTokens(jsonCache.IdToken)\n : {},\n accessTokens: jsonCache.AccessToken\n ? this.deserializeAccessTokens(jsonCache.AccessToken)\n : {},\n refreshTokens: jsonCache.RefreshToken\n ? this.deserializeRefreshTokens(jsonCache.RefreshToken)\n : {},\n appMetadata: jsonCache.AppMetadata\n ? this.deserializeAppMetadata(jsonCache.AppMetadata)\n : {},\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AccountCache, IdTokenCache, AccessTokenCache, RefreshTokenCache, AppMetadataCache } from \"@azure/msal-common\";\nimport { InMemoryCache, JsonCache, SerializedAccountEntity, SerializedIdTokenEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedAppMetadataEntity } from \"./SerializerTypes\";\n\nexport class Serializer {\n /**\n * serialize the JSON blob\n * @param data\n */\n static serializeJSONBlob(data: JsonCache): string {\n return JSON.stringify(data);\n }\n\n /**\n * Serialize Accounts\n * @param accCache\n */\n static serializeAccounts(accCache: AccountCache): Record<string, SerializedAccountEntity> {\n const accounts: Record<string, SerializedAccountEntity> = {};\n Object.keys(accCache).map(function (key) {\n const accountEntity = accCache[key];\n accounts[key] = {\n home_account_id: accountEntity.homeAccountId,\n environment: accountEntity.environment,\n realm: accountEntity.realm,\n local_account_id: accountEntity.localAccountId,\n username: accountEntity.username,\n authority_type: accountEntity.authorityType,\n name: accountEntity.name,\n client_info: accountEntity.clientInfo,\n last_modification_time: accountEntity.lastModificationTime,\n last_modification_app: accountEntity.lastModificationApp,\n };\n });\n\n return accounts;\n }\n\n /**\n * Serialize IdTokens\n * @param idTCache\n */\n static serializeIdTokens(idTCache: IdTokenCache): Record<string, SerializedIdTokenEntity> {\n const idTokens: Record<string, SerializedIdTokenEntity> = {};\n Object.keys(idTCache).map(function (key) {\n const idTEntity = idTCache[key];\n idTokens[key] = {\n home_account_id: idTEntity.homeAccountId,\n environment: idTEntity.environment,\n credential_type: idTEntity.credentialType,\n client_id: idTEntity.clientId,\n secret: idTEntity.secret,\n realm: idTEntity.realm,\n };\n });\n\n return idTokens;\n }\n\n /**\n * Serializes AccessTokens\n * @param atCache\n */\n static serializeAccessTokens(atCache: AccessTokenCache): Record<string, SerializedAccessTokenEntity> {\n const accessTokens: Record<string, SerializedAccessTokenEntity> = {};\n Object.keys(atCache).map(function (key) {\n const atEntity = atCache[key];\n accessTokens[key] = {\n home_account_id: atEntity.homeAccountId,\n environment: atEntity.environment,\n credential_type: atEntity.credentialType,\n client_id: atEntity.clientId,\n secret: atEntity.secret,\n realm: atEntity.realm,\n target: atEntity.target,\n cached_at: atEntity.cachedAt,\n expires_on: atEntity.expiresOn,\n extended_expires_on: atEntity.extendedExpiresOn,\n refresh_on: atEntity.refreshOn,\n key_id: atEntity.keyId,\n token_type: atEntity.tokenType,\n requestedClaims: atEntity.requestedClaims,\n requestedClaimsHash: atEntity.requestedClaimsHash,\n userAssertionHash: atEntity.userAssertionHash\n };\n });\n\n return accessTokens;\n }\n\n /**\n * Serialize refreshTokens\n * @param rtCache\n */\n static serializeRefreshTokens(rtCache: RefreshTokenCache): Record<string, SerializedRefreshTokenEntity> {\n const refreshTokens: Record<string, SerializedRefreshTokenEntity> = {};\n Object.keys(rtCache).map(function (key) {\n const rtEntity = rtCache[key];\n refreshTokens[key] = {\n home_account_id: rtEntity.homeAccountId,\n environment: rtEntity.environment,\n credential_type: rtEntity.credentialType,\n client_id: rtEntity.clientId,\n secret: rtEntity.secret,\n family_id: rtEntity.familyId,\n target: rtEntity.target,\n realm: rtEntity.realm\n };\n });\n\n return refreshTokens;\n }\n\n /**\n * Serialize amdtCache\n * @param amdtCache\n */\n static serializeAppMetadata(amdtCache: AppMetadataCache): Record<string, SerializedAppMetadataEntity> {\n const appMetadata: Record<string, SerializedAppMetadataEntity> = {};\n Object.keys(amdtCache).map(function (key) {\n const amdtEntity = amdtCache[key];\n appMetadata[key] = {\n client_id: amdtEntity.clientId,\n environment: amdtEntity.environment,\n family_id: amdtEntity.familyId,\n };\n });\n\n return appMetadata;\n }\n\n /**\n * Serialize the cache\n * @param jsonContent\n */\n static serializeAllCache(inMemCache: InMemoryCache): JsonCache {\n return {\n Account: this.serializeAccounts(inMemCache.accounts),\n IdToken: this.serializeIdTokens(inMemCache.idTokens),\n AccessToken: this.serializeAccessTokens(inMemCache.accessTokens),\n RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens),\n AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata),\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AccountEntity,\n IdTokenEntity,\n AccessTokenEntity,\n RefreshTokenEntity,\n AppMetadataEntity,\n ServerTelemetryEntity,\n ThrottlingEntity,\n CacheManager,\n Logger,\n ValidCacheType,\n ICrypto,\n AuthorityMetadataEntity,\n ValidCredentialType\n} from \"@azure/msal-common\";\nimport { Deserializer } from \"./serializer/Deserializer\";\nimport { Serializer } from \"./serializer/Serializer\";\nimport { InMemoryCache, JsonCache, CacheKVStore } from \"./serializer/SerializerTypes\";\n\n/**\n * This class implements Storage for node, reading cache from user specified storage location or an extension library\n * @public\n */\nexport class NodeStorage extends CacheManager {\n // Cache configuration, either set by user or default values.\n private logger: Logger;\n private cache: CacheKVStore = {};\n private changeEmitters: Array<Function> = [];\n\n constructor(logger: Logger, clientId: string, cryptoImpl: ICrypto) {\n super(clientId, cryptoImpl);\n this.logger = logger;\n }\n\n /**\n * Queue up callbacks\n * @param func - a callback function for cache change indication\n */\n registerChangeEmitter(func: () => void): void {\n this.changeEmitters.push(func);\n }\n\n /**\n * Invoke the callback when cache changes\n */\n emitChange(): void {\n this.changeEmitters.forEach(func => func.call(null));\n }\n\n /**\n * Converts cacheKVStore to InMemoryCache\n * @param cache - key value store\n */\n cacheToInMemoryCache(cache: CacheKVStore): InMemoryCache {\n const inMemoryCache: InMemoryCache = {\n accounts: {},\n idTokens: {},\n accessTokens: {},\n refreshTokens: {},\n appMetadata: {},\n };\n\n for (const key in cache) {\n if (cache[key as string] instanceof AccountEntity) {\n inMemoryCache.accounts[key] = cache[key] as AccountEntity;\n } else if (cache[key] instanceof IdTokenEntity) {\n inMemoryCache.idTokens[key] = cache[key] as IdTokenEntity;\n } else if (cache[key] instanceof AccessTokenEntity) {\n inMemoryCache.accessTokens[key] = cache[key] as AccessTokenEntity;\n } else if (cache[key] instanceof RefreshTokenEntity) {\n inMemoryCache.refreshTokens[key] = cache[key] as RefreshTokenEntity;\n } else if (cache[key] instanceof AppMetadataEntity) {\n inMemoryCache.appMetadata[key] = cache[key] as AppMetadataEntity;\n } else {\n continue;\n }\n }\n\n return inMemoryCache;\n }\n\n /**\n * converts inMemoryCache to CacheKVStore\n * @param inMemoryCache - kvstore map for inmemory\n */\n inMemoryCacheToCache(inMemoryCache: InMemoryCache): CacheKVStore {\n\n // convert in memory cache to a flat Key-Value map\n let cache = this.getCache();\n\n cache = {\n ...cache,\n ...inMemoryCache.accounts,\n ...inMemoryCache.idTokens,\n ...inMemoryCache.accessTokens,\n ...inMemoryCache.refreshTokens,\n ...inMemoryCache.appMetadata\n };\n\n // convert in memory cache to a flat Key-Value map\n return cache;\n }\n\n /**\n * gets the current in memory cache for the client\n */\n getInMemoryCache(): InMemoryCache {\n this.logger.trace(\"Getting in-memory cache\");\n\n // convert the cache key value store to inMemoryCache\n const inMemoryCache = this.cacheToInMemoryCache(this.getCache());\n return inMemoryCache;\n }\n\n /**\n * sets the current in memory cache for the client\n * @param inMemoryCache - key value map in memory\n */\n setInMemoryCache(inMemoryCache: InMemoryCache): void{\n this.logger.trace(\"Setting in-memory cache\");\n\n // convert and append the inMemoryCache to cacheKVStore\n const cache = this.inMemoryCacheToCache(inMemoryCache);\n this.setCache(cache);\n\n this.emitChange();\n }\n\n /**\n * get the current cache key-value store\n */\n getCache(): CacheKVStore {\n this.logger.trace(\"Getting cache key-value store\");\n return this.cache;\n }\n\n /**\n * sets the current cache (key value store)\n * @param cacheMap - key value map\n */\n setCache(cache: CacheKVStore): void {\n this.logger.trace(\"Setting cache key value store\");\n this.cache = cache;\n\n // mark change in cache\n this.emitChange();\n }\n\n /**\n * Gets cache item with given key.\n * @param key - lookup key for the cache entry\n */\n getItem(key: string): ValidCacheType {\n this.logger.tracePii(`Item key: ${key}`);\n\n // read cache\n const cache = this.getCache();\n return cache[key];\n }\n\n /**\n * Gets cache item with given key-value\n * @param key - lookup key for the cache entry\n * @param value - value of the cache entry\n */\n setItem(key: string, value: ValidCacheType): void {\n this.logger.tracePii(`Item key: ${key}`);\n\n // read cache\n const cache = this.getCache();\n cache[key] = value;\n\n // write to cache\n this.setCache(cache);\n }\n\n /**\n * fetch the account entity\n * @param accountKey - lookup key to fetch cache type AccountEntity\n */\n getAccount(accountKey: string): AccountEntity | null {\n const account = this.getItem(accountKey) as AccountEntity;\n if (AccountEntity.isAccountEntity(account)) {\n return account;\n }\n return null;\n }\n\n /**\n * set account entity\n * @param account - cache value to be set of type AccountEntity\n */\n setAccount(account: AccountEntity): void {\n const accountKey = account.generateAccountKey();\n this.setItem(accountKey, account);\n }\n\n /**\n * fetch the idToken credential\n * @param idTokenKey - lookup key to fetch cache type IdTokenEntity\n */\n getIdTokenCredential(idTokenKey: string): IdTokenEntity | null {\n const idToken = this.getItem(idTokenKey) as IdTokenEntity;\n if (IdTokenEntity.isIdTokenEntity(idToken)) {\n return idToken;\n }\n return null;\n }\n\n /**\n * set idToken credential\n * @param idToken - cache value to be set of type IdTokenEntity\n */\n setIdTokenCredential(idToken: IdTokenEntity): void {\n const idTokenKey = idToken.generateCredentialKey();\n this.setItem(idTokenKey, idToken);\n }\n\n /**\n * fetch the accessToken credential\n * @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity\n */\n getAccessTokenCredential(accessTokenKey: string): AccessTokenEntity | null {\n const accessToken = this.getItem(accessTokenKey) as AccessTokenEntity;\n if (AccessTokenEntity.isAccessTokenEntity(accessToken)) {\n return accessToken;\n }\n return null;\n }\n\n /**\n * set accessToken credential\n * @param accessToken - cache value to be set of type AccessTokenEntity\n */\n setAccessTokenCredential(accessToken: AccessTokenEntity): void {\n const accessTokenKey = accessToken.generateCredentialKey();\n this.setItem(accessTokenKey, accessToken);\n }\n\n /**\n * fetch the refreshToken credential\n * @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity\n */\n getRefreshTokenCredential(refreshTokenKey: string): RefreshTokenEntity | null {\n const refreshToken = this.getItem(refreshTokenKey) as RefreshTokenEntity;\n if (RefreshTokenEntity.isRefreshTokenEntity(refreshToken)) {\n return refreshToken as RefreshTokenEntity;\n }\n return null;\n }\n\n /**\n * set refreshToken credential\n * @param refreshToken - cache value to be set of type RefreshTokenEntity\n */\n setRefreshTokenCredential(refreshToken: RefreshTokenEntity): void {\n const refreshTokenKey = refreshToken.generateCredentialKey();\n this.setItem(refreshTokenKey, refreshToken);\n }\n\n /**\n * fetch appMetadata entity from the platform cache\n * @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity\n */\n getAppMetadata(appMetadataKey: string): AppMetadataEntity | null {\n const appMetadata: AppMetadataEntity = this.getItem(appMetadataKey) as AppMetadataEntity;\n if (AppMetadataEntity.isAppMetadataEntity(appMetadataKey, appMetadata)) {\n return appMetadata;\n }\n return null;\n }\n\n /**\n * set appMetadata entity to the platform cache\n * @param appMetadata - cache value to be set of type AppMetadataEntity\n */\n setAppMetadata(appMetadata: AppMetadataEntity): void {\n const appMetadataKey = appMetadata.generateAppMetadataKey();\n this.setItem(appMetadataKey, appMetadata);\n }\n\n /**\n * fetch server telemetry entity from the platform cache\n * @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity\n */\n getServerTelemetry(serverTelemetrykey: string): ServerTelemetryEntity | null {\n const serverTelemetryEntity: ServerTelemetryEntity = this.getItem(serverTelemetrykey) as ServerTelemetryEntity;\n if (serverTelemetryEntity && ServerTelemetryEntity.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) {\n return serverTelemetryEntity;\n }\n return null;\n }\n\n /**\n * set server telemetry entity to the platform cache\n * @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity\n * @param serverTelemetry - cache value to be set of type ServerTelemetryEntity\n */\n setServerTelemetry(serverTelemetryKey: string, serverTelemetry: ServerTelemetryEntity): void {\n this.setItem(serverTelemetryKey, serverTelemetry);\n }\n\n /**\n * fetch authority metadata entity from the platform cache\n * @param key - lookup key to fetch cache type AuthorityMetadataEntity\n */\n getAuthorityMetadata(key: string): AuthorityMetadataEntity | null {\n const authorityMetadataEntity: AuthorityMetadataEntity = this.getItem(key) as AuthorityMetadataEntity;\n if (authorityMetadataEntity && AuthorityMetadataEntity.isAuthorityMetadataEntity(key, authorityMetadataEntity)) {\n return authorityMetadataEntity;\n }\n return null;\n }\n\n /**\n * Get all authority metadata keys\n */\n getAuthorityMetadataKeys(): Array<string> {\n return this.getKeys().filter((key) => {\n return this.isAuthorityMetadata(key);\n });\n }\n\n /**\n * set authority metadata entity to the platform cache\n * @param key - lookup key to fetch cache type AuthorityMetadataEntity\n * @param metadata - cache value to be set of type AuthorityMetadataEntity\n */\n setAuthorityMetadata(key: string, metadata: AuthorityMetadataEntity): void {\n this.setItem(key, metadata);\n }\n\n /**\n * fetch throttling entity from the platform cache\n * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity\n */\n getThrottlingCache(throttlingCacheKey: string): ThrottlingEntity | null {\n const throttlingCache: ThrottlingEntity = this.getItem(throttlingCacheKey) as ThrottlingEntity;\n if (throttlingCache && ThrottlingEntity.isThrottlingEntity(throttlingCacheKey, throttlingCache)) {\n return throttlingCache;\n }\n return null;\n }\n\n /**\n * set throttling entity to the platform cache\n * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity\n * @param throttlingCache - cache value to be set of type ThrottlingEntity\n */\n setThrottlingCache(throttlingCacheKey: string, throttlingCache: ThrottlingEntity): void {\n this.setItem(throttlingCacheKey, throttlingCache);\n }\n\n /**\n * Removes the cache item from memory with the given key.\n * @param key - lookup key to remove a cache entity\n * @param inMemory - key value map of the cache\n */\n removeItem(key: string): boolean {\n this.logger.tracePii(`Item key: ${key}`);\n\n // read inMemoryCache\n let result: boolean = false;\n const cache = this.getCache();\n\n if (!!cache[key]) {\n delete cache[key];\n result = true;\n }\n\n // write to the cache after removal\n if (result) {\n this.setCache(cache);\n this.emitChange();\n }\n return result;\n }\n\n /**\n * Checks whether key is in cache.\n * @param key - look up key for a cache entity\n */\n containsKey(key: string): boolean {\n return this.getKeys().includes(key);\n }\n\n /**\n * Gets all keys in window.\n */\n getKeys(): string[] {\n this.logger.trace(\"Retrieving all cache keys\");\n\n // read cache\n const cache = this.getCache();\n return [ ...Object.keys(cache)];\n }\n\n /**\n * Clears all cache entries created by MSAL (except tokens).\n */\n async clear(): Promise<void> {\n this.logger.trace(\"Clearing cache entries created by MSAL\");\n\n // read inMemoryCache\n const cacheKeys = this.getKeys();\n\n // delete each element\n cacheKeys.forEach(key => {\n this.removeItem(key);\n });\n this.emitChange();\n }\n\n /**\n * Initialize in memory cache from an exisiting cache vault\n * @param cache - blob formatted cache (JSON)\n */\n static generateInMemoryCache(cache: string): InMemoryCache {\n return Deserializer.deserializeAllCache(\n Deserializer.deserializeJSONBlob(cache)\n );\n }\n\n /**\n * retrieves the final JSON\n * @param inMemoryCache - itemised cache read from the JSON\n */\n static generateJsonCache(inMemoryCache: InMemoryCache): JsonCache {\n return Serializer.serializeAllCache(inMemoryCache);\n }\n\n /**\n * Updates a credential's cache key if the current cache key is outdated\n */\n updateCredentialCacheKey(currentCacheKey: string, credential: ValidCredentialType): string {\n const updatedCacheKey = credential.generateCredentialKey();\n\n if (currentCacheKey !== updatedCacheKey) {\n const cacheItem = this.getItem(currentCacheKey);\n if (cacheItem) {\n this.removeItem(currentCacheKey);\n this.setItem(updatedCacheKey, cacheItem);\n this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`);\n return updatedCacheKey;\n } else {\n this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`);\n }\n }\n\n return currentCacheKey;\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NodeStorage } from \"./NodeStorage\";\nimport { StringUtils, AccountEntity, AccountInfo, Logger, ISerializableTokenCache, ICachePlugin, TokenCacheContext } from \"@azure/msal-common\";\nimport { InMemoryCache, JsonCache, SerializedAccountEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedIdTokenEntity, SerializedAppMetadataEntity, CacheKVStore } from \"./serializer/SerializerTypes\";\nimport { Deserializer } from \"./serializer/Deserializer\";\nimport { Serializer } from \"./serializer/Serializer\";\nimport { ITokenCache } from \"./ITokenCache\";\n\nconst defaultSerializedCache: JsonCache = {\n Account: {},\n IdToken: {},\n AccessToken: {},\n RefreshToken: {},\n AppMetadata: {},\n};\n\n/**\n * In-memory token cache manager\n * @public\n */\nexport class TokenCache implements ISerializableTokenCache, ITokenCache {\n\n private storage: NodeStorage;\n private cacheHasChanged: boolean;\n private cacheSnapshot: string;\n private readonly persistence: ICachePlugin;\n private logger: Logger;\n\n constructor(storage: NodeStorage, logger: Logger, cachePlugin?: ICachePlugin) {\n this.cacheHasChanged = false;\n this.storage = storage;\n this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this));\n if (cachePlugin) {\n this.persistence = cachePlugin;\n }\n this.logger = logger;\n }\n\n /**\n * Set to true if cache state has changed since last time serialize or writeToPersistence was called\n */\n hasChanged(): boolean {\n return this.cacheHasChanged;\n }\n\n /**\n * Serializes in memory cache to JSON\n */\n serialize(): string {\n this.logger.trace(\"Serializing in-memory cache\");\n let finalState = Serializer.serializeAllCache(\n this.storage.getInMemoryCache() as InMemoryCache\n );\n\n // if cacheSnapshot not null or empty, merge\n if (!StringUtils.isEmpty(this.cacheSnapshot)) {\n this.logger.trace(\"Reading cache snapshot from disk\");\n finalState = this.mergeState(\n JSON.parse(this.cacheSnapshot),\n finalState\n );\n } else {\n this.logger.trace(\"No cache snapshot to merge\");\n }\n this.cacheHasChanged = false;\n\n return JSON.stringify(finalState);\n }\n\n /**\n * Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format\n * @param cache - blob formatted cache\n */\n deserialize(cache: string): void {\n this.logger.trace(\"Deserializing JSON to in-memory cache\");\n this.cacheSnapshot = cache;\n\n if (!StringUtils.isEmpty(this.cacheSnapshot)) {\n this.logger.trace(\"Reading cache snapshot from disk\");\n const deserializedCache = Deserializer.deserializeAllCache(\n this.overlayDefaults(JSON.parse(this.cacheSnapshot))\n );\n this.storage.setInMemoryCache(deserializedCache);\n } else {\n this.logger.trace(\"No cache snapshot to deserialize\");\n }\n }\n\n /**\n * Fetches the cache key-value map\n */\n getKVStore(): CacheKVStore {\n return this.storage.getCache();\n }\n\n /**\n * API that retrieves all accounts currently in cache to the user\n */\n async getAllAccounts(): Promise<AccountInfo[]> {\n\n this.logger.trace(\"getAllAccounts called\");\n let cacheContext;\n try {\n if (this.persistence) {\n cacheContext = new TokenCacheContext(this, false);\n await this.persistence.beforeCacheAccess(cacheContext);\n }\n return this.storage.getAllAccounts();\n } finally {\n if (this.persistence && cacheContext) {\n await this.persistence.afterCacheAccess(cacheContext);\n }\n }\n }\n\n /**\n * Returns the signed in account matching homeAccountId.\n * (the account object is created at the time of successful login)\n * or null when no matching account is found\n * @param homeAccountId - unique identifier for an account (uid.utid)\n */\n async getAccountByHomeId(homeAccountId: string): Promise<AccountInfo | null> {\n const allAccounts = await this.getAllAccounts();\n if (!StringUtils.isEmpty(homeAccountId) && allAccounts && allAccounts.length) {\n return allAccounts.filter(accountObj => accountObj.homeAccountId === homeAccountId)[0] || null;\n } else {\n return null;\n }\n }\n\n /**\n * Returns the signed in account matching localAccountId.\n * (the account object is created at the time of successful login)\n * or null when no matching account is found\n * @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated)\n */\n async getAccountByLocalId(localAccountId: string): Promise<AccountInfo | null> {\n const allAccounts = await this.getAllAccounts();\n if (!StringUtils.isEmpty(localAccountId) && allAccounts && allAccounts.length) {\n return allAccounts.filter(accountObj => accountObj.localAccountId === localAccountId)[0] || null;\n } else {\n return null;\n }\n }\n\n /**\n * API to remove a specific account and the relevant data from cache\n * @param account - AccountInfo passed by the user\n */\n async removeAccount(account: AccountInfo): Promise<void> {\n this.logger.trace(\"removeAccount called\");\n let cacheContext;\n try {\n if (this.persistence) {\n cacheContext = new TokenCacheContext(this, true);\n await this.persistence.beforeCacheAccess(cacheContext);\n }\n await this.storage.removeAccount(AccountEntity.generateAccountCacheKey(account));\n } finally {\n if (this.persistence && cacheContext) {\n await this.persistence.afterCacheAccess(cacheContext);\n }\n }\n }\n\n /**\n * Called when the cache has changed state.\n */\n private handleChangeEvent() {\n this.cacheHasChanged = true;\n }\n\n /**\n * Merge in memory cache with the cache snapshot.\n * @param oldState - cache before changes\n * @param currentState - current cache state in the library\n */\n private mergeState(oldState: JsonCache, currentState: JsonCache): JsonCache {\n this.logger.trace(\"Merging in-memory cache with cache snapshot\");\n const stateAfterRemoval = this.mergeRemovals(oldState, currentState);\n return this.mergeUpdates(stateAfterRemoval, currentState);\n }\n\n /**\n * Deep update of oldState based on newState values\n * @param oldState - cache before changes\n * @param newState - updated cache\n */\n private mergeUpdates(oldState: object, newState: object): JsonCache {\n Object.keys(newState).forEach((newKey: string) => {\n const newValue = newState[newKey];\n\n // if oldState does not contain value but newValue does, add it\n if (!oldState.hasOwnProperty(newKey)) {\n if (newValue !== null) {\n oldState[newKey] = newValue;\n }\n } else {\n // both oldState and newState contain the key, do deep update\n const newValueNotNull = newValue !== null;\n const newValueIsObject = typeof newValue === \"object\";\n const newValueIsNotArray = !Array.isArray(newValue);\n const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== \"undefined\" && oldState[newKey] !== null;\n\n if (newValueNotNull && newValueIsObject && newValueIsNotArray && oldStateNotUndefinedOrNull) {\n this.mergeUpdates(oldState[newKey], newValue);\n } else {\n oldState[newKey] = newValue;\n }\n }\n });\n\n return oldState as JsonCache;\n }\n\n /**\n * Removes entities in oldState that the were removed from newState. If there are any unknown values in root of\n * oldState that are not recognized, they are left untouched.\n * @param oldState - cache before changes\n * @param newState - updated cache\n */\n private mergeRemovals(oldState: JsonCache, newState: JsonCache): JsonCache {\n this.logger.trace(\"Remove updated entries in cache\");\n const accounts = oldState.Account ? this.mergeRemovalsDict<SerializedAccountEntity>(oldState.Account, newState.Account) : oldState.Account;\n const accessTokens = oldState.AccessToken ? this.mergeRemovalsDict<SerializedAccessTokenEntity>(oldState.AccessToken, newState.AccessToken) : oldState.AccessToken;\n const refreshTokens = oldState.RefreshToken ? this.mergeRemovalsDict<SerializedRefreshTokenEntity>(oldState.RefreshToken, newState.RefreshToken) : oldState.RefreshToken;\n const idTokens = oldState.IdToken ? this.mergeRemovalsDict<SerializedIdTokenEntity>(oldState.IdToken, newState.IdToken) : oldState.IdToken;\n const appMetadata = oldState.AppMetadata ? this.mergeRemovalsDict<SerializedAppMetadataEntity>(oldState.AppMetadata, newState.AppMetadata) : oldState.AppMetadata;\n\n return {\n ...oldState,\n Account: accounts,\n AccessToken: accessTokens,\n RefreshToken: refreshTokens,\n IdToken: idTokens,\n AppMetadata: appMetadata\n };\n }\n\n /**\n * Helper to merge new cache with the old one\n * @param oldState - cache before changes\n * @param newState - updated cache\n */\n private mergeRemovalsDict<T>(oldState: Record<string, T>, newState?: Record<string, T>): Record<string, T> {\n const finalState = { ...oldState };\n Object.keys(oldState).forEach((oldKey) => {\n if (!newState || !(newState.hasOwnProperty(oldKey))) {\n delete finalState[oldKey];\n }\n });\n return finalState;\n }\n\n /**\n * Helper to overlay as a part of cache merge\n * @param passedInCache - cache read from the blob\n */\n private overlayDefaults(passedInCache: JsonCache): JsonCache {\n this.logger.trace(\"Overlaying input cache with the default cache\");\n return {\n Account: {\n ...defaultSerializedCache.Account,\n ...passedInCache.Account,\n },\n IdToken: {\n ...defaultSerializedCache.IdToken,\n ...passedInCache.IdToken,\n },\n AccessToken: {\n ...defaultSerializedCache.AccessToken,\n ...passedInCache.AccessToken,\n },\n RefreshToken: {\n ...defaultSerializedCache.RefreshToken,\n ...passedInCache.RefreshToken,\n },\n AppMetadata: {\n ...defaultSerializedCache.AppMetadata,\n ...passedInCache.AppMetadata,\n },\n };\n }\n}\n","/* eslint-disable header/header */\nexport const name = \"@azure/msal-node\";\nexport const version = \"1.14.5\";\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AuthError } from \"@azure/msal-common\";\n\n/**\n * NodeAuthErrorMessage class containing string constants used by error codes and messages.\n */\nexport const NodeAuthErrorMessage = {\n invalidLoopbackAddressType: {\n code: \"invalid_loopback_server_address_type\",\n desc: \"Loopback server address is not type string. This is unexpected.\"\n },\n unableToLoadRedirectUri: {\n code: \"unable_to_load_redirectUrl\",\n desc: \"Loopback server callback was invoked without a url. This is unexpected.\"\n },\n noAuthCodeInResponse: {\n code: \"no_auth_code_in_response\",\n desc: \"No auth code found in the server response. Please check your network trace to determine what happened.\"\n },\n noLoopbackServerExists: {\n code: \"no_loopback_server_exists\",\n desc: \"No loopback server exists yet.\"\n },\n loopbackServerAlreadyExists: {\n code: \"loopback_server_already_exists\",\n desc: \"Loopback server already exists. Cannot create another.\"\n },\n loopbackServerTimeout: {\n code: \"loopback_server_timeout\",\n desc: \"Timed out waiting for auth code listener to be registered.\"\n },\n stateNotFoundError: {\n code: \"state_not_found\",\n desc: \"State not found. Please verify that the request originated from msal.\"\n },\n};\n\nexport class NodeAuthError extends AuthError {\n constructor(errorCode: string, errorMessage?: string) {\n super(errorCode, errorMessage);\n this.name = \"NodeAuthError\";\n }\n\n /**\n * Creates an error thrown if loopback server address is of type string.\n */\n static createInvalidLoopbackAddressTypeError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code,\n `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`);\n }\n\n /**\n * Creates an error thrown if the loopback server is unable to get a url.\n */\n static createUnableToLoadRedirectUrlError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code,\n `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`);\n }\n\n /**\n * Creates an error thrown if the server response does not contain an auth code.\n */\n static createNoAuthCodeInResponseError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code,\n `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`);\n }\n\n /**\n * Creates an error thrown if the loopback server has not been spun up yet.\n */\n static createNoLoopbackServerExistsError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code,\n `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`);\n }\n\n /**\n * Creates an error thrown if a loopback server already exists when attempting to create another one.\n */\n static createLoopbackServerAlreadyExistsError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code,\n `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`);\n }\n\n /**\n * Creates an error thrown if the loopback server times out registering the auth code listener.\n */\n static createLoopbackServerTimeoutError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code,\n `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`);\n }\n\n /**\n * Creates an error thrown when the state is not present.\n */\n static createStateNotFoundError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, NodeAuthErrorMessage.stateNotFoundError.desc);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AuthorizationCodeClient,\n ClientConfiguration,\n RefreshTokenClient,\n AuthenticationResult,\n Authority,\n AuthorityFactory,\n BaseAuthRequest,\n SilentFlowClient,\n Logger,\n ServerTelemetryManager,\n ServerTelemetryRequest,\n CommonSilentFlowRequest,\n CommonRefreshTokenRequest,\n CommonAuthorizationCodeRequest,\n CommonAuthorizationUrlRequest,\n CommonUsernamePasswordRequest,\n UsernamePasswordClient,\n AuthenticationScheme,\n ResponseMode,\n AuthorityOptions,\n OIDC_DEFAULT_SCOPES,\n AzureRegionConfiguration,\n AuthError,\n AzureCloudOptions,\n AuthorizationCodePayload,\n StringUtils,\n ClientAuthError,\n Constants,\n} from \"@azure/msal-common\";\nimport { Configuration, buildAppConfiguration, NodeConfiguration } from \"../config/Configuration\";\nimport { CryptoProvider } from \"../crypto/CryptoProvider\";\nimport { NodeStorage } from \"../cache/NodeStorage\";\nimport { Constants as NodeConstants, ApiId } from \"../utils/Constants\";\nimport { TokenCache } from \"../cache/TokenCache\";\nimport { ClientAssertion } from \"./ClientAssertion\";\nimport { AuthorizationUrlRequest } from \"../request/AuthorizationUrlRequest\";\nimport { AuthorizationCodeRequest } from \"../request/AuthorizationCodeRequest\";\nimport { RefreshTokenRequest } from \"../request/RefreshTokenRequest\";\nimport { SilentFlowRequest } from \"../request/SilentFlowRequest\";\nimport { version, name } from \"../packageMetadata\";\nimport { UsernamePasswordRequest } from \"../request/UsernamePasswordRequest\";\nimport { NodeAuthError } from \"../error/NodeAuthError\";\n\n/**\n * Base abstract class for all ClientApplications - public and confidential\n * @public\n */\nexport abstract class ClientApplication {\n\n protected readonly cryptoProvider: CryptoProvider;\n private tokenCache: TokenCache;\n\n /**\n * Platform storage object\n */\n protected storage: NodeStorage;\n /**\n * Logger object to log the application flow\n */\n protected logger: Logger;\n /**\n * Platform configuration initialized by the application\n */\n protected config: NodeConfiguration;\n /**\n * Client assertion passed by the user for confidential client flows\n */\n protected clientAssertion: ClientAssertion;\n /**\n * Client secret passed by the user for confidential client flows\n */\n protected clientSecret: string;\n\n /**\n * Constructor for the ClientApplication\n */\n protected constructor(configuration: Configuration) {\n this.config = buildAppConfiguration(configuration);\n this.cryptoProvider = new CryptoProvider();\n this.logger = new Logger(this.config.system.loggerOptions, name, version);\n this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider);\n this.tokenCache = new TokenCache(\n this.storage,\n this.logger,\n this.config.cache.cachePlugin\n );\n }\n\n /**\n * Creates the URL of the authorization request, letting the user input credentials and consent to the\n * application. The URL targets the /authorize endpoint of the authority configured in the\n * application object.\n *\n * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI\n * sent in the request and should contain an authorization code, which can then be used to acquire tokens via\n * `acquireTokenByCode(AuthorizationCodeRequest)`.\n */\n async getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string> {\n this.logger.info(\"getAuthCodeUrl called\", request.correlationId);\n const validRequest: CommonAuthorizationUrlRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n responseMode: request.responseMode || ResponseMode.QUERY,\n authenticationScheme: AuthenticationScheme.BEARER\n };\n\n const authClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n undefined,\n undefined,\n request.azureCloudOptions\n );\n const authorizationCodeClient = new AuthorizationCodeClient(\n authClientConfig\n );\n this.logger.verbose(\"Auth code client created\", validRequest.correlationId);\n return authorizationCodeClient.getAuthCodeUrl(validRequest);\n }\n\n /**\n * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0\n * Authorization Code flow.\n *\n * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0\n * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and\n * AuthorizationCodeRequest are the same.\n */\n async acquireTokenByCode(request: AuthorizationCodeRequest, authCodePayLoad?: AuthorizationCodePayload): Promise<AuthenticationResult> {\n this.logger.info(\"acquireTokenByCode called\");\n if (request.state && authCodePayLoad){\n this.logger.info(\"acquireTokenByCode - validating state\");\n this.validateState(request.state, authCodePayLoad.state || \"\");\n // eslint-disable-next-line no-param-reassign\n authCodePayLoad= {...authCodePayLoad, state: \"\"};\n }\n const validRequest: CommonAuthorizationCodeRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n authenticationScheme: AuthenticationScheme.BEARER\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId);\n try {\n const authClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const authorizationCodeClient = new AuthorizationCodeClient(\n authClientConfig\n );\n this.logger.verbose(\"Auth code client created\", validRequest.correlationId);\n return authorizationCodeClient.acquireToken(validRequest, authCodePayLoad);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires a token by exchanging the refresh token provided for a new set of tokens.\n *\n * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is\n * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will\n * handle the caching and refreshing of tokens automatically.\n */\n async acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByRefreshToken called\", request.correlationId);\n const validRequest: CommonRefreshTokenRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n authenticationScheme: AuthenticationScheme.BEARER\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId);\n try {\n const refreshTokenClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const refreshTokenClient = new RefreshTokenClient(\n refreshTokenClientConfig\n );\n this.logger.verbose(\"Refresh token client created\", validRequest.correlationId);\n return refreshTokenClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires a token silently when a user specifies the account the token is requested for.\n *\n * This API expects the user to provide an account object and looks into the cache to retrieve the token if present.\n * There is also an optional \"forceRefresh\" boolean the user can send to bypass the cache for access_token and id_token.\n * In case the refresh_token is expired or not found, an error is thrown\n * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).\n */\n async acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult | null> {\n const validRequest: CommonSilentFlowRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n forceRefresh: request.forceRefresh || false\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);\n try {\n const silentFlowClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const silentFlowClient = new SilentFlowClient(\n silentFlowClientConfig\n );\n this.logger.verbose(\"Silent flow client created\", validRequest.correlationId);\n return silentFlowClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires tokens with password grant by exchanging client applications username and password for credentials\n *\n * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.\n * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4\n * Microsoft's documentation and recommendations are at:\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword\n *\n * @param request - UsenamePasswordRequest\n */\n async acquireTokenByUsernamePassword(request: UsernamePasswordRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByUsernamePassword called\", request.correlationId);\n const validRequest: CommonUsernamePasswordRequest = {\n ...request,\n ... await this.initializeBaseRequest(request)\n };\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);\n try {\n const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const usernamePasswordClient = new UsernamePasswordClient(usernamePasswordClientConfig);\n this.logger.verbose(\"Username password client created\", validRequest.correlationId);\n return usernamePasswordClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Gets the token cache for the application.\n */\n getTokenCache(): TokenCache {\n this.logger.info(\"getTokenCache called\");\n return this.tokenCache;\n }\n\n /**\n * Validates OIDC state by comparing the user cached state with the state received from the server.\n * \n * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against\n * CSRF attacks.\n * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.\n * @param state\n * @param cachedState\n */\n protected validateState(state: string, cachedState: string): void {\n if(!state) {\n throw NodeAuthError.createStateNotFoundError();\n }\n\n if(state !== cachedState) {\n throw ClientAuthError.createStateMismatchError();\n }\n }\n\n /**\n * Returns the logger instance\n */\n getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Replaces the default logger set in configurations with new Logger with new configurations\n * @param logger - Logger instance\n */\n setLogger(logger: Logger): void {\n this.logger = logger;\n }\n\n /**\n * Builds the common configuration to be passed to the common component based on the platform configurarion\n * @param authority - user passed authority in configuration\n * @param serverTelemetryManager - initializes servertelemetry if passed\n */\n protected async buildOauthClientConfiguration(\n authority: string,\n requestCorrelationId?: string, \n serverTelemetryManager?: ServerTelemetryManager,\n azureRegionConfiguration?: AzureRegionConfiguration, \n azureCloudOptions?: AzureCloudOptions): Promise<ClientConfiguration> {\n \n this.logger.verbose(\"buildOauthClientConfiguration called\", requestCorrelationId);\n\n // precedence - azureCloudInstance + tenant >> authority and request >> config\n const userAzureCloudOptions = azureCloudOptions ? azureCloudOptions : this.config.auth.azureCloudOptions;\n\n // using null assertion operator as we ensure that all config values have default values in buildConfiguration()\n this.logger.verbose(`building oauth client configuration with the authority: ${authority}`, requestCorrelationId);\n const discoveredAuthority = await this.createAuthority(authority, azureRegionConfiguration, requestCorrelationId, userAzureCloudOptions);\n\n serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);\n\n const clientConfiguration: ClientConfiguration = {\n authOptions: {\n clientId: this.config.auth.clientId,\n authority: discoveredAuthority,\n clientCapabilities: this.config.auth.clientCapabilities\n },\n systemOptions: {\n proxyUrl: this.config.system.proxyUrl,\n },\n loggerOptions: {\n logLevel: this.config.system.loggerOptions.logLevel,\n loggerCallback: this.config.system.loggerOptions\n .loggerCallback,\n piiLoggingEnabled: this.config.system.loggerOptions\n .piiLoggingEnabled,\n correlationId: requestCorrelationId\n },\n cryptoInterface: this.cryptoProvider,\n networkInterface: this.config.system.networkClient,\n storageInterface: this.storage,\n serverTelemetryManager: serverTelemetryManager,\n clientCredentials: {\n clientSecret: this.clientSecret,\n clientAssertion: this.clientAssertion ? this.getClientAssertion(discoveredAuthority) : undefined,\n },\n libraryInfo: {\n sku: NodeConstants.MSAL_SKU,\n version: version,\n cpu: process.arch || Constants.EMPTY_STRING,\n os: process.platform || Constants.EMPTY_STRING,\n },\n telemetry: this.config.telemetry,\n persistencePlugin: this.config.cache.cachePlugin,\n serializableCache: this.tokenCache \n };\n\n return clientConfiguration;\n }\n\n private getClientAssertion(authority: Authority): { assertion: string, assertionType: string } {\n return {\n assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),\n assertionType: NodeConstants.JWT_BEARER_ASSERTION_TYPE\n };\n }\n\n /**\n * Generates a request with the default scopes & generates a correlationId.\n * @param authRequest - BaseAuthRequest for initialization\n */\n protected async initializeBaseRequest(authRequest: Partial<BaseAuthRequest>): Promise<BaseAuthRequest> {\n this.logger.verbose(\"initializeRequestScopes called\", authRequest.correlationId);\n // Default authenticationScheme to Bearer, log that POP isn't supported yet\n if (authRequest.authenticationScheme && authRequest.authenticationScheme === AuthenticationScheme.POP) {\n this.logger.verbose(\"Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request\", authRequest.correlationId);\n }\n\n authRequest.authenticationScheme = AuthenticationScheme.BEARER;\n\n // Set requested claims hash if claims were requested\n if (authRequest.claims && !StringUtils.isEmpty(authRequest.claims)) {\n authRequest.requestedClaimsHash = await this.cryptoProvider.hashString(authRequest.claims);\n }\n\n return {\n ...authRequest,\n scopes: [...((authRequest && authRequest.scopes) || []), ...OIDC_DEFAULT_SCOPES],\n correlationId: authRequest && authRequest.correlationId || this.cryptoProvider.createNewGuid(),\n authority: authRequest.authority || this.config.auth.authority\n };\n }\n\n /**\n * Initializes the server telemetry payload\n * @param apiId - Id for a specific request\n * @param correlationId - GUID\n * @param forceRefresh - boolean to indicate network call\n */\n protected initializeServerTelemetryManager(apiId: number, correlationId: string, forceRefresh?: boolean): ServerTelemetryManager {\n const telemetryPayload: ServerTelemetryRequest = {\n clientId: this.config.auth.clientId,\n correlationId: correlationId,\n apiId: apiId,\n forceRefresh: forceRefresh || false\n };\n\n return new ServerTelemetryManager(telemetryPayload, this.storage);\n }\n\n /**\n * Create authority instance. If authority not passed in request, default to authority set on the application\n * object. If no authority set in application object, then default to common authority.\n * @param authorityString - authority from user configuration\n */\n private async createAuthority(authorityString: string, azureRegionConfiguration?: AzureRegionConfiguration, requestCorrelationId?: string, azureCloudOptions?: AzureCloudOptions): Promise<Authority> {\n this.logger.verbose(\"createAuthority called\", requestCorrelationId);\n\n // build authority string based on auth params - azureCloudInstance is prioritized if provided\n const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions);\n\n const authorityOptions: AuthorityOptions = {\n protocolMode: this.config.auth.protocolMode,\n knownAuthorities: this.config.auth.knownAuthorities,\n cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,\n authorityMetadata: this.config.auth.authorityMetadata,\n azureRegionConfiguration,\n skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache,\n };\n\n return await AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, this.config.system.proxyUrl);\n }\n\n /**\n * Clear the cache\n */\n clearCache(): void {\n this.storage.clear();\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants as CommonConstants, ServerAuthorizationCodeResponse, UrlString } from \"@azure/msal-common\";\nimport { createServer, IncomingMessage, Server, ServerResponse } from \"http\";\nimport { NodeAuthError } from \"../error/NodeAuthError\";\nimport { Constants, HttpStatus, LOOPBACK_SERVER_CONSTANTS } from \"../utils/Constants\";\n\nexport class LoopbackClient {\n private server: Server;\n\n /**\n * Spins up a loopback server which returns the server response when the localhost redirectUri is hit\n * @param successTemplate \n * @param errorTemplate \n * @returns \n */\n async listenForAuthCode(successTemplate?: string, errorTemplate?: string): Promise<ServerAuthorizationCodeResponse> {\n if (!!this.server) {\n throw NodeAuthError.createLoopbackServerAlreadyExistsError();\n }\n\n const authCodeListener = new Promise<ServerAuthorizationCodeResponse>((resolve, reject) => {\n this.server = createServer(async (req: IncomingMessage, res: ServerResponse) => {\n const url = req.url;\n if (!url) {\n res.end(errorTemplate || \"Error occurred loading redirectUrl\");\n reject(NodeAuthError.createUnableToLoadRedirectUrlError());\n return;\n } else if (url === CommonConstants.FORWARD_SLASH) {\n res.end(successTemplate || \"Auth code was successfully acquired. You can close this window now.\");\n return;\n }\n \n const authCodeResponse = UrlString.getDeserializedQueryString(url);\n if (authCodeResponse.code) {\n const redirectUri = await this.getRedirectUri();\n res.writeHead(HttpStatus.REDIRECT, { location: redirectUri }); // Prevent auth code from being saved in the browser history\n res.end();\n }\n resolve(authCodeResponse);\n });\n this.server.listen(0); // Listen on any available port\n });\n\n // Wait for server to be listening\n await new Promise<void>((resolve) => {\n let ticks = 0;\n const id = setInterval(() => {\n if ((LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS) < ticks) {\n throw NodeAuthError.createLoopbackServerTimeoutError();\n }\n \n if (this.server.listening) {\n clearInterval(id);\n resolve();\n }\n ticks++;\n }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);\n });\n\n return authCodeListener;\n }\n\n /**\n * Get the port that the loopback server is running on\n * @returns \n */\n getRedirectUri(): string {\n if (!this.server) {\n throw NodeAuthError.createNoLoopbackServerExistsError();\n }\n \n const address = this.server.address();\n if (!address || typeof address === \"string\" || !address.port) {\n this.closeServer();\n throw NodeAuthError.createInvalidLoopbackAddressTypeError();\n } \n\n const port = address && address.port;\n\n return `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}:${port}`;\n }\n\n /**\n * Close the loopback server\n */\n closeServer(): void {\n if (!!this.server) {\n this.server.close();\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ApiId } from \"../utils/Constants\";\nimport {\n DeviceCodeClient,\n AuthenticationResult,\n CommonDeviceCodeRequest,\n AuthError,\n ResponseMode,\n OIDC_DEFAULT_SCOPES,\n CodeChallengeMethodValues,\n Constants as CommonConstants,\n ServerError\n} from \"@azure/msal-common\";\nimport { Configuration } from \"../config/Configuration\";\nimport { ClientApplication } from \"./ClientApplication\";\nimport { IPublicClientApplication } from \"./IPublicClientApplication\";\nimport { DeviceCodeRequest } from \"../request/DeviceCodeRequest\";\nimport { AuthorizationUrlRequest } from \"../request/AuthorizationUrlRequest\";\nimport { AuthorizationCodeRequest } from \"../request/AuthorizationCodeRequest\";\nimport { InteractiveRequest } from \"../request/InteractiveRequest\";\nimport { NodeAuthError } from \"../error/NodeAuthError\";\nimport { LoopbackClient } from \"../network/LoopbackClient\";\n\n/**\n * This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications\n * are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user.\n * @public\n */\nexport class PublicClientApplication extends ClientApplication implements IPublicClientApplication {\n /**\n * Important attributes in the Configuration object for auth are:\n * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.\n * - authority: the authority URL for your application.\n *\n * AAD authorities are of the form https://login.microsoftonline.com/\\{Enter_the_Tenant_Info_Here\\}.\n * - If your application supports Accounts in one organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).\n * - If your application supports Accounts in any organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with organizations.\n * - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace \"Enter_the_Tenant_Info_Here\" value with common.\n * - To restrict support to Personal Microsoft accounts only, replace \"Enter_the_Tenant_Info_Here\" value with consumers.\n *\n * Azure B2C authorities are of the form https://\\{instance\\}/\\{tenant\\}/\\{policy\\}. Each policy is considered\n * its own authority. You will have to set the all of the knownAuthorities at the time of the client application\n * construction.\n *\n * ADFS authorities are of the form https://\\{instance\\}/adfs.\n */\n constructor(configuration: Configuration) {\n super(configuration);\n }\n\n /**\n * Acquires a token from the authority using OAuth2.0 device code flow.\n * This flow is designed for devices that do not have access to a browser or have input constraints.\n * The authorization server issues a DeviceCode object with a verification code, an end-user code,\n * and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be\n * instructed to use another device to navigate to the verification URI to input credentials.\n * Since the client cannot receive incoming requests, it polls the authorization server repeatedly\n * until the end-user completes input of credentials.\n */\n public async acquireTokenByDeviceCode(request: DeviceCodeRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByDeviceCode called\", request.correlationId);\n const validRequest: CommonDeviceCodeRequest = Object.assign(request, await this.initializeBaseRequest(request));\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId);\n try {\n const deviceCodeConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig);\n this.logger.verbose(\"Device code client created\", validRequest.correlationId);\n return deviceCodeClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires a token by requesting an Authorization code then exchanging it for a token.\n */\n async acquireTokenInteractive(request: InteractiveRequest): Promise<AuthenticationResult> {\n const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes();\n const { openBrowser, successTemplate, errorTemplate, ...remainingProperties } = request;\n\n const loopbackClient = new LoopbackClient();\n const authCodeListener = loopbackClient.listenForAuthCode(successTemplate, errorTemplate);\n const redirectUri = loopbackClient.getRedirectUri();\n\n const validRequest: AuthorizationUrlRequest = {\n ...remainingProperties,\n scopes: request.scopes || OIDC_DEFAULT_SCOPES,\n redirectUri: redirectUri,\n responseMode: ResponseMode.QUERY,\n codeChallenge: challenge, \n codeChallengeMethod: CodeChallengeMethodValues.S256\n };\n\n const authCodeUrl = await this.getAuthCodeUrl(validRequest);\n await openBrowser(authCodeUrl);\n const authCodeResponse = await authCodeListener.finally(() => {\n loopbackClient.closeServer();\n });\n\n if (authCodeResponse.error) {\n throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror);\n } else if (!authCodeResponse.code) {\n throw NodeAuthError.createNoAuthCodeInResponseError();\n }\n\n const clientInfo = authCodeResponse.client_info;\n const tokenRequest: AuthorizationCodeRequest = {\n code: authCodeResponse.code,\n codeVerifier: verifier,\n clientInfo: clientInfo || CommonConstants.EMPTY_STRING,\n ...validRequest\n };\n return this.acquireTokenByCode(tokenRequest);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { JwtHeader, sign } from \"jsonwebtoken\";\nimport { TimeUtils, ClientAuthError, Constants } from \"@azure/msal-common\";\nimport { CryptoProvider } from \"../crypto/CryptoProvider\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\nimport { JwtConstants } from \"../utils/Constants\";\n\n/**\n * Client assertion of type jwt-bearer used in confidential client flows\n * @public\n */\nexport class ClientAssertion {\n\n private jwt: string;\n private privateKey: string;\n private thumbprint: string;\n private expirationTime: number;\n private issuer: string;\n private jwtAudience: string;\n private publicCertificate: Array<string>;\n\n /**\n * Initialize the ClientAssertion class from the clientAssertion passed by the user\n * @param assertion - refer https://tools.ietf.org/html/rfc7521\n */\n public static fromAssertion(assertion: string): ClientAssertion {\n const clientAssertion = new ClientAssertion();\n clientAssertion.jwt = assertion;\n return clientAssertion;\n }\n\n /**\n * Initialize the ClientAssertion class from the certificate passed by the user\n * @param thumbprint - identifier of a certificate\n * @param privateKey - secret key\n * @param publicCertificate - electronic document provided to prove the ownership of the public key\n */\n public static fromCertificate(thumbprint: string, privateKey: string, publicCertificate?: string): ClientAssertion {\n const clientAssertion = new ClientAssertion();\n clientAssertion.privateKey = privateKey;\n clientAssertion.thumbprint = thumbprint;\n if (publicCertificate) {\n clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);\n }\n return clientAssertion;\n }\n\n /**\n * Update JWT for certificate based clientAssertion, if passed by the user, uses it as is\n * @param cryptoProvider - library's crypto helper\n * @param issuer - iss claim\n * @param jwtAudience - aud claim\n */\n public getJwt(cryptoProvider: CryptoProvider, issuer: string, jwtAudience: string): string {\n // if assertion was created from certificate, check if jwt is expired and create new one.\n if (this.privateKey && this.thumbprint) {\n\n if (this.jwt && !this.isExpired() && issuer === this.issuer && jwtAudience === this.jwtAudience) {\n return this.jwt;\n }\n\n return this.createJwt(cryptoProvider, issuer, jwtAudience);\n }\n\n /*\n * if assertion was created by caller, then we just append it. It is up to the caller to\n * ensure that it contains necessary claims and that it is not expired.\n */\n if (this.jwt) {\n return this.jwt;\n }\n\n throw ClientAuthError.createInvalidAssertionError();\n }\n\n /**\n * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3\n */\n private createJwt(cryptoProvider: CryptoProvider, issuer: string, jwtAudience: string): string {\n\n this.issuer = issuer;\n this.jwtAudience = jwtAudience;\n const issuedAt = TimeUtils.nowSeconds();\n this.expirationTime = issuedAt + 600;\n\n const header: JwtHeader = {\n alg: JwtConstants.RSA_256,\n x5t: EncodingUtils.base64EncodeUrl(this.thumbprint, \"hex\")\n };\n\n if (this.publicCertificate) {\n Object.assign(header, {\n x5c: this.publicCertificate\n } as Partial<JwtHeader>);\n }\n\n const payload = {\n [JwtConstants.AUDIENCE]: this.jwtAudience,\n [JwtConstants.EXPIRATION_TIME]: this.expirationTime,\n [JwtConstants.ISSUER]: this.issuer,\n [JwtConstants.SUBJECT]: this.issuer,\n [JwtConstants.NOT_BEFORE]: issuedAt,\n [JwtConstants.JWT_ID]: cryptoProvider.createNewGuid()\n };\n\n this.jwt = sign(payload, this.privateKey, { header });\n return this.jwt;\n }\n\n /**\n * Utility API to check expiration\n */\n private isExpired(): boolean {\n return this.expirationTime < TimeUtils.nowSeconds();\n }\n\n /**\n * Extracts the raw certs from a given certificate string and returns them in an array.\n * @param publicCertificate - electronic document provided to prove the ownership of the public key\n */\n public static parseCertificate(publicCertificate: string): Array<string> {\n /**\n * This is regex to identify the certs in a given certificate string.\n * We want to look for the contents between the BEGIN and END certificate strings, without the associated newlines.\n * The information in parens \"(.+?)\" is the capture group to represent the cert we want isolated.\n * \".\" means any string character, \"+\" means match 1 or more times, and \"?\" means the shortest match.\n * The \"g\" at the end of the regex means search the string globally, and the \"s\" enables the \".\" to match newlines.\n */\n const regexToFindCerts = /-----BEGIN CERTIFICATE-----\\r*\\n(.+?)\\r*\\n-----END CERTIFICATE-----/gs;\n const certs: string[] = [];\n\n let matches;\n while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {\n // matches[1] represents the first parens capture group in the regex.\n certs.push(matches[1].replace(/\\r*\\n/g, Constants.EMPTY_STRING));\n }\n\n return certs;\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ClientApplication } from \"./ClientApplication\";\nimport { Configuration } from \"../config/Configuration\";\nimport { ClientAssertion } from \"./ClientAssertion\";\nimport { Constants as NodeConstants, ApiId, REGION_ENVIRONMENT_VARIABLE } from \"../utils/Constants\";\nimport {\n ClientCredentialClient,\n OnBehalfOfClient,\n CommonClientCredentialRequest,\n CommonOnBehalfOfRequest,\n AuthenticationResult,\n StringUtils,\n ClientAuthError,\n AzureRegionConfiguration,\n AuthError,\n Constants,\n IAppTokenProvider,\n OIDC_DEFAULT_SCOPES\n} from \"@azure/msal-common\";\nimport { IConfidentialClientApplication } from \"./IConfidentialClientApplication\";\nimport { OnBehalfOfRequest } from \"../request/OnBehalfOfRequest\";\nimport { ClientCredentialRequest } from \"../request/ClientCredentialRequest\";\n\n/**\n * This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications\n * will configure application secrets, client certificates/assertions as applicable\n * @public\n */\nexport class ConfidentialClientApplication extends ClientApplication implements IConfidentialClientApplication {\n private appTokenProvider?: IAppTokenProvider;\n\n /**\n * Constructor for the ConfidentialClientApplication\n *\n * Required attributes in the Configuration object are:\n * - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal\n * - authority: the authority URL for your application.\n * - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.\n *\n * In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\\{Enter_the_Tenant_Info_Here\\}.\n * If your application supports Accounts in one organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).\n * If your application supports Accounts in any organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with organizations.\n * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace \"Enter_the_Tenant_Info_Here\" value with common.\n * To restrict support to Personal Microsoft accounts only, replace \"Enter_the_Tenant_Info_Here\" value with consumers.\n *\n * In Azure B2C, authority is of the form https://\\{instance\\}/tfp/\\{tenant\\}/\\{policyName\\}/\n * Full B2C functionality will be available in this library in future versions.\n *\n * @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance\n */\n constructor(configuration: Configuration) {\n super(configuration);\n this.setClientCredential(this.config);\n this.appTokenProvider = undefined;\n }\n\n /** \n * This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and\n * is meant for Azure SDK to enhance Managed Identity support.\n * \n * @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source. \n */\n SetAppTokenProvider(provider: IAppTokenProvider): void {\n this.appTokenProvider = provider;\n }\n\n /**\n * Acquires tokens from the authority for the application (not for an end user).\n */\n public async acquireTokenByClientCredential(request: ClientCredentialRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByClientCredential called\", request.correlationId);\n\n // If there is a client assertion present in the request, it overrides the one present in the client configuration\n let clientAssertion;\n if (request.clientAssertion) {\n clientAssertion = {\n assertion: request.clientAssertion,\n assertionType: NodeConstants.JWT_BEARER_ASSERTION_TYPE\n };\n }\n\n const baseRequest = await this.initializeBaseRequest(request);\n\n // valid base request should not contain oidc scopes in this grant type\n const validBaseRequest = {\n ...baseRequest,\n scopes: baseRequest.scopes.filter((scope: string) => !OIDC_DEFAULT_SCOPES.includes(scope))\n };\n\n const validRequest: CommonClientCredentialRequest = {\n ...request,\n ...validBaseRequest,\n clientAssertion\n };\n\n const azureRegionConfiguration: AzureRegionConfiguration = {\n azureRegion: validRequest.azureRegion,\n environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE]\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache);\n try {\n const clientCredentialConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n azureRegionConfiguration,\n request.azureCloudOptions\n );\n const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig, this.appTokenProvider);\n this.logger.verbose(\"Client credential client created\", validRequest.correlationId);\n return clientCredentialClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires tokens from the authority for the application.\n *\n * Used in scenarios where the current app is a middle-tier service which was called with a token\n * representing an end user. The current app can use the token (oboAssertion) to request another\n * token to access downstream web API, on behalf of that user.\n *\n * The current middle-tier app has no user interaction to obtain consent.\n * See how to gain consent upfront for your middle-tier app from this article.\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application\n */\n public async acquireTokenOnBehalfOf(request: OnBehalfOfRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenOnBehalfOf called\", request.correlationId);\n const validRequest: CommonOnBehalfOfRequest = {\n ...request,\n ... await this.initializeBaseRequest(request)\n };\n try {\n const onBehalfOfConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n undefined,\n undefined,\n request.azureCloudOptions\n );\n const oboClient = new OnBehalfOfClient(onBehalfOfConfig);\n this.logger.verbose(\"On behalf of client created\", validRequest.correlationId);\n return oboClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n throw e;\n }\n }\n\n private setClientCredential(configuration: Configuration): void {\n const clientSecretNotEmpty = !StringUtils.isEmpty(configuration.auth.clientSecret);\n const clientAssertionNotEmpty = !StringUtils.isEmpty(configuration.auth.clientAssertion);\n const certificate = configuration.auth.clientCertificate || {\n thumbprint: Constants.EMPTY_STRING,\n privateKey: Constants.EMPTY_STRING\n };\n const certificateNotEmpty = !StringUtils.isEmpty(certificate.thumbprint) || !StringUtils.isEmpty(certificate.privateKey);\n\n /*\n * If app developer configures this callback, they don't need a credential\n * i.e. AzureSDK can get token from Managed Identity without a cert / secret\n */\n if (this.appTokenProvider) {\n return;\n }\n\n // Check that at most one credential is set on the application\n if (\n clientSecretNotEmpty && clientAssertionNotEmpty ||\n clientAssertionNotEmpty && certificateNotEmpty ||\n clientSecretNotEmpty && certificateNotEmpty) {\n throw ClientAuthError.createInvalidCredentialError();\n }\n\n if (configuration.auth.clientSecret) {\n this.clientSecret = configuration.auth.clientSecret;\n return;\n }\n\n if (configuration.auth.clientAssertion) {\n this.clientAssertion = ClientAssertion.fromAssertion(configuration.auth.clientAssertion);\n return;\n }\n\n if (!certificateNotEmpty) {\n throw ClientAuthError.createInvalidCredentialError();\n } else {\n this.clientAssertion = ClientAssertion.fromCertificate(certificate.thumbprint, certificate.privateKey, configuration.auth.clientCertificate?.x5c);\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AccountEntity, ICachePlugin, TokenCacheContext } from \"@azure/msal-common\";\nimport { TokenCache } from \"../TokenCache\";\nimport { IPartitionManager } from \"./IPartitionManager\";\nimport { ICacheClient } from \"./ICacheClient\";\n\nexport class DistributedCachePlugin implements ICachePlugin {\n private client: ICacheClient;\n private partitionManager: IPartitionManager;\n\n constructor(client: ICacheClient, partitionManager: IPartitionManager) {\n this.client = client;\n this.partitionManager = partitionManager;\n }\n \n public async beforeCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n const partitionKey = await this.partitionManager.getKey();\n const cacheData = await this.client.get(partitionKey);\n cacheContext.tokenCache.deserialize(cacheData);\n }\n \n public async afterCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n if (cacheContext.cacheHasChanged) {\n const kvStore = (cacheContext.tokenCache as TokenCache).getKVStore();\n const accountEntities = Object.values(kvStore).filter(value => AccountEntity.isAccountEntity(value as object));\n\n if (accountEntities.length > 0) {\n const accountEntity = accountEntities[0] as AccountEntity;\n const partitionKey = await this.partitionManager.extractKey(accountEntity);\n \n await this.client.set(partitionKey, cacheContext.tokenCache.serialize()); \n }\n }\n }\n}\n"],"names":["HttpMethod","HttpStatus","ProxyStatus","REGION_ENVIRONMENT_VARIABLE","RANDOM_OCTET_SIZE","Hash","SHA256","CharSet","CV_CHARSET","Constants","MSAL_SKU","JWT_BEARER_ASSERTION_TYPE","AUTHORIZATION_PENDING","HTTP_PROTOCOL","LOCALHOST","ApiId","JwtConstants","ALGORITHM","RSA_256","X5T","X5C","AUDIENCE","EXPIRATION_TIME","ISSUER","SUBJECT","NOT_BEFORE","JWT_ID","LOOPBACK_SERVER_CONSTANTS","INTERVAL_MS","TIMEOUT_MS","NetworkUtils","getNetworkResponse","headers","body","statusCode","status","HttpClient","sendGetRequestAsync","url","options","proxyUrl","networkRequestViaProxy","GET","networkRequestViaHttps","sendPostRequestAsync","cancellationToken","POST","httpMethod","timeout","URL","destinationUrl","tunnelRequestOptions","host","hostname","port","method","path","postRequestStringContent","length","outgoingRequestString","toUpperCase","href","Promise","resolve","reject","request","http","on","destroy","Error","end","response","socket","proxyStatusCode","SERVER_ERROR","SUCCESS_RANGE_START","SUCCESS_RANGE_END","statusMessage","setTimeout","write","data","chunk","push","dataString","Buffer","concat","toString","dataStringArray","split","httpStatusCode","parseInt","slice","join","headersArray","entries","Map","forEach","header","headerKeyValue","RegExp","headerKey","headerValue","object","JSON","parse","e","set","Object","fromEntries","parsedHeaders","networkResponse","parseBody","isPostRequest","emptyHeaders","customOptions","https","parsedBody","error","errorType","errorDescriptionHelper","CLIENT_ERROR_RANGE_START","CLIENT_ERROR_RANGE_END","SERVER_ERROR_RANGE_START","SERVER_ERROR_RANGE_END","error_description","stringify","DEFAULT_AUTH_OPTIONS","clientId","EMPTY_STRING","authority","DEFAULT_AUTHORITY","clientSecret","clientAssertion","clientCertificate","thumbprint","privateKey","x5c","knownAuthorities","cloudDiscoveryMetadata","authorityMetadata","clientCapabilities","protocolMode","ProtocolMode","AAD","azureCloudOptions","azureCloudInstance","AzureCloudInstance","None","tenant","skipAuthorityMetadataCache","DEFAULT_CACHE_OPTIONS","DEFAULT_LOGGER_OPTIONS","loggerCallback","piiLoggingEnabled","logLevel","LogLevel","Info","DEFAULT_SYSTEM_OPTIONS","loggerOptions","networkClient","DEFAULT_TELEMETRY_OPTIONS","application","appName","appVersion","buildAppConfiguration","auth","cache","system","telemetry","GuidGenerator","generateGuid","uuidv4","isGuid","guid","regexGuid","test","EncodingUtils","base64Encode","str","encoding","from","base64EncodeUrl","replace","base64Decode","base64Str","base64DecodeUrl","HashUtils","sha256","buffer","crypto","createHash","update","digest","PkceGenerator","constructor","hashUtils","generatePkceCodes","verifier","generateCodeVerifier","challenge","generateCodeChallengeFromVerifier","charArr","maxNumber","byte","randomBytes","index","codeVerifier","CryptoProvider","pkceGenerator","guidGenerator","createNewGuid","input","getPublicKeyThumbprint","removeTokenBindingKey","clearKeystore","signJwt","hashString","plainText","Deserializer","deserializeJSONBlob","jsonFile","deserializedCache","StringUtils","isEmpty","deserializeAccounts","accounts","accountObjects","keys","map","key","serializedAcc","mappedAcc","homeAccountId","home_account_id","environment","realm","localAccountId","local_account_id","username","authorityType","authority_type","name","clientInfo","client_info","lastModificationTime","last_modification_time","lastModificationApp","last_modification_app","account","AccountEntity","CacheManager","toObject","deserializeIdTokens","idTokens","idObjects","serializedIdT","mappedIdT","credentialType","credential_type","client_id","secret","idToken","IdTokenEntity","deserializeAccessTokens","accessTokens","atObjects","serializedAT","mappedAT","target","cachedAt","cached_at","expiresOn","expires_on","extendedExpiresOn","extended_expires_on","refreshOn","refresh_on","keyId","key_id","tokenType","token_type","requestedClaims","requestedClaimsHash","userAssertionHash","accessToken","AccessTokenEntity","deserializeRefreshTokens","refreshTokens","rtObjects","serializedRT","mappedRT","familyId","family_id","refreshToken","RefreshTokenEntity","deserializeAppMetadata","appMetadata","appMetadataObjects","serializedAmdt","mappedAmd","amd","AppMetadataEntity","deserializeAllCache","jsonCache","Account","IdToken","AccessToken","RefreshToken","AppMetadata","Serializer","serializeJSONBlob","serializeAccounts","accCache","accountEntity","serializeIdTokens","idTCache","idTEntity","serializeAccessTokens","atCache","atEntity","serializeRefreshTokens","rtCache","rtEntity","serializeAppMetadata","amdtCache","amdtEntity","serializeAllCache","inMemCache","NodeStorage","logger","cryptoImpl","registerChangeEmitter","func","changeEmitters","emitChange","call","cacheToInMemoryCache","inMemoryCache","inMemoryCacheToCache","getCache","getInMemoryCache","trace","setInMemoryCache","setCache","getItem","tracePii","setItem","value","getAccount","accountKey","isAccountEntity","setAccount","generateAccountKey","getIdTokenCredential","idTokenKey","isIdTokenEntity","setIdTokenCredential","generateCredentialKey","getAccessTokenCredential","accessTokenKey","isAccessTokenEntity","setAccessTokenCredential","getRefreshTokenCredential","refreshTokenKey","isRefreshTokenEntity","setRefreshTokenCredential","getAppMetadata","appMetadataKey","isAppMetadataEntity","setAppMetadata","generateAppMetadataKey","getServerTelemetry","serverTelemetrykey","serverTelemetryEntity","ServerTelemetryEntity","isServerTelemetryEntity","setServerTelemetry","serverTelemetryKey","serverTelemetry","getAuthorityMetadata","authorityMetadataEntity","AuthorityMetadataEntity","isAuthorityMetadataEntity","getAuthorityMetadataKeys","getKeys","filter","isAuthorityMetadata","setAuthorityMetadata","metadata","getThrottlingCache","throttlingCacheKey","throttlingCache","ThrottlingEntity","isThrottlingEntity","setThrottlingCache","removeItem","result","containsKey","includes","clear","cacheKeys","generateInMemoryCache","generateJsonCache","updateCredentialCacheKey","currentCacheKey","credential","updatedCacheKey","cacheItem","verbose","defaultSerializedCache","TokenCache","storage","cachePlugin","cacheHasChanged","handleChangeEvent","bind","persistence","hasChanged","serialize","finalState","cacheSnapshot","mergeState","deserialize","overlayDefaults","getKVStore","getAllAccounts","cacheContext","TokenCacheContext","beforeCacheAccess","afterCacheAccess","getAccountByHomeId","allAccounts","accountObj","getAccountByLocalId","removeAccount","generateAccountCacheKey","oldState","currentState","stateAfterRemoval","mergeRemovals","mergeUpdates","newState","newKey","newValue","hasOwnProperty","newValueNotNull","newValueIsObject","newValueIsNotArray","Array","isArray","oldStateNotUndefinedOrNull","mergeRemovalsDict","oldKey","passedInCache","version","NodeAuthErrorMessage","invalidLoopbackAddressType","code","desc","unableToLoadRedirectUri","noAuthCodeInResponse","noLoopbackServerExists","loopbackServerAlreadyExists","loopbackServerTimeout","stateNotFoundError","NodeAuthError","AuthError","errorCode","errorMessage","createInvalidLoopbackAddressTypeError","createUnableToLoadRedirectUrlError","createNoAuthCodeInResponseError","createNoLoopbackServerExistsError","createLoopbackServerAlreadyExistsError","createLoopbackServerTimeoutError","createStateNotFoundError","ClientApplication","configuration","config","cryptoProvider","Logger","tokenCache","getAuthCodeUrl","info","correlationId","validRequest","initializeBaseRequest","responseMode","ResponseMode","QUERY","authenticationScheme","AuthenticationScheme","BEARER","authClientConfig","buildOauthClientConfiguration","undefined","authorizationCodeClient","AuthorizationCodeClient","acquireTokenByCode","authCodePayLoad","state","validateState","serverTelemetryManager","initializeServerTelemetryManager","acquireToken","setCorrelationId","cacheFailedRequest","acquireTokenByRefreshToken","refreshTokenClientConfig","refreshTokenClient","RefreshTokenClient","acquireTokenSilent","forceRefresh","silentFlowClientConfig","silentFlowClient","SilentFlowClient","acquireTokenByUsernamePassword","usernamePasswordClientConfig","usernamePasswordClient","UsernamePasswordClient","getTokenCache","cachedState","ClientAuthError","createStateMismatchError","getLogger","setLogger","requestCorrelationId","azureRegionConfiguration","userAzureCloudOptions","discoveredAuthority","createAuthority","updateRegionDiscoveryMetadata","regionDiscoveryMetadata","clientConfiguration","authOptions","systemOptions","cryptoInterface","networkInterface","storageInterface","clientCredentials","getClientAssertion","libraryInfo","sku","NodeConstants","cpu","process","arch","os","platform","persistencePlugin","serializableCache","assertion","getJwt","tokenEndpoint","assertionType","authRequest","POP","claims","scopes","OIDC_DEFAULT_SCOPES","apiId","telemetryPayload","ServerTelemetryManager","authorityString","authorityUrl","Authority","generateAuthority","authorityOptions","AuthorityFactory","createDiscoveredInstance","clearCache","LoopbackClient","listenForAuthCode","successTemplate","errorTemplate","server","authCodeListener","createServer","req","res","CommonConstants","FORWARD_SLASH","authCodeResponse","UrlString","getDeserializedQueryString","redirectUri","getRedirectUri","writeHead","REDIRECT","location","listen","ticks","id","setInterval","listening","clearInterval","address","closeServer","close","PublicClientApplication","acquireTokenByDeviceCode","assign","deviceCodeConfig","deviceCodeClient","DeviceCodeClient","acquireTokenInteractive","openBrowser","remainingProperties","loopbackClient","codeChallenge","codeChallengeMethod","CodeChallengeMethodValues","S256","authCodeUrl","finally","ServerError","suberror","tokenRequest","ClientAssertion","fromAssertion","jwt","fromCertificate","publicCertificate","parseCertificate","issuer","jwtAudience","isExpired","createJwt","createInvalidAssertionError","issuedAt","TimeUtils","nowSeconds","expirationTime","alg","x5t","payload","sign","regexToFindCerts","certs","matches","exec","ConfidentialClientApplication","setClientCredential","appTokenProvider","SetAppTokenProvider","provider","acquireTokenByClientCredential","baseRequest","validBaseRequest","scope","azureRegion","environmentRegion","env","skipCache","clientCredentialConfig","clientCredentialClient","ClientCredentialClient","acquireTokenOnBehalfOf","onBehalfOfConfig","oboClient","OnBehalfOfClient","clientSecretNotEmpty","clientAssertionNotEmpty","certificate","certificateNotEmpty","createInvalidCredentialError","DistributedCachePlugin","client","partitionManager","partitionKey","getKey","cacheData","get","kvStore","accountEntities","values","extractKey"],"mappings":";;;;;;;;;;;;;;AAAA;;;;;AAKA;;;AAGA,IAAYA,UAAZ;;AAAA,WAAYA;EACRA,iBAAA,QAAA;EACAA,kBAAA,SAAA;AACH,CAHD,EAAYA,UAAU,KAAVA,UAAU,KAAA,CAAtB;;AAKA,IAAYC,UAAZ;;AAAA,WAAYA;EACRA,mDAAA,wBAAA;EACAA,iDAAA,sBAAA;EACAA,wCAAA,aAAA;EACAA,wDAAA,6BAAA;EACAA,sDAAA,2BAAA;EACAA,wDAAA,6BAAA;EACAA,sDAAA,2BAAA;AACH,CARD,EAAYA,UAAU,KAAVA,UAAU,KAAA,CAAtB;;AAUA,IAAYC,WAAZ;;AAAA,WAAYA;EACRA,qDAAA,wBAAA;EACAA,mDAAA,sBAAA;EACAA,8CAAA,iBAAA;AACH,CAJD,EAAYA,WAAW,KAAXA,WAAW,KAAA,CAAvB;AAMA;;;;;AAGO,MAAMC,2BAA2B,GAAG,aAApC;AAEP;;;;AAGO,MAAMC,iBAAiB,GAAG,EAA1B;AAEP;;;;AAGO,MAAMC,IAAI,GAAG;EAChBC,MAAM,EAAE;AAD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AAL,CAAYK,GAAZ,CAAgBH,YAAhB,CAAxB;IACAnP,YAAY,CAACuD,UAAb,CAAwB3D,WAAxB,CAAoCyP,SAApC;;;EAGyB,MAAhBlP,gBAAgB,CAACH,YAAD;IACzB,IAAIA,YAAY,CAACb,eAAjB,EAAkC;MAC9B,MAAMoQ,OAAO,GAAIvP,YAAY,CAACuD,UAAb,CAAuCzD,UAAvC,EAAjB;MACA,MAAM0P,eAAe,GAAGvjB,MAAM,CAACwjB,MAAP,CAAcF,OAAd,EAAuBhS,MAAvB,CAA8BtC,KAAK,IAAIlG,wBAAa,CAACqG,eAAd,CAA8BH,KAA9B,CAAvC,CAAxB;;MAEA,IAAIuU,eAAe,CAACxmB,MAAhB,GAAyB,CAA7B,EAAgC;QAC5B,MAAM+P,aAAa,GAAGyW,eAAe,CAAC,CAAD,CAArC;QACA,MAAML,YAAY,GAAG,MAAM,KAAKD,gBAAL,CAAsBQ,UAAtB,CAAiC3W,aAAjC,CAA3B;QAEA,MAAM,KAAKkW,MAAL,CAAYjjB,GAAZ,CAAgBmjB,YAAhB,EAA8BnP,YAAY,CAACuD,UAAb,CAAwB/D,SAAxB,EAA9B,CAAN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
"use strict";functione(e){returne&&"object"==typeofe&&"default"ine?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});vart,r,n,i=require("@azure/msal-common"),o=require("http"),s=e(o),a=e(require("https")),c=require("uuid"),l=e(require("crypto")),h=require("jsonwebtoken");!function(e){e.GET="get",e.POST="post"}(t||(t={})),function(e){e[e.SUCCESS_RANGE_START=200]="SUCCESS_RANGE_START",e[e.SUCCESS_RANGE_END=299]="SUCCESS_RANGE_END",e[e.REDIRECT=302]="REDIRECT",e[e.CLIENT_ERROR_RANGE_START=400]="CLIENT_ERROR_RANGE_START",e[e.CLIENT_ERROR_RANGE_END=499]="CLIENT_ERROR_RANGE_END",e[e.SERVER_ERROR_RANGE_START=500]="SERVER_ERROR_RANGE_START",e[e.SERVER_ERROR_RANGE_END=599]="SERVER_ERROR_RANGE_END"}(r||(r={})),function(e){e[e.SUCCESS_RANGE_START=200]="SUCCESS_RANGE_START",e[e.SUCCESS_RANGE_END=299]="SUCCESS_RANGE_END",e[e.SERVER_ERROR=500]="SERVER_ERROR"}(n||(n={}));constu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";vard;!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"}(d||(d={}));classg{staticgetNetworkResponse(e,t,r){return{headers:e,body:t,status:r}}}classp{asyncsendGetRequestAsync(e,r){returnnull!=r&&r.proxyUrl?y(e,t.GET,r):m(e,t.GET,r)}asyncsendPostRequestAsync(e,r,n){returnnull!=r&&r.proxyUrl?y(e,t.POST,r,n):m(e,t.POST,r,n)}}consty=(e,i,o,a)=>{constc=(null==o?void0:o.headers)||{},l=newURL((null==o?void0:o.proxyUrl)||""),h=newURL(e),u={host:l.hostname,port:l.port,method:"CONNECT",path:h.hostname,headers:c};a&&(u.timeout=a);letd="";if(i===t.POST){conste=(null==o?void0:o.body)||"";d=`Content-Type: application/x-www-form-urlencoded\r\nContent-Length: ${e.length}\r\n\r\n`+e}constp=`${i.toUpperCase()}${h.href} HTTP/1.1\r\nHost: ${h.host}\r\nConnection: close\r\n`+d+"\r\n";returnnewPromise((e,t)=>{consti=s.request(u);u.timeout&&i.on("timeout",()=>{i.destroy(),t(newError("Request time out"))}),i.end(),i.on("connect",(o,s)=>{consta=(null==o?void0:o.statusCode)||n.SERVER_ERROR;(a<n.SUCCESS_RANGE_START||a>n.SUCCESS_RANGE_END)&&(i.destroy(),s.destroy(),t(newError(`Error connecting to proxy. Http status code: ${o.statusCode}. Http status message: ${(null==o?void0:o.statusMessage)||"Unknown"}`))),u.timeout&&(s.setTimeout(u.timeout),s.on("timeout",()=>{i.destroy(),s.destroy(),t(newError("Request time out"))})),s.write(p);constc=[];s.on("data",e=>{c.push(e)}),s.on("end",()=>{constt=Buffer.concat([...c]).toString().split("\r\n"),n=parseInt(t[0].split("")[1]),o=t[0].split("").slice(2).join(""),s=t[t.length-1],a=t.slice(1,t.length-2),l=newMap;a.forEach(e=>{constt=e.split(newRegExp(/:\s(.*)/s)),r=t[0];letn=t[1];try{conste=JSON.parse(n);e&&"object"==typeofe&&(n=e)}catch(e){}l.set(r,n)});consth=Object.fromEntries(l),u=g.getNetworkResponse(h,C(n,o,h,s),n);(n<r.SUCCESS_RANGE_START||n>r.SUCCESS_RANGE_END)&&"authorization_pending"!==u.body.error&&i.destroy(),e(u)}),s.on("error",e=>{i.destroy(),s.destroy(),t(newError(e.toString()))})}),i.on("error",e=>{i.destroy(),t(newError(e.toString()))})})},m=(e,n,i,o)=>{consts=n===t.POST,c=(null==i?void0:i.body)||"",l={method:n,headers:(null==i?void0:i.headers)||{}};returno&&(l.timeout=o),s&&(l.headers={...l.headers,"Content-Length":c.length}),newPromise((t,n)=>{consti=a.request(e,l);o&&i.on("timeout",()=>{i.destroy(),n(newError("Request time out"))}),s&&i.write(c),i.end(),i.on("response",e=>{constn=e.headers,o=e.statusCode,s=e.statusMessage,a=[];e.on("data",e=>{a.push(e)}),e.on("end",()=>{conste=Buffer.concat([...a]).toString(),c=g.getNetworkResponse(n,C(o,s,n,e),o);(o<r.SUCCESS_RANGE_START||o>r.SUCCESS_RANGE_END)&&"authorization_pending"!==c.body.error&&i.destroy(),t(c)})}),i.on("error",e=>{i.destroy(),n(newError(e.toString()))})})},C=(e,t,n,i)=>{leto;try{o=JSON.parse(i)}catch(i){lets,a;e>=r.CLIENT_ERROR_RANGE_START&&e<=r.CLIENT_ERROR_RANGE_END?(s="client_error",a="A client"):e>=r.SERVER_ERROR_RANGE_START&&e<=r.SERVER_ERROR_RANGE_END?(s="server_error",a="A server"):(s="unknown_error",a="An unknown"),o={error:s,error_description:`${a} error occured.\nHttp status code: ${e}\nHttp status message: ${t||"Unknown"}\nHeaders: ${JSON.stringify(n)}`}}returno},f={clientId:i.Constants.EMPTY_STRING,authority:i.Constants.DEFAULT_AUTHORITY,clientSecret:i.Constants.EMPTY_STRING,clientAssertion:i.Constants.EMPTY_STRING,clientCertificate:{thumbprint:i.Constants.EMPTY_STRING,privateKey:i.Constants.EMPTY_STRING,x5c:i.Constants.EMPTY_STRING},knownAuthorities:[],cloudDiscoveryMetadata:i.Constants.EMPTY_STRING,authorityMetadata:i.Constants.EMPTY_STRING,clientCapabilities:[],protocolMode:i.ProtocolMode.AAD,azureCloudOptions:{azureCloudInstance:i.AzureCloudInstance.None,tenant:i.Constants.EMPTY_STRING},skipAuthorityMetadataCache:!1},T={},E={loggerOptions:{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:i.LogLevel.Info},networkClient:newp,proxyUrl:i.Constants.EMPTY_STRING},A={application:{appName:i.Constants.EMPTY_STRING,appVersion:i.Constants.EMPTY_STRING}};functionR({auth:e,cache:t,system:r,telemetry:n}){return{auth:{...f,...e},cache:{...T,...t},system:{...E,...r},telemetry:{...A,...n}}}classk{generateGuid(){returnc.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)}}classS{staticbase64Encode(e,t){returnBuffer.from(e,t).toString("base64")}staticbase64EncodeUrl(e,t){returnS.base64Encode(e,t).replace(/=/g,i.Constants.EMPTY_STRING).replace(/\+/g,"-").replace(/\//g,"_")}staticbase64Decode(e){returnBuffer.from(e,"base64").toString("utf8")}staticbase64DecodeUrl(e){lett=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";returnS.base64Decode(t)}}classI{sha256(e){returnl.createHash("sha256").update(e).digest()}}class_{constructor(){this.hashUtils=newI}asyncgeneratePkceCodes(){conste=this.generateCodeVerifier();return{verifier:e,challenge:this.generateCodeChallengeFromVerifier(e)}}generateCodeVerifier(){conste=[],t=256-256%u.length;for(;e.length<=32;){constr=l.randomBytes(1)[0];r>=t||e.push(u[r%u.length])}constr=e.join(i.Constants.EMPTY_STRING);returnS.base64EncodeUrl(r)}generateCodeChallengeFromVerifier(e){returnS.base64EncodeUrl(this.hashUtils.sha256(e).toString("base64"),"base64")}}classv{constructor(){this.pkceGenerator=new_,this.guidGenerator=newk,this.hashUtils=newI}createNewGuid(){returnthis.guidGenerator.generateGuid()}base64Encode(e){returnS.base64Encode(e)}base64Decode(e){returnS.base64Decode(e)}generatePkceCodes(){returnthis.pkceGenerator.generatePkceCodes()}getPublicKeyThumbprint(){thrownewError("Method not implemented.")}removeTokenBindingKey(){thrownewError("Method not implemented.")}clearKeystore(){thrownewError("Method not implemented.")}signJwt(){thrownewError("Method not implemented.")}asynchashString(e){returnS.base64EncodeUrl(this.hashUtils.sha256(e).toString("base64"),"base64")}}classw{staticdeserializeJSONBlob(e){returni.StringUtils.isEmpty(e)?{}:JSON.parse(e)}staticdeserializeAccounts(e){constt={};returne&&Object.keys(e).map((function(r){constn=e[r],o={homeAccountId:n.home_account_id,environment:n.environment,realm:n.realm,localAccountId:n.local_account_id,username:n.username,authorityType:n.authority_type,name:n.name,clientInfo:n.client_info,lastModificationTime:n.last_modification_time,lastModificationApp:n.last_modification_app},s=newi.AccountEntity;i.CacheManager.toObject(s,o),t[r]=s})),t}staticdeserializeIdTokens(e){constt={};returne&&Object.keys(e).map((function(r){constn=e[r],o={homeAccountId:n.home_account_id,environment:n.environment,credentialType:n.credential_type,clientId:n.client_id,secret:n.secret,realm:n.realm},s=newi.IdTokenEntity;i.CacheManager.toObject(s,o),t[r]=s})),t}staticdeserializeAccessTokens(e){constt={};returne&&Object.keys(e).map((function(r){constn=e[r],o={homeAccountId:n.home_account_id,environment:n.environment,credentialType:n.credential_type,clientId:n.client_id,secret:n.secret,realm:n.realm,target:n.target,cachedAt:n.cached_at,expiresOn:n.expires_on,extendedExpiresOn:n.extended_expires_on,refreshOn:n.refresh_on,keyId:n.key_id,tokenType:n.token_type,requestedClaims:n.requestedClaims,requestedClaimsHash:n.requestedClaimsHash,userAssertionHash:n.userAssertionHash},s=newi.AccessTokenEntity;i.CacheManager.toObject(s,o),t[r]=s})),t}staticdeserializeRefreshTokens(e){constt={};returne&&Object.keys(e).map((function(r){constn=e[r],o={homeAccountId:n.home_account_id,environment:n.environment,credentialType:n.credential_type,clientId:n.client_id,secret:n.secret,familyId:n.family_id,target:n.target,realm:n.realm},s=newi.RefreshTokenEntity;i.CacheManager.toObject(s,o),t[r]=s})),t}staticdeserializeAppMetadata(e){constt={};returne&&Object.keys(e).map((function(r){constn=e[r],o={clientId:n.client_id,environment:n.environment,familyId:n.family_id},s=newi.AppMetadataEntity;i.CacheManager.toObject(s,o),t[r]=s})),t}staticdeserializeAllCache(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):{}}}}classb{staticserializeJSONBlob(e){returnJSON.stringify(e)}staticserializeAccounts(e){constt={};returnObject.keys(e).map((function(r){constn=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}staticserializeIdTokens(e){constt={};returnObject.keys(e).map((function(r){constn=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}staticserializeAccessTokens(e){constt={};returnObject.keys(e).map((function(r){constn=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,userAssertionHash:n.userAssertionHash}})),t}staticserializeRefreshTokens(e){constt={};returnObject.keys(e).map((function(r){constn=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}staticserializeAppMetadata(e){constt={};returnObject.keys(e).map((function(r){constn=e[r];t[r]={client_id:n.clientId,environment:n.environment,family_id:n.familyId}})),t}staticserializeAllCache(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)}}}classMextendsi.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){constt={accounts:{},idTokens:{},accessTokens:{},refreshTokens:{},appMetadata:{}};for(constrine)if(e[r]instanceofi.AccountEntity)t.accounts[r]=e[r];elseif(e[r]instanceofi.IdTokenEntity)t.idTokens[r]=e[r];elseif(e[r]instanceofi.AccessTokenEntity)t.accessTokens[r]=e[r];elseif(e[r]instanceofi.RefreshTokenEntity)t.refreshTokens[r]=e[r];else{if(!(e[r]instanceofi.AppMetadataEntity))continue;t.appMetadata[r]=e[r]}returnt}inMemoryCacheToCache(e){lett=this.getCache();returnt={...t,...e.accounts,...e.idTokens,...e.accessTokens,...e.refreshTokens,...e.appMetadata},t}getInMemoryCache(){returnthis.logger.trace("Getting in-memory cache"),this.cacheToInMemoryCache(this.getCache())}setInMemoryCache(e){this.logger.trace("Setting in-memory cache");constt=this.inMemoryCacheToCache(e);this.setCache(t),this.emitChange()}getCache(){returnthis.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){returnthis.logger.tracePii("Item key: "+e),this.getCache()[e]}setItem(e,t){this.logger.tracePii("Item key: "+e);constr=this.getCache();r[e]=t,this.setCache(r)}getAccount(e){constt=this.getItem(e);returni.AccountEntity.isAccountEntity(t)?t:null}setAccount(e){constt=e.generateAccountKey();this.setItem(t,e)}getIdTokenCredential(e){constt=this.getItem(e);returni.IdTokenEntity.isIdTokenEntity(t)?t:null}setIdTokenCredential(e){constt=e.generateCredentialKey();this.setItem(t,e)}getAccessTokenCredential(e){constt=this.getItem(e);returni.AccessTokenEntity.isAccessTokenEntity(t)?t:null}setAccessTokenCredential(e){constt=e.generateCredentialKey();this.setItem(t,e)}getRefreshTokenCredential(e){constt=this.getItem(e);returni.RefreshTokenEntity.isRefreshTokenEntity(t)?t:null}setRefreshTokenCredential(e){constt=e.generateCredentialKey();this.setItem(t,e)}getAppMetadata(e){constt=this.getItem(e);returni.AppMetadataEntity.isAppMetadataEntity(e,t)?t:null}setAppMetadata(e){constt=e.generateAppMetadataKey();this.setItem(t,e)}getServerTelemetry(e){constt=this.getItem(e);returnt&&i.ServerTelemetryEntity.isServerTelemetryEntity(e,t)?t:null}setServerTelemetry(e,t){this.setItem(e,t)}getAuthorityMetadata(e){constt=this.getItem(e);returnt&&i.AuthorityMetadataEntity.isAuthorityMetadataEntity(e,t)?t:null}getAuthorityMetadataKeys(){returnthis.getKeys().filter(e=>this.isAuthorityMetadata(e))}setAuthorityMetadata(e,t){this.setItem(e,t)}getThrottlingCache(e){constt=this.getItem(e);returnt&&i.ThrottlingEntity.isThrottlingEntity(e,t)?t:null}setThrottlingCache(e,t){this.setItem(e,t)}removeItem(e){this.logger.tracePii("Item key: "+e);lett=!1;constr=this.getCache();returnr[e]&&(deleter[e],t=!0),t&&(this.setCache(r),this.emitChange()),t}containsKey(e){returnthis.getKeys().includes(e)}getKeys(){this.logger.trace("Retrieving all cache keys");conste=this.getCache();return[...Object.keys(e)]}asyncclear(){this.logger.trace("Clearing cache entries created by MSAL"),this.getKeys().forEach(e=>{this.removeItem(e)}),this.emitChange()}staticgenerateInMemoryCache(e){returnw.deserializeAllCache(w.deserializeJSONBlob(e))}staticgenerateJsonCache(e){returnb.serializeAllCache(e)}updateCredentialCacheKey(e,t){constr=t.generateCredentialKey();if(e!==r){constn=this.getItem(e);if(n)returnthis.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`)}returne}}constO={},N={},P={},q={},U={};classx{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(){returnthis.cacheHasChanged}serialize(){this.logger.trace("Serializing in-memory cache");lete=b.serializeAllCache(this.storage.getInMemoryCache());returni.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,i.StringUtils.isEmpty(this.cacheSnapshot))this.logger.trace("No cache snapshot to deserialize");else{this.logger.trace("Reading cache snapshot from disk");conste=w.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));this.storage.setInMemoryCache(e)}}getKVStore(){returnthis.storage.getCache()}asyncgetAllAccounts(){lete;this.logger.trace("getAllAccounts called");try{returnthis.persistence&&(e=newi.TokenCacheContext(this,!1),awaitthis.persistence.beforeCacheAccess(e)),this.storage.getAllAccounts()}finally{this.persistence&&e&&awaitthis.persistence.afterCacheAccess(e)}}asyncgetAccountByHomeId(e){constt=awaitthis.getAllAccounts();return!i.StringUtils.isEmpty(e)&&t&&t.length&&t.filter(t=>t.homeAccountId===e)[0]||null}asyncgetAccountByLocalId(e){constt=awaitthis.getAllAccounts();return!i.StringUtils.isEmpty(e)&&t&&t.length&&t.filter(t=>t.localAccountId===e)[0]||null}asyncremoveAccount(e){lett;this.logger.trace("removeAccount called");try{this.persistence&&(t=newi.TokenCacheContext(this,!0),awaitthis.persistence.beforeCacheAccess(t)),awaitthis.storage.removeAccount(i.AccountEntity.generateAccountCacheKey(e))}finally{this.persistence&&t&&awaitthis.persistence.afterCacheAccess(t)}}handleChangeEvent(){this.cacheHasChanged=!0}mergeState(e,t){this.logger.trace("Merging in-memory cache with cache snapshot");constr=this.mergeRemovals(e,t);returnthis.mergeUpdates(r,t)}mergeUpdates(e,t){returnObject.keys(t).forEach(r=>{constn=t[r];if(e.hasOwnProperty(r)){constt=null!==n,i="object"==typeofn,o=!Array.isArray(n),s=null!=e[r];t&&i&&o&&s?this.mergeUpdates(e[r],n):e[r]=n}elsenull!==n&&(e[r]=n)}),e}mergeRemovals(e,t){this.logger.trace("Remove updated entries in cache");constr=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){constr={...e};returnObject.keys(e).forEach(e=>{t&&t.hasOwnProperty(e)||deleter[e]}),r}overlayDefaults(e){returnthis.logger.trace("Overlaying input cache with the default cache"),{Account:{...O,...e.Account},IdToken:{...N,...e.IdToken},AccessToken:{...P,...e.AccessToken},RefreshToken:{...q,...e.RefreshToken},AppMetadata:{...U,...e.AppMetadata}}}}classzextendsi.AuthError{constructor(e,t){super(e,t),this.name="NodeAuthError"}staticcreateInvalidLoopbackAddressTypeError(){returnnewz("invalid_loopback_server_address_type","Loopback server address is not type string. This is unexpected.")}staticcreateUnableToLoadRedirectUrlError(){returnnewz("unable_to_load_redirectUrl","Loopback server callback was invoked without a url. This is unexpected.")}staticcreateNoAuthCodeInResponseError(){returnnewz("no_auth_code_in_response","No auth code found in the server response. Please check your network trace to determine what happened.")}staticcreateNoLoopbackServerExistsError(){returnnewz("no_loopback_server_exists","No loopback server exists yet.")}staticcreateLoopbackServerAlreadyExistsError(){returnnewz("loopback_server_already_exists","Loopback server already exists. Cannot create another.")}staticcreateLoopbackServerTimeoutError(){returnnewz("loopback_server_timeout","Timed out waiting for auth code listener to be registered.")}staticcreateStateNotFoundError(){returnnewz("state_not_found","State not found. Please verify that the request originated from msal.")}}classG{constructor(e){this.config=R(e),this.cryptoProvider=newv,this.logger=newi.Logger(this.config.system.loggerOptions,"@azure/msal-node","1.14.5"),this.storage=newM(this.logger,this.config.auth.clientId,this.cryptoProvider),this.tokenCache=newx(this.storage,this.logger,this.config.cache.cachePlugin)}asyncgetAuthCodeUrl(e){this.logger.info("getAuthCodeUrl called",e.correlationId);constt={...e,...awaitthis.initializeBaseRequest(e),responseMode:e.responseMode||i.ResponseMode.QUERY,authenticationScheme:i.AuthenticationScheme.BEARER},r=awaitthis.buildOauthClientConfiguration(t.authority,t.correlationId,void0,void0,e.azureCloudOptions),n=newi.AuthorizationCodeClient(r);returnthis.logger.verbose("Auth code client created",t.correlationId),n.getAuthCodeUrl(t)}asyncacquireTokenByCode(e,t){this.logger.info("acquireTokenByCode called"),e.state&&t&&(this.logger.info("acquireTokenByCode - validating state"),this.validateState(e.state,t.state||""),t={...t,state:""});constr={...e,...awaitthis.initializeBaseRequest(e),authenticationScheme:i.AuthenticationScheme.BEARER},n=this.initializeServerTelemetryManager(d.acquireTokenByCode,r.correlationId);try{consto=awaitthis.buildOauthClientConfiguration(r.authority,r.correlationId,n,void0,e.azureCloudOptions),s=newi.AuthorizationCodeClient(o);returnthis.logger.verbose("Auth code client created",r.correlationId),s.acquireToken(r,t)}catch(e){throweinstanceofi.AuthError&&e.setCorrelationId(r.correlationId),n.cacheFailedRequest(e),e}}asyncacquireTokenByRefreshToken(e){this.logger.info("acquireTokenByRefreshToken called",e.correlationId);constt={...e,...awaitthis.initializeBaseRequest(e),authenticationScheme:i.AuthenticationScheme.BEARER},r=this.initializeServerTelemetryManager(d.acquireTokenByRefreshToken,t.correlationId);try{constn=awaitthis.buildOauthClientConfiguration(t.authority,t.correlationId,r,void0,e.azureCloudOptions),o=newi.RefreshTokenClient(n);returnthis.logger.verbose("Refresh token client created",t.correlationId),o.acquireToken(t)}catch(e){throweinstanceofi.AuthError&&e.setCorrelationId(t.correlationId),r.cacheFailedRequest(e),e}}asyncacquireTokenSilent(e){constt={...e,...awaitthis.initializeBaseRequest(e),forceRefresh:e.forceRefresh||!1},r=this.initializeServerTelemetryManager(d.acquireTokenSilent,t.correlationId,t.forceRefresh);try{constn=awaitthis.buildOauthClientConfiguration(t.authority,t.correlationId,r,void0,e.azureCloudOptions),o=newi.SilentFlowClient(n);returnthis.logger.verbose("Silent flow client created",t.correlationId),o.acquireToken(t)}catch(e){throweinstanceofi.AuthError&&e.setCorrelationId(t.correlationId),r.cacheFailedRequest(e),e}}asyncacquireTokenByUsernamePassword(e){this.logger.info("acquireTokenByUsernamePassword called",e.correlationId);constt={...e,...awaitthis.initializeBaseRequest(e)},r=this.initializeServerTelemetryManager(d.acquireTokenByUsernamePassword,t.correlationId);try{constn=awaitthis.buildOauthClientConfiguration(t.authority,t.correlationId,r,void0,e.azureCloudOptions),o=newi.UsernamePasswordClient(n);returnthis.logger.verbose("Username password client created",t.correlationId),o.acquireToken(t)}catch(e){throweinstanceofi.AuthError&&e.setCorrelationId(t.correlationId),r.cacheFailedRequest(e),e}}getTokenCache(){returnthis.logger.info("getTokenCache called"),this.tokenCache}validateState(e,t){if(!e)throwz.createStateNotFoundError();if(e!==t)throwi.ClientAuthError.createStateMismatchError()}getLogger(){returnthis.logger}setLogger(e){this.logger=e}asyncbuildOauthClientConfiguration(e,t,r,n,o){this.logger.verbose("buildOauthClientConfiguration called",t);consts=o||this.config.auth.azureCloudOptions;this.logger.verbose("building oauth client configuration with the authority: "+e,t);consta=awaitthis.createAuthority(e,n,t,s);returnnull==r||r.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:r,clientCredentials:{clientSecret:this.clientSecret,clientAssertion:this.clientAssertion?this.getClientAssertion(a):void0},libraryInfo:{sku:"msal.js.node",version:"1.14.5",cpu:process.arch||i.Constants.EMPTY_STRING,os:process.platform||i.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"}}asyncinitializeBaseRequest(e){returnthis.logger.verbose("initializeRequestScopes called",e.correlationId),e.authenticationScheme&&e.authenticationScheme===i.AuthenticationScheme.POP&&this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request",e.correlationId),e.authenticationScheme=i.AuthenticationScheme.BEARER,e.claims&&!i.StringUtils.isEmpty(e.claims)&&(e.requestedClaimsHash=awaitthis.cryptoProvider.hashString(e.claims)),{...e,scopes:[...e&&e.scopes||[],...i.OIDC_DEFAULT_SCOPES],correlationId:e&&e.correlationId||this.cryptoProvider.createNewGuid(),authority:e.authority||this.config.auth.authority}}initializeServerTelemetryManager(e,t,r){returnnewi.ServerTelemetryManager({clientId:this.config.auth.clientId,correlationId:t,apiId:e,forceRefresh:r||!1},this.storage)}asynccreateAuthority(e,t,r,n){this.logger.verbose("createAuthority called",r);consto=i.Authority.generateAuthority(e,n),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};returnawaiti.AuthorityFactory.createDiscoveredInstance(o,this.config.system.networkClient,this.storage,s,this.logger,this.config.system.proxyUrl)}clearCache(){this.storage.clear()}}classj{asynclistenForAuthCode(e,t){if(this.server)throwz.createLoopbackServerAlreadyExistsError();constn=newPromise((n,s)=>{this.server=o.createServer(async(o,a)=>{constc=o.url;if(!c)returna.end(t||"Error occurred loading redirectUrl"),voids(z.createUnableToLoadRedirectUrlError());if(c===i.Constants.FORWARD_SLASH)returnvoida.end(e||"Auth code was successfully acquired. You can close this window now.");constl=i.UrlString.getDeserializedQueryString(c);if(l.code){conste=awaitthis.getRedirectUri();a.writeHead(r.REDIRECT,{location:e}),a.end()}n(l)}),this.server.listen(0)});returnawaitnewPromise(e=>{lett=0;constr=setInterval(()=>{if(50<t)throwz.createLoopbackServerTimeoutError();this.server.listening&&(clearInterval(r),e()),t++},100)}),n}getRedirectUri(){if(!this.server)throwz.createNoLoopbackServerExistsError();conste=this.server.address();if(!e||"string"==typeofe||!e.port)throwthis.closeServer(),z.createInvalidLoopbackAddressTypeError();return"http://localhost:"+(e&&e.port)}closeServer(){this.server&&this.server.close()}}classB{staticfromAssertion(e){constt=newB;returnt.jwt=e,t}staticfromCertificate(e,t,r){constn=newB;returnn.privateKey=t,n.thumbprint=e,r&&(n.publicCertificate=this.parseCertificate(r)),n}getJwt(e,t,r){if(this.privateKey&&this.thumbprint)returnthis.jwt&&!this.isExpired()&&t===this.issuer&&r===this.jwtAudience?this.jwt:this.createJwt(e,t,r);if(this.jwt)returnthis.jwt;throwi.ClientAuthError.createInvalidAssertionError()}createJwt(e,t,r){this.issuer=t,this.jwtAudience=r;constn=i.TimeUtils.nowSeconds();this.expirationTime=n+600;consto={alg:"RS256",x5t:S.base64EncodeUrl(this.thumbprint,"hex")};this.publicCertificate&&Object.assign(o,{x5c:this.publicCertificate});consts={aud:this.jwtAudience,exp:this.expirationTime,iss:this.issuer,sub:this.issuer,nbf:n,jti:e.createNewGuid()};returnthis.jwt=h.sign(s,this.privateKey,{header:o}),this.jwt}isExpired(){returnthis.expirationTime<i.TimeUtils.nowSeconds()}staticparseCertificate(e){constt=/-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs,r=[];letn;for(;null!==(n=t.exec(e));)r.push(n[1].replace(/\r*\n/g,i.Constants.EMPTY_STRING));returnr}}Object.defineProperty(exports,"AuthError",{enumerable:!0,get:function(){returni.AuthError}}),Object.defineProperty(exports,"AuthErrorMessage",{enumerable:!0,get:function(){returni.AuthErrorMessage}}),Object.defineProperty(exports,"AzureCloudInstance",{enumerable:!0,get:function(){returni.AzureCloudInstance}}),Object.defineProperty(exports,"ClientAuthError",{enumerable:!0,get:function(){returni.ClientAuthError}}),Object.defineProperty(exports,"ClientAuthErrorMessage",{enumerable:!0,get:function(){returni.ClientAuthErrorMessage}}),Object.defineProperty(exports,"ClientConfigurationError",{enumerable:!0,get:function(){returni.ClientConfigurationError}}),Object.defineProperty(exports,"ClientConfigurationErrorMessage",{enumerable:!0,get:function(){returni.ClientConfigurationErrorMessage}}),Object.defineProperty(exports,"InteractionRequiredAuthError",{enumerable:!0,get:function(){returni.InteractionRequiredAuthError}}),Object.defineProperty(exports,"InteractionRequiredAuthErrorMessage",{enumerable:!0,get:function(){returni.InteractionRequiredAuthErrorMessage}}),Object.defineProperty(exports,"LogLevel",{enumerable:!0,get:function(){returni.LogLevel}}),Object.defineProperty(exports,"Logger",{enumerable:!0,get:function(){returni.Logger}}),Object.defineProperty(exports,"PromptValue",{enumerable:!0,get:function(){returni.PromptValue}}),Object.defineProperty(exports,"ProtocolMode",{enumerable:!0,get:function(){returni.ProtocolMode}}),Object.defineProperty(exports,"ResponseMode",{enumerable:!0,get:function(){returni.ResponseMode}}),Object.defineProperty(exports,"ServerError",{enumerable:!0,get:function(){returni.ServerError}}),Object.defineProperty(exports,"TokenCacheContext",{enumerable:!0,get:function(){returni.TokenCacheContext}}),exports.ClientApplication=G,exports.ClientAssertion=B,exports.ConfidentialClientApplication=classextendsG{constructor(e){super(e),this.setClientCredential(this.config),this.appTokenProvider=void0}SetAppTokenProvider(e){this.appTokenProvider=e}asyncacquireTokenByClientCredential(e){lett;this.logger.info("acquireTokenByClientCredential called",e.correlationId),e.clientAssertion&&(t={assertion:e.clientAssertion,assertionType:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"});constr=awaitthis.initializeBaseRequest(e),n={...r,scopes:r.scopes.filter(e=>!i.OIDC_DEFAULT_SCOPES.includes(e))},o={...e,...n,clientAssertion:t},s={azureRegion:o.azureRegion,environmentRegion:process.env.REGION_NAME},a=this.initializeServerTelemetryManager(d.acquireTokenByClientCredential,o.correlationId,o.skipCache);try{constt=awaitthis.buildOauthClientConfiguration(o.authority,o.correlationId,a,s,e.azureCloudOptions),r=newi.ClientCredentialClient(t,this.appTokenProvider);returnthis.logger.verbose("Client credential client created",o.correlationId),r.acquireToken(o)}catch(e){throweinstanceofi.AuthError&&e.setCorrelationId(o.correlationId),a.cacheFailedRequest(e),e}}asyncacquireTokenOnBehalfOf(e){this.logger.info("acquireTokenOnBehalfOf called",e.correlationId);constt={...e,...awaitthis.initializeBaseRequest(e)};try{constr=awaitthis.buildOauthClientConfiguration(t.authority,t.correlationId,void0,void0,e.azureCloudOptions),n=newi.OnBehalfOfClient(r);returnthis.logger.verbose("On behalf of client created",t.correlationId),n.acquireToken(t)}catch(e){throweinstanceofi.AuthError&&e.setCorrelationId(t.correlationId),e}}setClientCredential(e){constt=!i.StringUtils.isEmpty(e.auth.clientSecret),r=!i.StringUtils.isEmpty(e.auth.clientAssertion),n=e.auth.clientCertificate||{thumbprint:i.Constants.EMPTY_STRING,privateKey:i.Constants.EMPTY_STRING},o=!i.StringUtils.isEmpty(n.thumbprint)||!i.StringUtils.isEmpty(n.privateKey);if(!this.appTokenProvider){if(t&&r||r&&o||t&&o)throwi.ClientAuthError.createInvalidCredentialError();if(e.auth.clientSecret)this.clientSecret=e.auth.clientSecret;elseif(e.auth.clientAssertion)this.clientAssertion=B.fromAssertion(e.auth.clientAssertion);else{if(!o)throwi.ClientAuthError.createInvalidCredentialError();vars;this.clientAssertion=B.fromCertificate(n.thumbprint,n.privateKey,null==(s=e.auth.clientCertificate)?void0:s.x5c)}}}},exports.CryptoProvider=v,exports.DistributedCachePlugin=class{constructor(e,t){this.client=e,this.partitionManager=t}asyncbeforeCacheAccess(e){constt=awaitthis.partitionManager.getKey(),r=awaitthis.client.get(t);e.tokenCache.deserialize(r)}asyncafterCacheAccess(e){if(e.cacheHasChanged){constt=e.tokenCache.getKVStore(),r=Object.values(t).filter(e=>i.AccountEntity.isAccountEntity(e));if(r.length>0){constt=r[0],n=awaitthis.partitionManager.extractKey(t);awaitthis.client.set(n,e.tokenCache.serialize())}}}},exports.NodeStorage=M,exports.PublicClientApplication=classextendsG{constructor(e){super(e)}asyncacquireTokenByDeviceCode(e){this.logger.info("acquireTokenByDeviceCode called",e.correlationId);constt=Object.assign(e,awaitthis.initializeBaseRequest(e)),r=this.initializeServerTelemetryManager(d.acquireTokenByDeviceCode,t.correlationId);try{constn=awaitthis.buildOauthClientConfiguration(t.authority,t.correlationId,r,void0,e.azureCloudOptions),o=newi.DeviceCodeClient(n);returnthis.logger.verbose("Device code client created",t.correlationId),o.acquireToken(t)}catch(e){throweinstanceofi.AuthError&&e.setCorrelationId(t.correlationId),r.cacheFailedRequest(e),e}}asyncacquireTokenInteractive(e){const{verifier:t,challenge:r}=awaitthis.cryptoProvider.generatePkceCodes(),{openBrowser:n,successTemplate:o,errorTemplate:s,...a}=e,c=newj,l=c.listenForAuthCode(o,s),h=c.getRedirectUri(),u={...a,scopes:e.scopes||i.OIDC_DEFAULT_SCOPES,redirectUri:h,responseMode:i.ResponseMode.QUERY,codeChallenge:r,codeChallengeMethod:i.CodeChallengeMethodValues.S256},d=awaitthis.getAuthCodeUrl(u);awaitn(d);constg=awaitl.finally(()=>{c.closeServer()});if(g.error)thrownewi.ServerError(g.error,g.error_description,g.suberror);if(!g.code)throwz.createNoAuthCodeInResponseError();constp={code:g.code,codeVerifier:t,clientInfo:g.client_info||i.Constants.EMPTY_STRING,...u};returnthis.acquireTokenByCode(p)}},exports.TokenCache=x,exports.buildAppConfiguration=R,exports.version="1.14.5";
{"version":3,"file":"msal-node.cjs.production.min.js","sources":["../src/utils/Constants.ts","../src/utils/NetworkUtils.ts","../src/network/HttpClient.ts","../src/config/Configuration.ts","../src/crypto/GuidGenerator.ts","../src/utils/EncodingUtils.ts","../src/crypto/HashUtils.ts","../src/crypto/PkceGenerator.ts","../src/crypto/CryptoProvider.ts","../src/cache/serializer/Deserializer.ts","../src/cache/serializer/Serializer.ts","../src/cache/NodeStorage.ts","../src/cache/TokenCache.ts","../src/error/NodeAuthError.ts","../src/client/ClientApplication.ts","../src/packageMetadata.ts","../src/network/LoopbackClient.ts","../src/client/ClientAssertion.ts","../src/client/ConfidentialClientApplication.ts","../src/cache/distributed/DistributedCachePlugin.ts","../src/client/PublicClientApplication.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * http methods\n */\nexport enum HttpMethod {\n GET = \"get\",\n POST = \"post\",\n}\n\nexport enum HttpStatus {\n SUCCESS_RANGE_START = 200,\n SUCCESS_RANGE_END = 299,\n REDIRECT = 302,\n CLIENT_ERROR_RANGE_START = 400,\n CLIENT_ERROR_RANGE_END = 499,\n SERVER_ERROR_RANGE_START = 500,\n SERVER_ERROR_RANGE_END = 599\n}\n\nexport enum ProxyStatus {\n SUCCESS_RANGE_START = 200,\n SUCCESS_RANGE_END = 299,\n SERVER_ERROR = 500\n}\n\n/**\n * Constants used for region discovery\n */\nexport const REGION_ENVIRONMENT_VARIABLE = \"REGION_NAME\";\n\n/**\n * Constant used for PKCE\n */\nexport const RANDOM_OCTET_SIZE = 32;\n\n/**\n * Constants used in PKCE\n */\nexport const Hash = {\n SHA256: \"sha256\",\n};\n\n/**\n * Constants for encoding schemes\n */\nexport const CharSet = {\n CV_CHARSET:\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~\",\n};\n\n/**\n * Cache Constants\n */\nexport const CACHE = {\n FILE_CACHE: \"fileCache\",\n EXTENSION_LIB: \"extenstion_library\",\n};\n\n/**\n * Constants\n */\nexport const Constants = {\n MSAL_SKU: \"msal.js.node\",\n JWT_BEARER_ASSERTION_TYPE: \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n AUTHORIZATION_PENDING: \"authorization_pending\",\n HTTP_PROTOCOL: \"http://\",\n LOCALHOST: \"localhost\"\n};\n\n/**\n * API Codes for Telemetry purposes.\n * Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs\n * 0-99 Silent Flow\n * 600-699 Device Code Flow\n * 800-899 Auth Code Flow\n */\nexport enum ApiId {\n acquireTokenSilent = 62,\n acquireTokenByUsernamePassword = 371,\n acquireTokenByDeviceCode = 671,\n acquireTokenByClientCredential = 771,\n acquireTokenByCode = 871,\n acquireTokenByRefreshToken = 872\n}\n\n/**\n * JWT constants\n */\nexport const JwtConstants = {\n ALGORITHM: \"alg\",\n RSA_256: \"RS256\",\n X5T: \"x5t\", \n X5C: \"x5c\",\n AUDIENCE: \"aud\",\n EXPIRATION_TIME: \"exp\",\n ISSUER: \"iss\",\n SUBJECT: \"sub\",\n NOT_BEFORE: \"nbf\",\n JWT_ID: \"jti\",\n};\n\nexport const LOOPBACK_SERVER_CONSTANTS = {\n INTERVAL_MS: 100,\n TIMEOUT_MS: 5000\n};\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NetworkResponse } from \"@azure/msal-common\";\n\nexport class NetworkUtils {\n static getNetworkResponse<T>(headers: Record<string, string>, body: T, statusCode: number): NetworkResponse<T> {\n return {\n headers: headers,\n body: body,\n status: statusCode,\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n INetworkModule,\n NetworkRequestOptions,\n NetworkResponse\n} from \"@azure/msal-common\";\nimport { HttpMethod, Constants, HttpStatus, ProxyStatus } from \"../utils/Constants\";\nimport { NetworkUtils } from \"../utils/NetworkUtils\";\nimport http from \"http\";\nimport https from \"https\";\n\n/**\n * This class implements the API for network requests.\n */\nexport class HttpClient implements INetworkModule {\n\n /**\n * Http Get request\n * @param url\n * @param options\n */\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n ): Promise<NetworkResponse<T>> {\n if (options?.proxyUrl) {\n return networkRequestViaProxy(url, HttpMethod.GET, options);\n } else {\n return networkRequestViaHttps(url, HttpMethod.GET, options);\n }\n }\n\n /**\n * Http Post request\n * @param url\n * @param options\n */\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n cancellationToken?: number,\n ): Promise<NetworkResponse<T>> {\n if (options?.proxyUrl) {\n return networkRequestViaProxy(url, HttpMethod.POST, options, cancellationToken);\n } else {\n return networkRequestViaHttps(url, HttpMethod.POST, options, cancellationToken);\n }\n }\n}\n\nconst networkRequestViaProxy = <T>(\n url: string,\n httpMethod: string,\n options: NetworkRequestOptions,\n timeout?: number,\n): Promise<NetworkResponse<T>> => {\n const headers = options?.headers || {} as Record<string, string>;\n const proxyUrl = new URL(options?.proxyUrl || \"\");\n const destinationUrl = new URL(url);\n\n // \"method: connect\" must be used to establish a connection to the proxy\n const tunnelRequestOptions: https.RequestOptions = {\n host: proxyUrl.hostname,\n port: proxyUrl.port,\n method: \"CONNECT\",\n path: destinationUrl.hostname,\n headers: headers,\n };\n\n if (timeout) {\n tunnelRequestOptions.timeout = timeout;\n }\n\n // compose a request string for the socket\n let postRequestStringContent: string = \"\";\n if (httpMethod === HttpMethod.POST) {\n const body = options?.body || \"\";\n postRequestStringContent =\n \"Content-Type: application/x-www-form-urlencoded\\r\\n\" +\n `Content-Length: ${body.length}\\r\\n` +\n `\\r\\n${body}`;\n }\n const outgoingRequestString = `${httpMethod.toUpperCase()} ${destinationUrl.href} HTTP/1.1\\r\\n` +\n `Host: ${destinationUrl.host}\\r\\n` +\n \"Connection: close\\r\\n\" +\n postRequestStringContent +\n \"\\r\\n\";\n\n return new Promise<NetworkResponse<T>>(((resolve, reject) => {\n const request = http.request(tunnelRequestOptions);\n\n if (tunnelRequestOptions.timeout) {\n request.on(\"timeout\", () => {\n request.destroy();\n reject(new Error(\"Request time out\"));\n });\n }\n\n request.end();\n\n // establish connection to the proxy\n request.on(\"connect\", (response, socket) => {\n const proxyStatusCode = response?.statusCode || ProxyStatus.SERVER_ERROR;\n if ((proxyStatusCode < ProxyStatus.SUCCESS_RANGE_START) || (proxyStatusCode > ProxyStatus.SUCCESS_RANGE_END)) {\n request.destroy();\n socket.destroy();\n reject(new Error(`Error connecting to proxy. Http status code: ${response.statusCode}. Http status message: ${response?.statusMessage || \"Unknown\"}`));\n }\n if (tunnelRequestOptions.timeout) {\n socket.setTimeout(tunnelRequestOptions.timeout);\n socket.on(\"timeout\", () => {\n request.destroy();\n socket.destroy();\n reject(new Error(\"Request time out\"));\n });\n }\n\n // make a request over an HTTP tunnel\n socket.write(outgoingRequestString);\n\n const data: Buffer[] = [];\n socket.on(\"data\", (chunk) => {\n data.push(chunk);\n });\n\n socket.on(\"end\", () => {\n // combine all received buffer streams into one buffer, and then into a string\n const dataString = Buffer.concat([...data]).toString();\n\n // separate each line into it's own entry in an arry\n const dataStringArray = dataString.split(\"\\r\\n\");\n // the first entry will contain the statusCode and statusMessage\n const httpStatusCode = parseInt(dataStringArray[0].split(\" \")[1]);\n // remove \"HTTP/1.1\" and the status code to get the status message\n const statusMessage = dataStringArray[0].split(\" \").slice(2).join(\" \");\n // the last entry will contain the body\n const body = dataStringArray[dataStringArray.length - 1];\n\n // everything in between the first and last entries are the headers\n const headersArray = dataStringArray.slice(1, dataStringArray.length - 2);\n\n // build an object out of all the headers\n const entries = new Map();\n headersArray.forEach((header) => {\n /**\n * the header might look like \"Content-Length: 1531\", but that is just a string\n * it needs to be converted to a key/value pair\n * split the string at the first instance of \":\"\n * there may be more than one \":\" if the value of the header is supposed to be a JSON object\n */\n const headerKeyValue = header.split(new RegExp(/:\\s(.*)/s));\n const headerKey = headerKeyValue[0];\n let headerValue = headerKeyValue[1];\n\n // check if the value of the header is supposed to be a JSON object\n try {\n const object = JSON.parse(headerValue);\n\n // if it is, then convert it from a string to a JSON object\n if (object && (typeof object === \"object\")) {\n headerValue = object;\n }\n } catch (e) {\n // otherwise, leave it as a string\n }\n\n entries.set(headerKey, headerValue);\n });\n const headers = Object.fromEntries(entries);\n\n const parsedHeaders = headers as Record<string, string>;\n const networkResponse = NetworkUtils.getNetworkResponse(\n parsedHeaders,\n parseBody(httpStatusCode, statusMessage, parsedHeaders, body) as T,\n httpStatusCode\n );\n\n if (((httpStatusCode < HttpStatus.SUCCESS_RANGE_START) || (httpStatusCode > HttpStatus.SUCCESS_RANGE_END)) &&\n // do not destroy the request for the device code flow\n networkResponse.body[\"error\"] !== Constants.AUTHORIZATION_PENDING) {\n request.destroy();\n }\n resolve(networkResponse);\n });\n\n socket.on(\"error\", (chunk) => {\n request.destroy();\n socket.destroy();\n reject(new Error(chunk.toString()));\n });\n });\n\n request.on(\"error\", (chunk) => {\n request.destroy();\n reject(new Error(chunk.toString()));\n });\n }));\n};\n\nconst networkRequestViaHttps = <T>(\n url: string,\n httpMethod: string,\n options?: NetworkRequestOptions,\n timeout?: number,\n): Promise<NetworkResponse<T>> => {\n const isPostRequest = httpMethod === HttpMethod.POST;\n const body: string = options?.body || \"\";\n\n const emptyHeaders: Record<string, string> = {};\n const customOptions: https.RequestOptions = {\n method: httpMethod,\n headers: options?.headers || emptyHeaders,\n };\n\n if (timeout) {\n customOptions.timeout = timeout;\n }\n\n if (isPostRequest) {\n // needed for post request to work\n customOptions.headers = {\n ...customOptions.headers,\n \"Content-Length\": body.length,\n };\n }\n\n return new Promise<NetworkResponse<T>>((resolve, reject) => {\n const request = https.request(url, customOptions);\n\n if (timeout) {\n request.on(\"timeout\", () => {\n request.destroy();\n reject(new Error(\"Request time out\"));\n });\n }\n\n if (isPostRequest) {\n request.write(body);\n }\n\n request.end();\n\n request.on(\"response\", (response) => {\n const headers = response.headers;\n const statusCode = response.statusCode as number;\n const statusMessage = response.statusMessage;\n\n const data: Buffer[] = [];\n response.on(\"data\", (chunk) => {\n data.push(chunk);\n });\n\n response.on(\"end\", () => {\n // combine all received buffer streams into one buffer, and then into a string\n const body = Buffer.concat([...data]).toString();\n\n const parsedHeaders = headers as Record<string, string>;\n const networkResponse = NetworkUtils.getNetworkResponse(\n parsedHeaders,\n parseBody(statusCode, statusMessage, parsedHeaders, body) as T,\n statusCode\n );\n\n if (((statusCode < HttpStatus.SUCCESS_RANGE_START) || (statusCode > HttpStatus.SUCCESS_RANGE_END)) &&\n // do not destroy the request for the device code flow\n networkResponse.body[\"error\"] !== Constants.AUTHORIZATION_PENDING) {\n request.destroy();\n }\n resolve(networkResponse);\n });\n });\n\n request.on(\"error\", (chunk) => {\n request.destroy();\n reject(new Error(chunk.toString()));\n });\n });\n};\n\n/**\n * Check if extra parsing is needed on the repsonse from the server\n * @param statusCode {number} the status code of the response from the server\n * @param statusMessage {string | undefined} the status message of the response from the server\n * @param headers {Record<string, string>} the headers of the response from the server\n * @param body {string} the body from the response of the server\n * @returns {Object} JSON parsed body or error object\n */\nconst parseBody = (statusCode: number, statusMessage: string | undefined, headers: Record<string, string>, body: string) => {\n /*\n * Informational responses (100 – 199)\n * Successful responses (200 – 299)\n * Redirection messages (300 – 399)\n * Client error responses (400 – 499)\n * Server error responses (500 – 599)\n */\n \n let parsedBody;\n try {\n parsedBody = JSON.parse(body);\n } catch (error) {\n let errorType;\n let errorDescriptionHelper;\n if ((statusCode >= HttpStatus.CLIENT_ERROR_RANGE_START) && (statusCode <= HttpStatus.CLIENT_ERROR_RANGE_END)) {\n errorType = \"client_error\";\n errorDescriptionHelper = \"A client\";\n } else if ((statusCode >= HttpStatus.SERVER_ERROR_RANGE_START) && (statusCode <= HttpStatus.SERVER_ERROR_RANGE_END)) {\n errorType = \"server_error\";\n errorDescriptionHelper = \"A server\";\n } else {\n errorType = \"unknown_error\";\n errorDescriptionHelper = \"An unknown\";\n }\n\n parsedBody = {\n error: errorType,\n error_description: `${errorDescriptionHelper} error occured.\\nHttp status code: ${statusCode}\\nHttp status message: ${statusMessage || \"Unknown\"}\\nHeaders: ${JSON.stringify(headers)}`\n };\n }\n\n return parsedBody;\n};\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n LoggerOptions,\n INetworkModule,\n LogLevel,\n ProtocolMode,\n ICachePlugin,\n Constants,\n AzureCloudInstance,\n AzureCloudOptions,\n ApplicationTelemetry\n} from \"@azure/msal-common\";\nimport { HttpClient } from \"../network/HttpClient\";\n\n/**\n * - clientId - Client id of the application.\n * - authority - Url of the authority. If no value is set, defaults to https://login.microsoftonline.com/common.\n * - knownAuthorities - Needed for Azure B2C and ADFS. All authorities that will be used in the client application. Only the host of the authority should be passed in.\n * - clientSecret - Secret string that the application uses when requesting a token. Only used in confidential client applications. Can be created in the Azure app registration portal.\n * - clientAssertion - Assertion string that the application uses when requesting a token. Only used in confidential client applications. Assertion should be of type urn:ietf:params:oauth:client-assertion-type:jwt-bearer.\n * - clientCertificate - Certificate that the application uses when requesting a token. Only used in confidential client applications. Requires hex encoded X.509 SHA-1 thumbprint of the certificiate, and the PEM encoded private key (string should contain -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- )\n * - protocolMode - Enum that represents the protocol that msal follows. Used for configuring proper endpoints.\n * - skipAuthorityMetadataCache - A flag to choose whether to use or not use the local metadata cache during authority initialization. Defaults to false.\n * @public\n */\nexport type NodeAuthOptions = {\n clientId: string;\n authority?: string;\n clientSecret?: string;\n clientAssertion?: string;\n clientCertificate?: {\n thumbprint: string,\n privateKey: string,\n x5c?: string\n };\n knownAuthorities?: Array<string>;\n cloudDiscoveryMetadata?: string;\n authorityMetadata?: string;\n clientCapabilities?: Array<string>;\n protocolMode?: ProtocolMode;\n azureCloudOptions?: AzureCloudOptions;\n skipAuthorityMetadataCache?: boolean;\n};\n\n/**\n * Use this to configure the below cache configuration options:\n *\n * - cachePlugin - Plugin for reading and writing token cache to disk.\n * @public\n */\nexport type CacheOptions = {\n cachePlugin?: ICachePlugin;\n};\n\n/**\n * Type for configuring logger and http client options\n *\n * - logger - Used to initialize the Logger object; TODO: Expand on logger details or link to the documentation on logger\n * - networkClient - Http client used for all http get and post calls. Defaults to using MSAL's default http client.\n * @public\n */\nexport type NodeSystemOptions = {\n loggerOptions?: LoggerOptions;\n networkClient?: INetworkModule;\n proxyUrl?: string;\n};\n\nexport type NodeTelemetryOptions = {\n application?: ApplicationTelemetry;\n};\n\n/**\n * Use the configuration object to configure MSAL and initialize the client application object\n *\n * - auth: this is where you configure auth elements like clientID, authority used for authenticating against the Microsoft Identity Platform\n * - cache: this is where you configure cache location\n * - system: this is where you can configure the network client, logger\n * @public\n */\nexport type Configuration = {\n auth: NodeAuthOptions;\n cache?: CacheOptions;\n system?: NodeSystemOptions;\n telemetry?: NodeTelemetryOptions;\n};\n\nconst DEFAULT_AUTH_OPTIONS: Required<NodeAuthOptions> = {\n clientId: Constants.EMPTY_STRING,\n authority: Constants.DEFAULT_AUTHORITY,\n clientSecret: Constants.EMPTY_STRING,\n clientAssertion: Constants.EMPTY_STRING,\n clientCertificate: {\n thumbprint: Constants.EMPTY_STRING,\n privateKey: Constants.EMPTY_STRING,\n x5c: Constants.EMPTY_STRING\n },\n knownAuthorities: [],\n cloudDiscoveryMetadata: Constants.EMPTY_STRING,\n authorityMetadata: Constants.EMPTY_STRING,\n clientCapabilities: [],\n protocolMode: ProtocolMode.AAD,\n azureCloudOptions: {\n azureCloudInstance: AzureCloudInstance.None,\n tenant: Constants.EMPTY_STRING\n },\n skipAuthorityMetadataCache: false,\n};\n\nconst DEFAULT_CACHE_OPTIONS: CacheOptions = {};\n\nconst DEFAULT_LOGGER_OPTIONS: LoggerOptions = {\n loggerCallback: (): void => {\n // allow users to not set logger call back\n },\n piiLoggingEnabled: false,\n logLevel: LogLevel.Info,\n};\n\nconst DEFAULT_SYSTEM_OPTIONS: Required<NodeSystemOptions> = {\n loggerOptions: DEFAULT_LOGGER_OPTIONS,\n networkClient: new HttpClient(),\n proxyUrl: Constants.EMPTY_STRING,\n};\n\nconst DEFAULT_TELEMETRY_OPTIONS: Required<NodeTelemetryOptions> = {\n application: {\n appName: Constants.EMPTY_STRING,\n appVersion: Constants.EMPTY_STRING\n }\n};\n\nexport type NodeConfiguration = {\n auth: Required<NodeAuthOptions>;\n cache: CacheOptions;\n system: Required<NodeSystemOptions>;\n telemetry: Required<NodeTelemetryOptions>;\n};\n\n/**\n * Sets the default options when not explicitly configured from app developer\n *\n * @param auth - Authentication options\n * @param cache - Cache options\n * @param system - System options\n * @param telemetry - Telemetry options\n *\n * @returns Configuration\n * @public\n */\nexport function buildAppConfiguration({\n auth,\n cache,\n system,\n telemetry\n}: Configuration): NodeConfiguration {\n\n return {\n auth: { ...DEFAULT_AUTH_OPTIONS, ...auth },\n cache: { ...DEFAULT_CACHE_OPTIONS, ...cache },\n system: { ...DEFAULT_SYSTEM_OPTIONS, ...system },\n telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry }\n };\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IGuidGenerator } from \"@azure/msal-common\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nexport class GuidGenerator implements IGuidGenerator {\n /**\n *\n * RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers.\n * uuidv4 generates guids from cryprtographically-string random\n */\n generateGuid(): string {\n return uuidv4();\n }\n\n /**\n * verifies if a string is GUID\n * @param guid\n */\n isGuid(guid: string): boolean {\n const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return regexGuid.test(guid);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants } from \"@azure/msal-common\";\n\nexport class EncodingUtils {\n /**\n * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.\n * 'base64': Base64 encoding.\n *\n * @param str text\n */\n static base64Encode(str: string, encoding?: BufferEncoding): string {\n return Buffer.from(str, encoding).toString(\"base64\");\n }\n\n /**\n * encode a URL\n * @param str\n */\n static base64EncodeUrl(str: string, encoding?: BufferEncoding): string {\n return EncodingUtils.base64Encode(str, encoding)\n .replace(/=/g, Constants.EMPTY_STRING)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\");\n }\n\n /**\n * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.\n * 'base64': Base64 encoding.\n *\n * @param base64Str Base64 encoded text\n */\n static base64Decode(base64Str: string): string {\n return Buffer.from(base64Str, \"base64\").toString(\"utf8\");\n }\n\n /**\n * @param base64Str Base64 encoded Url\n */\n static base64DecodeUrl(base64Str: string): string {\n let str = base64Str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (str.length % 4) {\n str += \"=\";\n }\n return EncodingUtils.base64Decode(str);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Hash } from \"../utils/Constants\";\nimport crypto from \"crypto\";\n\nexport class HashUtils {\n /**\n * generate 'SHA256' hash\n * @param buffer\n */\n sha256(buffer: string): Buffer {\n return crypto\n .createHash(Hash.SHA256)\n .update(buffer)\n .digest();\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants, PkceCodes } from \"@azure/msal-common\";\nimport { CharSet, RANDOM_OCTET_SIZE } from \"../utils/Constants\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\nimport { HashUtils } from \"./HashUtils\";\nimport crypto from \"crypto\";\n\n/**\n * https://tools.ietf.org/html/rfc7636#page-8\n */\nexport class PkceGenerator {\n private hashUtils: HashUtils;\n\n constructor() {\n this.hashUtils = new HashUtils();\n }\n /**\n * generates the codeVerfier and the challenge from the codeVerfier\n * reference: https://tools.ietf.org/html/rfc7636#section-4.1 and https://tools.ietf.org/html/rfc7636#section-4.2\n */\n async generatePkceCodes(): Promise<PkceCodes> {\n const verifier = this.generateCodeVerifier();\n const challenge = this.generateCodeChallengeFromVerifier(verifier);\n return { verifier, challenge };\n }\n\n /**\n * generates the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.1\n */\n private generateCodeVerifier(): string {\n const charArr = [];\n const maxNumber = 256 - (256 % CharSet.CV_CHARSET.length);\n while (charArr.length <= RANDOM_OCTET_SIZE) {\n const byte = crypto.randomBytes(1)[0];\n if (byte >= maxNumber) {\n /* \n * Ignore this number to maintain randomness.\n * Including it would result in an unequal distribution of characters after doing the modulo\n */\n continue;\n }\n const index = byte % CharSet.CV_CHARSET.length;\n charArr.push(CharSet.CV_CHARSET[index]);\n }\n const verifier: string = charArr.join(Constants.EMPTY_STRING);\n return EncodingUtils.base64EncodeUrl(verifier);\n }\n\n /**\n * generate the challenge from the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.2\n * @param codeVerifier\n */\n private generateCodeChallengeFromVerifier(codeVerifier: string): string {\n return EncodingUtils.base64EncodeUrl(\n this.hashUtils.sha256(codeVerifier).toString(\"base64\"), \n \"base64\" \n );\n }\n\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ICrypto, PkceCodes } from \"@azure/msal-common\";\nimport { GuidGenerator } from \"./GuidGenerator\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\nimport { PkceGenerator } from \"./PkceGenerator\";\nimport { HashUtils } from \"./HashUtils\";\n\n/**\n * This class implements MSAL node's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and\n * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).\n * @public\n */\nexport class CryptoProvider implements ICrypto {\n private pkceGenerator: PkceGenerator;\n private guidGenerator: GuidGenerator;\n private hashUtils: HashUtils;\n\n constructor() {\n // Browser crypto needs to be validated first before any other classes can be set.\n this.pkceGenerator = new PkceGenerator();\n this.guidGenerator = new GuidGenerator();\n this.hashUtils = new HashUtils();\n }\n\n /**\n * Creates a new random GUID - used to populate state and nonce.\n * @returns string (GUID)\n */\n createNewGuid(): string {\n return this.guidGenerator.generateGuid();\n }\n\n /**\n * Encodes input string to base64.\n * @param input - string to be encoded\n */\n base64Encode(input: string): string {\n return EncodingUtils.base64Encode(input);\n }\n\n /**\n * Decodes input string from base64.\n * @param input - string to be decoded\n */\n base64Decode(input: string): string {\n return EncodingUtils.base64Decode(input);\n }\n\n /**\n * Generates PKCE codes used in Authorization Code Flow.\n */\n generatePkceCodes(): Promise<PkceCodes> {\n return this.pkceGenerator.generatePkceCodes();\n }\n\n /**\n * Generates a keypair, stores it and returns a thumbprint - not yet implemented for node\n */\n getPublicKeyThumbprint(): Promise<string> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Removes cryptographic keypair from key store matching the keyId passed in\n * @param kid \n */\n removeTokenBindingKey(): Promise<boolean> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Removes all cryptographic keys from Keystore\n */\n clearKeystore(): Promise<boolean> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node\n */\n signJwt(): Promise<string> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Returns the SHA-256 hash of an input string\n */\n async hashString(plainText: string): Promise<string> {\n return EncodingUtils.base64EncodeUrl(\n this.hashUtils.sha256(plainText).toString(\"base64\"), \n \"base64\" \n );\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { StringUtils, AccountCache, IdTokenCache, AccessTokenCache, RefreshTokenCache, AppMetadataCache, AccountEntity, IdTokenEntity, AccessTokenEntity, RefreshTokenEntity, AppMetadataEntity, CacheManager } from \"@azure/msal-common\";\nimport { JsonCache, InMemoryCache, SerializedAccountEntity, SerializedIdTokenEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedAppMetadataEntity } from \"./SerializerTypes\";\n\n/**\n * This class deserializes cache entities read from the file into in memory object types defined internally\n */\nexport class Deserializer {\n /**\n * Parse the JSON blob in memory and deserialize the content\n * @param cachedJson\n */\n static deserializeJSONBlob(jsonFile: string): JsonCache {\n const deserializedCache = StringUtils.isEmpty(jsonFile)\n ? {}\n : JSON.parse(jsonFile);\n return deserializedCache;\n }\n\n /**\n * Deserializes accounts to AccountEntity objects\n * @param accounts\n */\n static deserializeAccounts(accounts: Record<string, SerializedAccountEntity>): AccountCache {\n const accountObjects: AccountCache = {};\n if (accounts) {\n Object.keys(accounts).map(function (key) {\n const serializedAcc = accounts[key];\n const mappedAcc = {\n homeAccountId: serializedAcc.home_account_id,\n environment: serializedAcc.environment,\n realm: serializedAcc.realm,\n localAccountId: serializedAcc.local_account_id,\n username: serializedAcc.username,\n authorityType: serializedAcc.authority_type,\n name: serializedAcc.name,\n clientInfo: serializedAcc.client_info,\n lastModificationTime: serializedAcc.last_modification_time,\n lastModificationApp: serializedAcc.last_modification_app,\n };\n const account: AccountEntity = new AccountEntity();\n CacheManager.toObject(account, mappedAcc);\n accountObjects[key] = account;\n });\n }\n\n return accountObjects;\n }\n\n /**\n * Deserializes id tokens to IdTokenEntity objects\n * @param idTokens\n */\n static deserializeIdTokens(idTokens: Record<string, SerializedIdTokenEntity>): IdTokenCache {\n const idObjects: IdTokenCache = {};\n if (idTokens) {\n Object.keys(idTokens).map(function (key) {\n const serializedIdT = idTokens[key];\n const mappedIdT = {\n homeAccountId: serializedIdT.home_account_id,\n environment: serializedIdT.environment,\n credentialType: serializedIdT.credential_type,\n clientId: serializedIdT.client_id,\n secret: serializedIdT.secret,\n realm: serializedIdT.realm,\n };\n const idToken: IdTokenEntity = new IdTokenEntity();\n CacheManager.toObject(idToken, mappedIdT);\n idObjects[key] = idToken;\n });\n }\n return idObjects;\n }\n\n /**\n * Deserializes access tokens to AccessTokenEntity objects\n * @param accessTokens\n */\n static deserializeAccessTokens(accessTokens: Record<string, SerializedAccessTokenEntity>): AccessTokenCache {\n const atObjects: AccessTokenCache = {};\n if (accessTokens) {\n Object.keys(accessTokens).map(function (key) {\n const serializedAT = accessTokens[key];\n const mappedAT = {\n homeAccountId: serializedAT.home_account_id,\n environment: serializedAT.environment,\n credentialType: serializedAT.credential_type,\n clientId: serializedAT.client_id,\n secret: serializedAT.secret,\n realm: serializedAT.realm,\n target: serializedAT.target,\n cachedAt: serializedAT.cached_at,\n expiresOn: serializedAT.expires_on,\n extendedExpiresOn: serializedAT.extended_expires_on,\n refreshOn: serializedAT.refresh_on,\n keyId: serializedAT.key_id,\n tokenType: serializedAT.token_type,\n requestedClaims: serializedAT.requestedClaims,\n requestedClaimsHash: serializedAT.requestedClaimsHash,\n userAssertionHash: serializedAT.userAssertionHash,\n };\n const accessToken: AccessTokenEntity = new AccessTokenEntity();\n CacheManager.toObject(accessToken, mappedAT);\n atObjects[key] = accessToken;\n });\n }\n\n return atObjects;\n }\n\n /**\n * Deserializes refresh tokens to RefreshTokenEntity objects\n * @param refreshTokens\n */\n static deserializeRefreshTokens(refreshTokens: Record<string, SerializedRefreshTokenEntity>): RefreshTokenCache {\n const rtObjects: RefreshTokenCache = {};\n if (refreshTokens) {\n Object.keys(refreshTokens).map(function (key) {\n const serializedRT = refreshTokens[key];\n const mappedRT = {\n homeAccountId: serializedRT.home_account_id,\n environment: serializedRT.environment,\n credentialType: serializedRT.credential_type,\n clientId: serializedRT.client_id,\n secret: serializedRT.secret,\n familyId: serializedRT.family_id,\n target: serializedRT.target,\n realm: serializedRT.realm,\n };\n const refreshToken: RefreshTokenEntity = new RefreshTokenEntity();\n CacheManager.toObject(refreshToken, mappedRT);\n rtObjects[key] = refreshToken;\n });\n }\n\n return rtObjects;\n }\n\n /**\n * Deserializes appMetadata to AppMetaData objects\n * @param appMetadata\n */\n static deserializeAppMetadata(appMetadata: Record<string, SerializedAppMetadataEntity>): AppMetadataCache {\n const appMetadataObjects: AppMetadataCache = {};\n if (appMetadata) {\n Object.keys(appMetadata).map(function (key) {\n const serializedAmdt = appMetadata[key];\n const mappedAmd = {\n clientId: serializedAmdt.client_id,\n environment: serializedAmdt.environment,\n familyId: serializedAmdt.family_id,\n };\n const amd: AppMetadataEntity = new AppMetadataEntity();\n CacheManager.toObject(amd, mappedAmd);\n appMetadataObjects[key] = amd;\n });\n }\n\n return appMetadataObjects;\n }\n\n /**\n * Deserialize an inMemory Cache\n * @param jsonCache\n */\n static deserializeAllCache(jsonCache: JsonCache): InMemoryCache {\n return {\n accounts: jsonCache.Account\n ? this.deserializeAccounts(jsonCache.Account)\n : {},\n idTokens: jsonCache.IdToken\n ? this.deserializeIdTokens(jsonCache.IdToken)\n : {},\n accessTokens: jsonCache.AccessToken\n ? this.deserializeAccessTokens(jsonCache.AccessToken)\n : {},\n refreshTokens: jsonCache.RefreshToken\n ? this.deserializeRefreshTokens(jsonCache.RefreshToken)\n : {},\n appMetadata: jsonCache.AppMetadata\n ? this.deserializeAppMetadata(jsonCache.AppMetadata)\n : {},\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AccountCache, IdTokenCache, AccessTokenCache, RefreshTokenCache, AppMetadataCache } from \"@azure/msal-common\";\nimport { InMemoryCache, JsonCache, SerializedAccountEntity, SerializedIdTokenEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedAppMetadataEntity } from \"./SerializerTypes\";\n\nexport class Serializer {\n /**\n * serialize the JSON blob\n * @param data\n */\n static serializeJSONBlob(data: JsonCache): string {\n return JSON.stringify(data);\n }\n\n /**\n * Serialize Accounts\n * @param accCache\n */\n static serializeAccounts(accCache: AccountCache): Record<string, SerializedAccountEntity> {\n const accounts: Record<string, SerializedAccountEntity> = {};\n Object.keys(accCache).map(function (key) {\n const accountEntity = accCache[key];\n accounts[key] = {\n home_account_id: accountEntity.homeAccountId,\n environment: accountEntity.environment,\n realm: accountEntity.realm,\n local_account_id: accountEntity.localAccountId,\n username: accountEntity.username,\n authority_type: accountEntity.authorityType,\n name: accountEntity.name,\n client_info: accountEntity.clientInfo,\n last_modification_time: accountEntity.lastModificationTime,\n last_modification_app: accountEntity.lastModificationApp,\n };\n });\n\n return accounts;\n }\n\n /**\n * Serialize IdTokens\n * @param idTCache\n */\n static serializeIdTokens(idTCache: IdTokenCache): Record<string, SerializedIdTokenEntity> {\n const idTokens: Record<string, SerializedIdTokenEntity> = {};\n Object.keys(idTCache).map(function (key) {\n const idTEntity = idTCache[key];\n idTokens[key] = {\n home_account_id: idTEntity.homeAccountId,\n environment: idTEntity.environment,\n credential_type: idTEntity.credentialType,\n client_id: idTEntity.clientId,\n secret: idTEntity.secret,\n realm: idTEntity.realm,\n };\n });\n\n return idTokens;\n }\n\n /**\n * Serializes AccessTokens\n * @param atCache\n */\n static serializeAccessTokens(atCache: AccessTokenCache): Record<string, SerializedAccessTokenEntity> {\n const accessTokens: Record<string, SerializedAccessTokenEntity> = {};\n Object.keys(atCache).map(function (key) {\n const atEntity = atCache[key];\n accessTokens[key] = {\n home_account_id: atEntity.homeAccountId,\n environment: atEntity.environment,\n credential_type: atEntity.credentialType,\n client_id: atEntity.clientId,\n secret: atEntity.secret,\n realm: atEntity.realm,\n target: atEntity.target,\n cached_at: atEntity.cachedAt,\n expires_on: atEntity.expiresOn,\n extended_expires_on: atEntity.extendedExpiresOn,\n refresh_on: atEntity.refreshOn,\n key_id: atEntity.keyId,\n token_type: atEntity.tokenType,\n requestedClaims: atEntity.requestedClaims,\n requestedClaimsHash: atEntity.requestedClaimsHash,\n userAssertionHash: atEntity.userAssertionHash\n };\n });\n\n return accessTokens;\n }\n\n /**\n * Serialize refreshTokens\n * @param rtCache\n */\n static serializeRefreshTokens(rtCache: RefreshTokenCache): Record<string, SerializedRefreshTokenEntity> {\n const refreshTokens: Record<string, SerializedRefreshTokenEntity> = {};\n Object.keys(rtCache).map(function (key) {\n const rtEntity = rtCache[key];\n refreshTokens[key] = {\n home_account_id: rtEntity.homeAccountId,\n environment: rtEntity.environment,\n credential_type: rtEntity.credentialType,\n client_id: rtEntity.clientId,\n secret: rtEntity.secret,\n family_id: rtEntity.familyId,\n target: rtEntity.target,\n realm: rtEntity.realm\n };\n });\n\n return refreshTokens;\n }\n\n /**\n * Serialize amdtCache\n * @param amdtCache\n */\n static serializeAppMetadata(amdtCache: AppMetadataCache): Record<string, SerializedAppMetadataEntity> {\n const appMetadata: Record<string, SerializedAppMetadataEntity> = {};\n Object.keys(amdtCache).map(function (key) {\n const amdtEntity = amdtCache[key];\n appMetadata[key] = {\n client_id: amdtEntity.clientId,\n environment: amdtEntity.environment,\n family_id: amdtEntity.familyId,\n };\n });\n\n return appMetadata;\n }\n\n /**\n * Serialize the cache\n * @param jsonContent\n */\n static serializeAllCache(inMemCache: InMemoryCache): JsonCache {\n return {\n Account: this.serializeAccounts(inMemCache.accounts),\n IdToken: this.serializeIdTokens(inMemCache.idTokens),\n AccessToken: this.serializeAccessTokens(inMemCache.accessTokens),\n RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens),\n AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata),\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AccountEntity,\n IdTokenEntity,\n AccessTokenEntity,\n RefreshTokenEntity,\n AppMetadataEntity,\n ServerTelemetryEntity,\n ThrottlingEntity,\n CacheManager,\n Logger,\n ValidCacheType,\n ICrypto,\n AuthorityMetadataEntity,\n ValidCredentialType\n} from \"@azure/msal-common\";\nimport { Deserializer } from \"./serializer/Deserializer\";\nimport { Serializer } from \"./serializer/Serializer\";\nimport { InMemoryCache, JsonCache, CacheKVStore } from \"./serializer/SerializerTypes\";\n\n/**\n * This class implements Storage for node, reading cache from user specified storage location or an extension library\n * @public\n */\nexport class NodeStorage extends CacheManager {\n // Cache configuration, either set by user or default values.\n private logger: Logger;\n private cache: CacheKVStore = {};\n private changeEmitters: Array<Function> = [];\n\n constructor(logger: Logger, clientId: string, cryptoImpl: ICrypto) {\n super(clientId, cryptoImpl);\n this.logger = logger;\n }\n\n /**\n * Queue up callbacks\n * @param func - a callback function for cache change indication\n */\n registerChangeEmitter(func: () => void): void {\n this.changeEmitters.push(func);\n }\n\n /**\n * Invoke the callback when cache changes\n */\n emitChange(): void {\n this.changeEmitters.forEach(func => func.call(null));\n }\n\n /**\n * Converts cacheKVStore to InMemoryCache\n * @param cache - key value store\n */\n cacheToInMemoryCache(cache: CacheKVStore): InMemoryCache {\n const inMemoryCache: InMemoryCache = {\n accounts: {},\n idTokens: {},\n accessTokens: {},\n refreshTokens: {},\n appMetadata: {},\n };\n\n for (const key in cache) {\n if (cache[key as string] instanceof AccountEntity) {\n inMemoryCache.accounts[key] = cache[key] as AccountEntity;\n } else if (cache[key] instanceof IdTokenEntity) {\n inMemoryCache.idTokens[key] = cache[key] as IdTokenEntity;\n } else if (cache[key] instanceof AccessTokenEntity) {\n inMemoryCache.accessTokens[key] = cache[key] as AccessTokenEntity;\n } else if (cache[key] instanceof RefreshTokenEntity) {\n inMemoryCache.refreshTokens[key] = cache[key] as RefreshTokenEntity;\n } else if (cache[key] instanceof AppMetadataEntity) {\n inMemoryCache.appMetadata[key] = cache[key] as AppMetadataEntity;\n } else {\n continue;\n }\n }\n\n return inMemoryCache;\n }\n\n /**\n * converts inMemoryCache to CacheKVStore\n * @param inMemoryCache - kvstore map for inmemory\n */\n inMemoryCacheToCache(inMemoryCache: InMemoryCache): CacheKVStore {\n\n // convert in memory cache to a flat Key-Value map\n let cache = this.getCache();\n\n cache = {\n ...cache,\n ...inMemoryCache.accounts,\n ...inMemoryCache.idTokens,\n ...inMemoryCache.accessTokens,\n ...inMemoryCache.refreshTokens,\n ...inMemoryCache.appMetadata\n };\n\n // convert in memory cache to a flat Key-Value map\n return cache;\n }\n\n /**\n * gets the current in memory cache for the client\n */\n getInMemoryCache(): InMemoryCache {\n this.logger.trace(\"Getting in-memory cache\");\n\n // convert the cache key value store to inMemoryCache\n const inMemoryCache = this.cacheToInMemoryCache(this.getCache());\n return inMemoryCache;\n }\n\n /**\n * sets the current in memory cache for the client\n * @param inMemoryCache - key value map in memory\n */\n setInMemoryCache(inMemoryCache: InMemoryCache): void{\n this.logger.trace(\"Setting in-memory cache\");\n\n // convert and append the inMemoryCache to cacheKVStore\n const cache = this.inMemoryCacheToCache(inMemoryCache);\n this.setCache(cache);\n\n this.emitChange();\n }\n\n /**\n * get the current cache key-value store\n */\n getCache(): CacheKVStore {\n this.logger.trace(\"Getting cache key-value store\");\n return this.cache;\n }\n\n /**\n * sets the current cache (key value store)\n * @param cacheMap - key value map\n */\n setCache(cache: CacheKVStore): void {\n this.logger.trace(\"Setting cache key value store\");\n this.cache = cache;\n\n // mark change in cache\n this.emitChange();\n }\n\n /**\n * Gets cache item with given key.\n * @param key - lookup key for the cache entry\n */\n getItem(key: string): ValidCacheType {\n this.logger.tracePii(`Item key: ${key}`);\n\n // read cache\n const cache = this.getCache();\n return cache[key];\n }\n\n /**\n * Gets cache item with given key-value\n * @param key - lookup key for the cache entry\n * @param value - value of the cache entry\n */\n setItem(key: string, value: ValidCacheType): void {\n this.logger.tracePii(`Item key: ${key}`);\n\n // read cache\n const cache = this.getCache();\n cache[key] = value;\n\n // write to cache\n this.setCache(cache);\n }\n\n /**\n * fetch the account entity\n * @param accountKey - lookup key to fetch cache type AccountEntity\n */\n getAccount(accountKey: string): AccountEntity | null {\n const account = this.getItem(accountKey) as AccountEntity;\n if (AccountEntity.isAccountEntity(account)) {\n return account;\n }\n return null;\n }\n\n /**\n * set account entity\n * @param account - cache value to be set of type AccountEntity\n */\n setAccount(account: AccountEntity): void {\n const accountKey = account.generateAccountKey();\n this.setItem(accountKey, account);\n }\n\n /**\n * fetch the idToken credential\n * @param idTokenKey - lookup key to fetch cache type IdTokenEntity\n */\n getIdTokenCredential(idTokenKey: string): IdTokenEntity | null {\n const idToken = this.getItem(idTokenKey) as IdTokenEntity;\n if (IdTokenEntity.isIdTokenEntity(idToken)) {\n return idToken;\n }\n return null;\n }\n\n /**\n * set idToken credential\n * @param idToken - cache value to be set of type IdTokenEntity\n */\n setIdTokenCredential(idToken: IdTokenEntity): void {\n const idTokenKey = idToken.generateCredentialKey();\n this.setItem(idTokenKey, idToken);\n }\n\n /**\n * fetch the accessToken credential\n * @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity\n */\n getAccessTokenCredential(accessTokenKey: string): AccessTokenEntity | null {\n const accessToken = this.getItem(accessTokenKey) as AccessTokenEntity;\n if (AccessTokenEntity.isAccessTokenEntity(accessToken)) {\n return accessToken;\n }\n return null;\n }\n\n /**\n * set accessToken credential\n * @param accessToken - cache value to be set of type AccessTokenEntity\n */\n setAccessTokenCredential(accessToken: AccessTokenEntity): void {\n const accessTokenKey = accessToken.generateCredentialKey();\n this.setItem(accessTokenKey, accessToken);\n }\n\n /**\n * fetch the refreshToken credential\n * @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity\n */\n getRefreshTokenCredential(refreshTokenKey: string): RefreshTokenEntity | null {\n const refreshToken = this.getItem(refreshTokenKey) as RefreshTokenEntity;\n if (RefreshTokenEntity.isRefreshTokenEntity(refreshToken)) {\n return refreshToken as RefreshTokenEntity;\n }\n return null;\n }\n\n /**\n * set refreshToken credential\n * @param refreshToken - cache value to be set of type RefreshTokenEntity\n */\n setRefreshTokenCredential(refreshToken: RefreshTokenEntity): void {\n const refreshTokenKey = refreshToken.generateCredentialKey();\n this.setItem(refreshTokenKey, refreshToken);\n }\n\n /**\n * fetch appMetadata entity from the platform cache\n * @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity\n */\n getAppMetadata(appMetadataKey: string): AppMetadataEntity | null {\n const appMetadata: AppMetadataEntity = this.getItem(appMetadataKey) as AppMetadataEntity;\n if (AppMetadataEntity.isAppMetadataEntity(appMetadataKey, appMetadata)) {\n return appMetadata;\n }\n return null;\n }\n\n /**\n * set appMetadata entity to the platform cache\n * @param appMetadata - cache value to be set of type AppMetadataEntity\n */\n setAppMetadata(appMetadata: AppMetadataEntity): void {\n const appMetadataKey = appMetadata.generateAppMetadataKey();\n this.setItem(appMetadataKey, appMetadata);\n }\n\n /**\n * fetch server telemetry entity from the platform cache\n * @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity\n */\n getServerTelemetry(serverTelemetrykey: string): ServerTelemetryEntity | null {\n const serverTelemetryEntity: ServerTelemetryEntity = this.getItem(serverTelemetrykey) as ServerTelemetryEntity;\n if (serverTelemetryEntity && ServerTelemetryEntity.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) {\n return serverTelemetryEntity;\n }\n return null;\n }\n\n /**\n * set server telemetry entity to the platform cache\n * @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity\n * @param serverTelemetry - cache value to be set of type ServerTelemetryEntity\n */\n setServerTelemetry(serverTelemetryKey: string, serverTelemetry: ServerTelemetryEntity): void {\n this.setItem(serverTelemetryKey, serverTelemetry);\n }\n\n /**\n * fetch authority metadata entity from the platform cache\n * @param key - lookup key to fetch cache type AuthorityMetadataEntity\n */\n getAuthorityMetadata(key: string): AuthorityMetadataEntity | null {\n const authorityMetadataEntity: AuthorityMetadataEntity = this.getItem(key) as AuthorityMetadataEntity;\n if (authorityMetadataEntity && AuthorityMetadataEntity.isAuthorityMetadataEntity(key, authorityMetadataEntity)) {\n return authorityMetadataEntity;\n }\n return null;\n }\n\n /**\n * Get all authority metadata keys\n */\n getAuthorityMetadataKeys(): Array<string> {\n return this.getKeys().filter((key) => {\n return this.isAuthorityMetadata(key);\n });\n }\n\n /**\n * set authority metadata entity to the platform cache\n * @param key - lookup key to fetch cache type AuthorityMetadataEntity\n * @param metadata - cache value to be set of type AuthorityMetadataEntity\n */\n setAuthorityMetadata(key: string, metadata: AuthorityMetadataEntity): void {\n this.setItem(key, metadata);\n }\n\n /**\n * fetch throttling entity from the platform cache\n * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity\n */\n getThrottlingCache(throttlingCacheKey: string): ThrottlingEntity | null {\n const throttlingCache: ThrottlingEntity = this.getItem(throttlingCacheKey) as ThrottlingEntity;\n if (throttlingCache && ThrottlingEntity.isThrottlingEntity(throttlingCacheKey, throttlingCache)) {\n return throttlingCache;\n }\n return null;\n }\n\n /**\n * set throttling entity to the platform cache\n * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity\n * @param throttlingCache - cache value to be set of type ThrottlingEntity\n */\n setThrottlingCache(throttlingCacheKey: string, throttlingCache: ThrottlingEntity): void {\n this.setItem(throttlingCacheKey, throttlingCache);\n }\n\n /**\n * Removes the cache item from memory with the given key.\n * @param key - lookup key to remove a cache entity\n * @param inMemory - key value map of the cache\n */\n removeItem(key: string): boolean {\n this.logger.tracePii(`Item key: ${key}`);\n\n // read inMemoryCache\n let result: boolean = false;\n const cache = this.getCache();\n\n if (!!cache[key]) {\n delete cache[key];\n result = true;\n }\n\n // write to the cache after removal\n if (result) {\n this.setCache(cache);\n this.emitChange();\n }\n return result;\n }\n\n /**\n * Checks whether key is in cache.\n * @param key - look up key for a cache entity\n */\n containsKey(key: string): boolean {\n return this.getKeys().includes(key);\n }\n\n /**\n * Gets all keys in window.\n */\n getKeys(): string[] {\n this.logger.trace(\"Retrieving all cache keys\");\n\n // read cache\n const cache = this.getCache();\n return [ ...Object.keys(cache)];\n }\n\n /**\n * Clears all cache entries created by MSAL (except tokens).\n */\n async clear(): Promise<void> {\n this.logger.trace(\"Clearing cache entries created by MSAL\");\n\n // read inMemoryCache\n const cacheKeys = this.getKeys();\n\n // delete each element\n cacheKeys.forEach(key => {\n this.removeItem(key);\n });\n this.emitChange();\n }\n\n /**\n * Initialize in memory cache from an exisiting cache vault\n * @param cache - blob formatted cache (JSON)\n */\n static generateInMemoryCache(cache: string): InMemoryCache {\n return Deserializer.deserializeAllCache(\n Deserializer.deserializeJSONBlob(cache)\n );\n }\n\n /**\n * retrieves the final JSON\n * @param inMemoryCache - itemised cache read from the JSON\n */\n static generateJsonCache(inMemoryCache: InMemoryCache): JsonCache {\n return Serializer.serializeAllCache(inMemoryCache);\n }\n\n /**\n * Updates a credential's cache key if the current cache key is outdated\n */\n updateCredentialCacheKey(currentCacheKey: string, credential: ValidCredentialType): string {\n const updatedCacheKey = credential.generateCredentialKey();\n\n if (currentCacheKey !== updatedCacheKey) {\n const cacheItem = this.getItem(currentCacheKey);\n if (cacheItem) {\n this.removeItem(currentCacheKey);\n this.setItem(updatedCacheKey, cacheItem);\n this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`);\n return updatedCacheKey;\n } else {\n this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`);\n }\n }\n\n return currentCacheKey;\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NodeStorage } from \"./NodeStorage\";\nimport { StringUtils, AccountEntity, AccountInfo, Logger, ISerializableTokenCache, ICachePlugin, TokenCacheContext } from \"@azure/msal-common\";\nimport { InMemoryCache, JsonCache, SerializedAccountEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedIdTokenEntity, SerializedAppMetadataEntity, CacheKVStore } from \"./serializer/SerializerTypes\";\nimport { Deserializer } from \"./serializer/Deserializer\";\nimport { Serializer } from \"./serializer/Serializer\";\nimport { ITokenCache } from \"./ITokenCache\";\n\nconst defaultSerializedCache: JsonCache = {\n Account: {},\n IdToken: {},\n AccessToken: {},\n RefreshToken: {},\n AppMetadata: {},\n};\n\n/**\n * In-memory token cache manager\n * @public\n */\nexport class TokenCache implements ISerializableTokenCache, ITokenCache {\n\n private storage: NodeStorage;\n private cacheHasChanged: boolean;\n private cacheSnapshot: string;\n private readonly persistence: ICachePlugin;\n private logger: Logger;\n\n constructor(storage: NodeStorage, logger: Logger, cachePlugin?: ICachePlugin) {\n this.cacheHasChanged = false;\n this.storage = storage;\n this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this));\n if (cachePlugin) {\n this.persistence = cachePlugin;\n }\n this.logger = logger;\n }\n\n /**\n * Set to true if cache state has changed since last time serialize or writeToPersistence was called\n */\n hasChanged(): boolean {\n return this.cacheHasChanged;\n }\n\n /**\n * Serializes in memory cache to JSON\n */\n serialize(): string {\n this.logger.trace(\"Serializing in-memory cache\");\n let finalState = Serializer.serializeAllCache(\n this.storage.getInMemoryCache() as InMemoryCache\n );\n\n // if cacheSnapshot not null or empty, merge\n if (!StringUtils.isEmpty(this.cacheSnapshot)) {\n this.logger.trace(\"Reading cache snapshot from disk\");\n finalState = this.mergeState(\n JSON.parse(this.cacheSnapshot),\n finalState\n );\n } else {\n this.logger.trace(\"No cache snapshot to merge\");\n }\n this.cacheHasChanged = false;\n\n return JSON.stringify(finalState);\n }\n\n /**\n * Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format\n * @param cache - blob formatted cache\n */\n deserialize(cache: string): void {\n this.logger.trace(\"Deserializing JSON to in-memory cache\");\n this.cacheSnapshot = cache;\n\n if (!StringUtils.isEmpty(this.cacheSnapshot)) {\n this.logger.trace(\"Reading cache snapshot from disk\");\n const deserializedCache = Deserializer.deserializeAllCache(\n this.overlayDefaults(JSON.parse(this.cacheSnapshot))\n );\n this.storage.setInMemoryCache(deserializedCache);\n } else {\n this.logger.trace(\"No cache snapshot to deserialize\");\n }\n }\n\n /**\n * Fetches the cache key-value map\n */\n getKVStore(): CacheKVStore {\n return this.storage.getCache();\n }\n\n /**\n * API that retrieves all accounts currently in cache to the user\n */\n async getAllAccounts(): Promise<AccountInfo[]> {\n\n this.logger.trace(\"getAllAccounts called\");\n let cacheContext;\n try {\n if (this.persistence) {\n cacheContext = new TokenCacheContext(this, false);\n await this.persistence.beforeCacheAccess(cacheContext);\n }\n return this.storage.getAllAccounts();\n } finally {\n if (this.persistence && cacheContext) {\n await this.persistence.afterCacheAccess(cacheContext);\n }\n }\n }\n\n /**\n * Returns the signed in account matching homeAccountId.\n * (the account object is created at the time of successful login)\n * or null when no matching account is found\n * @param homeAccountId - unique identifier for an account (uid.utid)\n */\n async getAccountByHomeId(homeAccountId: string): Promise<AccountInfo | null> {\n const allAccounts = await this.getAllAccounts();\n if (!StringUtils.isEmpty(homeAccountId) && allAccounts && allAccounts.length) {\n return allAccounts.filter(accountObj => accountObj.homeAccountId === homeAccountId)[0] || null;\n } else {\n return null;\n }\n }\n\n /**\n * Returns the signed in account matching localAccountId.\n * (the account object is created at the time of successful login)\n * or null when no matching account is found\n * @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated)\n */\n async getAccountByLocalId(localAccountId: string): Promise<AccountInfo | null> {\n const allAccounts = await this.getAllAccounts();\n if (!StringUtils.isEmpty(localAccountId) && allAccounts && allAccounts.length) {\n return allAccounts.filter(accountObj => accountObj.localAccountId === localAccountId)[0] || null;\n } else {\n return null;\n }\n }\n\n /**\n * API to remove a specific account and the relevant data from cache\n * @param account - AccountInfo passed by the user\n */\n async removeAccount(account: AccountInfo): Promise<void> {\n this.logger.trace(\"removeAccount called\");\n let cacheContext;\n try {\n if (this.persistence) {\n cacheContext = new TokenCacheContext(this, true);\n await this.persistence.beforeCacheAccess(cacheContext);\n }\n await this.storage.removeAccount(AccountEntity.generateAccountCacheKey(account));\n } finally {\n if (this.persistence && cacheContext) {\n await this.persistence.afterCacheAccess(cacheContext);\n }\n }\n }\n\n /**\n * Called when the cache has changed state.\n */\n private handleChangeEvent() {\n this.cacheHasChanged = true;\n }\n\n /**\n * Merge in memory cache with the cache snapshot.\n * @param oldState - cache before changes\n * @param currentState - current cache state in the library\n */\n private mergeState(oldState: JsonCache, currentState: JsonCache): JsonCache {\n this.logger.trace(\"Merging in-memory cache with cache snapshot\");\n const stateAfterRemoval = this.mergeRemovals(oldState, currentState);\n return this.mergeUpdates(stateAfterRemoval, currentState);\n }\n\n /**\n * Deep update of oldState based on newState values\n * @param oldState - cache before changes\n * @param newState - updated cache\n */\n private mergeUpdates(oldState: object, newState: object): JsonCache {\n Object.keys(newState).forEach((newKey: string) => {\n const newValue = newState[newKey];\n\n // if oldState does not contain value but newValue does, add it\n if (!oldState.hasOwnProperty(newKey)) {\n if (newValue !== null) {\n oldState[newKey] = newValue;\n }\n } else {\n // both oldState and newState contain the key, do deep update\n const newValueNotNull = newValue !== null;\n const newValueIsObject = typeof newValue === \"object\";\n const newValueIsNotArray = !Array.isArray(newValue);\n const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== \"undefined\" && oldState[newKey] !== null;\n\n if (newValueNotNull && newValueIsObject && newValueIsNotArray && oldStateNotUndefinedOrNull) {\n this.mergeUpdates(oldState[newKey], newValue);\n } else {\n oldState[newKey] = newValue;\n }\n }\n });\n\n return oldState as JsonCache;\n }\n\n /**\n * Removes entities in oldState that the were removed from newState. If there are any unknown values in root of\n * oldState that are not recognized, they are left untouched.\n * @param oldState - cache before changes\n * @param newState - updated cache\n */\n private mergeRemovals(oldState: JsonCache, newState: JsonCache): JsonCache {\n this.logger.trace(\"Remove updated entries in cache\");\n const accounts = oldState.Account ? this.mergeRemovalsDict<SerializedAccountEntity>(oldState.Account, newState.Account) : oldState.Account;\n const accessTokens = oldState.AccessToken ? this.mergeRemovalsDict<SerializedAccessTokenEntity>(oldState.AccessToken, newState.AccessToken) : oldState.AccessToken;\n const refreshTokens = oldState.RefreshToken ? this.mergeRemovalsDict<SerializedRefreshTokenEntity>(oldState.RefreshToken, newState.RefreshToken) : oldState.RefreshToken;\n const idTokens = oldState.IdToken ? this.mergeRemovalsDict<SerializedIdTokenEntity>(oldState.IdToken, newState.IdToken) : oldState.IdToken;\n const appMetadata = oldState.AppMetadata ? this.mergeRemovalsDict<SerializedAppMetadataEntity>(oldState.AppMetadata, newState.AppMetadata) : oldState.AppMetadata;\n\n return {\n ...oldState,\n Account: accounts,\n AccessToken: accessTokens,\n RefreshToken: refreshTokens,\n IdToken: idTokens,\n AppMetadata: appMetadata\n };\n }\n\n /**\n * Helper to merge new cache with the old one\n * @param oldState - cache before changes\n * @param newState - updated cache\n */\n private mergeRemovalsDict<T>(oldState: Record<string, T>, newState?: Record<string, T>): Record<string, T> {\n const finalState = { ...oldState };\n Object.keys(oldState).forEach((oldKey) => {\n if (!newState || !(newState.hasOwnProperty(oldKey))) {\n delete finalState[oldKey];\n }\n });\n return finalState;\n }\n\n /**\n * Helper to overlay as a part of cache merge\n * @param passedInCache - cache read from the blob\n */\n private overlayDefaults(passedInCache: JsonCache): JsonCache {\n this.logger.trace(\"Overlaying input cache with the default cache\");\n return {\n Account: {\n ...defaultSerializedCache.Account,\n ...passedInCache.Account,\n },\n IdToken: {\n ...defaultSerializedCache.IdToken,\n ...passedInCache.IdToken,\n },\n AccessToken: {\n ...defaultSerializedCache.AccessToken,\n ...passedInCache.AccessToken,\n },\n RefreshToken: {\n ...defaultSerializedCache.RefreshToken,\n ...passedInCache.RefreshToken,\n },\n AppMetadata: {\n ...defaultSerializedCache.AppMetadata,\n ...passedInCache.AppMetadata,\n },\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AuthError } from \"@azure/msal-common\";\n\n/**\n * NodeAuthErrorMessage class containing string constants used by error codes and messages.\n */\nexport const NodeAuthErrorMessage = {\n invalidLoopbackAddressType: {\n code: \"invalid_loopback_server_address_type\",\n desc: \"Loopback server address is not type string. This is unexpected.\"\n },\n unableToLoadRedirectUri: {\n code: \"unable_to_load_redirectUrl\",\n desc: \"Loopback server callback was invoked without a url. This is unexpected.\"\n },\n noAuthCodeInResponse: {\n code: \"no_auth_code_in_response\",\n desc: \"No auth code found in the server response. Please check your network trace to determine what happened.\"\n },\n noLoopbackServerExists: {\n code: \"no_loopback_server_exists\",\n desc: \"No loopback server exists yet.\"\n },\n loopbackServerAlreadyExists: {\n code: \"loopback_server_already_exists\",\n desc: \"Loopback server already exists. Cannot create another.\"\n },\n loopbackServerTimeout: {\n code: \"loopback_server_timeout\",\n desc: \"Timed out waiting for auth code listener to be registered.\"\n },\n stateNotFoundError: {\n code: \"state_not_found\",\n desc: \"State not found. Please verify that the request originated from msal.\"\n },\n};\n\nexport class NodeAuthError extends AuthError {\n constructor(errorCode: string, errorMessage?: string) {\n super(errorCode, errorMessage);\n this.name = \"NodeAuthError\";\n }\n\n /**\n * Creates an error thrown if loopback server address is of type string.\n */\n static createInvalidLoopbackAddressTypeError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code,\n `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`);\n }\n\n /**\n * Creates an error thrown if the loopback server is unable to get a url.\n */\n static createUnableToLoadRedirectUrlError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code,\n `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`);\n }\n\n /**\n * Creates an error thrown if the server response does not contain an auth code.\n */\n static createNoAuthCodeInResponseError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code,\n `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`);\n }\n\n /**\n * Creates an error thrown if the loopback server has not been spun up yet.\n */\n static createNoLoopbackServerExistsError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code,\n `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`);\n }\n\n /**\n * Creates an error thrown if a loopback server already exists when attempting to create another one.\n */\n static createLoopbackServerAlreadyExistsError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code,\n `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`);\n }\n\n /**\n * Creates an error thrown if the loopback server times out registering the auth code listener.\n */\n static createLoopbackServerTimeoutError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code,\n `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`);\n }\n\n /**\n * Creates an error thrown when the state is not present.\n */\n static createStateNotFoundError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, NodeAuthErrorMessage.stateNotFoundError.desc);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AuthorizationCodeClient,\n ClientConfiguration,\n RefreshTokenClient,\n AuthenticationResult,\n Authority,\n AuthorityFactory,\n BaseAuthRequest,\n SilentFlowClient,\n Logger,\n ServerTelemetryManager,\n ServerTelemetryRequest,\n CommonSilentFlowRequest,\n CommonRefreshTokenRequest,\n CommonAuthorizationCodeRequest,\n CommonAuthorizationUrlRequest,\n CommonUsernamePasswordRequest,\n UsernamePasswordClient,\n AuthenticationScheme,\n ResponseMode,\n AuthorityOptions,\n OIDC_DEFAULT_SCOPES,\n AzureRegionConfiguration,\n AuthError,\n AzureCloudOptions,\n AuthorizationCodePayload,\n StringUtils,\n ClientAuthError,\n Constants,\n} from \"@azure/msal-common\";\nimport { Configuration, buildAppConfiguration, NodeConfiguration } from \"../config/Configuration\";\nimport { CryptoProvider } from \"../crypto/CryptoProvider\";\nimport { NodeStorage } from \"../cache/NodeStorage\";\nimport { Constants as NodeConstants, ApiId } from \"../utils/Constants\";\nimport { TokenCache } from \"../cache/TokenCache\";\nimport { ClientAssertion } from \"./ClientAssertion\";\nimport { AuthorizationUrlRequest } from \"../request/AuthorizationUrlRequest\";\nimport { AuthorizationCodeRequest } from \"../request/AuthorizationCodeRequest\";\nimport { RefreshTokenRequest } from \"../request/RefreshTokenRequest\";\nimport { SilentFlowRequest } from \"../request/SilentFlowRequest\";\nimport { version, name } from \"../packageMetadata\";\nimport { UsernamePasswordRequest } from \"../request/UsernamePasswordRequest\";\nimport { NodeAuthError } from \"../error/NodeAuthError\";\n\n/**\n * Base abstract class for all ClientApplications - public and confidential\n * @public\n */\nexport abstract class ClientApplication {\n\n protected readonly cryptoProvider: CryptoProvider;\n private tokenCache: TokenCache;\n\n /**\n * Platform storage object\n */\n protected storage: NodeStorage;\n /**\n * Logger object to log the application flow\n */\n protected logger: Logger;\n /**\n * Platform configuration initialized by the application\n */\n protected config: NodeConfiguration;\n /**\n * Client assertion passed by the user for confidential client flows\n */\n protected clientAssertion: ClientAssertion;\n /**\n * Client secret passed by the user for confidential client flows\n */\n protected clientSecret: string;\n\n /**\n * Constructor for the ClientApplication\n */\n protected constructor(configuration: Configuration) {\n this.config = buildAppConfiguration(configuration);\n this.cryptoProvider = new CryptoProvider();\n this.logger = new Logger(this.config.system.loggerOptions, name, version);\n this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider);\n this.tokenCache = new TokenCache(\n this.storage,\n this.logger,\n this.config.cache.cachePlugin\n );\n }\n\n /**\n * Creates the URL of the authorization request, letting the user input credentials and consent to the\n * application. The URL targets the /authorize endpoint of the authority configured in the\n * application object.\n *\n * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI\n * sent in the request and should contain an authorization code, which can then be used to acquire tokens via\n * `acquireTokenByCode(AuthorizationCodeRequest)`.\n */\n async getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string> {\n this.logger.info(\"getAuthCodeUrl called\", request.correlationId);\n const validRequest: CommonAuthorizationUrlRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n responseMode: request.responseMode || ResponseMode.QUERY,\n authenticationScheme: AuthenticationScheme.BEARER\n };\n\n const authClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n undefined,\n undefined,\n request.azureCloudOptions\n );\n const authorizationCodeClient = new AuthorizationCodeClient(\n authClientConfig\n );\n this.logger.verbose(\"Auth code client created\", validRequest.correlationId);\n return authorizationCodeClient.getAuthCodeUrl(validRequest);\n }\n\n /**\n * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0\n * Authorization Code flow.\n *\n * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0\n * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and\n * AuthorizationCodeRequest are the same.\n */\n async acquireTokenByCode(request: AuthorizationCodeRequest, authCodePayLoad?: AuthorizationCodePayload): Promise<AuthenticationResult> {\n this.logger.info(\"acquireTokenByCode called\");\n if (request.state && authCodePayLoad){\n this.logger.info(\"acquireTokenByCode - validating state\");\n this.validateState(request.state, authCodePayLoad.state || \"\");\n // eslint-disable-next-line no-param-reassign\n authCodePayLoad= {...authCodePayLoad, state: \"\"};\n }\n const validRequest: CommonAuthorizationCodeRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n authenticationScheme: AuthenticationScheme.BEARER\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId);\n try {\n const authClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const authorizationCodeClient = new AuthorizationCodeClient(\n authClientConfig\n );\n this.logger.verbose(\"Auth code client created\", validRequest.correlationId);\n return authorizationCodeClient.acquireToken(validRequest, authCodePayLoad);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires a token by exchanging the refresh token provided for a new set of tokens.\n *\n * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is\n * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will\n * handle the caching and refreshing of tokens automatically.\n */\n async acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByRefreshToken called\", request.correlationId);\n const validRequest: CommonRefreshTokenRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n authenticationScheme: AuthenticationScheme.BEARER\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId);\n try {\n const refreshTokenClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const refreshTokenClient = new RefreshTokenClient(\n refreshTokenClientConfig\n );\n this.logger.verbose(\"Refresh token client created\", validRequest.correlationId);\n return refreshTokenClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires a token silently when a user specifies the account the token is requested for.\n *\n * This API expects the user to provide an account object and looks into the cache to retrieve the token if present.\n * There is also an optional \"forceRefresh\" boolean the user can send to bypass the cache for access_token and id_token.\n * In case the refresh_token is expired or not found, an error is thrown\n * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).\n */\n async acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult | null> {\n const validRequest: CommonSilentFlowRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n forceRefresh: request.forceRefresh || false\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);\n try {\n const silentFlowClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const silentFlowClient = new SilentFlowClient(\n silentFlowClientConfig\n );\n this.logger.verbose(\"Silent flow client created\", validRequest.correlationId);\n return silentFlowClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires tokens with password grant by exchanging client applications username and password for credentials\n *\n * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.\n * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4\n * Microsoft's documentation and recommendations are at:\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword\n *\n * @param request - UsenamePasswordRequest\n */\n async acquireTokenByUsernamePassword(request: UsernamePasswordRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByUsernamePassword called\", request.correlationId);\n const validRequest: CommonUsernamePasswordRequest = {\n ...request,\n ... await this.initializeBaseRequest(request)\n };\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);\n try {\n const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const usernamePasswordClient = new UsernamePasswordClient(usernamePasswordClientConfig);\n this.logger.verbose(\"Username password client created\", validRequest.correlationId);\n return usernamePasswordClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Gets the token cache for the application.\n */\n getTokenCache(): TokenCache {\n this.logger.info(\"getTokenCache called\");\n return this.tokenCache;\n }\n\n /**\n * Validates OIDC state by comparing the user cached state with the state received from the server.\n * \n * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against\n * CSRF attacks.\n * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.\n * @param state\n * @param cachedState\n */\n protected validateState(state: string, cachedState: string): void {\n if(!state) {\n throw NodeAuthError.createStateNotFoundError();\n }\n\n if(state !== cachedState) {\n throw ClientAuthError.createStateMismatchError();\n }\n }\n\n /**\n * Returns the logger instance\n */\n getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Replaces the default logger set in configurations with new Logger with new configurations\n * @param logger - Logger instance\n */\n setLogger(logger: Logger): void {\n this.logger = logger;\n }\n\n /**\n * Builds the common configuration to be passed to the common component based on the platform configurarion\n * @param authority - user passed authority in configuration\n * @param serverTelemetryManager - initializes servertelemetry if passed\n */\n protected async buildOauthClientConfiguration(\n authority: string,\n requestCorrelationId?: string, \n serverTelemetryManager?: ServerTelemetryManager,\n azureRegionConfiguration?: AzureRegionConfiguration, \n azureCloudOptions?: AzureCloudOptions): Promise<ClientConfiguration> {\n \n this.logger.verbose(\"buildOauthClientConfiguration called\", requestCorrelationId);\n\n // precedence - azureCloudInstance + tenant >> authority and request >> config\n const userAzureCloudOptions = azureCloudOptions ? azureCloudOptions : this.config.auth.azureCloudOptions;\n\n // using null assertion operator as we ensure that all config values have default values in buildConfiguration()\n this.logger.verbose(`building oauth client configuration with the authority: ${authority}`, requestCorrelationId);\n const discoveredAuthority = await this.createAuthority(authority, azureRegionConfiguration, requestCorrelationId, userAzureCloudOptions);\n\n serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);\n\n const clientConfiguration: ClientConfiguration = {\n authOptions: {\n clientId: this.config.auth.clientId,\n authority: discoveredAuthority,\n clientCapabilities: this.config.auth.clientCapabilities\n },\n systemOptions: {\n proxyUrl: this.config.system.proxyUrl,\n },\n loggerOptions: {\n logLevel: this.config.system.loggerOptions.logLevel,\n loggerCallback: this.config.system.loggerOptions\n .loggerCallback,\n piiLoggingEnabled: this.config.system.loggerOptions\n .piiLoggingEnabled,\n correlationId: requestCorrelationId\n },\n cryptoInterface: this.cryptoProvider,\n networkInterface: this.config.system.networkClient,\n storageInterface: this.storage,\n serverTelemetryManager: serverTelemetryManager,\n clientCredentials: {\n clientSecret: this.clientSecret,\n clientAssertion: this.clientAssertion ? this.getClientAssertion(discoveredAuthority) : undefined,\n },\n libraryInfo: {\n sku: NodeConstants.MSAL_SKU,\n version: version,\n cpu: process.arch || Constants.EMPTY_STRING,\n os: process.platform || Constants.EMPTY_STRING,\n },\n telemetry: this.config.telemetry,\n persistencePlugin: this.config.cache.cachePlugin,\n serializableCache: this.tokenCache \n };\n\n return clientConfiguration;\n }\n\n private getClientAssertion(authority: Authority): { assertion: string, assertionType: string } {\n return {\n assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),\n assertionType: NodeConstants.JWT_BEARER_ASSERTION_TYPE\n };\n }\n\n /**\n * Generates a request with the default scopes & generates a correlationId.\n * @param authRequest - BaseAuthRequest for initialization\n */\n protected async initializeBaseRequest(authRequest: Partial<BaseAuthRequest>): Promise<BaseAuthRequest> {\n this.logger.verbose(\"initializeRequestScopes called\", authRequest.correlationId);\n // Default authenticationScheme to Bearer, log that POP isn't supported yet\n if (authRequest.authenticationScheme && authRequest.authenticationScheme === AuthenticationScheme.POP) {\n this.logger.verbose(\"Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request\", authRequest.correlationId);\n }\n\n authRequest.authenticationScheme = AuthenticationScheme.BEARER;\n\n // Set requested claims hash if claims were requested\n if (authRequest.claims && !StringUtils.isEmpty(authRequest.claims)) {\n authRequest.requestedClaimsHash = await this.cryptoProvider.hashString(authRequest.claims);\n }\n\n return {\n ...authRequest,\n scopes: [...((authRequest && authRequest.scopes) || []), ...OIDC_DEFAULT_SCOPES],\n correlationId: authRequest && authRequest.correlationId || this.cryptoProvider.createNewGuid(),\n authority: authRequest.authority || this.config.auth.authority\n };\n }\n\n /**\n * Initializes the server telemetry payload\n * @param apiId - Id for a specific request\n * @param correlationId - GUID\n * @param forceRefresh - boolean to indicate network call\n */\n protected initializeServerTelemetryManager(apiId: number, correlationId: string, forceRefresh?: boolean): ServerTelemetryManager {\n const telemetryPayload: ServerTelemetryRequest = {\n clientId: this.config.auth.clientId,\n correlationId: correlationId,\n apiId: apiId,\n forceRefresh: forceRefresh || false\n };\n\n return new ServerTelemetryManager(telemetryPayload, this.storage);\n }\n\n /**\n * Create authority instance. If authority not passed in request, default to authority set on the application\n * object. If no authority set in application object, then default to common authority.\n * @param authorityString - authority from user configuration\n */\n private async createAuthority(authorityString: string, azureRegionConfiguration?: AzureRegionConfiguration, requestCorrelationId?: string, azureCloudOptions?: AzureCloudOptions): Promise<Authority> {\n this.logger.verbose(\"createAuthority called\", requestCorrelationId);\n\n // build authority string based on auth params - azureCloudInstance is prioritized if provided\n const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions);\n\n const authorityOptions: AuthorityOptions = {\n protocolMode: this.config.auth.protocolMode,\n knownAuthorities: this.config.auth.knownAuthorities,\n cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,\n authorityMetadata: this.config.auth.authorityMetadata,\n azureRegionConfiguration,\n skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache,\n };\n\n return await AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, this.config.system.proxyUrl);\n }\n\n /**\n * Clear the cache\n */\n clearCache(): void {\n this.storage.clear();\n }\n}\n","/* eslint-disable header/header */\nexport const name = \"@azure/msal-node\";\nexport const version = \"1.14.5\";\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants as CommonConstants, ServerAuthorizationCodeResponse, UrlString } from \"@azure/msal-common\";\nimport { createServer, IncomingMessage, Server, ServerResponse } from \"http\";\nimport { NodeAuthError } from \"../error/NodeAuthError\";\nimport { Constants, HttpStatus, LOOPBACK_SERVER_CONSTANTS } from \"../utils/Constants\";\n\nexport class LoopbackClient {\n private server: Server;\n\n /**\n * Spins up a loopback server which returns the server response when the localhost redirectUri is hit\n * @param successTemplate \n * @param errorTemplate \n * @returns \n */\n async listenForAuthCode(successTemplate?: string, errorTemplate?: string): Promise<ServerAuthorizationCodeResponse> {\n if (!!this.server) {\n throw NodeAuthError.createLoopbackServerAlreadyExistsError();\n }\n\n const authCodeListener = new Promise<ServerAuthorizationCodeResponse>((resolve, reject) => {\n this.server = createServer(async (req: IncomingMessage, res: ServerResponse) => {\n const url = req.url;\n if (!url) {\n res.end(errorTemplate || \"Error occurred loading redirectUrl\");\n reject(NodeAuthError.createUnableToLoadRedirectUrlError());\n return;\n } else if (url === CommonConstants.FORWARD_SLASH) {\n res.end(successTemplate || \"Auth code was successfully acquired. You can close this window now.\");\n return;\n }\n \n const authCodeResponse = UrlString.getDeserializedQueryString(url);\n if (authCodeResponse.code) {\n const redirectUri = await this.getRedirectUri();\n res.writeHead(HttpStatus.REDIRECT, { location: redirectUri }); // Prevent auth code from being saved in the browser history\n res.end();\n }\n resolve(authCodeResponse);\n });\n this.server.listen(0); // Listen on any available port\n });\n\n // Wait for server to be listening\n await new Promise<void>((resolve) => {\n let ticks = 0;\n const id = setInterval(() => {\n if ((LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS) < ticks) {\n throw NodeAuthError.createLoopbackServerTimeoutError();\n }\n \n if (this.server.listening) {\n clearInterval(id);\n resolve();\n }\n ticks++;\n }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);\n });\n\n return authCodeListener;\n }\n\n /**\n * Get the port that the loopback server is running on\n * @returns \n */\n getRedirectUri(): string {\n if (!this.server) {\n throw NodeAuthError.createNoLoopbackServerExistsError();\n }\n \n const address = this.server.address();\n if (!address || typeof address === \"string\" || !address.port) {\n this.closeServer();\n throw NodeAuthError.createInvalidLoopbackAddressTypeError();\n } \n\n const port = address && address.port;\n\n return `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}:${port}`;\n }\n\n /**\n * Close the loopback server\n */\n closeServer(): void {\n if (!!this.server) {\n this.server.close();\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { JwtHeader, sign } from \"jsonwebtoken\";\nimport { TimeUtils, ClientAuthError, Constants } from \"@azure/msal-common\";\nimport { CryptoProvider } from \"../crypto/CryptoProvider\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\nimport { JwtConstants } from \"../utils/Constants\";\n\n/**\n * Client assertion of type jwt-bearer used in confidential client flows\n * @public\n */\nexport class ClientAssertion {\n\n private jwt: string;\n private privateKey: string;\n private thumbprint: string;\n private expirationTime: number;\n private issuer: string;\n private jwtAudience: string;\n private publicCertificate: Array<string>;\n\n /**\n * Initialize the ClientAssertion class from the clientAssertion passed by the user\n * @param assertion - refer https://tools.ietf.org/html/rfc7521\n */\n public static fromAssertion(assertion: string): ClientAssertion {\n const clientAssertion = new ClientAssertion();\n clientAssertion.jwt = assertion;\n return clientAssertion;\n }\n\n /**\n * Initialize the ClientAssertion class from the certificate passed by the user\n * @param thumbprint - identifier of a certificate\n * @param privateKey - secret key\n * @param publicCertificate - electronic document provided to prove the ownership of the public key\n */\n public static fromCertificate(thumbprint: string, privateKey: string, publicCertificate?: string): ClientAssertion {\n const clientAssertion = new ClientAssertion();\n clientAssertion.privateKey = privateKey;\n clientAssertion.thumbprint = thumbprint;\n if (publicCertificate) {\n clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);\n }\n return clientAssertion;\n }\n\n /**\n * Update JWT for certificate based clientAssertion, if passed by the user, uses it as is\n * @param cryptoProvider - library's crypto helper\n * @param issuer - iss claim\n * @param jwtAudience - aud claim\n */\n public getJwt(cryptoProvider: CryptoProvider, issuer: string, jwtAudience: string): string {\n // if assertion was created from certificate, check if jwt is expired and create new one.\n if (this.privateKey && this.thumbprint) {\n\n if (this.jwt && !this.isExpired() && issuer === this.issuer && jwtAudience === this.jwtAudience) {\n return this.jwt;\n }\n\n return this.createJwt(cryptoProvider, issuer, jwtAudience);\n }\n\n /*\n * if assertion was created by caller, then we just append it. It is up to the caller to\n * ensure that it contains necessary claims and that it is not expired.\n */\n if (this.jwt) {\n return this.jwt;\n }\n\n throw ClientAuthError.createInvalidAssertionError();\n }\n\n /**\n * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3\n */\n private createJwt(cryptoProvider: CryptoProvider, issuer: string, jwtAudience: string): string {\n\n this.issuer = issuer;\n this.jwtAudience = jwtAudience;\n const issuedAt = TimeUtils.nowSeconds();\n this.expirationTime = issuedAt + 600;\n\n const header: JwtHeader = {\n alg: JwtConstants.RSA_256,\n x5t: EncodingUtils.base64EncodeUrl(this.thumbprint, \"hex\")\n };\n\n if (this.publicCertificate) {\n Object.assign(header, {\n x5c: this.publicCertificate\n } as Partial<JwtHeader>);\n }\n\n const payload = {\n [JwtConstants.AUDIENCE]: this.jwtAudience,\n [JwtConstants.EXPIRATION_TIME]: this.expirationTime,\n [JwtConstants.ISSUER]: this.issuer,\n [JwtConstants.SUBJECT]: this.issuer,\n [JwtConstants.NOT_BEFORE]: issuedAt,\n [JwtConstants.JWT_ID]: cryptoProvider.createNewGuid()\n };\n\n this.jwt = sign(payload, this.privateKey, { header });\n return this.jwt;\n }\n\n /**\n * Utility API to check expiration\n */\n private isExpired(): boolean {\n return this.expirationTime < TimeUtils.nowSeconds();\n }\n\n /**\n * Extracts the raw certs from a given certificate string and returns them in an array.\n * @param publicCertificate - electronic document provided to prove the ownership of the public key\n */\n public static parseCertificate(publicCertificate: string): Array<string> {\n /**\n * This is regex to identify the certs in a given certificate string.\n * We want to look for the contents between the BEGIN and END certificate strings, without the associated newlines.\n * The information in parens \"(.+?)\" is the capture group to represent the cert we want isolated.\n * \".\" means any string character, \"+\" means match 1 or more times, and \"?\" means the shortest match.\n * The \"g\" at the end of the regex means search the string globally, and the \"s\" enables the \".\" to match newlines.\n */\n const regexToFindCerts = /-----BEGIN CERTIFICATE-----\\r*\\n(.+?)\\r*\\n-----END CERTIFICATE-----/gs;\n const certs: string[] = [];\n\n let matches;\n while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {\n // matches[1] represents the first parens capture group in the regex.\n certs.push(matches[1].replace(/\\r*\\n/g, Constants.EMPTY_STRING));\n }\n\n return certs;\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ClientApplication } from \"./ClientApplication\";\nimport { Configuration } from \"../config/Configuration\";\nimport { ClientAssertion } from \"./ClientAssertion\";\nimport { Constants as NodeConstants, ApiId, REGION_ENVIRONMENT_VARIABLE } from \"../utils/Constants\";\nimport {\n ClientCredentialClient,\n OnBehalfOfClient,\n CommonClientCredentialRequest,\n CommonOnBehalfOfRequest,\n AuthenticationResult,\n StringUtils,\n ClientAuthError,\n AzureRegionConfiguration,\n AuthError,\n Constants,\n IAppTokenProvider,\n OIDC_DEFAULT_SCOPES\n} from \"@azure/msal-common\";\nimport { IConfidentialClientApplication } from \"./IConfidentialClientApplication\";\nimport { OnBehalfOfRequest } from \"../request/OnBehalfOfRequest\";\nimport { ClientCredentialRequest } from \"../request/ClientCredentialRequest\";\n\n/**\n * This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications\n * will configure application secrets, client certificates/assertions as applicable\n * @public\n */\nexport class ConfidentialClientApplication extends ClientApplication implements IConfidentialClientApplication {\n private appTokenProvider?: IAppTokenProvider;\n\n /**\n * Constructor for the ConfidentialClientApplication\n *\n * Required attributes in the Configuration object are:\n * - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal\n * - authority: the authority URL for your application.\n * - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.\n *\n * In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\\{Enter_the_Tenant_Info_Here\\}.\n * If your application supports Accounts in one organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).\n * If your application supports Accounts in any organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with organizations.\n * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace \"Enter_the_Tenant_Info_Here\" value with common.\n * To restrict support to Personal Microsoft accounts only, replace \"Enter_the_Tenant_Info_Here\" value with consumers.\n *\n * In Azure B2C, authority is of the form https://\\{instance\\}/tfp/\\{tenant\\}/\\{policyName\\}/\n * Full B2C functionality will be available in this library in future versions.\n *\n * @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance\n */\n constructor(configuration: Configuration) {\n super(configuration);\n this.setClientCredential(this.config);\n this.appTokenProvider = undefined;\n }\n\n /** \n * This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and\n * is meant for Azure SDK to enhance Managed Identity support.\n * \n * @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source. \n */\n SetAppTokenProvider(provider: IAppTokenProvider): void {\n this.appTokenProvider = provider;\n }\n\n /**\n * Acquires tokens from the authority for the application (not for an end user).\n */\n public async acquireTokenByClientCredential(request: ClientCredentialRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByClientCredential called\", request.correlationId);\n\n // If there is a client assertion present in the request, it overrides the one present in the client configuration\n let clientAssertion;\n if (request.clientAssertion) {\n clientAssertion = {\n assertion: request.clientAssertion,\n assertionType: NodeConstants.JWT_BEARER_ASSERTION_TYPE\n };\n }\n\n const baseRequest = await this.initializeBaseRequest(request);\n\n // valid base request should not contain oidc scopes in this grant type\n const validBaseRequest = {\n ...baseRequest,\n scopes: baseRequest.scopes.filter((scope: string) => !OIDC_DEFAULT_SCOPES.includes(scope))\n };\n\n const validRequest: CommonClientCredentialRequest = {\n ...request,\n ...validBaseRequest,\n clientAssertion\n };\n\n const azureRegionConfiguration: AzureRegionConfiguration = {\n azureRegion: validRequest.azureRegion,\n environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE]\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache);\n try {\n const clientCredentialConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n azureRegionConfiguration,\n request.azureCloudOptions\n );\n const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig, this.appTokenProvider);\n this.logger.verbose(\"Client credential client created\", validRequest.correlationId);\n return clientCredentialClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires tokens from the authority for the application.\n *\n * Used in scenarios where the current app is a middle-tier service which was called with a token\n * representing an end user. The current app can use the token (oboAssertion) to request another\n * token to access downstream web API, on behalf of that user.\n *\n * The current middle-tier app has no user interaction to obtain consent.\n * See how to gain consent upfront for your middle-tier app from this article.\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application\n */\n public async acquireTokenOnBehalfOf(request: OnBehalfOfRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenOnBehalfOf called\", request.correlationId);\n const validRequest: CommonOnBehalfOfRequest = {\n ...request,\n ... await this.initializeBaseRequest(request)\n };\n try {\n const onBehalfOfConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n undefined,\n undefined,\n request.azureCloudOptions\n );\n const oboClient = new OnBehalfOfClient(onBehalfOfConfig);\n this.logger.verbose(\"On behalf of client created\", validRequest.correlationId);\n return oboClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n throw e;\n }\n }\n\n private setClientCredential(configuration: Configuration): void {\n const clientSecretNotEmpty = !StringUtils.isEmpty(configuration.auth.clientSecret);\n const clientAssertionNotEmpty = !StringUtils.isEmpty(configuration.auth.clientAssertion);\n const certificate = configuration.auth.clientCertificate || {\n thumbprint: Constants.EMPTY_STRING,\n privateKey: Constants.EMPTY_STRING\n };\n const certificateNotEmpty = !StringUtils.isEmpty(certificate.thumbprint) || !StringUtils.isEmpty(certificate.privateKey);\n\n /*\n * If app developer configures this callback, they don't need a credential\n * i.e. AzureSDK can get token from Managed Identity without a cert / secret\n */\n if (this.appTokenProvider) {\n return;\n }\n\n // Check that at most one credential is set on the application\n if (\n clientSecretNotEmpty && clientAssertionNotEmpty ||\n clientAssertionNotEmpty && certificateNotEmpty ||\n clientSecretNotEmpty && certificateNotEmpty) {\n throw ClientAuthError.createInvalidCredentialError();\n }\n\n if (configuration.auth.clientSecret) {\n this.clientSecret = configuration.auth.clientSecret;\n return;\n }\n\n if (configuration.auth.clientAssertion) {\n this.clientAssertion = ClientAssertion.fromAssertion(configuration.auth.clientAssertion);\n return;\n }\n\n if (!certificateNotEmpty) {\n throw ClientAuthError.createInvalidCredentialError();\n } else {\n this.clientAssertion = ClientAssertion.fromCertificate(certificate.thumbprint, certificate.privateKey, configuration.auth.clientCertificate?.x5c);\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AccountEntity, ICachePlugin, TokenCacheContext } from \"@azure/msal-common\";\nimport { TokenCache } from \"../TokenCache\";\nimport { IPartitionManager } from \"./IPartitionManager\";\nimport { ICacheClient } from \"./ICacheClient\";\n\nexport class DistributedCachePlugin implements ICachePlugin {\n private client: ICacheClient;\n private partitionManager: IPartitionManager;\n\n constructor(client: ICacheClient, partitionManager: IPartitionManager) {\n this.client = client;\n this.partitionManager = partitionManager;\n }\n \n public async beforeCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n const partitionKey = await this.partitionManager.getKey();\n const cacheData = await this.client.get(partitionKey);\n cacheContext.tokenCache.deserialize(cacheData);\n }\n \n public async afterCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n if (cacheContext.cacheHasChanged) {\n const kvStore = (cacheContext.tokenCache as TokenCache).getKVStore();\n const accountEntities = Object.values(kvStore).filter(value => AccountEntity.isAccountEntity(value as object));\n\n if (accountEntities.length > 0) {\n const accountEntity = accountEntities[0] as AccountEntity;\n const partitionKey = await this.partitionManager.extractKey(accountEntity);\n \n await this.client.set(partitionKey, cacheContext.tokenCache.serialize()); \n }\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ApiId } from \"../utils/Constants\";\nimport {\n DeviceCodeClient,\n AuthenticationResult,\n CommonDeviceCodeRequest,\n AuthError,\n ResponseMode,\n OIDC_DEFAULT_SCOPES,\n CodeChallengeMethodValues,\n Constants as CommonConstants,\n ServerError\n} from \"@azure/msal-common\";\nimport { Configuration } from \"../config/Configuration\";\nimport { ClientApplication } from \"./ClientApplication\";\nimport { IPublicClientApplication } from \"./IPublicClientApplication\";\nimport { DeviceCodeRequest } from \"../request/DeviceCodeRequest\";\nimport { AuthorizationUrlRequest } from \"../request/AuthorizationUrlRequest\";\nimport { AuthorizationCodeRequest } from \"../request/AuthorizationCodeRequest\";\nimport { InteractiveRequest } from \"../request/InteractiveRequest\";\nimport { NodeAuthError } from \"../error/NodeAuthError\";\nimport { LoopbackClient } from \"../network/LoopbackClient\";\n\n/**\n * This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications\n * are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user.\n * @public\n */\nexport class PublicClientApplication extends ClientApplication implements IPublicClientApplication {\n /**\n * Important attributes in the Configuration object for auth are:\n * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.\n * - authority: the authority URL for your application.\n *\n * AAD authorities are of the form https://login.microsoftonline.com/\\{Enter_the_Tenant_Info_Here\\}.\n * - If your application supports Accounts in one organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).\n * - If your application supports Accounts in any organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with organizations.\n * - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace \"Enter_the_Tenant_Info_Here\" value with common.\n * - To restrict support to Personal Microsoft accounts only, replace \"Enter_the_Tenant_Info_Here\" value with consumers.\n *\n * Azure B2C authorities are of the form https://\\{instance\\}/\\{tenant\\}/\\{policy\\}. Each policy is considered\n * its own authority. You will have to set the all of the knownAuthorities at the time of the client application\n * construction.\n *\n * ADFS authorities are of the form https://\\{instance\\}/adfs.\n */\n constructor(configuration: Configuration) {\n super(configuration);\n }\n\n /**\n * Acquires a token from the authority using OAuth2.0 device code flow.\n * This flow is designed for devices that do not have access to a browser or have input constraints.\n * The authorization server issues a DeviceCode object with a verification code, an end-user code,\n * and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be\n * instructed to use another device to navigate to the verification URI to input credentials.\n * Since the client cannot receive incoming requests, it polls the authorization server repeatedly\n * until the end-user completes input of credentials.\n */\n public async acquireTokenByDeviceCode(request: DeviceCodeRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByDeviceCode called\", request.correlationId);\n const validRequest: CommonDeviceCodeRequest = Object.assign(request, await this.initializeBaseRequest(request));\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId);\n try {\n const deviceCodeConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig);\n this.logger.verbose(\"Device code client created\", validRequest.correlationId);\n return deviceCodeClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires a token by requesting an Authorization code then exchanging it for a token.\n */\n async acquireTokenInteractive(request: InteractiveRequest): Promise<AuthenticationResult> {\n const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes();\n const { openBrowser, successTemplate, errorTemplate, ...remainingProperties } = request;\n\n const loopbackClient = new LoopbackClient();\n const authCodeListener = loopbackClient.listenForAuthCode(successTemplate, errorTemplate);\n const redirectUri = loopbackClient.getRedirectUri();\n\n const validRequest: AuthorizationUrlRequest = {\n ...remainingProperties,\n scopes: request.scopes || OIDC_DEFAULT_SCOPES,\n redirectUri: redirectUri,\n responseMode: ResponseMode.QUERY,\n codeChallenge: challenge, \n codeChallengeMethod: CodeChallengeMethodValues.S256\n };\n\n const authCodeUrl = await this.getAuthCodeUrl(validRequest);\n await openBrowser(authCodeUrl);\n const authCodeResponse = await authCodeListener.finally(() => {\n loopbackClient.closeServer();\n });\n\n if (authCodeResponse.error) {\n throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror);\n } else if (!authCodeResponse.code) {\n throw NodeAuthError.createNoAuthCodeInResponseError();\n }\n\n const clientInfo = authCodeResponse.client_info;\n const tokenRequest: AuthorizationCodeRequest = {\n code: authCodeResponse.code,\n codeVerifier: verifier,\n clientInfo: clientInfo || CommonConstants.EMPTY_STRING,\n ...validRequest\n };\n return this.acquireTokenByCode(tokenRequest);\n }\n}\n"],"names":["HttpMethod","HttpStatus","ProxyStatus","CharSet","ApiId","NetworkUtils","[object Object]","headers","body","statusCode","status","HttpClient","url","options","proxyUrl","networkRequestViaProxy","GET","networkRequestViaHttps","cancellationToken","POST","httpMethod","timeout","URL","destinationUrl","tunnelRequestOptions","host","hostname","port","method","path","postRequestStringContent","length","outgoingRequestString","toUpperCase","href","Promise","resolve","reject","request","http","on","destroy","Error","end","response","socket","proxyStatusCode","SERVER_ERROR","SUCCESS_RANGE_START","SUCCESS_RANGE_END","statusMessage","setTimeout","write","data","chunk","push","dataStringArray","Buffer","concat","toString","split","httpStatusCode","parseInt","slice","join","headersArray","entries","Map","forEach","header","headerKeyValue","RegExp","headerKey","headerValue","object","JSON","parse","e","set","Object","fromEntries","networkResponse","getNetworkResponse","parseBody","isPostRequest","customOptions","Content-Length","https","parsedBody","error","errorType","errorDescriptionHelper","CLIENT_ERROR_RANGE_START","CLIENT_ERROR_RANGE_END","SERVER_ERROR_RANGE_START","SERVER_ERROR_RANGE_END","error_description","stringify","DEFAULT_AUTH_OPTIONS","clientId","Constants","EMPTY_STRING","authority","DEFAULT_AUTHORITY","clientSecret","clientAssertion","clientCertificate","thumbprint","privateKey","x5c","knownAuthorities","cloudDiscoveryMetadata","authorityMetadata","clientCapabilities","protocolMode","ProtocolMode","AAD","azureCloudOptions","azureCloudInstance","AzureCloudInstance","None","tenant","skipAuthorityMetadataCache","DEFAULT_CACHE_OPTIONS","DEFAULT_SYSTEM_OPTIONS","loggerOptions","loggerCallback","piiLoggingEnabled","logLevel","LogLevel","Info","networkClient","DEFAULT_TELEMETRY_OPTIONS","application","appName","appVersion","buildAppConfiguration","auth","cache","system","telemetry","GuidGenerator","generateGuid","uuidv4","isGuid","guid","test","EncodingUtils","str","encoding","from","base64Encode","replace","base64Str","base64Decode","HashUtils","sha256","buffer","crypto","createHash","update","digest","PkceGenerator","constructor","this","hashUtils","verifier","generateCodeVerifier","challenge","generateCodeChallengeFromVerifier","charArr","maxNumber","byte","randomBytes","base64EncodeUrl","codeVerifier","CryptoProvider","pkceGenerator","guidGenerator","createNewGuid","input","generatePkceCodes","getPublicKeyThumbprint","removeTokenBindingKey","clearKeystore","signJwt","plainText","Deserializer","jsonFile","StringUtils","isEmpty","accounts","accountObjects","keys","map","key","serializedAcc","mappedAcc","homeAccountId","home_account_id","environment","realm","localAccountId","local_account_id","username","authorityType","authority_type","name","clientInfo","client_info","lastModificationTime","last_modification_time","lastModificationApp","last_modification_app","account","AccountEntity","CacheManager","toObject","idTokens","idObjects","serializedIdT","mappedIdT","credentialType","credential_type","client_id","secret","idToken","IdTokenEntity","accessTokens","atObjects","serializedAT","mappedAT","target","cachedAt","cached_at","expiresOn","expires_on","extendedExpiresOn","extended_expires_on","refreshOn","refresh_on","keyId","key_id","tokenType","token_type","requestedClaims","requestedClaimsHash","userAssertionHash","accessToken","AccessTokenEntity","refreshTokens","rtObjects","serializedRT","mappedRT","familyId","family_id","refreshToken","RefreshTokenEntity","appMetadata","appMetadataObjects","serializedAmdt","mappedAmd","amd","AppMetadataEntity","jsonCache","Account","deserializeAccounts","IdToken","deserializeIdTokens","AccessToken","deserializeAccessTokens","RefreshToken","deserializeRefreshTokens","AppMetadata","deserializeAppMetadata","Serializer","accCache","accountEntity","idTCache","idTEntity","atCache","atEntity","rtCache","rtEntity","amdtCache","amdtEntity","inMemCache","serializeAccounts","serializeIdTokens","serializeAccessTokens","serializeRefreshTokens","serializeAppMetadata","NodeStorage","logger","cryptoImpl","super","registerChangeEmitter","func","changeEmitters","emitChange","call","cacheToInMemoryCache","inMemoryCache","inMemoryCacheToCache","getCache","getInMemoryCache","trace","setInMemoryCache","setCache","getItem","tracePii","setItem","value","getAccount","accountKey","isAccountEntity","setAccount","generateAccountKey","getIdTokenCredential","idTokenKey","isIdTokenEntity","setIdTokenCredential","generateCredentialKey","getAccessTokenCredential","accessTokenKey","isAccessTokenEntity","setAccessTokenCredential","getRefreshTokenCredential","refreshTokenKey","isRefreshTokenEntity","setRefreshTokenCredential","getAppMetadata","appMetadataKey","isAppMetadataEntity","setAppMetadata","generateAppMetadataKey","getServerTelemetry","serverTelemetrykey","serverTelemetryEntity","ServerTelemetryEntity","isServerTelemetryEntity","setServerTelemetry","serverTelemetryKey","serverTelemetry","getAuthorityMetadata","authorityMetadataEntity","AuthorityMetadataEntity","isAuthorityMetadataEntity","getAuthorityMetadataKeys","getKeys","filter","isAuthorityMetadata","setAuthorityMetadata","metadata","getThrottlingCache","throttlingCacheKey","throttlingCache","ThrottlingEntity","isThrottlingEntity","setThrottlingCache","removeItem","result","containsKey","includes","deserializeAllCache","deserializeJSONBlob","serializeAllCache","updateCredentialCacheKey","currentCacheKey","credential","updatedCacheKey","cacheItem","verbose","defaultSerializedCache","TokenCache","storage","cachePlugin","cacheHasChanged","handleChangeEvent","bind","persistence","hasChanged","serialize","finalState","cacheSnapshot","mergeState","deserialize","deserializedCache","overlayDefaults","getKVStore","cacheContext","TokenCacheContext","beforeCacheAccess","getAllAccounts","afterCacheAccess","allAccounts","accountObj","removeAccount","generateAccountCacheKey","oldState","currentState","stateAfterRemoval","mergeRemovals","mergeUpdates","newState","newKey","newValue","hasOwnProperty","newValueNotNull","newValueIsObject","newValueIsNotArray","Array","isArray","oldStateNotUndefinedOrNull","mergeRemovalsDict","oldKey","passedInCache","NodeAuthError","AuthError","errorCode","errorMessage","ClientApplication","configuration","config","cryptoProvider","Logger","tokenCache","info","correlationId","validRequest","initializeBaseRequest","responseMode","ResponseMode","QUERY","authenticationScheme","AuthenticationScheme","BEARER","authClientConfig","buildOauthClientConfiguration","undefined","authorizationCodeClient","AuthorizationCodeClient","getAuthCodeUrl","authCodePayLoad","state","validateState","serverTelemetryManager","initializeServerTelemetryManager","acquireTokenByCode","acquireToken","setCorrelationId","cacheFailedRequest","acquireTokenByRefreshToken","refreshTokenClientConfig","refreshTokenClient","RefreshTokenClient","forceRefresh","acquireTokenSilent","silentFlowClientConfig","silentFlowClient","SilentFlowClient","acquireTokenByUsernamePassword","usernamePasswordClientConfig","usernamePasswordClient","UsernamePasswordClient","getTokenCache","cachedState","createStateNotFoundError","ClientAuthError","createStateMismatchError","getLogger","setLogger","requestCorrelationId","azureRegionConfiguration","userAzureCloudOptions","discoveredAuthority","createAuthority","updateRegionDiscoveryMetadata","regionDiscoveryMetadata","authOptions","systemOptions","cryptoInterface","networkInterface","storageInterface","clientCredentials","getClientAssertion","libraryInfo","sku","version","cpu","process","arch","os","platform","persistencePlugin","serializableCache","assertion","getJwt","tokenEndpoint","assertionType","authRequest","POP","claims","hashString","scopes","OIDC_DEFAULT_SCOPES","apiId","ServerTelemetryManager","authorityString","authorityUrl","Authority","generateAuthority","authorityOptions","AuthorityFactory","createDiscoveredInstance","clearCache","clear","LoopbackClient","successTemplate","errorTemplate","server","createLoopbackServerAlreadyExistsError","authCodeListener","createServer","async","req","res","createUnableToLoadRedirectUrlError","CommonConstants","FORWARD_SLASH","authCodeResponse","UrlString","getDeserializedQueryString","code","redirectUri","getRedirectUri","writeHead","REDIRECT","location","listen","ticks","id","setInterval","LOOPBACK_SERVER_CONSTANTS","createLoopbackServerTimeoutError","listening","clearInterval","createNoLoopbackServerExistsError","address","closeServer","createInvalidLoopbackAddressTypeError","close","ClientAssertion","jwt","publicCertificate","parseCertificate","issuer","jwtAudience","isExpired","createJwt","createInvalidAssertionError","issuedAt","TimeUtils","nowSeconds","expirationTime","alg","x5t","assign","payload","aud","exp","iss","sub","nbf","jti","sign","regexToFindCerts","certs","matches","exec","setClientCredential","appTokenProvider","SetAppTokenProvider","provider","baseRequest","validBaseRequest","scope","azureRegion","environmentRegion","env","acquireTokenByClientCredential","skipCache","clientCredentialConfig","clientCredentialClient","ClientCredentialClient","onBehalfOfConfig","oboClient","OnBehalfOfClient","clientSecretNotEmpty","clientAssertionNotEmpty","certificate","certificateNotEmpty","createInvalidCredentialError","fromAssertion","fromCertificate","_configuration$auth$c","client","partitionManager","partitionKey","getKey","cacheData","get","kvStore","accountEntities","values","extractKey","acquireTokenByDeviceCode","deviceCodeConfig","deviceCodeClient","DeviceCodeClient","openBrowser","remainingProperties","loopbackClient","listenForAuthCode","codeChallenge","codeChallengeMethod","CodeChallengeMethodValues","S256","authCodeUrl","finally","ServerError","suberror","createNoAuthCodeInResponseError","tokenRequest"],"mappings":"8IAQYA,E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GwZ,EAAyB1R,KAAK2R,iCAAiC3b,EAAMomB,yBAA0B3L,EAAaD,eAClH,IACI,MAAM6L,QAAyBrc,KAAKkR,8BAChCT,EAAavU,UACbuU,EAAaD,cACbkB,OACAP,EACAjZ,EAAQ+E,mBAENqf,EAAmB,IAAIC,mBAAiBF,GAE9C,OADArc,KAAKiI,OAAO+E,QAAQ,6BAA8ByD,EAAaD,eACxD8L,EAAiBzK,aAAapB,GACvC,MAAOhW,GAKL,MAJIA,aAAaqV,aACbrV,EAAEqX,iBAAiBrB,EAAaD,eAEpCkB,EAAuBK,mBAAmBtX,GACpCA,GAOevE,8BAACgC,GAC1B,MAAMgI,SAAEA,EAAFE,UAAYA,SAAoBJ,KAAKoQ,eAAenP,qBACpDub,YAAEA,EAAFtG,gBAAeA,EAAfC,cAAgCA,KAAkBsG,GAAwBvkB,EAE1EwkB,EAAiB,IAAIzG,EACrBK,EAAmBoG,EAAeC,kBAAkBzG,EAAiBC,GACrEe,EAAcwF,EAAevF,iBAE7B1G,EAAwC,IACvCgM,EACHrH,OAAQld,EAAQkd,QAAUC,sBAC1B6B,YAAaA,EACbvG,aAAcC,eAAaC,MAC3B+L,cAAexc,EACfyc,oBAAqBC,4BAA0BC,MAG7CC,QAAoBhd,KAAKsR,eAAeb,SACxC+L,EAAYQ,GAClB,MAAMlG,QAAyBR,EAAiB2G,QAAQ,KACpDP,EAAezE,gBAGnB,GAAInB,EAAiBzb,MACjB,MAAM,IAAI6hB,cAAYpG,EAAiBzb,MAAOyb,EAAiBlb,kBAAmBkb,EAAiBqG,UAChG,IAAKrG,EAAiBG,KACzB,MAAMpH,EAAcuN,kCAGxB,MACMC,EAAyC,CAC3CpG,KAAMH,EAAiBG,KACvBtW,aAAcT,EACd0C,WAJekU,EAAiBjU,aAIN+T,YAAgB3a,gBACvCwU,GAEP,OAAOzQ,KAAK4R,mBAAmByL,0EL5HhB"}
reject(newError(`Error connecting to proxy. Http status code: ${response.statusCode}. Http status message: ${(response==null?void0:response.statusMessage)||"Unknown"}`));
}
if(tunnelRequestOptions.timeout){
socket.setTimeout(tunnelRequestOptions.timeout);
socket.on("timeout",()=>{
request.destroy();
socket.destroy();
reject(newError("Request time out"));
});
}// make a request over an HTTP tunnel
socket.write(outgoingRequestString);
constdata=[];
socket.on("data",chunk=>{
data.push(chunk);
});
socket.on("end",()=>{
// combine all received buffer streams into one buffer, and then into a string
constdataString=Buffer.concat([...data]).toString();// separate each line into it's own entry in an arry
constdataStringArray=dataString.split("\r\n");// the first entry will contain the statusCode and statusMessage
consthttpStatusCode=parseInt(dataStringArray[0].split("")[1]);// remove "HTTP/1.1" and the status code to get the status message
conststatusMessage=dataStringArray[0].split("").slice(2).join("");// the last entry will contain the body
constbody=dataStringArray[dataStringArray.length-1];// everything in between the first and last entries are the headers
constheadersArray=dataStringArray.slice(1,dataStringArray.length-2);// build an object out of all the headers
constentries=newMap();
headersArray.forEach(header=>{
/**
* the header might look like "Content-Length: 1531", but that is just a string
* it needs to be converted to a key/value pair
* split the string at the first instance of ":"
* there may be more than one ":" if the value of the header is supposed to be a JSON object
if((httpStatusCode<HttpStatus.SUCCESS_RANGE_START||httpStatusCode>HttpStatus.SUCCESS_RANGE_END)&&// do not destroy the request for the device code flow
error_description:`${errorDescriptionHelper} error occured.\nHttp status code: ${statusCode}\nHttp status message: ${statusMessage||"Unknown"}\nHeaders: ${JSON.stringify(headers)}`
};
}
returnparsedBody;
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
constDEFAULT_AUTH_OPTIONS={
clientId:Constants$1.EMPTY_STRING,
authority:Constants$1.DEFAULT_AUTHORITY,
clientSecret:Constants$1.EMPTY_STRING,
clientAssertion:Constants$1.EMPTY_STRING,
clientCertificate:{
thumbprint:Constants$1.EMPTY_STRING,
privateKey:Constants$1.EMPTY_STRING,
x5c:Constants$1.EMPTY_STRING
},
knownAuthorities:[],
cloudDiscoveryMetadata:Constants$1.EMPTY_STRING,
authorityMetadata:Constants$1.EMPTY_STRING,
clientCapabilities:[],
protocolMode:ProtocolMode.AAD,
azureCloudOptions:{
azureCloudInstance:AzureCloudInstance.None,
tenant:Constants$1.EMPTY_STRING
},
skipAuthorityMetadataCache:false
};
constDEFAULT_CACHE_OPTIONS={};
constDEFAULT_LOGGER_OPTIONS={
loggerCallback:()=>{// allow users to not set logger call back
},
piiLoggingEnabled:false,
logLevel:LogLevel.Info
};
constDEFAULT_SYSTEM_OPTIONS={
loggerOptions:DEFAULT_LOGGER_OPTIONS,
networkClient:/*#__PURE__*/newHttpClient(),
proxyUrl:Constants$1.EMPTY_STRING
};
constDEFAULT_TELEMETRY_OPTIONS={
application:{
appName:Constants$1.EMPTY_STRING,
appVersion:Constants$1.EMPTY_STRING
}
};
/**
* Sets the default options when not explicitly configured from app developer
*
* @param auth - Authentication options
* @param cache - Cache options
* @param system - System options
* @param telemetry - Telemetry options
*
* @returns Configuration
* @public
*/
functionbuildAppConfiguration({
auth,
cache,
system,
telemetry
}){
return{
auth:{...DEFAULT_AUTH_OPTIONS,
...auth
},
cache:{...DEFAULT_CACHE_OPTIONS,
...cache
},
system:{...DEFAULT_SYSTEM_OPTIONS,
...system
},
telemetry:{...DEFAULT_TELEMETRY_OPTIONS,
...telemetry
}
};
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
classGuidGenerator{
/**
*
* RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers.
* uuidv4 generates guids from cryprtographically-string random
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This class implements MSAL node's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and
* implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
* @public
*/
classCryptoProvider{
constructor(){
// Browser crypto needs to be validated first before any other classes can be set.
this.pkceGenerator=newPkceGenerator();
this.guidGenerator=newGuidGenerator();
this.hashUtils=newHashUtils();
}
/**
* Creates a new random GUID - used to populate state and nonce.
* @returns string (GUID)
*/
createNewGuid(){
returnthis.guidGenerator.generateGuid();
}
/**
* Encodes input string to base64.
* @param input - string to be encoded
*/
base64Encode(input){
returnEncodingUtils.base64Encode(input);
}
/**
* Decodes input string from base64.
* @param input - string to be decoded
*/
base64Decode(input){
returnEncodingUtils.base64Decode(input);
}
/**
* Generates PKCE codes used in Authorization Code Flow.
*/
generatePkceCodes(){
returnthis.pkceGenerator.generatePkceCodes();
}
/**
* Generates a keypair, stores it and returns a thumbprint - not yet implemented for node
*/
getPublicKeyThumbprint(){
thrownewError("Method not implemented.");
}
/**
* Removes cryptographic keypair from key store matching the keyId passed in
* @param kid
*/
removeTokenBindingKey(){
thrownewError("Method not implemented.");
}
/**
* Removes all cryptographic keys from Keystore
*/
clearKeystore(){
thrownewError("Method not implemented.");
}
/**
* Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node
this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`);
returnupdatedCacheKey;
}else{
this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`);
}
}
returncurrentCacheKey;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
constuserAzureCloudOptions=azureCloudOptions?azureCloudOptions:this.config.auth.azureCloudOptions;// using null assertion operator as we ensure that all config values have default values in buildConfiguration()
this.logger.verbose(`building oauth client configuration with the authority: ${authority}`,requestCorrelationId);
* Generates a request with the default scopes & generates a correlationId.
* @param authRequest - BaseAuthRequest for initialization
*/
asyncinitializeBaseRequest(authRequest){
this.logger.verbose("initializeRequestScopes called",authRequest.correlationId);// Default authenticationScheme to Bearer, log that POP isn't supported yet
this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request",authRequest.correlationId);
}
authRequest.authenticationScheme=AuthenticationScheme.BEARER;// Set requested claims hash if claims were requested
this.logger.verbose("createAuthority called",requestCorrelationId);// build authority string based on auth params - azureCloudInstance is prioritized if provided
* Important attributes in the Configuration object for auth are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.
* - authority: the authority URL for your application.
*
* AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
* - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered
* its own authority. You will have to set the all of the knownAuthorities at the time of the client application
* construction.
*
* ADFS authorities are of the form https://\{instance\}/adfs.
*/
constructor(configuration){
super(configuration);
}
/**
* Acquires a token from the authority using OAuth2.0 device code flow.
* This flow is designed for devices that do not have access to a browser or have input constraints.
* The authorization server issues a DeviceCode object with a verification code, an end-user code,
* and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be
* instructed to use another device to navigate to the verification URI to input credentials.
* Since the client cannot receive incoming requests, it polls the authorization server repeatedly
* until the end-user completes input of credentials.
* Constructor for the ConfidentialClientApplication
*
* Required attributes in the Configuration object are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal
* - authority: the authority URL for your application.
* - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.
*
* In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
* If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* In Azure B2C, authority is of the form https://\{instance\}/tfp/\{tenant\}/\{policyName\}/
* Full B2C functionality will be available in this library in future versions.
*
* @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance
*/
constructor(configuration){
super(configuration);
this.setClientCredential(this.config);
this.appTokenProvider=undefined;
}
/**
* This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and
* is meant for Azure SDK to enhance Managed Identity support.
*
* @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source.
*/
SetAppTokenProvider(provider){
this.appTokenProvider=provider;
}
/**
* Acquires tokens from the authority for the application (not for an end user).
*/
asyncacquireTokenByClientCredential(request){
this.logger.info("acquireTokenByClientCredential called",request.correlationId);// If there is a client assertion present in the request, it overrides the one present in the client configuration
letclientAssertion;
if(request.clientAssertion){
clientAssertion={
assertion:request.clientAssertion,
assertionType:Constants.JWT_BEARER_ASSERTION_TYPE
};
}
constbaseRequest=awaitthis.initializeBaseRequest(request);// valid base request should not contain oidc scopes in this grant type
{"version":3,"file":"msal-node.esm.js","sources":["../src/utils/Constants.ts","../src/utils/NetworkUtils.ts","../src/network/HttpClient.ts","../src/config/Configuration.ts","../src/crypto/GuidGenerator.ts","../src/utils/EncodingUtils.ts","../src/crypto/HashUtils.ts","../src/crypto/PkceGenerator.ts","../src/crypto/CryptoProvider.ts","../src/cache/serializer/Deserializer.ts","../src/cache/serializer/Serializer.ts","../src/cache/NodeStorage.ts","../src/cache/TokenCache.ts","../src/packageMetadata.ts","../src/error/NodeAuthError.ts","../src/client/ClientApplication.ts","../src/network/LoopbackClient.ts","../src/client/PublicClientApplication.ts","../src/client/ClientAssertion.ts","../src/client/ConfidentialClientApplication.ts","../src/cache/distributed/DistributedCachePlugin.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * http methods\n */\nexport enum HttpMethod {\n GET = \"get\",\n POST = \"post\",\n}\n\nexport enum HttpStatus {\n SUCCESS_RANGE_START = 200,\n SUCCESS_RANGE_END = 299,\n REDIRECT = 302,\n CLIENT_ERROR_RANGE_START = 400,\n CLIENT_ERROR_RANGE_END = 499,\n SERVER_ERROR_RANGE_START = 500,\n SERVER_ERROR_RANGE_END = 599\n}\n\nexport enum ProxyStatus {\n SUCCESS_RANGE_START = 200,\n SUCCESS_RANGE_END = 299,\n SERVER_ERROR = 500\n}\n\n/**\n * Constants used for region discovery\n */\nexport const REGION_ENVIRONMENT_VARIABLE = \"REGION_NAME\";\n\n/**\n * Constant used for PKCE\n */\nexport const RANDOM_OCTET_SIZE = 32;\n\n/**\n * Constants used in PKCE\n */\nexport const Hash = {\n SHA256: \"sha256\",\n};\n\n/**\n * Constants for encoding schemes\n */\nexport const CharSet = {\n CV_CHARSET:\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~\",\n};\n\n/**\n * Cache Constants\n */\nexport const CACHE = {\n FILE_CACHE: \"fileCache\",\n EXTENSION_LIB: \"extenstion_library\",\n};\n\n/**\n * Constants\n */\nexport const Constants = {\n MSAL_SKU: \"msal.js.node\",\n JWT_BEARER_ASSERTION_TYPE: \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n AUTHORIZATION_PENDING: \"authorization_pending\",\n HTTP_PROTOCOL: \"http://\",\n LOCALHOST: \"localhost\"\n};\n\n/**\n * API Codes for Telemetry purposes.\n * Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs\n * 0-99 Silent Flow\n * 600-699 Device Code Flow\n * 800-899 Auth Code Flow\n */\nexport enum ApiId {\n acquireTokenSilent = 62,\n acquireTokenByUsernamePassword = 371,\n acquireTokenByDeviceCode = 671,\n acquireTokenByClientCredential = 771,\n acquireTokenByCode = 871,\n acquireTokenByRefreshToken = 872\n}\n\n/**\n * JWT constants\n */\nexport const JwtConstants = {\n ALGORITHM: \"alg\",\n RSA_256: \"RS256\",\n X5T: \"x5t\", \n X5C: \"x5c\",\n AUDIENCE: \"aud\",\n EXPIRATION_TIME: \"exp\",\n ISSUER: \"iss\",\n SUBJECT: \"sub\",\n NOT_BEFORE: \"nbf\",\n JWT_ID: \"jti\",\n};\n\nexport const LOOPBACK_SERVER_CONSTANTS = {\n INTERVAL_MS: 100,\n TIMEOUT_MS: 5000\n};\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NetworkResponse } from \"@azure/msal-common\";\n\nexport class NetworkUtils {\n static getNetworkResponse<T>(headers: Record<string, string>, body: T, statusCode: number): NetworkResponse<T> {\n return {\n headers: headers,\n body: body,\n status: statusCode,\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n INetworkModule,\n NetworkRequestOptions,\n NetworkResponse\n} from \"@azure/msal-common\";\nimport { HttpMethod, Constants, HttpStatus, ProxyStatus } from \"../utils/Constants\";\nimport { NetworkUtils } from \"../utils/NetworkUtils\";\nimport http from \"http\";\nimport https from \"https\";\n\n/**\n * This class implements the API for network requests.\n */\nexport class HttpClient implements INetworkModule {\n\n /**\n * Http Get request\n * @param url\n * @param options\n */\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n ): Promise<NetworkResponse<T>> {\n if (options?.proxyUrl) {\n return networkRequestViaProxy(url, HttpMethod.GET, options);\n } else {\n return networkRequestViaHttps(url, HttpMethod.GET, options);\n }\n }\n\n /**\n * Http Post request\n * @param url\n * @param options\n */\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions,\n cancellationToken?: number,\n ): Promise<NetworkResponse<T>> {\n if (options?.proxyUrl) {\n return networkRequestViaProxy(url, HttpMethod.POST, options, cancellationToken);\n } else {\n return networkRequestViaHttps(url, HttpMethod.POST, options, cancellationToken);\n }\n }\n}\n\nconst networkRequestViaProxy = <T>(\n url: string,\n httpMethod: string,\n options: NetworkRequestOptions,\n timeout?: number,\n): Promise<NetworkResponse<T>> => {\n const headers = options?.headers || {} as Record<string, string>;\n const proxyUrl = new URL(options?.proxyUrl || \"\");\n const destinationUrl = new URL(url);\n\n // \"method: connect\" must be used to establish a connection to the proxy\n const tunnelRequestOptions: https.RequestOptions = {\n host: proxyUrl.hostname,\n port: proxyUrl.port,\n method: \"CONNECT\",\n path: destinationUrl.hostname,\n headers: headers,\n };\n\n if (timeout) {\n tunnelRequestOptions.timeout = timeout;\n }\n\n // compose a request string for the socket\n let postRequestStringContent: string = \"\";\n if (httpMethod === HttpMethod.POST) {\n const body = options?.body || \"\";\n postRequestStringContent =\n \"Content-Type: application/x-www-form-urlencoded\\r\\n\" +\n `Content-Length: ${body.length}\\r\\n` +\n `\\r\\n${body}`;\n }\n const outgoingRequestString = `${httpMethod.toUpperCase()} ${destinationUrl.href} HTTP/1.1\\r\\n` +\n `Host: ${destinationUrl.host}\\r\\n` +\n \"Connection: close\\r\\n\" +\n postRequestStringContent +\n \"\\r\\n\";\n\n return new Promise<NetworkResponse<T>>(((resolve, reject) => {\n const request = http.request(tunnelRequestOptions);\n\n if (tunnelRequestOptions.timeout) {\n request.on(\"timeout\", () => {\n request.destroy();\n reject(new Error(\"Request time out\"));\n });\n }\n\n request.end();\n\n // establish connection to the proxy\n request.on(\"connect\", (response, socket) => {\n const proxyStatusCode = response?.statusCode || ProxyStatus.SERVER_ERROR;\n if ((proxyStatusCode < ProxyStatus.SUCCESS_RANGE_START) || (proxyStatusCode > ProxyStatus.SUCCESS_RANGE_END)) {\n request.destroy();\n socket.destroy();\n reject(new Error(`Error connecting to proxy. Http status code: ${response.statusCode}. Http status message: ${response?.statusMessage || \"Unknown\"}`));\n }\n if (tunnelRequestOptions.timeout) {\n socket.setTimeout(tunnelRequestOptions.timeout);\n socket.on(\"timeout\", () => {\n request.destroy();\n socket.destroy();\n reject(new Error(\"Request time out\"));\n });\n }\n\n // make a request over an HTTP tunnel\n socket.write(outgoingRequestString);\n\n const data: Buffer[] = [];\n socket.on(\"data\", (chunk) => {\n data.push(chunk);\n });\n\n socket.on(\"end\", () => {\n // combine all received buffer streams into one buffer, and then into a string\n const dataString = Buffer.concat([...data]).toString();\n\n // separate each line into it's own entry in an arry\n const dataStringArray = dataString.split(\"\\r\\n\");\n // the first entry will contain the statusCode and statusMessage\n const httpStatusCode = parseInt(dataStringArray[0].split(\" \")[1]);\n // remove \"HTTP/1.1\" and the status code to get the status message\n const statusMessage = dataStringArray[0].split(\" \").slice(2).join(\" \");\n // the last entry will contain the body\n const body = dataStringArray[dataStringArray.length - 1];\n\n // everything in between the first and last entries are the headers\n const headersArray = dataStringArray.slice(1, dataStringArray.length - 2);\n\n // build an object out of all the headers\n const entries = new Map();\n headersArray.forEach((header) => {\n /**\n * the header might look like \"Content-Length: 1531\", but that is just a string\n * it needs to be converted to a key/value pair\n * split the string at the first instance of \":\"\n * there may be more than one \":\" if the value of the header is supposed to be a JSON object\n */\n const headerKeyValue = header.split(new RegExp(/:\\s(.*)/s));\n const headerKey = headerKeyValue[0];\n let headerValue = headerKeyValue[1];\n\n // check if the value of the header is supposed to be a JSON object\n try {\n const object = JSON.parse(headerValue);\n\n // if it is, then convert it from a string to a JSON object\n if (object && (typeof object === \"object\")) {\n headerValue = object;\n }\n } catch (e) {\n // otherwise, leave it as a string\n }\n\n entries.set(headerKey, headerValue);\n });\n const headers = Object.fromEntries(entries);\n\n const parsedHeaders = headers as Record<string, string>;\n const networkResponse = NetworkUtils.getNetworkResponse(\n parsedHeaders,\n parseBody(httpStatusCode, statusMessage, parsedHeaders, body) as T,\n httpStatusCode\n );\n\n if (((httpStatusCode < HttpStatus.SUCCESS_RANGE_START) || (httpStatusCode > HttpStatus.SUCCESS_RANGE_END)) &&\n // do not destroy the request for the device code flow\n networkResponse.body[\"error\"] !== Constants.AUTHORIZATION_PENDING) {\n request.destroy();\n }\n resolve(networkResponse);\n });\n\n socket.on(\"error\", (chunk) => {\n request.destroy();\n socket.destroy();\n reject(new Error(chunk.toString()));\n });\n });\n\n request.on(\"error\", (chunk) => {\n request.destroy();\n reject(new Error(chunk.toString()));\n });\n }));\n};\n\nconst networkRequestViaHttps = <T>(\n url: string,\n httpMethod: string,\n options?: NetworkRequestOptions,\n timeout?: number,\n): Promise<NetworkResponse<T>> => {\n const isPostRequest = httpMethod === HttpMethod.POST;\n const body: string = options?.body || \"\";\n\n const emptyHeaders: Record<string, string> = {};\n const customOptions: https.RequestOptions = {\n method: httpMethod,\n headers: options?.headers || emptyHeaders,\n };\n\n if (timeout) {\n customOptions.timeout = timeout;\n }\n\n if (isPostRequest) {\n // needed for post request to work\n customOptions.headers = {\n ...customOptions.headers,\n \"Content-Length\": body.length,\n };\n }\n\n return new Promise<NetworkResponse<T>>((resolve, reject) => {\n const request = https.request(url, customOptions);\n\n if (timeout) {\n request.on(\"timeout\", () => {\n request.destroy();\n reject(new Error(\"Request time out\"));\n });\n }\n\n if (isPostRequest) {\n request.write(body);\n }\n\n request.end();\n\n request.on(\"response\", (response) => {\n const headers = response.headers;\n const statusCode = response.statusCode as number;\n const statusMessage = response.statusMessage;\n\n const data: Buffer[] = [];\n response.on(\"data\", (chunk) => {\n data.push(chunk);\n });\n\n response.on(\"end\", () => {\n // combine all received buffer streams into one buffer, and then into a string\n const body = Buffer.concat([...data]).toString();\n\n const parsedHeaders = headers as Record<string, string>;\n const networkResponse = NetworkUtils.getNetworkResponse(\n parsedHeaders,\n parseBody(statusCode, statusMessage, parsedHeaders, body) as T,\n statusCode\n );\n\n if (((statusCode < HttpStatus.SUCCESS_RANGE_START) || (statusCode > HttpStatus.SUCCESS_RANGE_END)) &&\n // do not destroy the request for the device code flow\n networkResponse.body[\"error\"] !== Constants.AUTHORIZATION_PENDING) {\n request.destroy();\n }\n resolve(networkResponse);\n });\n });\n\n request.on(\"error\", (chunk) => {\n request.destroy();\n reject(new Error(chunk.toString()));\n });\n });\n};\n\n/**\n * Check if extra parsing is needed on the repsonse from the server\n * @param statusCode {number} the status code of the response from the server\n * @param statusMessage {string | undefined} the status message of the response from the server\n * @param headers {Record<string, string>} the headers of the response from the server\n * @param body {string} the body from the response of the server\n * @returns {Object} JSON parsed body or error object\n */\nconst parseBody = (statusCode: number, statusMessage: string | undefined, headers: Record<string, string>, body: string) => {\n /*\n * Informational responses (100 – 199)\n * Successful responses (200 – 299)\n * Redirection messages (300 – 399)\n * Client error responses (400 – 499)\n * Server error responses (500 – 599)\n */\n \n let parsedBody;\n try {\n parsedBody = JSON.parse(body);\n } catch (error) {\n let errorType;\n let errorDescriptionHelper;\n if ((statusCode >= HttpStatus.CLIENT_ERROR_RANGE_START) && (statusCode <= HttpStatus.CLIENT_ERROR_RANGE_END)) {\n errorType = \"client_error\";\n errorDescriptionHelper = \"A client\";\n } else if ((statusCode >= HttpStatus.SERVER_ERROR_RANGE_START) && (statusCode <= HttpStatus.SERVER_ERROR_RANGE_END)) {\n errorType = \"server_error\";\n errorDescriptionHelper = \"A server\";\n } else {\n errorType = \"unknown_error\";\n errorDescriptionHelper = \"An unknown\";\n }\n\n parsedBody = {\n error: errorType,\n error_description: `${errorDescriptionHelper} error occured.\\nHttp status code: ${statusCode}\\nHttp status message: ${statusMessage || \"Unknown\"}\\nHeaders: ${JSON.stringify(headers)}`\n };\n }\n\n return parsedBody;\n};\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n LoggerOptions,\n INetworkModule,\n LogLevel,\n ProtocolMode,\n ICachePlugin,\n Constants,\n AzureCloudInstance,\n AzureCloudOptions,\n ApplicationTelemetry\n} from \"@azure/msal-common\";\nimport { HttpClient } from \"../network/HttpClient\";\n\n/**\n * - clientId - Client id of the application.\n * - authority - Url of the authority. If no value is set, defaults to https://login.microsoftonline.com/common.\n * - knownAuthorities - Needed for Azure B2C and ADFS. All authorities that will be used in the client application. Only the host of the authority should be passed in.\n * - clientSecret - Secret string that the application uses when requesting a token. Only used in confidential client applications. Can be created in the Azure app registration portal.\n * - clientAssertion - Assertion string that the application uses when requesting a token. Only used in confidential client applications. Assertion should be of type urn:ietf:params:oauth:client-assertion-type:jwt-bearer.\n * - clientCertificate - Certificate that the application uses when requesting a token. Only used in confidential client applications. Requires hex encoded X.509 SHA-1 thumbprint of the certificiate, and the PEM encoded private key (string should contain -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- )\n * - protocolMode - Enum that represents the protocol that msal follows. Used for configuring proper endpoints.\n * - skipAuthorityMetadataCache - A flag to choose whether to use or not use the local metadata cache during authority initialization. Defaults to false.\n * @public\n */\nexport type NodeAuthOptions = {\n clientId: string;\n authority?: string;\n clientSecret?: string;\n clientAssertion?: string;\n clientCertificate?: {\n thumbprint: string,\n privateKey: string,\n x5c?: string\n };\n knownAuthorities?: Array<string>;\n cloudDiscoveryMetadata?: string;\n authorityMetadata?: string;\n clientCapabilities?: Array<string>;\n protocolMode?: ProtocolMode;\n azureCloudOptions?: AzureCloudOptions;\n skipAuthorityMetadataCache?: boolean;\n};\n\n/**\n * Use this to configure the below cache configuration options:\n *\n * - cachePlugin - Plugin for reading and writing token cache to disk.\n * @public\n */\nexport type CacheOptions = {\n cachePlugin?: ICachePlugin;\n};\n\n/**\n * Type for configuring logger and http client options\n *\n * - logger - Used to initialize the Logger object; TODO: Expand on logger details or link to the documentation on logger\n * - networkClient - Http client used for all http get and post calls. Defaults to using MSAL's default http client.\n * @public\n */\nexport type NodeSystemOptions = {\n loggerOptions?: LoggerOptions;\n networkClient?: INetworkModule;\n proxyUrl?: string;\n};\n\nexport type NodeTelemetryOptions = {\n application?: ApplicationTelemetry;\n};\n\n/**\n * Use the configuration object to configure MSAL and initialize the client application object\n *\n * - auth: this is where you configure auth elements like clientID, authority used for authenticating against the Microsoft Identity Platform\n * - cache: this is where you configure cache location\n * - system: this is where you can configure the network client, logger\n * @public\n */\nexport type Configuration = {\n auth: NodeAuthOptions;\n cache?: CacheOptions;\n system?: NodeSystemOptions;\n telemetry?: NodeTelemetryOptions;\n};\n\nconst DEFAULT_AUTH_OPTIONS: Required<NodeAuthOptions> = {\n clientId: Constants.EMPTY_STRING,\n authority: Constants.DEFAULT_AUTHORITY,\n clientSecret: Constants.EMPTY_STRING,\n clientAssertion: Constants.EMPTY_STRING,\n clientCertificate: {\n thumbprint: Constants.EMPTY_STRING,\n privateKey: Constants.EMPTY_STRING,\n x5c: Constants.EMPTY_STRING\n },\n knownAuthorities: [],\n cloudDiscoveryMetadata: Constants.EMPTY_STRING,\n authorityMetadata: Constants.EMPTY_STRING,\n clientCapabilities: [],\n protocolMode: ProtocolMode.AAD,\n azureCloudOptions: {\n azureCloudInstance: AzureCloudInstance.None,\n tenant: Constants.EMPTY_STRING\n },\n skipAuthorityMetadataCache: false,\n};\n\nconst DEFAULT_CACHE_OPTIONS: CacheOptions = {};\n\nconst DEFAULT_LOGGER_OPTIONS: LoggerOptions = {\n loggerCallback: (): void => {\n // allow users to not set logger call back\n },\n piiLoggingEnabled: false,\n logLevel: LogLevel.Info,\n};\n\nconst DEFAULT_SYSTEM_OPTIONS: Required<NodeSystemOptions> = {\n loggerOptions: DEFAULT_LOGGER_OPTIONS,\n networkClient: new HttpClient(),\n proxyUrl: Constants.EMPTY_STRING,\n};\n\nconst DEFAULT_TELEMETRY_OPTIONS: Required<NodeTelemetryOptions> = {\n application: {\n appName: Constants.EMPTY_STRING,\n appVersion: Constants.EMPTY_STRING\n }\n};\n\nexport type NodeConfiguration = {\n auth: Required<NodeAuthOptions>;\n cache: CacheOptions;\n system: Required<NodeSystemOptions>;\n telemetry: Required<NodeTelemetryOptions>;\n};\n\n/**\n * Sets the default options when not explicitly configured from app developer\n *\n * @param auth - Authentication options\n * @param cache - Cache options\n * @param system - System options\n * @param telemetry - Telemetry options\n *\n * @returns Configuration\n * @public\n */\nexport function buildAppConfiguration({\n auth,\n cache,\n system,\n telemetry\n}: Configuration): NodeConfiguration {\n\n return {\n auth: { ...DEFAULT_AUTH_OPTIONS, ...auth },\n cache: { ...DEFAULT_CACHE_OPTIONS, ...cache },\n system: { ...DEFAULT_SYSTEM_OPTIONS, ...system },\n telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry }\n };\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IGuidGenerator } from \"@azure/msal-common\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nexport class GuidGenerator implements IGuidGenerator {\n /**\n *\n * RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers.\n * uuidv4 generates guids from cryprtographically-string random\n */\n generateGuid(): string {\n return uuidv4();\n }\n\n /**\n * verifies if a string is GUID\n * @param guid\n */\n isGuid(guid: string): boolean {\n const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return regexGuid.test(guid);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants } from \"@azure/msal-common\";\n\nexport class EncodingUtils {\n /**\n * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.\n * 'base64': Base64 encoding.\n *\n * @param str text\n */\n static base64Encode(str: string, encoding?: BufferEncoding): string {\n return Buffer.from(str, encoding).toString(\"base64\");\n }\n\n /**\n * encode a URL\n * @param str\n */\n static base64EncodeUrl(str: string, encoding?: BufferEncoding): string {\n return EncodingUtils.base64Encode(str, encoding)\n .replace(/=/g, Constants.EMPTY_STRING)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\");\n }\n\n /**\n * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.\n * 'base64': Base64 encoding.\n *\n * @param base64Str Base64 encoded text\n */\n static base64Decode(base64Str: string): string {\n return Buffer.from(base64Str, \"base64\").toString(\"utf8\");\n }\n\n /**\n * @param base64Str Base64 encoded Url\n */\n static base64DecodeUrl(base64Str: string): string {\n let str = base64Str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (str.length % 4) {\n str += \"=\";\n }\n return EncodingUtils.base64Decode(str);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Hash } from \"../utils/Constants\";\nimport crypto from \"crypto\";\n\nexport class HashUtils {\n /**\n * generate 'SHA256' hash\n * @param buffer\n */\n sha256(buffer: string): Buffer {\n return crypto\n .createHash(Hash.SHA256)\n .update(buffer)\n .digest();\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants, PkceCodes } from \"@azure/msal-common\";\nimport { CharSet, RANDOM_OCTET_SIZE } from \"../utils/Constants\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\nimport { HashUtils } from \"./HashUtils\";\nimport crypto from \"crypto\";\n\n/**\n * https://tools.ietf.org/html/rfc7636#page-8\n */\nexport class PkceGenerator {\n private hashUtils: HashUtils;\n\n constructor() {\n this.hashUtils = new HashUtils();\n }\n /**\n * generates the codeVerfier and the challenge from the codeVerfier\n * reference: https://tools.ietf.org/html/rfc7636#section-4.1 and https://tools.ietf.org/html/rfc7636#section-4.2\n */\n async generatePkceCodes(): Promise<PkceCodes> {\n const verifier = this.generateCodeVerifier();\n const challenge = this.generateCodeChallengeFromVerifier(verifier);\n return { verifier, challenge };\n }\n\n /**\n * generates the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.1\n */\n private generateCodeVerifier(): string {\n const charArr = [];\n const maxNumber = 256 - (256 % CharSet.CV_CHARSET.length);\n while (charArr.length <= RANDOM_OCTET_SIZE) {\n const byte = crypto.randomBytes(1)[0];\n if (byte >= maxNumber) {\n /* \n * Ignore this number to maintain randomness.\n * Including it would result in an unequal distribution of characters after doing the modulo\n */\n continue;\n }\n const index = byte % CharSet.CV_CHARSET.length;\n charArr.push(CharSet.CV_CHARSET[index]);\n }\n const verifier: string = charArr.join(Constants.EMPTY_STRING);\n return EncodingUtils.base64EncodeUrl(verifier);\n }\n\n /**\n * generate the challenge from the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.2\n * @param codeVerifier\n */\n private generateCodeChallengeFromVerifier(codeVerifier: string): string {\n return EncodingUtils.base64EncodeUrl(\n this.hashUtils.sha256(codeVerifier).toString(\"base64\"), \n \"base64\" \n );\n }\n\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ICrypto, PkceCodes } from \"@azure/msal-common\";\nimport { GuidGenerator } from \"./GuidGenerator\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\nimport { PkceGenerator } from \"./PkceGenerator\";\nimport { HashUtils } from \"./HashUtils\";\n\n/**\n * This class implements MSAL node's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and\n * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).\n * @public\n */\nexport class CryptoProvider implements ICrypto {\n private pkceGenerator: PkceGenerator;\n private guidGenerator: GuidGenerator;\n private hashUtils: HashUtils;\n\n constructor() {\n // Browser crypto needs to be validated first before any other classes can be set.\n this.pkceGenerator = new PkceGenerator();\n this.guidGenerator = new GuidGenerator();\n this.hashUtils = new HashUtils();\n }\n\n /**\n * Creates a new random GUID - used to populate state and nonce.\n * @returns string (GUID)\n */\n createNewGuid(): string {\n return this.guidGenerator.generateGuid();\n }\n\n /**\n * Encodes input string to base64.\n * @param input - string to be encoded\n */\n base64Encode(input: string): string {\n return EncodingUtils.base64Encode(input);\n }\n\n /**\n * Decodes input string from base64.\n * @param input - string to be decoded\n */\n base64Decode(input: string): string {\n return EncodingUtils.base64Decode(input);\n }\n\n /**\n * Generates PKCE codes used in Authorization Code Flow.\n */\n generatePkceCodes(): Promise<PkceCodes> {\n return this.pkceGenerator.generatePkceCodes();\n }\n\n /**\n * Generates a keypair, stores it and returns a thumbprint - not yet implemented for node\n */\n getPublicKeyThumbprint(): Promise<string> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Removes cryptographic keypair from key store matching the keyId passed in\n * @param kid \n */\n removeTokenBindingKey(): Promise<boolean> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Removes all cryptographic keys from Keystore\n */\n clearKeystore(): Promise<boolean> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node\n */\n signJwt(): Promise<string> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Returns the SHA-256 hash of an input string\n */\n async hashString(plainText: string): Promise<string> {\n return EncodingUtils.base64EncodeUrl(\n this.hashUtils.sha256(plainText).toString(\"base64\"), \n \"base64\" \n );\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { StringUtils, AccountCache, IdTokenCache, AccessTokenCache, RefreshTokenCache, AppMetadataCache, AccountEntity, IdTokenEntity, AccessTokenEntity, RefreshTokenEntity, AppMetadataEntity, CacheManager } from \"@azure/msal-common\";\nimport { JsonCache, InMemoryCache, SerializedAccountEntity, SerializedIdTokenEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedAppMetadataEntity } from \"./SerializerTypes\";\n\n/**\n * This class deserializes cache entities read from the file into in memory object types defined internally\n */\nexport class Deserializer {\n /**\n * Parse the JSON blob in memory and deserialize the content\n * @param cachedJson\n */\n static deserializeJSONBlob(jsonFile: string): JsonCache {\n const deserializedCache = StringUtils.isEmpty(jsonFile)\n ? {}\n : JSON.parse(jsonFile);\n return deserializedCache;\n }\n\n /**\n * Deserializes accounts to AccountEntity objects\n * @param accounts\n */\n static deserializeAccounts(accounts: Record<string, SerializedAccountEntity>): AccountCache {\n const accountObjects: AccountCache = {};\n if (accounts) {\n Object.keys(accounts).map(function (key) {\n const serializedAcc = accounts[key];\n const mappedAcc = {\n homeAccountId: serializedAcc.home_account_id,\n environment: serializedAcc.environment,\n realm: serializedAcc.realm,\n localAccountId: serializedAcc.local_account_id,\n username: serializedAcc.username,\n authorityType: serializedAcc.authority_type,\n name: serializedAcc.name,\n clientInfo: serializedAcc.client_info,\n lastModificationTime: serializedAcc.last_modification_time,\n lastModificationApp: serializedAcc.last_modification_app,\n };\n const account: AccountEntity = new AccountEntity();\n CacheManager.toObject(account, mappedAcc);\n accountObjects[key] = account;\n });\n }\n\n return accountObjects;\n }\n\n /**\n * Deserializes id tokens to IdTokenEntity objects\n * @param idTokens\n */\n static deserializeIdTokens(idTokens: Record<string, SerializedIdTokenEntity>): IdTokenCache {\n const idObjects: IdTokenCache = {};\n if (idTokens) {\n Object.keys(idTokens).map(function (key) {\n const serializedIdT = idTokens[key];\n const mappedIdT = {\n homeAccountId: serializedIdT.home_account_id,\n environment: serializedIdT.environment,\n credentialType: serializedIdT.credential_type,\n clientId: serializedIdT.client_id,\n secret: serializedIdT.secret,\n realm: serializedIdT.realm,\n };\n const idToken: IdTokenEntity = new IdTokenEntity();\n CacheManager.toObject(idToken, mappedIdT);\n idObjects[key] = idToken;\n });\n }\n return idObjects;\n }\n\n /**\n * Deserializes access tokens to AccessTokenEntity objects\n * @param accessTokens\n */\n static deserializeAccessTokens(accessTokens: Record<string, SerializedAccessTokenEntity>): AccessTokenCache {\n const atObjects: AccessTokenCache = {};\n if (accessTokens) {\n Object.keys(accessTokens).map(function (key) {\n const serializedAT = accessTokens[key];\n const mappedAT = {\n homeAccountId: serializedAT.home_account_id,\n environment: serializedAT.environment,\n credentialType: serializedAT.credential_type,\n clientId: serializedAT.client_id,\n secret: serializedAT.secret,\n realm: serializedAT.realm,\n target: serializedAT.target,\n cachedAt: serializedAT.cached_at,\n expiresOn: serializedAT.expires_on,\n extendedExpiresOn: serializedAT.extended_expires_on,\n refreshOn: serializedAT.refresh_on,\n keyId: serializedAT.key_id,\n tokenType: serializedAT.token_type,\n requestedClaims: serializedAT.requestedClaims,\n requestedClaimsHash: serializedAT.requestedClaimsHash,\n userAssertionHash: serializedAT.userAssertionHash,\n };\n const accessToken: AccessTokenEntity = new AccessTokenEntity();\n CacheManager.toObject(accessToken, mappedAT);\n atObjects[key] = accessToken;\n });\n }\n\n return atObjects;\n }\n\n /**\n * Deserializes refresh tokens to RefreshTokenEntity objects\n * @param refreshTokens\n */\n static deserializeRefreshTokens(refreshTokens: Record<string, SerializedRefreshTokenEntity>): RefreshTokenCache {\n const rtObjects: RefreshTokenCache = {};\n if (refreshTokens) {\n Object.keys(refreshTokens).map(function (key) {\n const serializedRT = refreshTokens[key];\n const mappedRT = {\n homeAccountId: serializedRT.home_account_id,\n environment: serializedRT.environment,\n credentialType: serializedRT.credential_type,\n clientId: serializedRT.client_id,\n secret: serializedRT.secret,\n familyId: serializedRT.family_id,\n target: serializedRT.target,\n realm: serializedRT.realm,\n };\n const refreshToken: RefreshTokenEntity = new RefreshTokenEntity();\n CacheManager.toObject(refreshToken, mappedRT);\n rtObjects[key] = refreshToken;\n });\n }\n\n return rtObjects;\n }\n\n /**\n * Deserializes appMetadata to AppMetaData objects\n * @param appMetadata\n */\n static deserializeAppMetadata(appMetadata: Record<string, SerializedAppMetadataEntity>): AppMetadataCache {\n const appMetadataObjects: AppMetadataCache = {};\n if (appMetadata) {\n Object.keys(appMetadata).map(function (key) {\n const serializedAmdt = appMetadata[key];\n const mappedAmd = {\n clientId: serializedAmdt.client_id,\n environment: serializedAmdt.environment,\n familyId: serializedAmdt.family_id,\n };\n const amd: AppMetadataEntity = new AppMetadataEntity();\n CacheManager.toObject(amd, mappedAmd);\n appMetadataObjects[key] = amd;\n });\n }\n\n return appMetadataObjects;\n }\n\n /**\n * Deserialize an inMemory Cache\n * @param jsonCache\n */\n static deserializeAllCache(jsonCache: JsonCache): InMemoryCache {\n return {\n accounts: jsonCache.Account\n ? this.deserializeAccounts(jsonCache.Account)\n : {},\n idTokens: jsonCache.IdToken\n ? this.deserializeIdTokens(jsonCache.IdToken)\n : {},\n accessTokens: jsonCache.AccessToken\n ? this.deserializeAccessTokens(jsonCache.AccessToken)\n : {},\n refreshTokens: jsonCache.RefreshToken\n ? this.deserializeRefreshTokens(jsonCache.RefreshToken)\n : {},\n appMetadata: jsonCache.AppMetadata\n ? this.deserializeAppMetadata(jsonCache.AppMetadata)\n : {},\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AccountCache, IdTokenCache, AccessTokenCache, RefreshTokenCache, AppMetadataCache } from \"@azure/msal-common\";\nimport { InMemoryCache, JsonCache, SerializedAccountEntity, SerializedIdTokenEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedAppMetadataEntity } from \"./SerializerTypes\";\n\nexport class Serializer {\n /**\n * serialize the JSON blob\n * @param data\n */\n static serializeJSONBlob(data: JsonCache): string {\n return JSON.stringify(data);\n }\n\n /**\n * Serialize Accounts\n * @param accCache\n */\n static serializeAccounts(accCache: AccountCache): Record<string, SerializedAccountEntity> {\n const accounts: Record<string, SerializedAccountEntity> = {};\n Object.keys(accCache).map(function (key) {\n const accountEntity = accCache[key];\n accounts[key] = {\n home_account_id: accountEntity.homeAccountId,\n environment: accountEntity.environment,\n realm: accountEntity.realm,\n local_account_id: accountEntity.localAccountId,\n username: accountEntity.username,\n authority_type: accountEntity.authorityType,\n name: accountEntity.name,\n client_info: accountEntity.clientInfo,\n last_modification_time: accountEntity.lastModificationTime,\n last_modification_app: accountEntity.lastModificationApp,\n };\n });\n\n return accounts;\n }\n\n /**\n * Serialize IdTokens\n * @param idTCache\n */\n static serializeIdTokens(idTCache: IdTokenCache): Record<string, SerializedIdTokenEntity> {\n const idTokens: Record<string, SerializedIdTokenEntity> = {};\n Object.keys(idTCache).map(function (key) {\n const idTEntity = idTCache[key];\n idTokens[key] = {\n home_account_id: idTEntity.homeAccountId,\n environment: idTEntity.environment,\n credential_type: idTEntity.credentialType,\n client_id: idTEntity.clientId,\n secret: idTEntity.secret,\n realm: idTEntity.realm,\n };\n });\n\n return idTokens;\n }\n\n /**\n * Serializes AccessTokens\n * @param atCache\n */\n static serializeAccessTokens(atCache: AccessTokenCache): Record<string, SerializedAccessTokenEntity> {\n const accessTokens: Record<string, SerializedAccessTokenEntity> = {};\n Object.keys(atCache).map(function (key) {\n const atEntity = atCache[key];\n accessTokens[key] = {\n home_account_id: atEntity.homeAccountId,\n environment: atEntity.environment,\n credential_type: atEntity.credentialType,\n client_id: atEntity.clientId,\n secret: atEntity.secret,\n realm: atEntity.realm,\n target: atEntity.target,\n cached_at: atEntity.cachedAt,\n expires_on: atEntity.expiresOn,\n extended_expires_on: atEntity.extendedExpiresOn,\n refresh_on: atEntity.refreshOn,\n key_id: atEntity.keyId,\n token_type: atEntity.tokenType,\n requestedClaims: atEntity.requestedClaims,\n requestedClaimsHash: atEntity.requestedClaimsHash,\n userAssertionHash: atEntity.userAssertionHash\n };\n });\n\n return accessTokens;\n }\n\n /**\n * Serialize refreshTokens\n * @param rtCache\n */\n static serializeRefreshTokens(rtCache: RefreshTokenCache): Record<string, SerializedRefreshTokenEntity> {\n const refreshTokens: Record<string, SerializedRefreshTokenEntity> = {};\n Object.keys(rtCache).map(function (key) {\n const rtEntity = rtCache[key];\n refreshTokens[key] = {\n home_account_id: rtEntity.homeAccountId,\n environment: rtEntity.environment,\n credential_type: rtEntity.credentialType,\n client_id: rtEntity.clientId,\n secret: rtEntity.secret,\n family_id: rtEntity.familyId,\n target: rtEntity.target,\n realm: rtEntity.realm\n };\n });\n\n return refreshTokens;\n }\n\n /**\n * Serialize amdtCache\n * @param amdtCache\n */\n static serializeAppMetadata(amdtCache: AppMetadataCache): Record<string, SerializedAppMetadataEntity> {\n const appMetadata: Record<string, SerializedAppMetadataEntity> = {};\n Object.keys(amdtCache).map(function (key) {\n const amdtEntity = amdtCache[key];\n appMetadata[key] = {\n client_id: amdtEntity.clientId,\n environment: amdtEntity.environment,\n family_id: amdtEntity.familyId,\n };\n });\n\n return appMetadata;\n }\n\n /**\n * Serialize the cache\n * @param jsonContent\n */\n static serializeAllCache(inMemCache: InMemoryCache): JsonCache {\n return {\n Account: this.serializeAccounts(inMemCache.accounts),\n IdToken: this.serializeIdTokens(inMemCache.idTokens),\n AccessToken: this.serializeAccessTokens(inMemCache.accessTokens),\n RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens),\n AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata),\n };\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AccountEntity,\n IdTokenEntity,\n AccessTokenEntity,\n RefreshTokenEntity,\n AppMetadataEntity,\n ServerTelemetryEntity,\n ThrottlingEntity,\n CacheManager,\n Logger,\n ValidCacheType,\n ICrypto,\n AuthorityMetadataEntity,\n ValidCredentialType\n} from \"@azure/msal-common\";\nimport { Deserializer } from \"./serializer/Deserializer\";\nimport { Serializer } from \"./serializer/Serializer\";\nimport { InMemoryCache, JsonCache, CacheKVStore } from \"./serializer/SerializerTypes\";\n\n/**\n * This class implements Storage for node, reading cache from user specified storage location or an extension library\n * @public\n */\nexport class NodeStorage extends CacheManager {\n // Cache configuration, either set by user or default values.\n private logger: Logger;\n private cache: CacheKVStore = {};\n private changeEmitters: Array<Function> = [];\n\n constructor(logger: Logger, clientId: string, cryptoImpl: ICrypto) {\n super(clientId, cryptoImpl);\n this.logger = logger;\n }\n\n /**\n * Queue up callbacks\n * @param func - a callback function for cache change indication\n */\n registerChangeEmitter(func: () => void): void {\n this.changeEmitters.push(func);\n }\n\n /**\n * Invoke the callback when cache changes\n */\n emitChange(): void {\n this.changeEmitters.forEach(func => func.call(null));\n }\n\n /**\n * Converts cacheKVStore to InMemoryCache\n * @param cache - key value store\n */\n cacheToInMemoryCache(cache: CacheKVStore): InMemoryCache {\n const inMemoryCache: InMemoryCache = {\n accounts: {},\n idTokens: {},\n accessTokens: {},\n refreshTokens: {},\n appMetadata: {},\n };\n\n for (const key in cache) {\n if (cache[key as string] instanceof AccountEntity) {\n inMemoryCache.accounts[key] = cache[key] as AccountEntity;\n } else if (cache[key] instanceof IdTokenEntity) {\n inMemoryCache.idTokens[key] = cache[key] as IdTokenEntity;\n } else if (cache[key] instanceof AccessTokenEntity) {\n inMemoryCache.accessTokens[key] = cache[key] as AccessTokenEntity;\n } else if (cache[key] instanceof RefreshTokenEntity) {\n inMemoryCache.refreshTokens[key] = cache[key] as RefreshTokenEntity;\n } else if (cache[key] instanceof AppMetadataEntity) {\n inMemoryCache.appMetadata[key] = cache[key] as AppMetadataEntity;\n } else {\n continue;\n }\n }\n\n return inMemoryCache;\n }\n\n /**\n * converts inMemoryCache to CacheKVStore\n * @param inMemoryCache - kvstore map for inmemory\n */\n inMemoryCacheToCache(inMemoryCache: InMemoryCache): CacheKVStore {\n\n // convert in memory cache to a flat Key-Value map\n let cache = this.getCache();\n\n cache = {\n ...cache,\n ...inMemoryCache.accounts,\n ...inMemoryCache.idTokens,\n ...inMemoryCache.accessTokens,\n ...inMemoryCache.refreshTokens,\n ...inMemoryCache.appMetadata\n };\n\n // convert in memory cache to a flat Key-Value map\n return cache;\n }\n\n /**\n * gets the current in memory cache for the client\n */\n getInMemoryCache(): InMemoryCache {\n this.logger.trace(\"Getting in-memory cache\");\n\n // convert the cache key value store to inMemoryCache\n const inMemoryCache = this.cacheToInMemoryCache(this.getCache());\n return inMemoryCache;\n }\n\n /**\n * sets the current in memory cache for the client\n * @param inMemoryCache - key value map in memory\n */\n setInMemoryCache(inMemoryCache: InMemoryCache): void{\n this.logger.trace(\"Setting in-memory cache\");\n\n // convert and append the inMemoryCache to cacheKVStore\n const cache = this.inMemoryCacheToCache(inMemoryCache);\n this.setCache(cache);\n\n this.emitChange();\n }\n\n /**\n * get the current cache key-value store\n */\n getCache(): CacheKVStore {\n this.logger.trace(\"Getting cache key-value store\");\n return this.cache;\n }\n\n /**\n * sets the current cache (key value store)\n * @param cacheMap - key value map\n */\n setCache(cache: CacheKVStore): void {\n this.logger.trace(\"Setting cache key value store\");\n this.cache = cache;\n\n // mark change in cache\n this.emitChange();\n }\n\n /**\n * Gets cache item with given key.\n * @param key - lookup key for the cache entry\n */\n getItem(key: string): ValidCacheType {\n this.logger.tracePii(`Item key: ${key}`);\n\n // read cache\n const cache = this.getCache();\n return cache[key];\n }\n\n /**\n * Gets cache item with given key-value\n * @param key - lookup key for the cache entry\n * @param value - value of the cache entry\n */\n setItem(key: string, value: ValidCacheType): void {\n this.logger.tracePii(`Item key: ${key}`);\n\n // read cache\n const cache = this.getCache();\n cache[key] = value;\n\n // write to cache\n this.setCache(cache);\n }\n\n /**\n * fetch the account entity\n * @param accountKey - lookup key to fetch cache type AccountEntity\n */\n getAccount(accountKey: string): AccountEntity | null {\n const account = this.getItem(accountKey) as AccountEntity;\n if (AccountEntity.isAccountEntity(account)) {\n return account;\n }\n return null;\n }\n\n /**\n * set account entity\n * @param account - cache value to be set of type AccountEntity\n */\n setAccount(account: AccountEntity): void {\n const accountKey = account.generateAccountKey();\n this.setItem(accountKey, account);\n }\n\n /**\n * fetch the idToken credential\n * @param idTokenKey - lookup key to fetch cache type IdTokenEntity\n */\n getIdTokenCredential(idTokenKey: string): IdTokenEntity | null {\n const idToken = this.getItem(idTokenKey) as IdTokenEntity;\n if (IdTokenEntity.isIdTokenEntity(idToken)) {\n return idToken;\n }\n return null;\n }\n\n /**\n * set idToken credential\n * @param idToken - cache value to be set of type IdTokenEntity\n */\n setIdTokenCredential(idToken: IdTokenEntity): void {\n const idTokenKey = idToken.generateCredentialKey();\n this.setItem(idTokenKey, idToken);\n }\n\n /**\n * fetch the accessToken credential\n * @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity\n */\n getAccessTokenCredential(accessTokenKey: string): AccessTokenEntity | null {\n const accessToken = this.getItem(accessTokenKey) as AccessTokenEntity;\n if (AccessTokenEntity.isAccessTokenEntity(accessToken)) {\n return accessToken;\n }\n return null;\n }\n\n /**\n * set accessToken credential\n * @param accessToken - cache value to be set of type AccessTokenEntity\n */\n setAccessTokenCredential(accessToken: AccessTokenEntity): void {\n const accessTokenKey = accessToken.generateCredentialKey();\n this.setItem(accessTokenKey, accessToken);\n }\n\n /**\n * fetch the refreshToken credential\n * @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity\n */\n getRefreshTokenCredential(refreshTokenKey: string): RefreshTokenEntity | null {\n const refreshToken = this.getItem(refreshTokenKey) as RefreshTokenEntity;\n if (RefreshTokenEntity.isRefreshTokenEntity(refreshToken)) {\n return refreshToken as RefreshTokenEntity;\n }\n return null;\n }\n\n /**\n * set refreshToken credential\n * @param refreshToken - cache value to be set of type RefreshTokenEntity\n */\n setRefreshTokenCredential(refreshToken: RefreshTokenEntity): void {\n const refreshTokenKey = refreshToken.generateCredentialKey();\n this.setItem(refreshTokenKey, refreshToken);\n }\n\n /**\n * fetch appMetadata entity from the platform cache\n * @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity\n */\n getAppMetadata(appMetadataKey: string): AppMetadataEntity | null {\n const appMetadata: AppMetadataEntity = this.getItem(appMetadataKey) as AppMetadataEntity;\n if (AppMetadataEntity.isAppMetadataEntity(appMetadataKey, appMetadata)) {\n return appMetadata;\n }\n return null;\n }\n\n /**\n * set appMetadata entity to the platform cache\n * @param appMetadata - cache value to be set of type AppMetadataEntity\n */\n setAppMetadata(appMetadata: AppMetadataEntity): void {\n const appMetadataKey = appMetadata.generateAppMetadataKey();\n this.setItem(appMetadataKey, appMetadata);\n }\n\n /**\n * fetch server telemetry entity from the platform cache\n * @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity\n */\n getServerTelemetry(serverTelemetrykey: string): ServerTelemetryEntity | null {\n const serverTelemetryEntity: ServerTelemetryEntity = this.getItem(serverTelemetrykey) as ServerTelemetryEntity;\n if (serverTelemetryEntity && ServerTelemetryEntity.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) {\n return serverTelemetryEntity;\n }\n return null;\n }\n\n /**\n * set server telemetry entity to the platform cache\n * @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity\n * @param serverTelemetry - cache value to be set of type ServerTelemetryEntity\n */\n setServerTelemetry(serverTelemetryKey: string, serverTelemetry: ServerTelemetryEntity): void {\n this.setItem(serverTelemetryKey, serverTelemetry);\n }\n\n /**\n * fetch authority metadata entity from the platform cache\n * @param key - lookup key to fetch cache type AuthorityMetadataEntity\n */\n getAuthorityMetadata(key: string): AuthorityMetadataEntity | null {\n const authorityMetadataEntity: AuthorityMetadataEntity = this.getItem(key) as AuthorityMetadataEntity;\n if (authorityMetadataEntity && AuthorityMetadataEntity.isAuthorityMetadataEntity(key, authorityMetadataEntity)) {\n return authorityMetadataEntity;\n }\n return null;\n }\n\n /**\n * Get all authority metadata keys\n */\n getAuthorityMetadataKeys(): Array<string> {\n return this.getKeys().filter((key) => {\n return this.isAuthorityMetadata(key);\n });\n }\n\n /**\n * set authority metadata entity to the platform cache\n * @param key - lookup key to fetch cache type AuthorityMetadataEntity\n * @param metadata - cache value to be set of type AuthorityMetadataEntity\n */\n setAuthorityMetadata(key: string, metadata: AuthorityMetadataEntity): void {\n this.setItem(key, metadata);\n }\n\n /**\n * fetch throttling entity from the platform cache\n * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity\n */\n getThrottlingCache(throttlingCacheKey: string): ThrottlingEntity | null {\n const throttlingCache: ThrottlingEntity = this.getItem(throttlingCacheKey) as ThrottlingEntity;\n if (throttlingCache && ThrottlingEntity.isThrottlingEntity(throttlingCacheKey, throttlingCache)) {\n return throttlingCache;\n }\n return null;\n }\n\n /**\n * set throttling entity to the platform cache\n * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity\n * @param throttlingCache - cache value to be set of type ThrottlingEntity\n */\n setThrottlingCache(throttlingCacheKey: string, throttlingCache: ThrottlingEntity): void {\n this.setItem(throttlingCacheKey, throttlingCache);\n }\n\n /**\n * Removes the cache item from memory with the given key.\n * @param key - lookup key to remove a cache entity\n * @param inMemory - key value map of the cache\n */\n removeItem(key: string): boolean {\n this.logger.tracePii(`Item key: ${key}`);\n\n // read inMemoryCache\n let result: boolean = false;\n const cache = this.getCache();\n\n if (!!cache[key]) {\n delete cache[key];\n result = true;\n }\n\n // write to the cache after removal\n if (result) {\n this.setCache(cache);\n this.emitChange();\n }\n return result;\n }\n\n /**\n * Checks whether key is in cache.\n * @param key - look up key for a cache entity\n */\n containsKey(key: string): boolean {\n return this.getKeys().includes(key);\n }\n\n /**\n * Gets all keys in window.\n */\n getKeys(): string[] {\n this.logger.trace(\"Retrieving all cache keys\");\n\n // read cache\n const cache = this.getCache();\n return [ ...Object.keys(cache)];\n }\n\n /**\n * Clears all cache entries created by MSAL (except tokens).\n */\n async clear(): Promise<void> {\n this.logger.trace(\"Clearing cache entries created by MSAL\");\n\n // read inMemoryCache\n const cacheKeys = this.getKeys();\n\n // delete each element\n cacheKeys.forEach(key => {\n this.removeItem(key);\n });\n this.emitChange();\n }\n\n /**\n * Initialize in memory cache from an exisiting cache vault\n * @param cache - blob formatted cache (JSON)\n */\n static generateInMemoryCache(cache: string): InMemoryCache {\n return Deserializer.deserializeAllCache(\n Deserializer.deserializeJSONBlob(cache)\n );\n }\n\n /**\n * retrieves the final JSON\n * @param inMemoryCache - itemised cache read from the JSON\n */\n static generateJsonCache(inMemoryCache: InMemoryCache): JsonCache {\n return Serializer.serializeAllCache(inMemoryCache);\n }\n\n /**\n * Updates a credential's cache key if the current cache key is outdated\n */\n updateCredentialCacheKey(currentCacheKey: string, credential: ValidCredentialType): string {\n const updatedCacheKey = credential.generateCredentialKey();\n\n if (currentCacheKey !== updatedCacheKey) {\n const cacheItem = this.getItem(currentCacheKey);\n if (cacheItem) {\n this.removeItem(currentCacheKey);\n this.setItem(updatedCacheKey, cacheItem);\n this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`);\n return updatedCacheKey;\n } else {\n this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`);\n }\n }\n\n return currentCacheKey;\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NodeStorage } from \"./NodeStorage\";\nimport { StringUtils, AccountEntity, AccountInfo, Logger, ISerializableTokenCache, ICachePlugin, TokenCacheContext } from \"@azure/msal-common\";\nimport { InMemoryCache, JsonCache, SerializedAccountEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedIdTokenEntity, SerializedAppMetadataEntity, CacheKVStore } from \"./serializer/SerializerTypes\";\nimport { Deserializer } from \"./serializer/Deserializer\";\nimport { Serializer } from \"./serializer/Serializer\";\nimport { ITokenCache } from \"./ITokenCache\";\n\nconst defaultSerializedCache: JsonCache = {\n Account: {},\n IdToken: {},\n AccessToken: {},\n RefreshToken: {},\n AppMetadata: {},\n};\n\n/**\n * In-memory token cache manager\n * @public\n */\nexport class TokenCache implements ISerializableTokenCache, ITokenCache {\n\n private storage: NodeStorage;\n private cacheHasChanged: boolean;\n private cacheSnapshot: string;\n private readonly persistence: ICachePlugin;\n private logger: Logger;\n\n constructor(storage: NodeStorage, logger: Logger, cachePlugin?: ICachePlugin) {\n this.cacheHasChanged = false;\n this.storage = storage;\n this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this));\n if (cachePlugin) {\n this.persistence = cachePlugin;\n }\n this.logger = logger;\n }\n\n /**\n * Set to true if cache state has changed since last time serialize or writeToPersistence was called\n */\n hasChanged(): boolean {\n return this.cacheHasChanged;\n }\n\n /**\n * Serializes in memory cache to JSON\n */\n serialize(): string {\n this.logger.trace(\"Serializing in-memory cache\");\n let finalState = Serializer.serializeAllCache(\n this.storage.getInMemoryCache() as InMemoryCache\n );\n\n // if cacheSnapshot not null or empty, merge\n if (!StringUtils.isEmpty(this.cacheSnapshot)) {\n this.logger.trace(\"Reading cache snapshot from disk\");\n finalState = this.mergeState(\n JSON.parse(this.cacheSnapshot),\n finalState\n );\n } else {\n this.logger.trace(\"No cache snapshot to merge\");\n }\n this.cacheHasChanged = false;\n\n return JSON.stringify(finalState);\n }\n\n /**\n * Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format\n * @param cache - blob formatted cache\n */\n deserialize(cache: string): void {\n this.logger.trace(\"Deserializing JSON to in-memory cache\");\n this.cacheSnapshot = cache;\n\n if (!StringUtils.isEmpty(this.cacheSnapshot)) {\n this.logger.trace(\"Reading cache snapshot from disk\");\n const deserializedCache = Deserializer.deserializeAllCache(\n this.overlayDefaults(JSON.parse(this.cacheSnapshot))\n );\n this.storage.setInMemoryCache(deserializedCache);\n } else {\n this.logger.trace(\"No cache snapshot to deserialize\");\n }\n }\n\n /**\n * Fetches the cache key-value map\n */\n getKVStore(): CacheKVStore {\n return this.storage.getCache();\n }\n\n /**\n * API that retrieves all accounts currently in cache to the user\n */\n async getAllAccounts(): Promise<AccountInfo[]> {\n\n this.logger.trace(\"getAllAccounts called\");\n let cacheContext;\n try {\n if (this.persistence) {\n cacheContext = new TokenCacheContext(this, false);\n await this.persistence.beforeCacheAccess(cacheContext);\n }\n return this.storage.getAllAccounts();\n } finally {\n if (this.persistence && cacheContext) {\n await this.persistence.afterCacheAccess(cacheContext);\n }\n }\n }\n\n /**\n * Returns the signed in account matching homeAccountId.\n * (the account object is created at the time of successful login)\n * or null when no matching account is found\n * @param homeAccountId - unique identifier for an account (uid.utid)\n */\n async getAccountByHomeId(homeAccountId: string): Promise<AccountInfo | null> {\n const allAccounts = await this.getAllAccounts();\n if (!StringUtils.isEmpty(homeAccountId) && allAccounts && allAccounts.length) {\n return allAccounts.filter(accountObj => accountObj.homeAccountId === homeAccountId)[0] || null;\n } else {\n return null;\n }\n }\n\n /**\n * Returns the signed in account matching localAccountId.\n * (the account object is created at the time of successful login)\n * or null when no matching account is found\n * @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated)\n */\n async getAccountByLocalId(localAccountId: string): Promise<AccountInfo | null> {\n const allAccounts = await this.getAllAccounts();\n if (!StringUtils.isEmpty(localAccountId) && allAccounts && allAccounts.length) {\n return allAccounts.filter(accountObj => accountObj.localAccountId === localAccountId)[0] || null;\n } else {\n return null;\n }\n }\n\n /**\n * API to remove a specific account and the relevant data from cache\n * @param account - AccountInfo passed by the user\n */\n async removeAccount(account: AccountInfo): Promise<void> {\n this.logger.trace(\"removeAccount called\");\n let cacheContext;\n try {\n if (this.persistence) {\n cacheContext = new TokenCacheContext(this, true);\n await this.persistence.beforeCacheAccess(cacheContext);\n }\n await this.storage.removeAccount(AccountEntity.generateAccountCacheKey(account));\n } finally {\n if (this.persistence && cacheContext) {\n await this.persistence.afterCacheAccess(cacheContext);\n }\n }\n }\n\n /**\n * Called when the cache has changed state.\n */\n private handleChangeEvent() {\n this.cacheHasChanged = true;\n }\n\n /**\n * Merge in memory cache with the cache snapshot.\n * @param oldState - cache before changes\n * @param currentState - current cache state in the library\n */\n private mergeState(oldState: JsonCache, currentState: JsonCache): JsonCache {\n this.logger.trace(\"Merging in-memory cache with cache snapshot\");\n const stateAfterRemoval = this.mergeRemovals(oldState, currentState);\n return this.mergeUpdates(stateAfterRemoval, currentState);\n }\n\n /**\n * Deep update of oldState based on newState values\n * @param oldState - cache before changes\n * @param newState - updated cache\n */\n private mergeUpdates(oldState: object, newState: object): JsonCache {\n Object.keys(newState).forEach((newKey: string) => {\n const newValue = newState[newKey];\n\n // if oldState does not contain value but newValue does, add it\n if (!oldState.hasOwnProperty(newKey)) {\n if (newValue !== null) {\n oldState[newKey] = newValue;\n }\n } else {\n // both oldState and newState contain the key, do deep update\n const newValueNotNull = newValue !== null;\n const newValueIsObject = typeof newValue === \"object\";\n const newValueIsNotArray = !Array.isArray(newValue);\n const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== \"undefined\" && oldState[newKey] !== null;\n\n if (newValueNotNull && newValueIsObject && newValueIsNotArray && oldStateNotUndefinedOrNull) {\n this.mergeUpdates(oldState[newKey], newValue);\n } else {\n oldState[newKey] = newValue;\n }\n }\n });\n\n return oldState as JsonCache;\n }\n\n /**\n * Removes entities in oldState that the were removed from newState. If there are any unknown values in root of\n * oldState that are not recognized, they are left untouched.\n * @param oldState - cache before changes\n * @param newState - updated cache\n */\n private mergeRemovals(oldState: JsonCache, newState: JsonCache): JsonCache {\n this.logger.trace(\"Remove updated entries in cache\");\n const accounts = oldState.Account ? this.mergeRemovalsDict<SerializedAccountEntity>(oldState.Account, newState.Account) : oldState.Account;\n const accessTokens = oldState.AccessToken ? this.mergeRemovalsDict<SerializedAccessTokenEntity>(oldState.AccessToken, newState.AccessToken) : oldState.AccessToken;\n const refreshTokens = oldState.RefreshToken ? this.mergeRemovalsDict<SerializedRefreshTokenEntity>(oldState.RefreshToken, newState.RefreshToken) : oldState.RefreshToken;\n const idTokens = oldState.IdToken ? this.mergeRemovalsDict<SerializedIdTokenEntity>(oldState.IdToken, newState.IdToken) : oldState.IdToken;\n const appMetadata = oldState.AppMetadata ? this.mergeRemovalsDict<SerializedAppMetadataEntity>(oldState.AppMetadata, newState.AppMetadata) : oldState.AppMetadata;\n\n return {\n ...oldState,\n Account: accounts,\n AccessToken: accessTokens,\n RefreshToken: refreshTokens,\n IdToken: idTokens,\n AppMetadata: appMetadata\n };\n }\n\n /**\n * Helper to merge new cache with the old one\n * @param oldState - cache before changes\n * @param newState - updated cache\n */\n private mergeRemovalsDict<T>(oldState: Record<string, T>, newState?: Record<string, T>): Record<string, T> {\n const finalState = { ...oldState };\n Object.keys(oldState).forEach((oldKey) => {\n if (!newState || !(newState.hasOwnProperty(oldKey))) {\n delete finalState[oldKey];\n }\n });\n return finalState;\n }\n\n /**\n * Helper to overlay as a part of cache merge\n * @param passedInCache - cache read from the blob\n */\n private overlayDefaults(passedInCache: JsonCache): JsonCache {\n this.logger.trace(\"Overlaying input cache with the default cache\");\n return {\n Account: {\n ...defaultSerializedCache.Account,\n ...passedInCache.Account,\n },\n IdToken: {\n ...defaultSerializedCache.IdToken,\n ...passedInCache.IdToken,\n },\n AccessToken: {\n ...defaultSerializedCache.AccessToken,\n ...passedInCache.AccessToken,\n },\n RefreshToken: {\n ...defaultSerializedCache.RefreshToken,\n ...passedInCache.RefreshToken,\n },\n AppMetadata: {\n ...defaultSerializedCache.AppMetadata,\n ...passedInCache.AppMetadata,\n },\n };\n }\n}\n","/* eslint-disable header/header */\nexport const name = \"@azure/msal-node\";\nexport const version = \"1.14.5\";\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AuthError } from \"@azure/msal-common\";\n\n/**\n * NodeAuthErrorMessage class containing string constants used by error codes and messages.\n */\nexport const NodeAuthErrorMessage = {\n invalidLoopbackAddressType: {\n code: \"invalid_loopback_server_address_type\",\n desc: \"Loopback server address is not type string. This is unexpected.\"\n },\n unableToLoadRedirectUri: {\n code: \"unable_to_load_redirectUrl\",\n desc: \"Loopback server callback was invoked without a url. This is unexpected.\"\n },\n noAuthCodeInResponse: {\n code: \"no_auth_code_in_response\",\n desc: \"No auth code found in the server response. Please check your network trace to determine what happened.\"\n },\n noLoopbackServerExists: {\n code: \"no_loopback_server_exists\",\n desc: \"No loopback server exists yet.\"\n },\n loopbackServerAlreadyExists: {\n code: \"loopback_server_already_exists\",\n desc: \"Loopback server already exists. Cannot create another.\"\n },\n loopbackServerTimeout: {\n code: \"loopback_server_timeout\",\n desc: \"Timed out waiting for auth code listener to be registered.\"\n },\n stateNotFoundError: {\n code: \"state_not_found\",\n desc: \"State not found. Please verify that the request originated from msal.\"\n },\n};\n\nexport class NodeAuthError extends AuthError {\n constructor(errorCode: string, errorMessage?: string) {\n super(errorCode, errorMessage);\n this.name = \"NodeAuthError\";\n }\n\n /**\n * Creates an error thrown if loopback server address is of type string.\n */\n static createInvalidLoopbackAddressTypeError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code,\n `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`);\n }\n\n /**\n * Creates an error thrown if the loopback server is unable to get a url.\n */\n static createUnableToLoadRedirectUrlError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code,\n `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`);\n }\n\n /**\n * Creates an error thrown if the server response does not contain an auth code.\n */\n static createNoAuthCodeInResponseError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code,\n `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`);\n }\n\n /**\n * Creates an error thrown if the loopback server has not been spun up yet.\n */\n static createNoLoopbackServerExistsError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code,\n `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`);\n }\n\n /**\n * Creates an error thrown if a loopback server already exists when attempting to create another one.\n */\n static createLoopbackServerAlreadyExistsError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code,\n `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`);\n }\n\n /**\n * Creates an error thrown if the loopback server times out registering the auth code listener.\n */\n static createLoopbackServerTimeoutError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code,\n `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`);\n }\n\n /**\n * Creates an error thrown when the state is not present.\n */\n static createStateNotFoundError(): NodeAuthError {\n return new NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, NodeAuthErrorMessage.stateNotFoundError.desc);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AuthorizationCodeClient,\n ClientConfiguration,\n RefreshTokenClient,\n AuthenticationResult,\n Authority,\n AuthorityFactory,\n BaseAuthRequest,\n SilentFlowClient,\n Logger,\n ServerTelemetryManager,\n ServerTelemetryRequest,\n CommonSilentFlowRequest,\n CommonRefreshTokenRequest,\n CommonAuthorizationCodeRequest,\n CommonAuthorizationUrlRequest,\n CommonUsernamePasswordRequest,\n UsernamePasswordClient,\n AuthenticationScheme,\n ResponseMode,\n AuthorityOptions,\n OIDC_DEFAULT_SCOPES,\n AzureRegionConfiguration,\n AuthError,\n AzureCloudOptions,\n AuthorizationCodePayload,\n StringUtils,\n ClientAuthError,\n Constants,\n} from \"@azure/msal-common\";\nimport { Configuration, buildAppConfiguration, NodeConfiguration } from \"../config/Configuration\";\nimport { CryptoProvider } from \"../crypto/CryptoProvider\";\nimport { NodeStorage } from \"../cache/NodeStorage\";\nimport { Constants as NodeConstants, ApiId } from \"../utils/Constants\";\nimport { TokenCache } from \"../cache/TokenCache\";\nimport { ClientAssertion } from \"./ClientAssertion\";\nimport { AuthorizationUrlRequest } from \"../request/AuthorizationUrlRequest\";\nimport { AuthorizationCodeRequest } from \"../request/AuthorizationCodeRequest\";\nimport { RefreshTokenRequest } from \"../request/RefreshTokenRequest\";\nimport { SilentFlowRequest } from \"../request/SilentFlowRequest\";\nimport { version, name } from \"../packageMetadata\";\nimport { UsernamePasswordRequest } from \"../request/UsernamePasswordRequest\";\nimport { NodeAuthError } from \"../error/NodeAuthError\";\n\n/**\n * Base abstract class for all ClientApplications - public and confidential\n * @public\n */\nexport abstract class ClientApplication {\n\n protected readonly cryptoProvider: CryptoProvider;\n private tokenCache: TokenCache;\n\n /**\n * Platform storage object\n */\n protected storage: NodeStorage;\n /**\n * Logger object to log the application flow\n */\n protected logger: Logger;\n /**\n * Platform configuration initialized by the application\n */\n protected config: NodeConfiguration;\n /**\n * Client assertion passed by the user for confidential client flows\n */\n protected clientAssertion: ClientAssertion;\n /**\n * Client secret passed by the user for confidential client flows\n */\n protected clientSecret: string;\n\n /**\n * Constructor for the ClientApplication\n */\n protected constructor(configuration: Configuration) {\n this.config = buildAppConfiguration(configuration);\n this.cryptoProvider = new CryptoProvider();\n this.logger = new Logger(this.config.system.loggerOptions, name, version);\n this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider);\n this.tokenCache = new TokenCache(\n this.storage,\n this.logger,\n this.config.cache.cachePlugin\n );\n }\n\n /**\n * Creates the URL of the authorization request, letting the user input credentials and consent to the\n * application. The URL targets the /authorize endpoint of the authority configured in the\n * application object.\n *\n * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI\n * sent in the request and should contain an authorization code, which can then be used to acquire tokens via\n * `acquireTokenByCode(AuthorizationCodeRequest)`.\n */\n async getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string> {\n this.logger.info(\"getAuthCodeUrl called\", request.correlationId);\n const validRequest: CommonAuthorizationUrlRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n responseMode: request.responseMode || ResponseMode.QUERY,\n authenticationScheme: AuthenticationScheme.BEARER\n };\n\n const authClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n undefined,\n undefined,\n request.azureCloudOptions\n );\n const authorizationCodeClient = new AuthorizationCodeClient(\n authClientConfig\n );\n this.logger.verbose(\"Auth code client created\", validRequest.correlationId);\n return authorizationCodeClient.getAuthCodeUrl(validRequest);\n }\n\n /**\n * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0\n * Authorization Code flow.\n *\n * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0\n * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and\n * AuthorizationCodeRequest are the same.\n */\n async acquireTokenByCode(request: AuthorizationCodeRequest, authCodePayLoad?: AuthorizationCodePayload): Promise<AuthenticationResult> {\n this.logger.info(\"acquireTokenByCode called\");\n if (request.state && authCodePayLoad){\n this.logger.info(\"acquireTokenByCode - validating state\");\n this.validateState(request.state, authCodePayLoad.state || \"\");\n // eslint-disable-next-line no-param-reassign\n authCodePayLoad= {...authCodePayLoad, state: \"\"};\n }\n const validRequest: CommonAuthorizationCodeRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n authenticationScheme: AuthenticationScheme.BEARER\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId);\n try {\n const authClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const authorizationCodeClient = new AuthorizationCodeClient(\n authClientConfig\n );\n this.logger.verbose(\"Auth code client created\", validRequest.correlationId);\n return authorizationCodeClient.acquireToken(validRequest, authCodePayLoad);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires a token by exchanging the refresh token provided for a new set of tokens.\n *\n * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is\n * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will\n * handle the caching and refreshing of tokens automatically.\n */\n async acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByRefreshToken called\", request.correlationId);\n const validRequest: CommonRefreshTokenRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n authenticationScheme: AuthenticationScheme.BEARER\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId);\n try {\n const refreshTokenClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const refreshTokenClient = new RefreshTokenClient(\n refreshTokenClientConfig\n );\n this.logger.verbose(\"Refresh token client created\", validRequest.correlationId);\n return refreshTokenClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires a token silently when a user specifies the account the token is requested for.\n *\n * This API expects the user to provide an account object and looks into the cache to retrieve the token if present.\n * There is also an optional \"forceRefresh\" boolean the user can send to bypass the cache for access_token and id_token.\n * In case the refresh_token is expired or not found, an error is thrown\n * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).\n */\n async acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult | null> {\n const validRequest: CommonSilentFlowRequest = {\n ...request,\n ... await this.initializeBaseRequest(request),\n forceRefresh: request.forceRefresh || false\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);\n try {\n const silentFlowClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const silentFlowClient = new SilentFlowClient(\n silentFlowClientConfig\n );\n this.logger.verbose(\"Silent flow client created\", validRequest.correlationId);\n return silentFlowClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires tokens with password grant by exchanging client applications username and password for credentials\n *\n * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.\n * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4\n * Microsoft's documentation and recommendations are at:\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword\n *\n * @param request - UsenamePasswordRequest\n */\n async acquireTokenByUsernamePassword(request: UsernamePasswordRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByUsernamePassword called\", request.correlationId);\n const validRequest: CommonUsernamePasswordRequest = {\n ...request,\n ... await this.initializeBaseRequest(request)\n };\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);\n try {\n const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const usernamePasswordClient = new UsernamePasswordClient(usernamePasswordClientConfig);\n this.logger.verbose(\"Username password client created\", validRequest.correlationId);\n return usernamePasswordClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Gets the token cache for the application.\n */\n getTokenCache(): TokenCache {\n this.logger.info(\"getTokenCache called\");\n return this.tokenCache;\n }\n\n /**\n * Validates OIDC state by comparing the user cached state with the state received from the server.\n * \n * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against\n * CSRF attacks.\n * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.\n * @param state\n * @param cachedState\n */\n protected validateState(state: string, cachedState: string): void {\n if(!state) {\n throw NodeAuthError.createStateNotFoundError();\n }\n\n if(state !== cachedState) {\n throw ClientAuthError.createStateMismatchError();\n }\n }\n\n /**\n * Returns the logger instance\n */\n getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Replaces the default logger set in configurations with new Logger with new configurations\n * @param logger - Logger instance\n */\n setLogger(logger: Logger): void {\n this.logger = logger;\n }\n\n /**\n * Builds the common configuration to be passed to the common component based on the platform configurarion\n * @param authority - user passed authority in configuration\n * @param serverTelemetryManager - initializes servertelemetry if passed\n */\n protected async buildOauthClientConfiguration(\n authority: string,\n requestCorrelationId?: string, \n serverTelemetryManager?: ServerTelemetryManager,\n azureRegionConfiguration?: AzureRegionConfiguration, \n azureCloudOptions?: AzureCloudOptions): Promise<ClientConfiguration> {\n \n this.logger.verbose(\"buildOauthClientConfiguration called\", requestCorrelationId);\n\n // precedence - azureCloudInstance + tenant >> authority and request >> config\n const userAzureCloudOptions = azureCloudOptions ? azureCloudOptions : this.config.auth.azureCloudOptions;\n\n // using null assertion operator as we ensure that all config values have default values in buildConfiguration()\n this.logger.verbose(`building oauth client configuration with the authority: ${authority}`, requestCorrelationId);\n const discoveredAuthority = await this.createAuthority(authority, azureRegionConfiguration, requestCorrelationId, userAzureCloudOptions);\n\n serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);\n\n const clientConfiguration: ClientConfiguration = {\n authOptions: {\n clientId: this.config.auth.clientId,\n authority: discoveredAuthority,\n clientCapabilities: this.config.auth.clientCapabilities\n },\n systemOptions: {\n proxyUrl: this.config.system.proxyUrl,\n },\n loggerOptions: {\n logLevel: this.config.system.loggerOptions.logLevel,\n loggerCallback: this.config.system.loggerOptions\n .loggerCallback,\n piiLoggingEnabled: this.config.system.loggerOptions\n .piiLoggingEnabled,\n correlationId: requestCorrelationId\n },\n cryptoInterface: this.cryptoProvider,\n networkInterface: this.config.system.networkClient,\n storageInterface: this.storage,\n serverTelemetryManager: serverTelemetryManager,\n clientCredentials: {\n clientSecret: this.clientSecret,\n clientAssertion: this.clientAssertion ? this.getClientAssertion(discoveredAuthority) : undefined,\n },\n libraryInfo: {\n sku: NodeConstants.MSAL_SKU,\n version: version,\n cpu: process.arch || Constants.EMPTY_STRING,\n os: process.platform || Constants.EMPTY_STRING,\n },\n telemetry: this.config.telemetry,\n persistencePlugin: this.config.cache.cachePlugin,\n serializableCache: this.tokenCache \n };\n\n return clientConfiguration;\n }\n\n private getClientAssertion(authority: Authority): { assertion: string, assertionType: string } {\n return {\n assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),\n assertionType: NodeConstants.JWT_BEARER_ASSERTION_TYPE\n };\n }\n\n /**\n * Generates a request with the default scopes & generates a correlationId.\n * @param authRequest - BaseAuthRequest for initialization\n */\n protected async initializeBaseRequest(authRequest: Partial<BaseAuthRequest>): Promise<BaseAuthRequest> {\n this.logger.verbose(\"initializeRequestScopes called\", authRequest.correlationId);\n // Default authenticationScheme to Bearer, log that POP isn't supported yet\n if (authRequest.authenticationScheme && authRequest.authenticationScheme === AuthenticationScheme.POP) {\n this.logger.verbose(\"Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request\", authRequest.correlationId);\n }\n\n authRequest.authenticationScheme = AuthenticationScheme.BEARER;\n\n // Set requested claims hash if claims were requested\n if (authRequest.claims && !StringUtils.isEmpty(authRequest.claims)) {\n authRequest.requestedClaimsHash = await this.cryptoProvider.hashString(authRequest.claims);\n }\n\n return {\n ...authRequest,\n scopes: [...((authRequest && authRequest.scopes) || []), ...OIDC_DEFAULT_SCOPES],\n correlationId: authRequest && authRequest.correlationId || this.cryptoProvider.createNewGuid(),\n authority: authRequest.authority || this.config.auth.authority\n };\n }\n\n /**\n * Initializes the server telemetry payload\n * @param apiId - Id for a specific request\n * @param correlationId - GUID\n * @param forceRefresh - boolean to indicate network call\n */\n protected initializeServerTelemetryManager(apiId: number, correlationId: string, forceRefresh?: boolean): ServerTelemetryManager {\n const telemetryPayload: ServerTelemetryRequest = {\n clientId: this.config.auth.clientId,\n correlationId: correlationId,\n apiId: apiId,\n forceRefresh: forceRefresh || false\n };\n\n return new ServerTelemetryManager(telemetryPayload, this.storage);\n }\n\n /**\n * Create authority instance. If authority not passed in request, default to authority set on the application\n * object. If no authority set in application object, then default to common authority.\n * @param authorityString - authority from user configuration\n */\n private async createAuthority(authorityString: string, azureRegionConfiguration?: AzureRegionConfiguration, requestCorrelationId?: string, azureCloudOptions?: AzureCloudOptions): Promise<Authority> {\n this.logger.verbose(\"createAuthority called\", requestCorrelationId);\n\n // build authority string based on auth params - azureCloudInstance is prioritized if provided\n const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions);\n\n const authorityOptions: AuthorityOptions = {\n protocolMode: this.config.auth.protocolMode,\n knownAuthorities: this.config.auth.knownAuthorities,\n cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,\n authorityMetadata: this.config.auth.authorityMetadata,\n azureRegionConfiguration,\n skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache,\n };\n\n return await AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, this.config.system.proxyUrl);\n }\n\n /**\n * Clear the cache\n */\n clearCache(): void {\n this.storage.clear();\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants as CommonConstants, ServerAuthorizationCodeResponse, UrlString } from \"@azure/msal-common\";\nimport { createServer, IncomingMessage, Server, ServerResponse } from \"http\";\nimport { NodeAuthError } from \"../error/NodeAuthError\";\nimport { Constants, HttpStatus, LOOPBACK_SERVER_CONSTANTS } from \"../utils/Constants\";\n\nexport class LoopbackClient {\n private server: Server;\n\n /**\n * Spins up a loopback server which returns the server response when the localhost redirectUri is hit\n * @param successTemplate \n * @param errorTemplate \n * @returns \n */\n async listenForAuthCode(successTemplate?: string, errorTemplate?: string): Promise<ServerAuthorizationCodeResponse> {\n if (!!this.server) {\n throw NodeAuthError.createLoopbackServerAlreadyExistsError();\n }\n\n const authCodeListener = new Promise<ServerAuthorizationCodeResponse>((resolve, reject) => {\n this.server = createServer(async (req: IncomingMessage, res: ServerResponse) => {\n const url = req.url;\n if (!url) {\n res.end(errorTemplate || \"Error occurred loading redirectUrl\");\n reject(NodeAuthError.createUnableToLoadRedirectUrlError());\n return;\n } else if (url === CommonConstants.FORWARD_SLASH) {\n res.end(successTemplate || \"Auth code was successfully acquired. You can close this window now.\");\n return;\n }\n \n const authCodeResponse = UrlString.getDeserializedQueryString(url);\n if (authCodeResponse.code) {\n const redirectUri = await this.getRedirectUri();\n res.writeHead(HttpStatus.REDIRECT, { location: redirectUri }); // Prevent auth code from being saved in the browser history\n res.end();\n }\n resolve(authCodeResponse);\n });\n this.server.listen(0); // Listen on any available port\n });\n\n // Wait for server to be listening\n await new Promise<void>((resolve) => {\n let ticks = 0;\n const id = setInterval(() => {\n if ((LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS) < ticks) {\n throw NodeAuthError.createLoopbackServerTimeoutError();\n }\n \n if (this.server.listening) {\n clearInterval(id);\n resolve();\n }\n ticks++;\n }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);\n });\n\n return authCodeListener;\n }\n\n /**\n * Get the port that the loopback server is running on\n * @returns \n */\n getRedirectUri(): string {\n if (!this.server) {\n throw NodeAuthError.createNoLoopbackServerExistsError();\n }\n \n const address = this.server.address();\n if (!address || typeof address === \"string\" || !address.port) {\n this.closeServer();\n throw NodeAuthError.createInvalidLoopbackAddressTypeError();\n } \n\n const port = address && address.port;\n\n return `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}:${port}`;\n }\n\n /**\n * Close the loopback server\n */\n closeServer(): void {\n if (!!this.server) {\n this.server.close();\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ApiId } from \"../utils/Constants\";\nimport {\n DeviceCodeClient,\n AuthenticationResult,\n CommonDeviceCodeRequest,\n AuthError,\n ResponseMode,\n OIDC_DEFAULT_SCOPES,\n CodeChallengeMethodValues,\n Constants as CommonConstants,\n ServerError\n} from \"@azure/msal-common\";\nimport { Configuration } from \"../config/Configuration\";\nimport { ClientApplication } from \"./ClientApplication\";\nimport { IPublicClientApplication } from \"./IPublicClientApplication\";\nimport { DeviceCodeRequest } from \"../request/DeviceCodeRequest\";\nimport { AuthorizationUrlRequest } from \"../request/AuthorizationUrlRequest\";\nimport { AuthorizationCodeRequest } from \"../request/AuthorizationCodeRequest\";\nimport { InteractiveRequest } from \"../request/InteractiveRequest\";\nimport { NodeAuthError } from \"../error/NodeAuthError\";\nimport { LoopbackClient } from \"../network/LoopbackClient\";\n\n/**\n * This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications\n * are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user.\n * @public\n */\nexport class PublicClientApplication extends ClientApplication implements IPublicClientApplication {\n /**\n * Important attributes in the Configuration object for auth are:\n * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.\n * - authority: the authority URL for your application.\n *\n * AAD authorities are of the form https://login.microsoftonline.com/\\{Enter_the_Tenant_Info_Here\\}.\n * - If your application supports Accounts in one organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).\n * - If your application supports Accounts in any organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with organizations.\n * - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace \"Enter_the_Tenant_Info_Here\" value with common.\n * - To restrict support to Personal Microsoft accounts only, replace \"Enter_the_Tenant_Info_Here\" value with consumers.\n *\n * Azure B2C authorities are of the form https://\\{instance\\}/\\{tenant\\}/\\{policy\\}. Each policy is considered\n * its own authority. You will have to set the all of the knownAuthorities at the time of the client application\n * construction.\n *\n * ADFS authorities are of the form https://\\{instance\\}/adfs.\n */\n constructor(configuration: Configuration) {\n super(configuration);\n }\n\n /**\n * Acquires a token from the authority using OAuth2.0 device code flow.\n * This flow is designed for devices that do not have access to a browser or have input constraints.\n * The authorization server issues a DeviceCode object with a verification code, an end-user code,\n * and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be\n * instructed to use another device to navigate to the verification URI to input credentials.\n * Since the client cannot receive incoming requests, it polls the authorization server repeatedly\n * until the end-user completes input of credentials.\n */\n public async acquireTokenByDeviceCode(request: DeviceCodeRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByDeviceCode called\", request.correlationId);\n const validRequest: CommonDeviceCodeRequest = Object.assign(request, await this.initializeBaseRequest(request));\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId);\n try {\n const deviceCodeConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig);\n this.logger.verbose(\"Device code client created\", validRequest.correlationId);\n return deviceCodeClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires a token by requesting an Authorization code then exchanging it for a token.\n */\n async acquireTokenInteractive(request: InteractiveRequest): Promise<AuthenticationResult> {\n const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes();\n const { openBrowser, successTemplate, errorTemplate, ...remainingProperties } = request;\n\n const loopbackClient = new LoopbackClient();\n const authCodeListener = loopbackClient.listenForAuthCode(successTemplate, errorTemplate);\n const redirectUri = loopbackClient.getRedirectUri();\n\n const validRequest: AuthorizationUrlRequest = {\n ...remainingProperties,\n scopes: request.scopes || OIDC_DEFAULT_SCOPES,\n redirectUri: redirectUri,\n responseMode: ResponseMode.QUERY,\n codeChallenge: challenge, \n codeChallengeMethod: CodeChallengeMethodValues.S256\n };\n\n const authCodeUrl = await this.getAuthCodeUrl(validRequest);\n await openBrowser(authCodeUrl);\n const authCodeResponse = await authCodeListener.finally(() => {\n loopbackClient.closeServer();\n });\n\n if (authCodeResponse.error) {\n throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror);\n } else if (!authCodeResponse.code) {\n throw NodeAuthError.createNoAuthCodeInResponseError();\n }\n\n const clientInfo = authCodeResponse.client_info;\n const tokenRequest: AuthorizationCodeRequest = {\n code: authCodeResponse.code,\n codeVerifier: verifier,\n clientInfo: clientInfo || CommonConstants.EMPTY_STRING,\n ...validRequest\n };\n return this.acquireTokenByCode(tokenRequest);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { JwtHeader, sign } from \"jsonwebtoken\";\nimport { TimeUtils, ClientAuthError, Constants } from \"@azure/msal-common\";\nimport { CryptoProvider } from \"../crypto/CryptoProvider\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\nimport { JwtConstants } from \"../utils/Constants\";\n\n/**\n * Client assertion of type jwt-bearer used in confidential client flows\n * @public\n */\nexport class ClientAssertion {\n\n private jwt: string;\n private privateKey: string;\n private thumbprint: string;\n private expirationTime: number;\n private issuer: string;\n private jwtAudience: string;\n private publicCertificate: Array<string>;\n\n /**\n * Initialize the ClientAssertion class from the clientAssertion passed by the user\n * @param assertion - refer https://tools.ietf.org/html/rfc7521\n */\n public static fromAssertion(assertion: string): ClientAssertion {\n const clientAssertion = new ClientAssertion();\n clientAssertion.jwt = assertion;\n return clientAssertion;\n }\n\n /**\n * Initialize the ClientAssertion class from the certificate passed by the user\n * @param thumbprint - identifier of a certificate\n * @param privateKey - secret key\n * @param publicCertificate - electronic document provided to prove the ownership of the public key\n */\n public static fromCertificate(thumbprint: string, privateKey: string, publicCertificate?: string): ClientAssertion {\n const clientAssertion = new ClientAssertion();\n clientAssertion.privateKey = privateKey;\n clientAssertion.thumbprint = thumbprint;\n if (publicCertificate) {\n clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);\n }\n return clientAssertion;\n }\n\n /**\n * Update JWT for certificate based clientAssertion, if passed by the user, uses it as is\n * @param cryptoProvider - library's crypto helper\n * @param issuer - iss claim\n * @param jwtAudience - aud claim\n */\n public getJwt(cryptoProvider: CryptoProvider, issuer: string, jwtAudience: string): string {\n // if assertion was created from certificate, check if jwt is expired and create new one.\n if (this.privateKey && this.thumbprint) {\n\n if (this.jwt && !this.isExpired() && issuer === this.issuer && jwtAudience === this.jwtAudience) {\n return this.jwt;\n }\n\n return this.createJwt(cryptoProvider, issuer, jwtAudience);\n }\n\n /*\n * if assertion was created by caller, then we just append it. It is up to the caller to\n * ensure that it contains necessary claims and that it is not expired.\n */\n if (this.jwt) {\n return this.jwt;\n }\n\n throw ClientAuthError.createInvalidAssertionError();\n }\n\n /**\n * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3\n */\n private createJwt(cryptoProvider: CryptoProvider, issuer: string, jwtAudience: string): string {\n\n this.issuer = issuer;\n this.jwtAudience = jwtAudience;\n const issuedAt = TimeUtils.nowSeconds();\n this.expirationTime = issuedAt + 600;\n\n const header: JwtHeader = {\n alg: JwtConstants.RSA_256,\n x5t: EncodingUtils.base64EncodeUrl(this.thumbprint, \"hex\")\n };\n\n if (this.publicCertificate) {\n Object.assign(header, {\n x5c: this.publicCertificate\n } as Partial<JwtHeader>);\n }\n\n const payload = {\n [JwtConstants.AUDIENCE]: this.jwtAudience,\n [JwtConstants.EXPIRATION_TIME]: this.expirationTime,\n [JwtConstants.ISSUER]: this.issuer,\n [JwtConstants.SUBJECT]: this.issuer,\n [JwtConstants.NOT_BEFORE]: issuedAt,\n [JwtConstants.JWT_ID]: cryptoProvider.createNewGuid()\n };\n\n this.jwt = sign(payload, this.privateKey, { header });\n return this.jwt;\n }\n\n /**\n * Utility API to check expiration\n */\n private isExpired(): boolean {\n return this.expirationTime < TimeUtils.nowSeconds();\n }\n\n /**\n * Extracts the raw certs from a given certificate string and returns them in an array.\n * @param publicCertificate - electronic document provided to prove the ownership of the public key\n */\n public static parseCertificate(publicCertificate: string): Array<string> {\n /**\n * This is regex to identify the certs in a given certificate string.\n * We want to look for the contents between the BEGIN and END certificate strings, without the associated newlines.\n * The information in parens \"(.+?)\" is the capture group to represent the cert we want isolated.\n * \".\" means any string character, \"+\" means match 1 or more times, and \"?\" means the shortest match.\n * The \"g\" at the end of the regex means search the string globally, and the \"s\" enables the \".\" to match newlines.\n */\n const regexToFindCerts = /-----BEGIN CERTIFICATE-----\\r*\\n(.+?)\\r*\\n-----END CERTIFICATE-----/gs;\n const certs: string[] = [];\n\n let matches;\n while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {\n // matches[1] represents the first parens capture group in the regex.\n certs.push(matches[1].replace(/\\r*\\n/g, Constants.EMPTY_STRING));\n }\n\n return certs;\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ClientApplication } from \"./ClientApplication\";\nimport { Configuration } from \"../config/Configuration\";\nimport { ClientAssertion } from \"./ClientAssertion\";\nimport { Constants as NodeConstants, ApiId, REGION_ENVIRONMENT_VARIABLE } from \"../utils/Constants\";\nimport {\n ClientCredentialClient,\n OnBehalfOfClient,\n CommonClientCredentialRequest,\n CommonOnBehalfOfRequest,\n AuthenticationResult,\n StringUtils,\n ClientAuthError,\n AzureRegionConfiguration,\n AuthError,\n Constants,\n IAppTokenProvider,\n OIDC_DEFAULT_SCOPES\n} from \"@azure/msal-common\";\nimport { IConfidentialClientApplication } from \"./IConfidentialClientApplication\";\nimport { OnBehalfOfRequest } from \"../request/OnBehalfOfRequest\";\nimport { ClientCredentialRequest } from \"../request/ClientCredentialRequest\";\n\n/**\n * This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications\n * will configure application secrets, client certificates/assertions as applicable\n * @public\n */\nexport class ConfidentialClientApplication extends ClientApplication implements IConfidentialClientApplication {\n private appTokenProvider?: IAppTokenProvider;\n\n /**\n * Constructor for the ConfidentialClientApplication\n *\n * Required attributes in the Configuration object are:\n * - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal\n * - authority: the authority URL for your application.\n * - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.\n *\n * In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\\{Enter_the_Tenant_Info_Here\\}.\n * If your application supports Accounts in one organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).\n * If your application supports Accounts in any organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with organizations.\n * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace \"Enter_the_Tenant_Info_Here\" value with common.\n * To restrict support to Personal Microsoft accounts only, replace \"Enter_the_Tenant_Info_Here\" value with consumers.\n *\n * In Azure B2C, authority is of the form https://\\{instance\\}/tfp/\\{tenant\\}/\\{policyName\\}/\n * Full B2C functionality will be available in this library in future versions.\n *\n * @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance\n */\n constructor(configuration: Configuration) {\n super(configuration);\n this.setClientCredential(this.config);\n this.appTokenProvider = undefined;\n }\n\n /** \n * This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and\n * is meant for Azure SDK to enhance Managed Identity support.\n * \n * @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source. \n */\n SetAppTokenProvider(provider: IAppTokenProvider): void {\n this.appTokenProvider = provider;\n }\n\n /**\n * Acquires tokens from the authority for the application (not for an end user).\n */\n public async acquireTokenByClientCredential(request: ClientCredentialRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenByClientCredential called\", request.correlationId);\n\n // If there is a client assertion present in the request, it overrides the one present in the client configuration\n let clientAssertion;\n if (request.clientAssertion) {\n clientAssertion = {\n assertion: request.clientAssertion,\n assertionType: NodeConstants.JWT_BEARER_ASSERTION_TYPE\n };\n }\n\n const baseRequest = await this.initializeBaseRequest(request);\n\n // valid base request should not contain oidc scopes in this grant type\n const validBaseRequest = {\n ...baseRequest,\n scopes: baseRequest.scopes.filter((scope: string) => !OIDC_DEFAULT_SCOPES.includes(scope))\n };\n\n const validRequest: CommonClientCredentialRequest = {\n ...request,\n ...validBaseRequest,\n clientAssertion\n };\n\n const azureRegionConfiguration: AzureRegionConfiguration = {\n azureRegion: validRequest.azureRegion,\n environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE]\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache);\n try {\n const clientCredentialConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n azureRegionConfiguration,\n request.azureCloudOptions\n );\n const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig, this.appTokenProvider);\n this.logger.verbose(\"Client credential client created\", validRequest.correlationId);\n return clientCredentialClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e);\n throw e;\n }\n }\n\n /**\n * Acquires tokens from the authority for the application.\n *\n * Used in scenarios where the current app is a middle-tier service which was called with a token\n * representing an end user. The current app can use the token (oboAssertion) to request another\n * token to access downstream web API, on behalf of that user.\n *\n * The current middle-tier app has no user interaction to obtain consent.\n * See how to gain consent upfront for your middle-tier app from this article.\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application\n */\n public async acquireTokenOnBehalfOf(request: OnBehalfOfRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"acquireTokenOnBehalfOf called\", request.correlationId);\n const validRequest: CommonOnBehalfOfRequest = {\n ...request,\n ... await this.initializeBaseRequest(request)\n };\n try {\n const onBehalfOfConfig = await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n undefined,\n undefined,\n request.azureCloudOptions\n );\n const oboClient = new OnBehalfOfClient(onBehalfOfConfig);\n this.logger.verbose(\"On behalf of client created\", validRequest.correlationId);\n return oboClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n throw e;\n }\n }\n\n private setClientCredential(configuration: Configuration): void {\n const clientSecretNotEmpty = !StringUtils.isEmpty(configuration.auth.clientSecret);\n const clientAssertionNotEmpty = !StringUtils.isEmpty(configuration.auth.clientAssertion);\n const certificate = configuration.auth.clientCertificate || {\n thumbprint: Constants.EMPTY_STRING,\n privateKey: Constants.EMPTY_STRING\n };\n const certificateNotEmpty = !StringUtils.isEmpty(certificate.thumbprint) || !StringUtils.isEmpty(certificate.privateKey);\n\n /*\n * If app developer configures this callback, they don't need a credential\n * i.e. AzureSDK can get token from Managed Identity without a cert / secret\n */\n if (this.appTokenProvider) {\n return;\n }\n\n // Check that at most one credential is set on the application\n if (\n clientSecretNotEmpty && clientAssertionNotEmpty ||\n clientAssertionNotEmpty && certificateNotEmpty ||\n clientSecretNotEmpty && certificateNotEmpty) {\n throw ClientAuthError.createInvalidCredentialError();\n }\n\n if (configuration.auth.clientSecret) {\n this.clientSecret = configuration.auth.clientSecret;\n return;\n }\n\n if (configuration.auth.clientAssertion) {\n this.clientAssertion = ClientAssertion.fromAssertion(configuration.auth.clientAssertion);\n return;\n }\n\n if (!certificateNotEmpty) {\n throw ClientAuthError.createInvalidCredentialError();\n } else {\n this.clientAssertion = ClientAssertion.fromCertificate(certificate.thumbprint, certificate.privateKey, configuration.auth.clientCertificate?.x5c);\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AccountEntity, ICachePlugin, TokenCacheContext } from \"@azure/msal-common\";\nimport { TokenCache } from \"../TokenCache\";\nimport { IPartitionManager } from \"./IPartitionManager\";\nimport { ICacheClient } from \"./ICacheClient\";\n\nexport class DistributedCachePlugin implements ICachePlugin {\n private client: ICacheClient;\n private partitionManager: IPartitionManager;\n\n constructor(client: ICacheClient, partitionManager: IPartitionManager) {\n this.client = client;\n this.partitionManager = partitionManager;\n }\n \n public async beforeCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n const partitionKey = await this.partitionManager.getKey();\n const cacheData = await this.client.get(partitionKey);\n cacheContext.tokenCache.deserialize(cacheData);\n }\n \n public async afterCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n if (cacheContext.cacheHasChanged) {\n const kvStore = (cacheContext.tokenCache as TokenCache).getKVStore();\n const accountEntities = Object.values(kvStore).filter(value => AccountEntity.isAccountEntity(value as object));\n\n if (accountEntities.length > 0) {\n const accountEntity = accountEntities[0] as AccountEntity;\n const partitionKey = await this.partitionManager.extractKey(accountEntity);\n \n await this.client.set(partitionKey, cacheContext.tokenCache.serialize()); \n }\n }\n }\n}\n"],"names":["HttpMethod","HttpStatus","ProxyStatus","REGION_ENVIRONMENT_VARIABLE","RANDOM_OCTET_SIZE","Hash","SHA256","CharSet","CV_CHARSET","Constants","MSAL_SKU","JWT_BEARER_ASSERTION_TYPE","AUTHORIZATION_PENDING","HTTP_PROTOCOL","LOCALHOST","ApiId","JwtConstants","ALGORITHM","RSA_256","X5T","X5C","AUDIENCE","EXPIRATION_TIME","ISSUER","SUBJECT","NOT_BEFORE","JWT_ID","LOOPBACK_SERVER_CONSTANTS","INTERVAL_MS","TIMEOUT_MS","NetworkUtils","getNetworkResponse","headers","body","statusCode","status","HttpClient","sendGetRequestAsync","url","options","proxyUrl","networkRequestViaProxy","GET","networkRequestViaHttps","sendPostRequestAsync","cancellationToken","POST","httpMethod","timeout","URL","destinationUrl","tunnelRequestOptions","host","hostname","port","method","path","postRequestStringContent","length","outgoingRequestString","toUpperCase","href","Promise","resolve","reject","request","http","on","destroy","Error","end","response","socket","proxyStatusCode","SERVER_ERROR","SUCCESS_RANGE_START","SUCCESS_RANGE_END","statusMessage","setTimeout","write","data","chunk","push","dataString","Buffer","concat","toString","dataStringArray","split","httpStatusCode","parseInt","slice","join","headersArray","entries","Map","forEach","header","headerKeyValue","RegExp","headerKey","headerValue","object","JSON","parse","e","set","Object","fromEntries","parsedHeaders","networkResponse","parseBody","isPostRequest","emptyHeaders","customOptions","https","parsedBody","error","errorType","errorDescriptionHelper","CLIENT_ERROR_RANGE_START","CLIENT_ERROR_RANGE_END","SERVER_ERROR_RANGE_START","SERVER_ERROR_RANGE_END","error_description","stringify","DEFAULT_AUTH_OPTIONS","clientId","EMPTY_STRING","authority","DEFAULT_AUTHORITY","clientSecret","clientAssertion","clientCertificate","thumbprint","privateKey","x5c","knownAuthorities","cloudDiscoveryMetadata","authorityMetadata","clientCapabilities","protocolMode","ProtocolMode","AAD","azureCloudOptions","azureCloudInstance","AzureCloudInstance","None","tenant","skipAuthorityMetadataCache","DEFAULT_CACHE_OPTIONS","DEFAULT_LOGGER_OPTIONS","loggerCallback","piiLoggingEnabled","logLevel","LogLevel","Info","DEFAULT_SYSTEM_OPTIONS","loggerOptions","networkClient","DEFAULT_TELEMETRY_OPTIONS","application","appName","appVersion","buildAppConfiguration","auth","cache","system","telemetry","GuidGenerator","generateGuid","uuidv4","isGuid","guid","regexGuid","test","EncodingUtils","base64Encode","str","encoding","from","base64EncodeUrl","replace","base64Decode","base64Str","base64DecodeUrl","HashUtils","sha256","buffer","crypto","createHash","update","digest","PkceGenerator","constructor","hashUtils","generatePkceCodes","verifier","generateCodeVerifier","challenge","generateCodeChallengeFromVerifier","charArr","maxNumber","byte","randomBytes","index","codeVerifier","CryptoProvider","pkceGenerator","guidGenerator","createNewGuid","input","getPublicKeyThumbprint","removeTokenBindingKey","clearKeystore","signJwt","hashString","plainText","Deserializer","deserializeJSONBlob","jsonFile","deserializedCache","StringUtils","isEmpty","deserializeAccounts","accounts","accountObjects","keys","map","key","serializedAcc","mappedAcc","homeAccountId","home_account_id","environment","realm","localAccountId","local_account_id","username","authorityType","authority_type","name","clientInfo","client_info","lastModificationTime","last_modification_time","lastModificationApp","last_modification_app","account","AccountEntity","CacheManager","toObject","deserializeIdTokens","idTokens","idObjects","serializedIdT","mappedIdT","credentialType","credential_type","client_id","secret","idToken","IdTokenEntity","deserializeAccessTokens","accessTokens","atObjects","serializedAT","mappedAT","target","cachedAt","cached_at","expiresOn","expires_on","extendedExpiresOn","extended_expires_on","refreshOn","refresh_on","keyId","key_id","tokenType","token_type","requestedClaims","requestedClaimsHash","userAssertionHash","accessToken","AccessTokenEntity","deserializeRefreshTokens","refreshTokens","rtObjects","serializedRT","mappedRT","familyId","family_id","refreshToken","RefreshTokenEntity","deserializeAppMetadata","appMetadata","appMetadataObjects","serializedAmdt","mappedAmd","amd","AppMetadataEntity","deserializeAllCache","jsonCache","Account","IdToken","AccessToken","RefreshToken","AppMetadata","Serializer","serializeJSONBlob","serializeAccounts","accCache","accountEntity","serializeIdTokens","idTCache","idTEntity","serializeAccessTokens","atCache","atEntity","serializeRefreshTokens","rtCache","rtEntity","serializeAppMetadata","amdtCache","amdtEntity","serializeAllCache","inMemCache","NodeStorage","logger","cryptoImpl","registerChangeEmitter","func","changeEmitters","emitChange","call","cacheToInMemoryCache","inMemoryCache","inMemoryCacheToCache","getCache","getInMemoryCache","trace","setInMemoryCache","setCache","getItem","tracePii","setItem","value","getAccount","accountKey","isAccountEntity","setAccount","generateAccountKey","getIdTokenCredential","idTokenKey","isIdTokenEntity","setIdTokenCredential","generateCredentialKey","getAccessTokenCredential","accessTokenKey","isAccessTokenEntity","setAccessTokenCredential","getRefreshTokenCredential","refreshTokenKey","isRefreshTokenEntity","setRefreshTokenCredential","getAppMetadata","appMetadataKey","isAppMetadataEntity","setAppMetadata","generateAppMetadataKey","getServerTelemetry","serverTelemetrykey","serverTelemetryEntity","ServerTelemetryEntity","isServerTelemetryEntity","setServerTelemetry","serverTelemetryKey","serverTelemetry","getAuthorityMetadata","authorityMetadataEntity","AuthorityMetadataEntity","isAuthorityMetadataEntity","getAuthorityMetadataKeys","getKeys","filter","isAuthorityMetadata","setAuthorityMetadata","metadata","getThrottlingCache","throttlingCacheKey","throttlingCache","ThrottlingEntity","isThrottlingEntity","setThrottlingCache","removeItem","result","containsKey","includes","clear","cacheKeys","generateInMemoryCache","generateJsonCache","updateCredentialCacheKey","currentCacheKey","credential","updatedCacheKey","cacheItem","verbose","defaultSerializedCache","TokenCache","storage","cachePlugin","cacheHasChanged","handleChangeEvent","bind","persistence","hasChanged","serialize","finalState","cacheSnapshot","mergeState","deserialize","overlayDefaults","getKVStore","getAllAccounts","cacheContext","TokenCacheContext","beforeCacheAccess","afterCacheAccess","getAccountByHomeId","allAccounts","accountObj","getAccountByLocalId","removeAccount","generateAccountCacheKey","oldState","currentState","stateAfterRemoval","mergeRemovals","mergeUpdates","newState","newKey","newValue","hasOwnProperty","newValueNotNull","newValueIsObject","newValueIsNotArray","Array","isArray","oldStateNotUndefinedOrNull","mergeRemovalsDict","oldKey","passedInCache","version","NodeAuthErrorMessage","invalidLoopbackAddressType","code","desc","unableToLoadRedirectUri","noAuthCodeInResponse","noLoopbackServerExists","loopbackServerAlreadyExists","loopbackServerTimeout","stateNotFoundError","NodeAuthError","AuthError","errorCode","errorMessage","createInvalidLoopbackAddressTypeError","createUnableToLoadRedirectUrlError","createNoAuthCodeInResponseError","createNoLoopbackServerExistsError","createLoopbackServerAlreadyExistsError","createLoopbackServerTimeoutError","createStateNotFoundError","ClientApplication","configuration","config","cryptoProvider","Logger","tokenCache","getAuthCodeUrl","info","correlationId","validRequest","initializeBaseRequest","responseMode","ResponseMode","QUERY","authenticationScheme","AuthenticationScheme","BEARER","authClientConfig","buildOauthClientConfiguration","undefined","authorizationCodeClient","AuthorizationCodeClient","acquireTokenByCode","authCodePayLoad","state","validateState","serverTelemetryManager","initializeServerTelemetryManager","acquireToken","setCorrelationId","cacheFailedRequest","acquireTokenByRefreshToken","refreshTokenClientConfig","refreshTokenClient","RefreshTokenClient","acquireTokenSilent","forceRefresh","silentFlowClientConfig","silentFlowClient","SilentFlowClient","acquireTokenByUsernamePassword","usernamePasswordClientConfig","usernamePasswordClient","UsernamePasswordClient","getTokenCache","cachedState","ClientAuthError","createStateMismatchError","getLogger","setLogger","requestCorrelationId","azureRegionConfiguration","userAzureCloudOptions","discoveredAuthority","createAuthority","updateRegionDiscoveryMetadata","regionDiscoveryMetadata","clientConfiguration","authOptions","systemOptions","cryptoInterface","networkInterface","storageInterface","clientCredentials","getClientAssertion","libraryInfo","sku","NodeConstants","cpu","process","arch","os","platform","persistencePlugin","serializableCache","assertion","getJwt","tokenEndpoint","assertionType","authRequest","POP","claims","scopes","OIDC_DEFAULT_SCOPES","apiId","telemetryPayload","ServerTelemetryManager","authorityString","authorityUrl","Authority","generateAuthority","authorityOptions","AuthorityFactory","createDiscoveredInstance","clearCache","LoopbackClient","listenForAuthCode","successTemplate","errorTemplate","server","authCodeListener","createServer","req","res","CommonConstants","FORWARD_SLASH","authCodeResponse","UrlString","getDeserializedQueryString","redirectUri","getRedirectUri","writeHead","REDIRECT","location","listen","ticks","id","setInterval","listening","clearInterval","address","closeServer","close","PublicClientApplication","acquireTokenByDeviceCode","assign","deviceCodeConfig","deviceCodeClient","DeviceCodeClient","acquireTokenInteractive","openBrowser","remainingProperties","loopbackClient","codeChallenge","codeChallengeMethod","CodeChallengeMethodValues","S256","authCodeUrl","finally","ServerError","suberror","tokenRequest","ClientAssertion","fromAssertion","jwt","fromCertificate","publicCertificate","parseCertificate","issuer","jwtAudience","isExpired","createJwt","createInvalidAssertionError","issuedAt","TimeUtils","nowSeconds","expirationTime","alg","x5t","payload","sign","regexToFindCerts","certs","matches","exec","ConfidentialClientApplication","setClientCredential","appTokenProvider","SetAppTokenProvider","provider","acquireTokenByClientCredential","baseRequest","validBaseRequest","scope","azureRegion","environmentRegion","env","skipCache","clientCredentialConfig","clientCredentialClient","ClientCredentialClient","acquireTokenOnBehalfOf","onBehalfOfConfig","oboClient","OnBehalfOfClient","clientSecretNotEmpty","clientAssertionNotEmpty","certificate","certificateNotEmpty","createInvalidCredentialError","DistributedCachePlugin","client","partitionManager","partitionKey","getKey","cacheData","get","kvStore","accountEntities","values","extractKey"],"mappings":";;;;;;;;AAAA;;;;;AAKA;;;AAGA,IAAYA,UAAZ;;AAAA,WAAYA;EACRA,iBAAA,QAAA;EACAA,kBAAA,SAAA;AACH,CAHD,EAAYA,UAAU,KAAVA,UAAU,KAAA,CAAtB;;AAKA,IAAYC,UAAZ;;AAAA,WAAYA;EACRA,mDAAA,wBAAA;EACAA,iDAAA,sBAAA;EACAA,wCAAA,aAAA;EACAA,wDAAA,6BAAA;EACAA,sDAAA,2BAAA;EACAA,wDAAA,6BAAA;EACAA,sDAAA,2BAAA;AACH,CARD,EAAYA,UAAU,KAAVA,UAAU,KAAA,CAAtB;;AAUA,IAAYC,WAAZ;;AAAA,WAAYA;EACRA,qDAAA,wBAAA;EACAA,mDAAA,sBAAA;EACAA,8CAAA,iBAAA;AACH,CAJD,EAAYA,WAAW,KAAXA,WAAW,KAAA,CAAvB;AAMA;;;;;AAGO,MAAMC,2BAA2B,GAAG,aAApC;AAEP;;;;AAGO,MAAMC,iBAAiB,GAAG,EAA1B;AAEP;;;;AAGO,MAAMC,IAAI,GAAG;EAChBC,MAAM,EAAE;AADQ,CAAb;AAIP;;;;AAGO,MAAMC,OAAO,GAAG;EACnBC,UAAU,EACN;AAF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