@ms-cloudpack/remote-cache 0.5.0 → 0.5.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/AzureRemoteCacheClient-2PRAPCJH.js +52049 -0
  2. package/dist/AzureRemoteCacheClient-2PRAPCJH.js.map +7 -0
  3. package/dist/ReporterDecorator-BYNXV72I.js +126 -0
  4. package/dist/ReporterDecorator-BYNXV72I.js.map +7 -0
  5. package/dist/chunk-G3ME7OWS.js +49567 -0
  6. package/dist/chunk-G3ME7OWS.js.map +7 -0
  7. package/dist/chunk-GFT2G5UO.js +50 -0
  8. package/dist/chunk-GFT2G5UO.js.map +7 -0
  9. package/dist/chunk-KKZU5JW4.js +1071 -0
  10. package/dist/chunk-KKZU5JW4.js.map +7 -0
  11. package/dist/chunk-VVROC42R.js +182 -0
  12. package/dist/chunk-VVROC42R.js.map +7 -0
  13. package/dist/chunk-XKOU5VXX.js +9 -0
  14. package/dist/chunk-XKOU5VXX.js.map +7 -0
  15. package/dist/getCredential-MJEIGDVB.js +23981 -0
  16. package/dist/getCredential-MJEIGDVB.js.map +7 -0
  17. package/dist/getListOfBlobs-LKU62UR5.js +26 -0
  18. package/dist/getListOfBlobs-LKU62UR5.js.map +7 -0
  19. package/dist/index.js +93 -0
  20. package/dist/index.js.map +7 -0
  21. package/lib/decorators/InMemoryDecorator.test.d.ts +2 -0
  22. package/lib/decorators/RetryDecorator.test.d.ts +2 -0
  23. package/package.json +13 -12
  24. package/lib/AzureRemoteCacheClient.d.ts.map +0 -1
  25. package/lib/AzureRemoteCacheClient.js +0 -51
  26. package/lib/AzureRemoteCacheClient.js.map +0 -1
  27. package/lib/Task.d.ts.map +0 -1
  28. package/lib/Task.js +0 -2
  29. package/lib/Task.js.map +0 -1
  30. package/lib/authentication/getAuthenticationRecord.d.ts.map +0 -1
  31. package/lib/authentication/getAuthenticationRecord.js +0 -17
  32. package/lib/authentication/getAuthenticationRecord.js.map +0 -1
  33. package/lib/authentication/getAuthenticationRecordPath.d.ts.map +0 -1
  34. package/lib/authentication/getAuthenticationRecordPath.js +0 -10
  35. package/lib/authentication/getAuthenticationRecordPath.js.map +0 -1
  36. package/lib/authentication/getCredential.d.ts.map +0 -1
  37. package/lib/authentication/getCredential.js +0 -61
  38. package/lib/authentication/getCredential.js.map +0 -1
  39. package/lib/authentication/saveAuthenticationRecord.d.ts.map +0 -1
  40. package/lib/authentication/saveAuthenticationRecord.js +0 -17
  41. package/lib/authentication/saveAuthenticationRecord.js.map +0 -1
  42. package/lib/cache-persistance/cachePersistencePlugin.d.ts.map +0 -1
  43. package/lib/cache-persistance/cachePersistencePlugin.js +0 -35
  44. package/lib/cache-persistance/cachePersistencePlugin.js.map +0 -1
  45. package/lib/cache-persistance/platforms.d.ts.map +0 -1
  46. package/lib/cache-persistance/platforms.js +0 -109
  47. package/lib/cache-persistance/platforms.js.map +0 -1
  48. package/lib/cache-persistance/provider.d.ts.map +0 -1
  49. package/lib/cache-persistance/provider.js +0 -26
  50. package/lib/cache-persistance/provider.js.map +0 -1
  51. package/lib/createBlobStorageUrl.d.ts.map +0 -1
  52. package/lib/createBlobStorageUrl.js +0 -4
  53. package/lib/createBlobStorageUrl.js.map +0 -1
  54. package/lib/createRemoteCacheClient.d.ts.map +0 -1
  55. package/lib/createRemoteCacheClient.js +0 -27
  56. package/lib/createRemoteCacheClient.js.map +0 -1
  57. package/lib/decorators/InMemoryDecorator.d.ts.map +0 -1
  58. package/lib/decorators/InMemoryDecorator.js +0 -29
  59. package/lib/decorators/InMemoryDecorator.js.map +0 -1
  60. package/lib/decorators/ReporterDecorator.d.ts.map +0 -1
  61. package/lib/decorators/ReporterDecorator.js +0 -121
  62. package/lib/decorators/ReporterDecorator.js.map +0 -1
  63. package/lib/decorators/RetryDecorator.d.ts.map +0 -1
  64. package/lib/decorators/RetryDecorator.js +0 -27
  65. package/lib/decorators/RetryDecorator.js.map +0 -1
  66. package/lib/getListOfBlobs.d.ts.map +0 -1
  67. package/lib/getListOfBlobs.js +0 -15
  68. package/lib/getListOfBlobs.js.map +0 -1
  69. package/lib/index.d.ts.map +0 -1
  70. package/lib/index.js +0 -2
  71. package/lib/index.js.map +0 -1
  72. package/lib/retry/blockListIsInvalidRetryPolicy.d.ts.map +0 -1
  73. package/lib/retry/blockListIsInvalidRetryPolicy.js +0 -8
  74. package/lib/retry/blockListIsInvalidRetryPolicy.js.map +0 -1
  75. package/lib/tsdoc-metadata.json +0 -11
  76. package/lib/types/LoginMethod.d.ts.map +0 -1
  77. package/lib/types/LoginMethod.js +0 -2
  78. package/lib/types/LoginMethod.js.map +0 -1
  79. package/lib/types/RemoteCacheClient.d.ts.map +0 -1
  80. package/lib/types/RemoteCacheClient.js +0 -2
  81. package/lib/types/RemoteCacheClient.js.map +0 -1
  82. package/lib/types/RemoteCacheClientOptions.d.ts.map +0 -1
  83. package/lib/types/RemoteCacheClientOptions.js +0 -2
  84. package/lib/types/RemoteCacheClientOptions.js.map +0 -1
  85. package/lib/types/RetryPolicy.d.ts.map +0 -1
  86. package/lib/types/RetryPolicy.js +0 -2
  87. package/lib/types/RetryPolicy.js.map +0 -1
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../node_modules/@azure/msal-node/src/cache/serializer/Serializer.ts", "../../../node_modules/@azure/msal-common/src/utils/Constants.ts", "../../../node_modules/@azure/msal-common/src/error/AuthErrorCodes.ts", "../../../node_modules/@azure/msal-common/src/error/AuthError.ts", "../../../node_modules/@azure/msal-common/src/error/ClientAuthErrorCodes.ts", "../../../node_modules/@azure/msal-common/src/error/ClientAuthError.ts", "../../../node_modules/@azure/msal-common/src/crypto/ICrypto.ts", "../../../node_modules/@azure/msal-common/src/logger/Logger.ts", "../../../node_modules/@azure/msal-common/src/packageMetadata.ts", "../../../node_modules/@azure/msal-common/src/authority/AuthorityOptions.ts", "../../../node_modules/@azure/msal-common/src/account/AuthToken.ts", "../../../node_modules/@azure/msal-common/src/utils/TimeUtils.ts", "../../../node_modules/@azure/msal-common/src/cache/utils/CacheHelpers.ts", "../../../node_modules/@azure/msal-common/src/error/ClientConfigurationErrorCodes.ts", "../../../node_modules/@azure/msal-common/src/error/ClientConfigurationError.ts", "../../../node_modules/@azure/msal-common/src/utils/StringUtils.ts", "../../../node_modules/@azure/msal-common/src/request/ScopeSet.ts", "../../../node_modules/@azure/msal-common/src/account/ClientInfo.ts", "../../../node_modules/@azure/msal-common/src/account/AccountInfo.ts", "../../../node_modules/@azure/msal-common/src/authority/AuthorityType.ts", "../../../node_modules/@azure/msal-common/src/account/TokenClaims.ts", "../../../node_modules/@azure/msal-common/src/authority/ProtocolMode.ts", "../../../node_modules/@azure/msal-common/src/cache/entities/AccountEntity.ts", "../../../node_modules/@azure/msal-common/src/utils/UrlUtils.ts", "../../../node_modules/@azure/msal-common/src/url/UrlString.ts", "../../../node_modules/@azure/msal-common/src/authority/AuthorityMetadata.ts", "../../../node_modules/@azure/msal-common/src/cache/CacheManager.ts", "../../../node_modules/@azure/msal-common/src/config/ClientConfiguration.ts", "../../../node_modules/@azure/msal-common/src/error/ServerError.ts", "../../../node_modules/@azure/msal-common/src/network/ThrottlingUtils.ts", "../../../node_modules/@azure/msal-common/src/network/NetworkManager.ts", "../../../node_modules/@azure/msal-common/src/account/CcsCredential.ts", "../../../node_modules/@azure/msal-common/src/constants/AADServerParamKeys.ts", "../../../node_modules/@azure/msal-common/src/request/RequestValidator.ts", "../../../node_modules/@azure/msal-common/src/request/RequestParameterBuilder.ts", "../../../node_modules/@azure/msal-common/src/authority/OpenIdConfigResponse.ts", "../../../node_modules/@azure/msal-common/src/authority/CloudInstanceDiscoveryResponse.ts", "../../../node_modules/@azure/msal-common/src/authority/CloudInstanceDiscoveryErrorResponse.ts", "../../../node_modules/@azure/msal-common/src/telemetry/performance/PerformanceEvent.ts", "../../../node_modules/@azure/msal-common/src/utils/FunctionWrappers.ts", "../../../node_modules/@azure/msal-common/src/authority/RegionDiscovery.ts", "../../../node_modules/@azure/msal-common/src/authority/Authority.ts", "../../../node_modules/@azure/msal-common/src/authority/AuthorityFactory.ts", "../../../node_modules/@azure/msal-common/src/client/BaseClient.ts", "../../../node_modules/@azure/msal-common/src/error/InteractionRequiredAuthErrorCodes.ts", "../../../node_modules/@azure/msal-common/src/error/InteractionRequiredAuthError.ts", "../../../node_modules/@azure/msal-common/src/cache/entities/CacheRecord.ts", "../../../node_modules/@azure/msal-common/src/utils/ProtocolUtils.ts", "../../../node_modules/@azure/msal-common/src/crypto/PopTokenGenerator.ts", "../../../node_modules/@azure/msal-common/src/cache/persistence/TokenCacheContext.ts", "../../../node_modules/@azure/msal-common/src/response/ResponseHandler.ts", "../../../node_modules/@azure/msal-common/src/client/AuthorizationCodeClient.ts", "../../../node_modules/@azure/msal-common/src/client/RefreshTokenClient.ts", "../../../node_modules/@azure/msal-common/src/client/SilentFlowClient.ts", "../../../node_modules/@azure/msal-common/src/telemetry/server/ServerTelemetryManager.ts", "../../../node_modules/@azure/msal-common/dist/index.mjs", "../../../node_modules/@azure/msal-node/src/cache/serializer/Deserializer.ts", "../../../node_modules/@azure/msal-node/src/utils/Constants.ts", "../../../node_modules/@azure/msal-node/src/utils/NetworkUtils.ts", "../../../node_modules/@azure/msal-node/src/network/HttpClient.ts", "../../../node_modules/@azure/msal-node/src/config/Configuration.ts", "../../../node_modules/@azure/msal-node/node_modules/uuid/dist/esm-node/rng.js", "../../../node_modules/@azure/msal-node/node_modules/uuid/dist/esm-node/regex.js", "../../../node_modules/@azure/msal-node/node_modules/uuid/dist/esm-node/validate.js", "../../../node_modules/@azure/msal-node/node_modules/uuid/dist/esm-node/stringify.js", "../../../node_modules/@azure/msal-node/node_modules/uuid/dist/esm-node/v4.js", "../../../node_modules/@azure/msal-node/node_modules/uuid/dist/esm-node/index.js", "../../../node_modules/@azure/msal-node/src/crypto/GuidGenerator.ts", "../../../node_modules/@azure/msal-node/src/utils/EncodingUtils.ts", "../../../node_modules/@azure/msal-node/src/crypto/HashUtils.ts", "../../../node_modules/@azure/msal-node/src/crypto/PkceGenerator.ts", "../../../node_modules/@azure/msal-node/src/crypto/CryptoProvider.ts", "../../../node_modules/@azure/msal-node/src/cache/NodeStorage.ts", "../../../node_modules/@azure/msal-node/src/cache/TokenCache.ts", "../../../node_modules/@azure/msal-node/src/packageMetadata.ts", "../../../node_modules/@azure/msal-node/src/error/NodeAuthError.ts", "../../../node_modules/@azure/msal-node/src/client/UsernamePasswordClient.ts", "../../../node_modules/@azure/msal-node/src/client/ClientApplication.ts", "../../../node_modules/@azure/msal-node/src/network/LoopbackClient.ts", "../../../node_modules/@azure/msal-node/src/client/DeviceCodeClient.ts", "../../../node_modules/@azure/msal-node/src/client/PublicClientApplication.ts", "../../../node_modules/jsonwebtoken/node_modules/jws/lib/data-stream.js", "../../../node_modules/buffer-equal-constant-time/index.js", "../../../node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js", "../../../node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js", "../../../node_modules/jsonwebtoken/node_modules/jwa/index.js", "../../../node_modules/jsonwebtoken/node_modules/jws/lib/tostring.js", "../../../node_modules/jsonwebtoken/node_modules/jws/lib/sign-stream.js", "../../../node_modules/jsonwebtoken/node_modules/jws/lib/verify-stream.js", "../../../node_modules/jsonwebtoken/node_modules/jws/index.js", "../../../node_modules/jsonwebtoken/decode.js", "../../../node_modules/jsonwebtoken/lib/JsonWebTokenError.js", "../../../node_modules/jsonwebtoken/lib/NotBeforeError.js", "../../../node_modules/jsonwebtoken/lib/TokenExpiredError.js", "../../../node_modules/ms/index.js", "../../../node_modules/jsonwebtoken/lib/timespan.js", "../../../node_modules/semver/internal/constants.js", "../../../node_modules/semver/internal/debug.js", "../../../node_modules/semver/internal/re.js", "../../../node_modules/semver/internal/parse-options.js", "../../../node_modules/semver/internal/identifiers.js", "../../../node_modules/semver/classes/semver.js", "../../../node_modules/semver/functions/parse.js", "../../../node_modules/semver/functions/valid.js", "../../../node_modules/semver/functions/clean.js", "../../../node_modules/semver/functions/inc.js", "../../../node_modules/semver/functions/diff.js", "../../../node_modules/semver/functions/major.js", "../../../node_modules/semver/functions/minor.js", "../../../node_modules/semver/functions/patch.js", "../../../node_modules/semver/functions/prerelease.js", "../../../node_modules/semver/functions/compare.js", "../../../node_modules/semver/functions/rcompare.js", "../../../node_modules/semver/functions/compare-loose.js", "../../../node_modules/semver/functions/compare-build.js", "../../../node_modules/semver/functions/sort.js", "../../../node_modules/semver/functions/rsort.js", "../../../node_modules/semver/functions/gt.js", "../../../node_modules/semver/functions/lt.js", "../../../node_modules/semver/functions/eq.js", "../../../node_modules/semver/functions/neq.js", "../../../node_modules/semver/functions/gte.js", "../../../node_modules/semver/functions/lte.js", "../../../node_modules/semver/functions/cmp.js", "../../../node_modules/semver/functions/coerce.js", "../../../node_modules/yallist/iterator.js", "../../../node_modules/yallist/yallist.js", "../../../node_modules/lru-cache/index.js", "../../../node_modules/semver/classes/range.js", "../../../node_modules/semver/classes/comparator.js", "../../../node_modules/semver/functions/satisfies.js", "../../../node_modules/semver/ranges/to-comparators.js", "../../../node_modules/semver/ranges/max-satisfying.js", "../../../node_modules/semver/ranges/min-satisfying.js", "../../../node_modules/semver/ranges/min-version.js", "../../../node_modules/semver/ranges/valid.js", "../../../node_modules/semver/ranges/outside.js", "../../../node_modules/semver/ranges/gtr.js", "../../../node_modules/semver/ranges/ltr.js", "../../../node_modules/semver/ranges/intersects.js", "../../../node_modules/semver/ranges/simplify.js", "../../../node_modules/semver/ranges/subset.js", "../../../node_modules/semver/index.js", "../../../node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js", "../../../node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js", "../../../node_modules/jsonwebtoken/lib/validateAsymmetricKey.js", "../../../node_modules/jsonwebtoken/lib/psSupported.js", "../../../node_modules/jsonwebtoken/verify.js", "../../../node_modules/lodash.includes/index.js", "../../../node_modules/lodash.isboolean/index.js", "../../../node_modules/lodash.isinteger/index.js", "../../../node_modules/lodash.isnumber/index.js", "../../../node_modules/lodash.isplainobject/index.js", "../../../node_modules/lodash.isstring/index.js", "../../../node_modules/lodash.once/index.js", "../../../node_modules/jsonwebtoken/sign.js", "../../../node_modules/jsonwebtoken/index.js", "../../../node_modules/@azure/msal-node/src/client/ClientAssertion.ts", "../../../node_modules/@azure/msal-node/src/client/ClientCredentialClient.ts", "../../../node_modules/@azure/msal-node/src/client/OnBehalfOfClient.ts", "../../../node_modules/@azure/msal-node/src/client/ConfidentialClientApplication.ts", "../../../node_modules/@azure/msal-node/src/cache/distributed/DistributedCachePlugin.ts", "../../../node_modules/@azure/msal-node/dist/index.mjs", "../../../node_modules/debug/node_modules/ms/index.js", "../../../node_modules/debug/src/common.js", "../../../node_modules/debug/src/browser.js", "../../../node_modules/debug/src/node.js", "../../../node_modules/debug/src/index.js", "../../../node_modules/https-proxy-agent/node_modules/agent-base/src/promisify.ts", "../../../node_modules/https-proxy-agent/node_modules/agent-base/src/index.ts", "../../../node_modules/https-proxy-agent/src/parse-proxy-response.ts", "../../../node_modules/https-proxy-agent/src/agent.ts", "../../../node_modules/https-proxy-agent/src/index.ts", "../../../node_modules/@tootallnate/once/src/index.ts", "../../../node_modules/http-proxy-agent/node_modules/agent-base/src/promisify.ts", "../../../node_modules/http-proxy-agent/node_modules/agent-base/src/index.ts", "../../../node_modules/http-proxy-agent/src/agent.ts", "../../../node_modules/http-proxy-agent/src/index.ts", "../../../node_modules/@azure/core-tracing/src/tracingContext.ts", "../../../node_modules/@azure/core-tracing/src/instrumenter.ts", "../../../node_modules/@azure/core-tracing/src/tracingClient.ts", "../../../node_modules/@azure/core-rest-pipeline/src/pipeline.ts", "../../../node_modules/@azure/core-rest-pipeline/src/log.ts", "../../../node_modules/@azure/core-rest-pipeline/src/util/sanitizer.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/logPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/redirectPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/util/userAgentPlatform.ts", "../../../node_modules/@azure/core-rest-pipeline/src/constants.ts", "../../../node_modules/@azure/core-rest-pipeline/src/util/userAgent.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/userAgentPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/decompressResponsePolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/util/helpers.ts", "../../../node_modules/@azure/core-rest-pipeline/src/retryStrategies/throttlingRetryStrategy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/retryStrategies/exponentialRetryStrategy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/retryPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/defaultRetryPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/httpHeaders.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/formDataPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/proxyPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/setClientRequestIdPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/tlsPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/util/inspect.ts", "../../../node_modules/@azure/core-rest-pipeline/src/restError.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/tracingPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/util/typeGuards.ts", "../../../node_modules/@azure/core-rest-pipeline/src/util/stream.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/multipartPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/createPipelineFromOptions.ts", "../../../node_modules/@azure/core-rest-pipeline/src/nodeHttpClient.ts", "../../../node_modules/@azure/core-rest-pipeline/src/defaultHttpClient.ts", "../../../node_modules/@azure/core-rest-pipeline/src/pipelineRequest.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/exponentialRetryPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/systemErrorRetryPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/throttlingRetryPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/util/tokenCycler.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/bearerTokenAuthenticationPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/ndJsonPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/policies/auxiliaryAuthenticationHeaderPolicy.ts", "../../../node_modules/@azure/core-rest-pipeline/src/util/file.ts", "../../../node_modules/@azure/core-client/src/base64.ts", "../../../node_modules/@azure/core-client/src/interfaces.ts", "../../../node_modules/@azure/core-client/src/utils.ts", "../../../node_modules/@azure/core-client/src/serializer.ts", "../../../node_modules/@azure/core-client/src/operationHelpers.ts", "../../../node_modules/@azure/core-client/src/deserializationPolicy.ts", "../../../node_modules/@azure/core-client/src/interfaceHelpers.ts", "../../../node_modules/@azure/core-client/src/serializationPolicy.ts", "../../../node_modules/@azure/core-client/src/pipeline.ts", "../../../node_modules/@azure/core-client/src/httpClientCache.ts", "../../../node_modules/@azure/core-client/src/urlHelpers.ts", "../../../node_modules/@azure/core-client/src/log.ts", "../../../node_modules/@azure/core-client/src/serviceClient.ts", "../../../node_modules/@azure/core-client/src/authorizeRequestOnClaimChallenge.ts", "../../../node_modules/@azure/core-client/src/authorizeRequestOnTenantChallenge.ts", "../../../node_modules/is-docker/index.js", "../../../node_modules/is-wsl/index.js", "../../../node_modules/define-lazy-prop/index.js", "../../../node_modules/open/index.js", "../../../node_modules/stoppable/lib/stoppable.js", "../../../node_modules/@azure/identity/src/errors.ts", "../../../node_modules/@azure/identity/src/util/logging.ts", "../../../node_modules/@azure/identity/src/constants.ts", "../../../node_modules/@azure/identity/src/msal/utils.ts", "../../../node_modules/@azure/identity/src/util/processMultiTenantRequest.ts", "../../../node_modules/@azure/identity/src/util/tenantIdUtils.ts", "../../../node_modules/@azure/identity/src/util/identityTokenEndpoint.ts", "../../../node_modules/@azure/identity/src/util/tracing.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/constants.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/utils.ts", "../../../node_modules/@azure/identity/src/client/identityClient.ts", "../../../node_modules/@azure/identity/src/regionalAuthority.ts", "../../../node_modules/@azure/identity/src/msal/nodeFlows/msalNodeCommon.ts", "../../../node_modules/@azure/identity/src/credentials/visualStudioCodeCredential.ts", "../../../node_modules/@azure/identity/src/plugins/consumer.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/appServiceMsi2017.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/cloudShellMsi.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/imdsMsi.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/arcMsi.ts", "../../../node_modules/@azure/identity/src/msal/nodeFlows/msalClientAssertion.ts", "../../../node_modules/@azure/identity/src/credentials/clientAssertionCredential.ts", "../../../node_modules/@azure/identity/src/credentials/workloadIdentityCredential.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/tokenExchangeMsi.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/fabricMsi.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/appServiceMsi2019.ts", "../../../node_modules/@azure/identity/src/credentials/managedIdentityCredential/index.ts", "../../../node_modules/@azure/identity/src/util/scopeUtils.ts", "../../../node_modules/@azure/identity/src/credentials/azureCliCredential.ts", "../../../node_modules/@azure/identity/src/util/processUtils.ts", "../../../node_modules/@azure/identity/src/credentials/azurePowerShellCredential.ts", "../../../node_modules/@azure/identity/src/credentials/chainedTokenCredential.ts", "../../../node_modules/@azure/identity/src/msal/nodeFlows/msalClientCertificate.ts", "../../../node_modules/@azure/identity/src/credentials/clientCertificateCredential.ts", "../../../node_modules/@azure/identity/src/msal/nodeFlows/msalClientSecret.ts", "../../../node_modules/@azure/identity/src/credentials/clientSecretCredential.ts", "../../../node_modules/@azure/identity/src/msal/nodeFlows/msalUsernamePassword.ts", "../../../node_modules/@azure/identity/src/credentials/usernamePasswordCredential.ts", "../../../node_modules/@azure/identity/src/credentials/environmentCredential.ts", "../../../node_modules/@azure/identity/src/credentials/azureDeveloperCliCredential.ts", "../../../node_modules/@azure/identity/src/credentials/defaultAzureCredential.ts", "../../../node_modules/@azure/identity/src/msal/nodeFlows/msalOpenBrowser.ts", "../../../node_modules/@azure/identity/src/credentials/interactiveBrowserCredential.ts", "../../../node_modules/@azure/identity/src/msal/nodeFlows/msalDeviceCode.ts", "../../../node_modules/@azure/identity/src/credentials/deviceCodeCredential.ts", "../../../node_modules/@azure/identity/src/msal/nodeFlows/msalAuthorizationCode.ts", "../../../node_modules/@azure/identity/src/credentials/authorizationCodeCredential.ts", "../../../node_modules/@azure/identity/src/msal/nodeFlows/msalOnBehalfOf.ts", "../../../node_modules/@azure/identity/src/credentials/onBehalfOfCredential.ts", "../../../node_modules/@azure/identity/src/index.ts", "../src/authentication/getCredential.ts", "../src/cache-persistance/platforms.ts", "../src/cache-persistance/provider.ts", "../src/cache-persistance/cachePersistencePlugin.ts", "../src/authentication/getAuthenticationRecord.ts", "../src/authentication/getAuthenticationRecordPath.ts", "../src/authentication/saveAuthenticationRecord.ts"],
4
+ "sourcesContent": ["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AccountCache,\n IdTokenCache,\n AccessTokenCache,\n RefreshTokenCache,\n AppMetadataCache,\n} from \"@azure/msal-common\";\nimport {\n InMemoryCache,\n JsonCache,\n SerializedAccountEntity,\n SerializedIdTokenEntity,\n SerializedAccessTokenEntity,\n SerializedRefreshTokenEntity,\n SerializedAppMetadataEntity,\n} from \"./SerializerTypes.js\";\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(\n accCache: AccountCache\n ): 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 tenantProfiles: accountEntity.tenantProfiles?.map(\n (tenantProfile) => {\n return JSON.stringify(tenantProfile);\n }\n ),\n };\n });\n\n return accounts;\n }\n\n /**\n * Serialize IdTokens\n * @param idTCache\n */\n static serializeIdTokens(\n idTCache: IdTokenCache\n ): 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(\n atCache: AccessTokenCache\n ): 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(\n rtCache: RefreshTokenCache\n ): 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(\n amdtCache: AppMetadataCache\n ): 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\nexport const Constants = {\n LIBRARY_NAME: \"MSAL.JS\",\n SKU: \"msal.js.common\",\n // Prefix for all library cache entries\n CACHE_PREFIX: \"msal\",\n // default authority\n DEFAULT_AUTHORITY: \"https://login.microsoftonline.com/common/\",\n DEFAULT_AUTHORITY_HOST: \"login.microsoftonline.com\",\n DEFAULT_COMMON_TENANT: \"common\",\n // ADFS String\n ADFS: \"adfs\",\n DSTS: \"dstsv2\",\n // Default AAD Instance Discovery Endpoint\n AAD_INSTANCE_DISCOVERY_ENDPT:\n \"https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=\",\n // CIAM URL\n CIAM_AUTH_URL: \".ciamlogin.com\",\n AAD_TENANT_DOMAIN_SUFFIX: \".onmicrosoft.com\",\n // Resource delimiter - used for certain cache entries\n RESOURCE_DELIM: \"|\",\n // Placeholder for non-existent account ids/objects\n NO_ACCOUNT: \"NO_ACCOUNT\",\n // Claims\n CLAIMS: \"claims\",\n // Consumer UTID\n CONSUMER_UTID: \"9188040d-6c67-4c5b-b112-36a304b66dad\",\n // Default scopes\n OPENID_SCOPE: \"openid\",\n PROFILE_SCOPE: \"profile\",\n OFFLINE_ACCESS_SCOPE: \"offline_access\",\n EMAIL_SCOPE: \"email\",\n // Default response type for authorization code flow\n CODE_RESPONSE_TYPE: \"code\",\n CODE_GRANT_TYPE: \"authorization_code\",\n RT_GRANT_TYPE: \"refresh_token\",\n FRAGMENT_RESPONSE_MODE: \"fragment\",\n S256_CODE_CHALLENGE_METHOD: \"S256\",\n URL_FORM_CONTENT_TYPE: \"application/x-www-form-urlencoded;charset=utf-8\",\n AUTHORIZATION_PENDING: \"authorization_pending\",\n NOT_DEFINED: \"not_defined\",\n EMPTY_STRING: \"\",\n NOT_APPLICABLE: \"N/A\",\n FORWARD_SLASH: \"/\",\n IMDS_ENDPOINT: \"http://169.254.169.254/metadata/instance/compute/location\",\n IMDS_VERSION: \"2020-06-01\",\n IMDS_TIMEOUT: 2000,\n AZURE_REGION_AUTO_DISCOVER_FLAG: \"TryAutoDetect\",\n REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX: \"login.microsoft.com\",\n KNOWN_PUBLIC_CLOUDS: [\n \"login.microsoftonline.com\",\n \"login.windows.net\",\n \"login.microsoft.com\",\n \"sts.windows.net\",\n ],\n TOKEN_RESPONSE_TYPE: \"token\",\n ID_TOKEN_RESPONSE_TYPE: \"id_token\",\n SHR_NONCE_VALIDITY: 240,\n INVALID_INSTANCE: \"invalid_instance\",\n};\n\nexport const 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} as const;\nexport type HttpStatus = (typeof HttpStatus)[keyof typeof HttpStatus];\n\nexport const OIDC_DEFAULT_SCOPES = [\n Constants.OPENID_SCOPE,\n Constants.PROFILE_SCOPE,\n Constants.OFFLINE_ACCESS_SCOPE,\n];\n\nexport const OIDC_SCOPES = [...OIDC_DEFAULT_SCOPES, Constants.EMAIL_SCOPE];\n\n/**\n * Request header names\n */\nexport const HeaderNames = {\n CONTENT_TYPE: \"Content-Type\",\n RETRY_AFTER: \"Retry-After\",\n CCS_HEADER: \"X-AnchorMailbox\",\n WWWAuthenticate: \"WWW-Authenticate\",\n AuthenticationInfo: \"Authentication-Info\",\n X_MS_REQUEST_ID: \"x-ms-request-id\",\n X_MS_HTTP_VERSION: \"x-ms-httpver\",\n} as const;\nexport type HeaderNames = (typeof HeaderNames)[keyof typeof HeaderNames];\n\n/**\n * Persistent cache keys MSAL which stay while user is logged in.\n */\nexport const PersistentCacheKeys = {\n ID_TOKEN: \"idtoken\",\n CLIENT_INFO: \"client.info\",\n ADAL_ID_TOKEN: \"adal.idtoken\",\n ERROR: \"error\",\n ERROR_DESC: \"error.description\",\n ACTIVE_ACCOUNT: \"active-account\", // Legacy active-account cache key, use new key instead\n ACTIVE_ACCOUNT_FILTERS: \"active-account-filters\", // new cache entry for active_account for a more robust version for browser\n} as const;\nexport type PersistentCacheKeys =\n (typeof PersistentCacheKeys)[keyof typeof PersistentCacheKeys];\n\n/**\n * String constants related to AAD Authority\n */\nexport const AADAuthorityConstants = {\n COMMON: \"common\",\n ORGANIZATIONS: \"organizations\",\n CONSUMERS: \"consumers\",\n} as const;\nexport type AADAuthorityConstants =\n (typeof AADAuthorityConstants)[keyof typeof AADAuthorityConstants];\n\n/**\n * Claims request keys\n */\nexport const ClaimsRequestKeys = {\n ACCESS_TOKEN: \"access_token\",\n XMS_CC: \"xms_cc\",\n} as const;\nexport type ClaimsRequestKeys =\n (typeof ClaimsRequestKeys)[keyof typeof ClaimsRequestKeys];\n\n/**\n * we considered making this \"enum\" in the request instead of string, however it looks like the allowed list of\n * prompt values kept changing over past couple of years. There are some undocumented prompt values for some\n * internal partners too, hence the choice of generic \"string\" type instead of the \"enum\"\n */\nexport const PromptValue = {\n LOGIN: \"login\",\n SELECT_ACCOUNT: \"select_account\",\n CONSENT: \"consent\",\n NONE: \"none\",\n CREATE: \"create\",\n NO_SESSION: \"no_session\",\n};\n\n/**\n * allowed values for codeVerifier\n */\nexport const CodeChallengeMethodValues = {\n PLAIN: \"plain\",\n S256: \"S256\",\n};\n\n/**\n * allowed values for server response type\n */\nexport const ServerResponseType = {\n QUERY: \"query\",\n FRAGMENT: \"fragment\",\n} as const;\nexport type ServerResponseType =\n (typeof ServerResponseType)[keyof typeof ServerResponseType];\n\n/**\n * allowed values for response_mode\n */\nexport const ResponseMode = {\n ...ServerResponseType,\n FORM_POST: \"form_post\",\n} as const;\nexport type ResponseMode = (typeof ResponseMode)[keyof typeof ResponseMode];\n\n/**\n * allowed grant_type\n */\nexport const GrantType = {\n IMPLICIT_GRANT: \"implicit\",\n AUTHORIZATION_CODE_GRANT: \"authorization_code\",\n CLIENT_CREDENTIALS_GRANT: \"client_credentials\",\n RESOURCE_OWNER_PASSWORD_GRANT: \"password\",\n REFRESH_TOKEN_GRANT: \"refresh_token\",\n DEVICE_CODE_GRANT: \"device_code\",\n JWT_BEARER: \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n} as const;\nexport type GrantType = (typeof GrantType)[keyof typeof GrantType];\n\n/**\n * Account types in Cache\n */\nexport const CacheAccountType = {\n MSSTS_ACCOUNT_TYPE: \"MSSTS\",\n ADFS_ACCOUNT_TYPE: \"ADFS\",\n MSAV1_ACCOUNT_TYPE: \"MSA\",\n GENERIC_ACCOUNT_TYPE: \"Generic\", // NTLM, Kerberos, FBA, Basic etc\n} as const;\nexport type CacheAccountType =\n (typeof CacheAccountType)[keyof typeof CacheAccountType];\n\n/**\n * Separators used in cache\n */\nexport const Separators = {\n CACHE_KEY_SEPARATOR: \"-\",\n CLIENT_INFO_SEPARATOR: \".\",\n} as const;\nexport type Separators = (typeof Separators)[keyof typeof Separators];\n\n/**\n * Credential Type stored in the cache\n */\nexport const CredentialType = {\n ID_TOKEN: \"IdToken\",\n ACCESS_TOKEN: \"AccessToken\",\n ACCESS_TOKEN_WITH_AUTH_SCHEME: \"AccessToken_With_AuthScheme\",\n REFRESH_TOKEN: \"RefreshToken\",\n} as const;\nexport type CredentialType =\n (typeof CredentialType)[keyof typeof CredentialType];\n\n/**\n * Combine all cache types\n */\nexport const CacheType = {\n ADFS: 1001,\n MSA: 1002,\n MSSTS: 1003,\n GENERIC: 1004,\n ACCESS_TOKEN: 2001,\n REFRESH_TOKEN: 2002,\n ID_TOKEN: 2003,\n APP_METADATA: 3001,\n UNDEFINED: 9999,\n} as const;\nexport type CacheType = (typeof CacheType)[keyof typeof CacheType];\n\n/**\n * More Cache related constants\n */\nexport const APP_METADATA = \"appmetadata\";\nexport const CLIENT_INFO = \"client_info\";\nexport const THE_FAMILY_ID = \"1\";\n\nexport const AUTHORITY_METADATA_CONSTANTS = {\n CACHE_KEY: \"authority-metadata\",\n REFRESH_TIME_SECONDS: 3600 * 24, // 24 Hours\n};\n\nexport const AuthorityMetadataSource = {\n CONFIG: \"config\",\n CACHE: \"cache\",\n NETWORK: \"network\",\n HARDCODED_VALUES: \"hardcoded_values\",\n} as const;\nexport type AuthorityMetadataSource =\n (typeof AuthorityMetadataSource)[keyof typeof AuthorityMetadataSource];\n\nexport const SERVER_TELEM_CONSTANTS = {\n SCHEMA_VERSION: 5,\n MAX_CUR_HEADER_BYTES: 80, // ESTS limit is 100B, set to 80 to provide a 20B buffer\n MAX_LAST_HEADER_BYTES: 330, // ESTS limit is 350B, set to 330 to provide a 20B buffer,\n MAX_CACHED_ERRORS: 50, // Limit the number of errors that can be stored to prevent uncontrolled size gains\n CACHE_KEY: \"server-telemetry\",\n CATEGORY_SEPARATOR: \"|\",\n VALUE_SEPARATOR: \",\",\n OVERFLOW_TRUE: \"1\",\n OVERFLOW_FALSE: \"0\",\n UNKNOWN_ERROR: \"unknown_error\",\n};\n\n/**\n * Type of the authentication request\n */\nexport const AuthenticationScheme = {\n BEARER: \"Bearer\",\n POP: \"pop\",\n SSH: \"ssh-cert\",\n} as const;\nexport type AuthenticationScheme =\n (typeof AuthenticationScheme)[keyof typeof AuthenticationScheme];\n\n/**\n * Constants related to throttling\n */\nexport const ThrottlingConstants = {\n // Default time to throttle RequestThumbprint in seconds\n DEFAULT_THROTTLE_TIME_SECONDS: 60,\n // Default maximum time to throttle in seconds, overrides what the server sends back\n DEFAULT_MAX_THROTTLE_TIME_SECONDS: 3600,\n // Prefix for storing throttling entries\n THROTTLING_PREFIX: \"throttling\",\n // Value assigned to the x-ms-lib-capability header to indicate to the server the library supports throttling\n X_MS_LIB_CAPABILITY_VALUE: \"retry-after, h429\",\n};\n\nexport const Errors = {\n INVALID_GRANT_ERROR: \"invalid_grant\",\n CLIENT_MISMATCH_ERROR: \"client_mismatch\",\n};\n\n/**\n * Password grant parameters\n */\nexport const PasswordGrantConstants = {\n username: \"username\",\n password: \"password\",\n} as const;\nexport type PasswordGrantConstants =\n (typeof PasswordGrantConstants)[keyof typeof PasswordGrantConstants];\n\n/**\n * Response codes\n */\nexport const ResponseCodes = {\n httpSuccess: 200,\n httpBadRequest: 400,\n} as const;\nexport type ResponseCodes = (typeof ResponseCodes)[keyof typeof ResponseCodes];\n\n/**\n * Region Discovery Sources\n */\nexport const RegionDiscoverySources = {\n FAILED_AUTO_DETECTION: \"1\",\n INTERNAL_CACHE: \"2\",\n ENVIRONMENT_VARIABLE: \"3\",\n IMDS: \"4\",\n} as const;\nexport type RegionDiscoverySources =\n (typeof RegionDiscoverySources)[keyof typeof RegionDiscoverySources];\n\n/**\n * Region Discovery Outcomes\n */\nexport const RegionDiscoveryOutcomes = {\n CONFIGURED_MATCHES_DETECTED: \"1\",\n CONFIGURED_NO_AUTO_DETECTION: \"2\",\n CONFIGURED_NOT_DETECTED: \"3\",\n AUTO_DETECTION_REQUESTED_SUCCESSFUL: \"4\",\n AUTO_DETECTION_REQUESTED_FAILED: \"5\",\n} as const;\nexport type RegionDiscoveryOutcomes =\n (typeof RegionDiscoveryOutcomes)[keyof typeof RegionDiscoveryOutcomes];\n\n/**\n * Specifies the reason for fetching the access token from the identity provider\n */\nexport const CacheOutcome = {\n // When a token is found in the cache or the cache is not supposed to be hit when making the request\n NOT_APPLICABLE: \"0\",\n // When the token request goes to the identity provider because force_refresh was set to true. Also occurs if claims were requested\n FORCE_REFRESH_OR_CLAIMS: \"1\",\n // When the token request goes to the identity provider because no cached access token exists\n NO_CACHED_ACCESS_TOKEN: \"2\",\n // When the token request goes to the identity provider because cached access token expired\n CACHED_ACCESS_TOKEN_EXPIRED: \"3\",\n // When the token request goes to the identity provider because refresh_in was used and the existing token needs to be refreshed\n PROACTIVELY_REFRESHED: \"4\",\n} as const;\nexport type CacheOutcome = (typeof CacheOutcome)[keyof typeof CacheOutcome];\n\nexport const JsonWebTokenTypes = {\n Jwt: \"JWT\",\n Jwk: \"JWK\",\n Pop: \"pop\",\n} as const;\nexport type JsonWebTokenTypes =\n (typeof JsonWebTokenTypes)[keyof typeof JsonWebTokenTypes];\n\nexport const ONE_DAY_IN_MS = 86400000;\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * AuthErrorMessage class containing string constants used by error codes and messages.\n */\nexport const unexpectedError = \"unexpected_error\";\nexport const postRequestFailed = \"post_request_failed\";\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants } from \"../utils/Constants\";\nimport * as AuthErrorCodes from \"./AuthErrorCodes\";\nexport { AuthErrorCodes };\n\nexport const AuthErrorMessages = {\n [AuthErrorCodes.unexpectedError]: \"Unexpected error in authentication.\",\n [AuthErrorCodes.postRequestFailed]:\n \"Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details.\",\n};\n\n/**\n * AuthErrorMessage class containing string constants used by error codes and messages.\n * @deprecated Use AuthErrorCodes instead\n */\nexport const AuthErrorMessage = {\n unexpectedError: {\n code: AuthErrorCodes.unexpectedError,\n desc: AuthErrorMessages[AuthErrorCodes.unexpectedError],\n },\n postRequestFailed: {\n code: AuthErrorCodes.postRequestFailed,\n desc: AuthErrorMessages[AuthErrorCodes.postRequestFailed],\n },\n};\n\n/**\n * General error class thrown by the MSAL.js library.\n */\nexport class AuthError extends Error {\n /**\n * Short string denoting error\n */\n errorCode: string;\n\n /**\n * Detailed description of error\n */\n errorMessage: string;\n\n /**\n * Describes the subclass of an error\n */\n subError: string;\n\n /**\n * CorrelationId associated with the error\n */\n correlationId: string;\n\n constructor(errorCode?: string, errorMessage?: string, suberror?: string) {\n const errorString = errorMessage\n ? `${errorCode}: ${errorMessage}`\n : errorCode;\n super(errorString);\n Object.setPrototypeOf(this, AuthError.prototype);\n\n this.errorCode = errorCode || Constants.EMPTY_STRING;\n this.errorMessage = errorMessage || Constants.EMPTY_STRING;\n this.subError = suberror || Constants.EMPTY_STRING;\n this.name = \"AuthError\";\n }\n\n setCorrelationId(correlationId: string): void {\n this.correlationId = correlationId;\n }\n}\n\nexport function createAuthError(\n code: string,\n additionalMessage?: string\n): AuthError {\n return new AuthError(\n code,\n additionalMessage\n ? `${AuthErrorMessages[code]} ${additionalMessage}`\n : AuthErrorMessages[code]\n );\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport const clientInfoDecodingError = \"client_info_decoding_error\";\nexport const clientInfoEmptyError = \"client_info_empty_error\";\nexport const tokenParsingError = \"token_parsing_error\";\nexport const nullOrEmptyToken = \"null_or_empty_token\";\nexport const endpointResolutionError = \"endpoints_resolution_error\";\nexport const networkError = \"network_error\";\nexport const openIdConfigError = \"openid_config_error\";\nexport const hashNotDeserialized = \"hash_not_deserialized\";\nexport const invalidState = \"invalid_state\";\nexport const stateMismatch = \"state_mismatch\";\nexport const stateNotFound = \"state_not_found\";\nexport const nonceMismatch = \"nonce_mismatch\";\nexport const authTimeNotFound = \"auth_time_not_found\";\nexport const maxAgeTranspired = \"max_age_transpired\";\nexport const multipleMatchingTokens = \"multiple_matching_tokens\";\nexport const multipleMatchingAccounts = \"multiple_matching_accounts\";\nexport const multipleMatchingAppMetadata = \"multiple_matching_appMetadata\";\nexport const requestCannotBeMade = \"request_cannot_be_made\";\nexport const cannotRemoveEmptyScope = \"cannot_remove_empty_scope\";\nexport const cannotAppendScopeSet = \"cannot_append_scopeset\";\nexport const emptyInputScopeSet = \"empty_input_scopeset\";\nexport const deviceCodePollingCancelled = \"device_code_polling_cancelled\";\nexport const deviceCodeExpired = \"device_code_expired\";\nexport const deviceCodeUnknownError = \"device_code_unknown_error\";\nexport const noAccountInSilentRequest = \"no_account_in_silent_request\";\nexport const invalidCacheRecord = \"invalid_cache_record\";\nexport const invalidCacheEnvironment = \"invalid_cache_environment\";\nexport const noAccountFound = \"no_account_found\";\nexport const noCryptoObject = \"no_crypto_object\";\nexport const unexpectedCredentialType = \"unexpected_credential_type\";\nexport const invalidAssertion = \"invalid_assertion\";\nexport const invalidClientCredential = \"invalid_client_credential\";\nexport const tokenRefreshRequired = \"token_refresh_required\";\nexport const userTimeoutReached = \"user_timeout_reached\";\nexport const tokenClaimsCnfRequiredForSignedJwt =\n \"token_claims_cnf_required_for_signedjwt\";\nexport const authorizationCodeMissingFromServerResponse =\n \"authorization_code_missing_from_server_response\";\nexport const bindingKeyNotRemoved = \"binding_key_not_removed\";\nexport const endSessionEndpointNotSupported =\n \"end_session_endpoint_not_supported\";\nexport const keyIdMissing = \"key_id_missing\";\nexport const noNetworkConnectivity = \"no_network_connectivity\";\nexport const userCanceled = \"user_canceled\";\nexport const missingTenantIdError = \"missing_tenant_id_error\";\nexport const methodNotImplemented = \"method_not_implemented\";\nexport const nestedAppAuthBridgeDisabled = \"nested_app_auth_bridge_disabled\";\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AuthError } from \"./AuthError\";\nimport * as ClientAuthErrorCodes from \"./ClientAuthErrorCodes\";\nexport { ClientAuthErrorCodes }; // Allow importing as \"ClientAuthErrorCodes\";\n\n/**\n * ClientAuthErrorMessage class containing string constants used by error codes and messages.\n */\n\nexport const ClientAuthErrorMessages = {\n [ClientAuthErrorCodes.clientInfoDecodingError]:\n \"The client info could not be parsed/decoded correctly\",\n [ClientAuthErrorCodes.clientInfoEmptyError]: \"The client info was empty\",\n [ClientAuthErrorCodes.tokenParsingError]: \"Token cannot be parsed\",\n [ClientAuthErrorCodes.nullOrEmptyToken]: \"The token is null or empty\",\n [ClientAuthErrorCodes.endpointResolutionError]:\n \"Endpoints cannot be resolved\",\n [ClientAuthErrorCodes.networkError]: \"Network request failed\",\n [ClientAuthErrorCodes.openIdConfigError]:\n \"Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.\",\n [ClientAuthErrorCodes.hashNotDeserialized]:\n \"The hash parameters could not be deserialized\",\n [ClientAuthErrorCodes.invalidState]: \"State was not the expected format\",\n [ClientAuthErrorCodes.stateMismatch]: \"State mismatch error\",\n [ClientAuthErrorCodes.stateNotFound]: \"State not found\",\n [ClientAuthErrorCodes.nonceMismatch]: \"Nonce mismatch error\",\n [ClientAuthErrorCodes.authTimeNotFound]:\n \"Max Age was requested and the ID token is missing the auth_time variable.\" +\n \" auth_time is an optional claim and is not enabled by default - it must be enabled.\" +\n \" See https://aka.ms/msaljs/optional-claims for more information.\",\n [ClientAuthErrorCodes.maxAgeTranspired]:\n \"Max Age is set to 0, or too much time has elapsed since the last end-user authentication.\",\n [ClientAuthErrorCodes.multipleMatchingTokens]:\n \"The cache contains multiple tokens satisfying the requirements. \" +\n \"Call AcquireToken again providing more requirements such as authority or account.\",\n [ClientAuthErrorCodes.multipleMatchingAccounts]:\n \"The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account\",\n [ClientAuthErrorCodes.multipleMatchingAppMetadata]:\n \"The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata\",\n [ClientAuthErrorCodes.requestCannotBeMade]:\n \"Token request cannot be made without authorization code or refresh token.\",\n [ClientAuthErrorCodes.cannotRemoveEmptyScope]:\n \"Cannot remove null or empty scope from ScopeSet\",\n [ClientAuthErrorCodes.cannotAppendScopeSet]: \"Cannot append ScopeSet\",\n [ClientAuthErrorCodes.emptyInputScopeSet]:\n \"Empty input ScopeSet cannot be processed\",\n [ClientAuthErrorCodes.deviceCodePollingCancelled]:\n \"Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.\",\n [ClientAuthErrorCodes.deviceCodeExpired]: \"Device code is expired.\",\n [ClientAuthErrorCodes.deviceCodeUnknownError]:\n \"Device code stopped polling for unknown reasons.\",\n [ClientAuthErrorCodes.noAccountInSilentRequest]:\n \"Please pass an account object, silent flow is not supported without account information\",\n [ClientAuthErrorCodes.invalidCacheRecord]:\n \"Cache record object was null or undefined.\",\n [ClientAuthErrorCodes.invalidCacheEnvironment]:\n \"Invalid environment when attempting to create cache entry\",\n [ClientAuthErrorCodes.noAccountFound]:\n \"No account found in cache for given key.\",\n [ClientAuthErrorCodes.noCryptoObject]: \"No crypto object detected.\",\n [ClientAuthErrorCodes.unexpectedCredentialType]:\n \"Unexpected credential type.\",\n [ClientAuthErrorCodes.invalidAssertion]:\n \"Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515\",\n [ClientAuthErrorCodes.invalidClientCredential]:\n \"Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential\",\n [ClientAuthErrorCodes.tokenRefreshRequired]:\n \"Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired.\",\n [ClientAuthErrorCodes.userTimeoutReached]:\n \"User defined timeout for device code polling reached\",\n [ClientAuthErrorCodes.tokenClaimsCnfRequiredForSignedJwt]:\n \"Cannot generate a POP jwt if the token_claims are not populated\",\n [ClientAuthErrorCodes.authorizationCodeMissingFromServerResponse]:\n \"Server response does not contain an authorization code to proceed\",\n [ClientAuthErrorCodes.bindingKeyNotRemoved]:\n \"Could not remove the credential's binding key from storage.\",\n [ClientAuthErrorCodes.endSessionEndpointNotSupported]:\n \"The provided authority does not support logout\",\n [ClientAuthErrorCodes.keyIdMissing]:\n \"A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key.\",\n [ClientAuthErrorCodes.noNetworkConnectivity]:\n \"No network connectivity. Check your internet connection.\",\n [ClientAuthErrorCodes.userCanceled]: \"User cancelled the flow.\",\n [ClientAuthErrorCodes.missingTenantIdError]:\n \"A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.\",\n [ClientAuthErrorCodes.methodNotImplemented]:\n \"This method has not been implemented\",\n [ClientAuthErrorCodes.nestedAppAuthBridgeDisabled]:\n \"The nested app auth bridge is disabled\",\n};\n\n/**\n * String constants used by error codes and messages.\n * @deprecated Use ClientAuthErrorCodes instead\n */\nexport const ClientAuthErrorMessage = {\n clientInfoDecodingError: {\n code: ClientAuthErrorCodes.clientInfoDecodingError,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.clientInfoDecodingError\n ],\n },\n clientInfoEmptyError: {\n code: ClientAuthErrorCodes.clientInfoEmptyError,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.clientInfoEmptyError\n ],\n },\n tokenParsingError: {\n code: ClientAuthErrorCodes.tokenParsingError,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.tokenParsingError],\n },\n nullOrEmptyToken: {\n code: ClientAuthErrorCodes.nullOrEmptyToken,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.nullOrEmptyToken],\n },\n endpointResolutionError: {\n code: ClientAuthErrorCodes.endpointResolutionError,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.endpointResolutionError\n ],\n },\n networkError: {\n code: ClientAuthErrorCodes.networkError,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.networkError],\n },\n unableToGetOpenidConfigError: {\n code: ClientAuthErrorCodes.openIdConfigError,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.openIdConfigError],\n },\n hashNotDeserialized: {\n code: ClientAuthErrorCodes.hashNotDeserialized,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.hashNotDeserialized],\n },\n invalidStateError: {\n code: ClientAuthErrorCodes.invalidState,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.invalidState],\n },\n stateMismatchError: {\n code: ClientAuthErrorCodes.stateMismatch,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.stateMismatch],\n },\n stateNotFoundError: {\n code: ClientAuthErrorCodes.stateNotFound,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.stateNotFound],\n },\n nonceMismatchError: {\n code: ClientAuthErrorCodes.nonceMismatch,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.nonceMismatch],\n },\n authTimeNotFoundError: {\n code: ClientAuthErrorCodes.authTimeNotFound,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.authTimeNotFound],\n },\n maxAgeTranspired: {\n code: ClientAuthErrorCodes.maxAgeTranspired,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.maxAgeTranspired],\n },\n multipleMatchingTokens: {\n code: ClientAuthErrorCodes.multipleMatchingTokens,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.multipleMatchingTokens\n ],\n },\n multipleMatchingAccounts: {\n code: ClientAuthErrorCodes.multipleMatchingAccounts,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.multipleMatchingAccounts\n ],\n },\n multipleMatchingAppMetadata: {\n code: ClientAuthErrorCodes.multipleMatchingAppMetadata,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.multipleMatchingAppMetadata\n ],\n },\n tokenRequestCannotBeMade: {\n code: ClientAuthErrorCodes.requestCannotBeMade,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.requestCannotBeMade],\n },\n removeEmptyScopeError: {\n code: ClientAuthErrorCodes.cannotRemoveEmptyScope,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.cannotRemoveEmptyScope\n ],\n },\n appendScopeSetError: {\n code: ClientAuthErrorCodes.cannotAppendScopeSet,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.cannotAppendScopeSet\n ],\n },\n emptyInputScopeSetError: {\n code: ClientAuthErrorCodes.emptyInputScopeSet,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.emptyInputScopeSet],\n },\n DeviceCodePollingCancelled: {\n code: ClientAuthErrorCodes.deviceCodePollingCancelled,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.deviceCodePollingCancelled\n ],\n },\n DeviceCodeExpired: {\n code: ClientAuthErrorCodes.deviceCodeExpired,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.deviceCodeExpired],\n },\n DeviceCodeUnknownError: {\n code: ClientAuthErrorCodes.deviceCodeUnknownError,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.deviceCodeUnknownError\n ],\n },\n NoAccountInSilentRequest: {\n code: ClientAuthErrorCodes.noAccountInSilentRequest,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.noAccountInSilentRequest\n ],\n },\n invalidCacheRecord: {\n code: ClientAuthErrorCodes.invalidCacheRecord,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.invalidCacheRecord],\n },\n invalidCacheEnvironment: {\n code: ClientAuthErrorCodes.invalidCacheEnvironment,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.invalidCacheEnvironment\n ],\n },\n noAccountFound: {\n code: ClientAuthErrorCodes.noAccountFound,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.noAccountFound],\n },\n noCryptoObj: {\n code: ClientAuthErrorCodes.noCryptoObject,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.noCryptoObject],\n },\n unexpectedCredentialType: {\n code: ClientAuthErrorCodes.unexpectedCredentialType,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.unexpectedCredentialType\n ],\n },\n invalidAssertion: {\n code: ClientAuthErrorCodes.invalidAssertion,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.invalidAssertion],\n },\n invalidClientCredential: {\n code: ClientAuthErrorCodes.invalidClientCredential,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.invalidClientCredential\n ],\n },\n tokenRefreshRequired: {\n code: ClientAuthErrorCodes.tokenRefreshRequired,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.tokenRefreshRequired\n ],\n },\n userTimeoutReached: {\n code: ClientAuthErrorCodes.userTimeoutReached,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.userTimeoutReached],\n },\n tokenClaimsRequired: {\n code: ClientAuthErrorCodes.tokenClaimsCnfRequiredForSignedJwt,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.tokenClaimsCnfRequiredForSignedJwt\n ],\n },\n noAuthorizationCodeFromServer: {\n code: ClientAuthErrorCodes.authorizationCodeMissingFromServerResponse,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.authorizationCodeMissingFromServerResponse\n ],\n },\n bindingKeyNotRemovedError: {\n code: ClientAuthErrorCodes.bindingKeyNotRemoved,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.bindingKeyNotRemoved\n ],\n },\n logoutNotSupported: {\n code: ClientAuthErrorCodes.endSessionEndpointNotSupported,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.endSessionEndpointNotSupported\n ],\n },\n keyIdMissing: {\n code: ClientAuthErrorCodes.keyIdMissing,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.keyIdMissing],\n },\n noNetworkConnectivity: {\n code: ClientAuthErrorCodes.noNetworkConnectivity,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.noNetworkConnectivity\n ],\n },\n userCanceledError: {\n code: ClientAuthErrorCodes.userCanceled,\n desc: ClientAuthErrorMessages[ClientAuthErrorCodes.userCanceled],\n },\n missingTenantIdError: {\n code: ClientAuthErrorCodes.missingTenantIdError,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.missingTenantIdError\n ],\n },\n nestedAppAuthBridgeDisabled: {\n code: ClientAuthErrorCodes.nestedAppAuthBridgeDisabled,\n desc: ClientAuthErrorMessages[\n ClientAuthErrorCodes.nestedAppAuthBridgeDisabled\n ],\n },\n};\n\n/**\n * Error thrown when there is an error in the client code running on the browser.\n */\nexport class ClientAuthError extends AuthError {\n constructor(errorCode: string, additionalMessage?: string) {\n super(\n errorCode,\n additionalMessage\n ? `${ClientAuthErrorMessages[errorCode]}: ${additionalMessage}`\n : ClientAuthErrorMessages[errorCode]\n );\n this.name = \"ClientAuthError\";\n\n Object.setPrototypeOf(this, ClientAuthError.prototype);\n }\n}\n\nexport function createClientAuthError(\n errorCode: string,\n additionalMessage?: string\n): ClientAuthError {\n return new ClientAuthError(errorCode, additionalMessage);\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../error/ClientAuthError\";\nimport { BaseAuthRequest } from \"../request/BaseAuthRequest\";\nimport { ShrOptions, SignedHttpRequest } from \"./SignedHttpRequest\";\n\n/**\n * The PkceCodes type describes the structure\n * of objects that contain PKCE code\n * challenge and verifier pairs\n */\nexport type PkceCodes = {\n verifier: string;\n challenge: string;\n};\n\nexport type SignedHttpRequestParameters = Pick<\n BaseAuthRequest,\n | \"resourceRequestMethod\"\n | \"resourceRequestUri\"\n | \"shrClaims\"\n | \"shrNonce\"\n | \"shrOptions\"\n> & {\n correlationId?: string;\n};\n\n/**\n * Interface for crypto functions used by library\n */\nexport interface ICrypto {\n /**\n * Creates a guid randomly.\n */\n createNewGuid(): string;\n /**\n * base64 Encode string\n * @param input\n */\n base64Encode(input: string): string;\n /**\n * base64 decode string\n * @param input\n */\n base64Decode(input: string): string;\n /**\n * Generates an JWK RSA S256 Thumbprint\n * @param request\n */\n getPublicKeyThumbprint(\n request: SignedHttpRequestParameters\n ): Promise<string>;\n /**\n * Removes cryptographic keypair from key store matching the keyId passed in\n * @param kid\n */\n removeTokenBindingKey(kid: string): Promise<boolean>;\n /**\n * Removes all cryptographic keys from IndexedDB storage\n */\n clearKeystore(): Promise<boolean>;\n /**\n * Returns a signed proof-of-possession token with a given acces token that contains a cnf claim with the required kid.\n * @param accessToken\n */\n signJwt(\n payload: SignedHttpRequest,\n kid: string,\n shrOptions?: ShrOptions,\n correlationId?: string\n ): Promise<string>;\n /**\n * Returns the SHA-256 hash of an input string\n * @param plainText\n */\n hashString(plainText: string): Promise<string>;\n}\n\nexport const DEFAULT_CRYPTO_IMPLEMENTATION: ICrypto = {\n createNewGuid: (): string => {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n base64Decode: (): string => {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n base64Encode: (): string => {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n async getPublicKeyThumbprint(): Promise<string> {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n async removeTokenBindingKey(): Promise<boolean> {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n async clearKeystore(): Promise<boolean> {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n async signJwt(): Promise<string> {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n async hashString(): Promise<string> {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n};\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { LoggerOptions } from \"../config/ClientConfiguration\";\nimport { Constants } from \"../utils/Constants\";\n\n/**\n * Options for logger messages.\n */\nexport type LoggerMessageOptions = {\n logLevel: LogLevel;\n containsPii?: boolean;\n context?: string;\n correlationId?: string;\n};\n\n/**\n * Log message level.\n */\nexport enum LogLevel {\n Error,\n Warning,\n Info,\n Verbose,\n Trace,\n}\n\n/**\n * Callback to send the messages to.\n */\nexport interface ILoggerCallback {\n (level: LogLevel, message: string, containsPii: boolean): void;\n}\n\n/**\n * Class which facilitates logging of messages to a specific place.\n */\nexport class Logger {\n // Correlation ID for request, usually set by user.\n private correlationId: string;\n\n // Current log level, defaults to info.\n private level: LogLevel = LogLevel.Info;\n\n // Boolean describing whether PII logging is allowed.\n private piiLoggingEnabled: boolean;\n\n // Callback to send messages to.\n private localCallback: ILoggerCallback;\n\n // Package name implementing this logger\n private packageName: string;\n\n // Package version implementing this logger\n private packageVersion: string;\n\n constructor(\n loggerOptions: LoggerOptions,\n packageName?: string,\n packageVersion?: string\n ) {\n const defaultLoggerCallback = () => {\n return;\n };\n const setLoggerOptions =\n loggerOptions || Logger.createDefaultLoggerOptions();\n this.localCallback =\n setLoggerOptions.loggerCallback || defaultLoggerCallback;\n this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false;\n this.level =\n typeof setLoggerOptions.logLevel === \"number\"\n ? setLoggerOptions.logLevel\n : LogLevel.Info;\n this.correlationId =\n setLoggerOptions.correlationId || Constants.EMPTY_STRING;\n this.packageName = packageName || Constants.EMPTY_STRING;\n this.packageVersion = packageVersion || Constants.EMPTY_STRING;\n }\n\n private static createDefaultLoggerOptions(): LoggerOptions {\n return {\n loggerCallback: () => {\n // allow users to not set loggerCallback\n },\n piiLoggingEnabled: false,\n logLevel: LogLevel.Info,\n };\n }\n\n /**\n * Create new Logger with existing configurations.\n */\n public clone(\n packageName: string,\n packageVersion: string,\n correlationId?: string\n ): Logger {\n return new Logger(\n {\n loggerCallback: this.localCallback,\n piiLoggingEnabled: this.piiLoggingEnabled,\n logLevel: this.level,\n correlationId: correlationId || this.correlationId,\n },\n packageName,\n packageVersion\n );\n }\n\n /**\n * Log message with required options.\n */\n private logMessage(\n logMessage: string,\n options: LoggerMessageOptions\n ): void {\n if (\n options.logLevel > this.level ||\n (!this.piiLoggingEnabled && options.containsPii)\n ) {\n return;\n }\n const timestamp = new Date().toUTCString();\n\n // Add correlationId to logs if set, correlationId provided on log messages take precedence\n const logHeader = `[${timestamp}] : [${\n options.correlationId || this.correlationId || \"\"\n }]`;\n\n const log = `${logHeader} : ${this.packageName}@${\n this.packageVersion\n } : ${LogLevel[options.logLevel]} - ${logMessage}`;\n // debug(`msal:${LogLevel[options.logLevel]}${options.containsPii ? \"-Pii\": Constants.EMPTY_STRING}${options.context ? `:${options.context}` : Constants.EMPTY_STRING}`)(logMessage);\n this.executeCallback(\n options.logLevel,\n log,\n options.containsPii || false\n );\n }\n\n /**\n * Execute callback with message.\n */\n executeCallback(\n level: LogLevel,\n message: string,\n containsPii: boolean\n ): void {\n if (this.localCallback) {\n this.localCallback(level, message, containsPii);\n }\n }\n\n /**\n * Logs error messages.\n */\n error(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Error,\n containsPii: false,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Logs error messages with PII.\n */\n errorPii(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Error,\n containsPii: true,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Logs warning messages.\n */\n warning(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Warning,\n containsPii: false,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Logs warning messages with PII.\n */\n warningPii(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Warning,\n containsPii: true,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Logs info messages.\n */\n info(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Info,\n containsPii: false,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Logs info messages with PII.\n */\n infoPii(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Info,\n containsPii: true,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Logs verbose messages.\n */\n verbose(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Verbose,\n containsPii: false,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Logs verbose messages with PII.\n */\n verbosePii(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Verbose,\n containsPii: true,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Logs trace messages.\n */\n trace(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Trace,\n containsPii: false,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Logs trace messages with PII.\n */\n tracePii(message: string, correlationId?: string): void {\n this.logMessage(message, {\n logLevel: LogLevel.Trace,\n containsPii: true,\n correlationId: correlationId || Constants.EMPTY_STRING,\n });\n }\n\n /**\n * Returns whether PII Logging is enabled or not.\n */\n isPiiLoggingEnabled(): boolean {\n return this.piiLoggingEnabled || false;\n }\n}\n", "/* eslint-disable header/header */\nexport const name = \"@azure/msal-common\";\nexport const version = \"14.6.1\";\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ProtocolMode } from \"./ProtocolMode\";\nimport { OIDCOptions } from \"./OIDCOptions\";\nimport { AzureRegionConfiguration } from \"./AzureRegionConfiguration\";\nimport { CloudInstanceDiscoveryResponse } from \"./CloudInstanceDiscoveryResponse\";\n\nexport type AuthorityOptions = {\n protocolMode: ProtocolMode;\n OIDCOptions?: OIDCOptions | null;\n knownAuthorities: Array<string>;\n cloudDiscoveryMetadata: string;\n authorityMetadata: string;\n skipAuthorityMetadataCache?: boolean;\n azureRegionConfiguration?: AzureRegionConfiguration;\n authority?: string;\n};\n\nexport type StaticAuthorityOptions = Partial<\n Pick<AuthorityOptions, \"knownAuthorities\">\n> & {\n canonicalAuthority?: string;\n cloudDiscoveryMetadata?: CloudInstanceDiscoveryResponse;\n};\n\nexport const AzureCloudInstance = {\n // AzureCloudInstance is not specified.\n None: \"none\",\n\n // Microsoft Azure public cloud\n AzurePublic: \"https://login.microsoftonline.com\",\n\n // Microsoft PPE\n AzurePpe: \"https://login.windows-ppe.net\",\n\n // Microsoft Chinese national/regional cloud\n AzureChina: \"https://login.chinacloudapi.cn\",\n\n // Microsoft German national/regional cloud (\"Black Forest\")\n AzureGermany: \"https://login.microsoftonline.de\",\n\n // US Government cloud\n AzureUsGovernment: \"https://login.microsoftonline.us\",\n} as const;\nexport type AzureCloudInstance =\n (typeof AzureCloudInstance)[keyof typeof AzureCloudInstance];\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { TokenClaims } from \"./TokenClaims\";\nimport {\n createClientAuthError,\n ClientAuthErrorCodes,\n} from \"../error/ClientAuthError\";\n\n/**\n * Extract token by decoding the rawToken\n *\n * @param encodedToken\n */\nexport function extractTokenClaims(\n encodedToken: string,\n base64Decode: (input: string) => string\n): TokenClaims {\n const jswPayload = getJWSPayload(encodedToken);\n\n // token will be decoded to get the username\n try {\n // base64Decode() should throw an error if there is an issue\n const base64Decoded = base64Decode(jswPayload);\n return JSON.parse(base64Decoded) as TokenClaims;\n } catch (err) {\n throw createClientAuthError(ClientAuthErrorCodes.tokenParsingError);\n }\n}\n\n/**\n * decode a JWT\n *\n * @param authToken\n */\nexport function getJWSPayload(authToken: string): string {\n if (!authToken) {\n throw createClientAuthError(ClientAuthErrorCodes.nullOrEmptyToken);\n }\n const tokenPartsRegex = /^([^\\.\\s]*)\\.([^\\.\\s]+)\\.([^\\.\\s]*)$/;\n const matches = tokenPartsRegex.exec(authToken);\n if (!matches || matches.length < 4) {\n throw createClientAuthError(ClientAuthErrorCodes.tokenParsingError);\n }\n /**\n * const crackedToken = {\n * header: matches[1],\n * JWSPayload: matches[2],\n * JWSSig: matches[3],\n * };\n */\n\n return matches[2];\n}\n\n/**\n * Determine if the token's max_age has transpired\n */\nexport function checkMaxAge(authTime: number, maxAge: number): void {\n /*\n * per https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest\n * To force an immediate re-authentication: If an app requires that a user re-authenticate prior to access,\n * provide a value of 0 for the max_age parameter and the AS will force a fresh login.\n */\n const fiveMinuteSkew = 300000; // five minutes in milliseconds\n if (maxAge === 0 || Date.now() - fiveMinuteSkew > authTime + maxAge) {\n throw createClientAuthError(ClientAuthErrorCodes.maxAgeTranspired);\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Utility class which exposes functions for managing date and time operations.\n */\nexport class TimeUtils {\n /**\n * return the current time in Unix time (seconds).\n */\n static nowSeconds(): number {\n // Date.getTime() returns in milliseconds.\n return Math.round(new Date().getTime() / 1000.0);\n }\n\n /**\n * check if a token is expired based on given UTC time in seconds.\n * @param expiresOn\n */\n static isTokenExpired(expiresOn: string, offset: number): boolean {\n // check for access token expiry\n const expirationSec = Number(expiresOn) || 0;\n const offsetCurrentTimeSec = TimeUtils.nowSeconds() + offset;\n\n // If current time + offset is greater than token expiration time, then token is expired.\n return offsetCurrentTimeSec > expirationSec;\n }\n\n /**\n * If the current time is earlier than the time that a token was cached at, we must discard the token\n * i.e. The system clock was turned back after acquiring the cached token\n * @param cachedAt\n * @param offset\n */\n static wasClockTurnedBack(cachedAt: string): boolean {\n const cachedAtSec = Number(cachedAt);\n\n return cachedAtSec > TimeUtils.nowSeconds();\n }\n\n /**\n * Waits for t number of milliseconds\n * @param t number\n * @param value T\n */\n static delay<T>(t: number, value?: T): Promise<T | void> {\n return new Promise((resolve) => setTimeout(() => resolve(value), t));\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { extractTokenClaims } from \"../../account/AuthToken\";\nimport { TokenClaims } from \"../../account/TokenClaims\";\nimport { CloudDiscoveryMetadata } from \"../../authority/CloudDiscoveryMetadata\";\nimport { OpenIdConfigResponse } from \"../../authority/OpenIdConfigResponse\";\nimport {\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../../error/ClientAuthError\";\nimport {\n APP_METADATA,\n AUTHORITY_METADATA_CONSTANTS,\n AuthenticationScheme,\n CredentialType,\n SERVER_TELEM_CONSTANTS,\n Separators,\n ThrottlingConstants,\n} from \"../../utils/Constants\";\nimport { TimeUtils } from \"../../utils/TimeUtils\";\nimport { AccessTokenEntity } from \"../entities/AccessTokenEntity\";\nimport { AppMetadataEntity } from \"../entities/AppMetadataEntity\";\nimport { AuthorityMetadataEntity } from \"../entities/AuthorityMetadataEntity\";\nimport { CredentialEntity } from \"../entities/CredentialEntity\";\nimport { IdTokenEntity } from \"../entities/IdTokenEntity\";\nimport { RefreshTokenEntity } from \"../entities/RefreshTokenEntity\";\n\n/**\n * Cache Key: <home_account_id>-<environment>-<credential_type>-<client_id or familyId>-<realm>-<scopes>-<claims hash>-<scheme>\n * IdToken Example: uid.utid-login.microsoftonline.com-idtoken-app_client_id-contoso.com\n * AccessToken Example: uid.utid-login.microsoftonline.com-accesstoken-app_client_id-contoso.com-scope1 scope2--pop\n * RefreshToken Example: uid.utid-login.microsoftonline.com-refreshtoken-1-contoso.com\n * @param credentialEntity\n * @returns\n */\nexport function generateCredentialKey(\n credentialEntity: CredentialEntity\n): string {\n const credentialKey = [\n generateAccountId(credentialEntity),\n generateCredentialId(credentialEntity),\n generateTarget(credentialEntity),\n generateClaimsHash(credentialEntity),\n generateScheme(credentialEntity),\n ];\n\n return credentialKey.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();\n}\n\n/**\n * Create IdTokenEntity\n * @param homeAccountId\n * @param authenticationResult\n * @param clientId\n * @param authority\n */\nexport function createIdTokenEntity(\n homeAccountId: string,\n environment: string,\n idToken: string,\n clientId: string,\n tenantId: string\n): IdTokenEntity {\n const idTokenEntity: IdTokenEntity = {\n credentialType: CredentialType.ID_TOKEN,\n homeAccountId: homeAccountId,\n environment: environment,\n clientId: clientId,\n secret: idToken,\n realm: tenantId,\n };\n\n return idTokenEntity;\n}\n\n/**\n * Create AccessTokenEntity\n * @param homeAccountId\n * @param environment\n * @param accessToken\n * @param clientId\n * @param tenantId\n * @param scopes\n * @param expiresOn\n * @param extExpiresOn\n */\nexport function createAccessTokenEntity(\n homeAccountId: string,\n environment: string,\n accessToken: string,\n clientId: string,\n tenantId: string,\n scopes: string,\n expiresOn: number,\n extExpiresOn: number,\n base64Decode: (input: string) => string,\n refreshOn?: number,\n tokenType?: AuthenticationScheme,\n userAssertionHash?: string,\n keyId?: string,\n requestedClaims?: string,\n requestedClaimsHash?: string\n): AccessTokenEntity {\n const atEntity: AccessTokenEntity = {\n homeAccountId: homeAccountId,\n credentialType: CredentialType.ACCESS_TOKEN,\n secret: accessToken,\n cachedAt: TimeUtils.nowSeconds().toString(),\n expiresOn: expiresOn.toString(),\n extendedExpiresOn: extExpiresOn.toString(),\n environment: environment,\n clientId: clientId,\n realm: tenantId,\n target: scopes,\n tokenType: tokenType || AuthenticationScheme.BEARER,\n };\n\n if (userAssertionHash) {\n atEntity.userAssertionHash = userAssertionHash;\n }\n\n if (refreshOn) {\n atEntity.refreshOn = refreshOn.toString();\n }\n\n if (requestedClaims) {\n atEntity.requestedClaims = requestedClaims;\n atEntity.requestedClaimsHash = requestedClaimsHash;\n }\n\n /*\n * Create Access Token With Auth Scheme instead of regular access token\n * Cast to lower to handle \"bearer\" from ADFS\n */\n if (\n atEntity.tokenType?.toLowerCase() !==\n AuthenticationScheme.BEARER.toLowerCase()\n ) {\n atEntity.credentialType = CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;\n switch (atEntity.tokenType) {\n case AuthenticationScheme.POP:\n // Make sure keyId is present and add it to credential\n const tokenClaims: TokenClaims | null = extractTokenClaims(\n accessToken,\n base64Decode\n );\n if (!tokenClaims?.cnf?.kid) {\n throw createClientAuthError(\n ClientAuthErrorCodes.tokenClaimsCnfRequiredForSignedJwt\n );\n }\n atEntity.keyId = tokenClaims.cnf.kid;\n break;\n case AuthenticationScheme.SSH:\n atEntity.keyId = keyId;\n }\n }\n\n return atEntity;\n}\n\n/**\n * Create RefreshTokenEntity\n * @param homeAccountId\n * @param authenticationResult\n * @param clientId\n * @param authority\n */\nexport function createRefreshTokenEntity(\n homeAccountId: string,\n environment: string,\n refreshToken: string,\n clientId: string,\n familyId?: string,\n userAssertionHash?: string,\n expiresOn?: number\n): RefreshTokenEntity {\n const rtEntity: RefreshTokenEntity = {\n credentialType: CredentialType.REFRESH_TOKEN,\n homeAccountId: homeAccountId,\n environment: environment,\n clientId: clientId,\n secret: refreshToken,\n };\n\n if (userAssertionHash) {\n rtEntity.userAssertionHash = userAssertionHash;\n }\n\n if (familyId) {\n rtEntity.familyId = familyId;\n }\n\n if (expiresOn) {\n rtEntity.expiresOn = expiresOn.toString();\n }\n\n return rtEntity;\n}\n\nexport function isCredentialEntity(entity: object): boolean {\n return (\n entity.hasOwnProperty(\"homeAccountId\") &&\n entity.hasOwnProperty(\"environment\") &&\n entity.hasOwnProperty(\"credentialType\") &&\n entity.hasOwnProperty(\"clientId\") &&\n entity.hasOwnProperty(\"secret\")\n );\n}\n\n/**\n * Validates an entity: checks for all expected params\n * @param entity\n */\nexport function isAccessTokenEntity(entity: object): boolean {\n if (!entity) {\n return false;\n }\n\n return (\n isCredentialEntity(entity) &&\n entity.hasOwnProperty(\"realm\") &&\n entity.hasOwnProperty(\"target\") &&\n (entity[\"credentialType\"] === CredentialType.ACCESS_TOKEN ||\n entity[\"credentialType\"] ===\n CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME)\n );\n}\n\n/**\n * Validates an entity: checks for all expected params\n * @param entity\n */\nexport function isIdTokenEntity(entity: object): boolean {\n if (!entity) {\n return false;\n }\n\n return (\n isCredentialEntity(entity) &&\n entity.hasOwnProperty(\"realm\") &&\n entity[\"credentialType\"] === CredentialType.ID_TOKEN\n );\n}\n\n/**\n * Validates an entity: checks for all expected params\n * @param entity\n */\nexport function isRefreshTokenEntity(entity: object): boolean {\n if (!entity) {\n return false;\n }\n\n return (\n isCredentialEntity(entity) &&\n entity[\"credentialType\"] === CredentialType.REFRESH_TOKEN\n );\n}\n\n/**\n * Generate Account Id key component as per the schema: <home_account_id>-<environment>\n */\nfunction generateAccountId(credentialEntity: CredentialEntity): string {\n const accountId: Array<string> = [\n credentialEntity.homeAccountId,\n credentialEntity.environment,\n ];\n return accountId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();\n}\n\n/**\n * Generate Credential Id key component as per the schema: <credential_type>-<client_id>-<realm>\n */\nfunction generateCredentialId(credentialEntity: CredentialEntity): string {\n const clientOrFamilyId =\n credentialEntity.credentialType === CredentialType.REFRESH_TOKEN\n ? credentialEntity.familyId || credentialEntity.clientId\n : credentialEntity.clientId;\n const credentialId: Array<string> = [\n credentialEntity.credentialType,\n clientOrFamilyId,\n credentialEntity.realm || \"\",\n ];\n\n return credentialId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();\n}\n\n/**\n * Generate target key component as per schema: <target>\n */\nfunction generateTarget(credentialEntity: CredentialEntity): string {\n return (credentialEntity.target || \"\").toLowerCase();\n}\n\n/**\n * Generate requested claims key component as per schema: <requestedClaims>\n */\nfunction generateClaimsHash(credentialEntity: CredentialEntity): string {\n return (credentialEntity.requestedClaimsHash || \"\").toLowerCase();\n}\n\n/**\n * Generate scheme key componenet as per schema: <scheme>\n */\nfunction generateScheme(credentialEntity: CredentialEntity): string {\n /*\n * PoP Tokens and SSH certs include scheme in cache key\n * Cast to lowercase to handle \"bearer\" from ADFS\n */\n return credentialEntity.tokenType &&\n credentialEntity.tokenType.toLowerCase() !==\n AuthenticationScheme.BEARER.toLowerCase()\n ? credentialEntity.tokenType.toLowerCase()\n : \"\";\n}\n\n/**\n * validates if a given cache entry is \"Telemetry\", parses <key,value>\n * @param key\n * @param entity\n */\nexport function isServerTelemetryEntity(key: string, entity?: object): boolean {\n const validateKey: boolean =\n key.indexOf(SERVER_TELEM_CONSTANTS.CACHE_KEY) === 0;\n let validateEntity: boolean = true;\n\n if (entity) {\n validateEntity =\n entity.hasOwnProperty(\"failedRequests\") &&\n entity.hasOwnProperty(\"errors\") &&\n entity.hasOwnProperty(\"cacheHits\");\n }\n\n return validateKey && validateEntity;\n}\n\n/**\n * validates if a given cache entry is \"Throttling\", parses <key,value>\n * @param key\n * @param entity\n */\nexport function isThrottlingEntity(key: string, entity?: object): boolean {\n let validateKey: boolean = false;\n if (key) {\n validateKey = key.indexOf(ThrottlingConstants.THROTTLING_PREFIX) === 0;\n }\n\n let validateEntity: boolean = true;\n if (entity) {\n validateEntity = entity.hasOwnProperty(\"throttleTime\");\n }\n\n return validateKey && validateEntity;\n}\n\n/**\n * Generate AppMetadata Cache Key as per the schema: appmetadata-<environment>-<client_id>\n */\nexport function generateAppMetadataKey({\n environment,\n clientId,\n}: AppMetadataEntity): string {\n const appMetaDataKeyArray: Array<string> = [\n APP_METADATA,\n environment,\n clientId,\n ];\n return appMetaDataKeyArray\n .join(Separators.CACHE_KEY_SEPARATOR)\n .toLowerCase();\n}\n\n/*\n * Validates an entity: checks for all expected params\n * @param entity\n */\nexport function isAppMetadataEntity(key: string, entity: object): boolean {\n if (!entity) {\n return false;\n }\n\n return (\n key.indexOf(APP_METADATA) === 0 &&\n entity.hasOwnProperty(\"clientId\") &&\n entity.hasOwnProperty(\"environment\")\n );\n}\n\n/**\n * Validates an entity: checks for all expected params\n * @param entity\n */\nexport function isAuthorityMetadataEntity(\n key: string,\n entity: object\n): boolean {\n if (!entity) {\n return false;\n }\n\n return (\n key.indexOf(AUTHORITY_METADATA_CONSTANTS.CACHE_KEY) === 0 &&\n entity.hasOwnProperty(\"aliases\") &&\n entity.hasOwnProperty(\"preferred_cache\") &&\n entity.hasOwnProperty(\"preferred_network\") &&\n entity.hasOwnProperty(\"canonical_authority\") &&\n entity.hasOwnProperty(\"authorization_endpoint\") &&\n entity.hasOwnProperty(\"token_endpoint\") &&\n entity.hasOwnProperty(\"issuer\") &&\n entity.hasOwnProperty(\"aliasesFromNetwork\") &&\n entity.hasOwnProperty(\"endpointsFromNetwork\") &&\n entity.hasOwnProperty(\"expiresAt\") &&\n entity.hasOwnProperty(\"jwks_uri\")\n );\n}\n\n/**\n * Reset the exiresAt value\n */\nexport function generateAuthorityMetadataExpiresAt(): number {\n return (\n TimeUtils.nowSeconds() +\n AUTHORITY_METADATA_CONSTANTS.REFRESH_TIME_SECONDS\n );\n}\n\nexport function updateAuthorityEndpointMetadata(\n authorityMetadata: AuthorityMetadataEntity,\n updatedValues: OpenIdConfigResponse,\n fromNetwork: boolean\n): void {\n authorityMetadata.authorization_endpoint =\n updatedValues.authorization_endpoint;\n authorityMetadata.token_endpoint = updatedValues.token_endpoint;\n authorityMetadata.end_session_endpoint = updatedValues.end_session_endpoint;\n authorityMetadata.issuer = updatedValues.issuer;\n authorityMetadata.endpointsFromNetwork = fromNetwork;\n authorityMetadata.jwks_uri = updatedValues.jwks_uri;\n}\n\nexport function updateCloudDiscoveryMetadata(\n authorityMetadata: AuthorityMetadataEntity,\n updatedValues: CloudDiscoveryMetadata,\n fromNetwork: boolean\n): void {\n authorityMetadata.aliases = updatedValues.aliases;\n authorityMetadata.preferred_cache = updatedValues.preferred_cache;\n authorityMetadata.preferred_network = updatedValues.preferred_network;\n authorityMetadata.aliasesFromNetwork = fromNetwork;\n}\n\n/**\n * Returns whether or not the data needs to be refreshed\n */\nexport function isAuthorityMetadataExpired(\n metadata: AuthorityMetadataEntity\n): boolean {\n return metadata.expiresAt <= TimeUtils.nowSeconds();\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport const redirectUriEmpty = \"redirect_uri_empty\";\nexport const claimsRequestParsingError = \"claims_request_parsing_error\";\nexport const authorityUriInsecure = \"authority_uri_insecure\";\nexport const urlParseError = \"url_parse_error\";\nexport const urlEmptyError = \"empty_url_error\";\nexport const emptyInputScopesError = \"empty_input_scopes_error\";\nexport const invalidPromptValue = \"invalid_prompt_value\";\nexport const invalidClaims = \"invalid_claims\";\nexport const tokenRequestEmpty = \"token_request_empty\";\nexport const logoutRequestEmpty = \"logout_request_empty\";\nexport const invalidCodeChallengeMethod = \"invalid_code_challenge_method\";\nexport const pkceParamsMissing = \"pkce_params_missing\";\nexport const invalidCloudDiscoveryMetadata = \"invalid_cloud_discovery_metadata\";\nexport const invalidAuthorityMetadata = \"invalid_authority_metadata\";\nexport const untrustedAuthority = \"untrusted_authority\";\nexport const missingSshJwk = \"missing_ssh_jwk\";\nexport const missingSshKid = \"missing_ssh_kid\";\nexport const missingNonceAuthenticationHeader =\n \"missing_nonce_authentication_header\";\nexport const invalidAuthenticationHeader = \"invalid_authentication_header\";\nexport const cannotSetOIDCOptions = \"cannot_set_OIDCOptions\";\nexport const cannotAllowNativeBroker = \"cannot_allow_native_broker\";\nexport const authorityMismatch = \"authority_mismatch\";\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AuthError } from \"./AuthError\";\nimport * as ClientConfigurationErrorCodes from \"./ClientConfigurationErrorCodes\";\nexport { ClientConfigurationErrorCodes };\n\nexport const ClientConfigurationErrorMessages = {\n [ClientConfigurationErrorCodes.redirectUriEmpty]:\n \"A redirect URI is required for all calls, and none has been set.\",\n [ClientConfigurationErrorCodes.claimsRequestParsingError]:\n \"Could not parse the given claims request object.\",\n [ClientConfigurationErrorCodes.authorityUriInsecure]:\n \"Authority URIs must use https. Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options\",\n [ClientConfigurationErrorCodes.urlParseError]:\n \"URL could not be parsed into appropriate segments.\",\n [ClientConfigurationErrorCodes.urlEmptyError]: \"URL was empty or null.\",\n [ClientConfigurationErrorCodes.emptyInputScopesError]:\n \"Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.\",\n [ClientConfigurationErrorCodes.invalidPromptValue]:\n \"Please see here for valid configuration options: https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_common.html#commonauthorizationurlrequest\",\n [ClientConfigurationErrorCodes.invalidClaims]:\n \"Given claims parameter must be a stringified JSON object.\",\n [ClientConfigurationErrorCodes.tokenRequestEmpty]:\n \"Token request was empty and not found in cache.\",\n [ClientConfigurationErrorCodes.logoutRequestEmpty]:\n \"The logout request was null or undefined.\",\n [ClientConfigurationErrorCodes.invalidCodeChallengeMethod]:\n 'code_challenge_method passed is invalid. Valid values are \"plain\" and \"S256\".',\n [ClientConfigurationErrorCodes.pkceParamsMissing]:\n \"Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request\",\n [ClientConfigurationErrorCodes.invalidCloudDiscoveryMetadata]:\n \"Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields\",\n [ClientConfigurationErrorCodes.invalidAuthorityMetadata]:\n \"Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.\",\n [ClientConfigurationErrorCodes.untrustedAuthority]:\n \"The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.\",\n [ClientConfigurationErrorCodes.missingSshJwk]:\n \"Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.\",\n [ClientConfigurationErrorCodes.missingSshKid]:\n \"Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.\",\n [ClientConfigurationErrorCodes.missingNonceAuthenticationHeader]:\n \"Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce.\",\n [ClientConfigurationErrorCodes.invalidAuthenticationHeader]:\n \"Invalid authentication header provided\",\n [ClientConfigurationErrorCodes.cannotSetOIDCOptions]:\n \"Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.\",\n [ClientConfigurationErrorCodes.cannotAllowNativeBroker]:\n \"Cannot set allowNativeBroker parameter to true when not in AAD protocol mode.\",\n [ClientConfigurationErrorCodes.authorityMismatch]:\n \"Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority.\",\n};\n\n/**\n * ClientConfigurationErrorMessage class containing string constants used by error codes and messages.\n * @deprecated Use ClientConfigurationErrorCodes instead\n */\nexport const ClientConfigurationErrorMessage = {\n redirectUriNotSet: {\n code: ClientConfigurationErrorCodes.redirectUriEmpty,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.redirectUriEmpty\n ],\n },\n claimsRequestParsingError: {\n code: ClientConfigurationErrorCodes.claimsRequestParsingError,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.claimsRequestParsingError\n ],\n },\n authorityUriInsecure: {\n code: ClientConfigurationErrorCodes.authorityUriInsecure,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.authorityUriInsecure\n ],\n },\n urlParseError: {\n code: ClientConfigurationErrorCodes.urlParseError,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.urlParseError\n ],\n },\n urlEmptyError: {\n code: ClientConfigurationErrorCodes.urlEmptyError,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.urlEmptyError\n ],\n },\n emptyScopesError: {\n code: ClientConfigurationErrorCodes.emptyInputScopesError,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.emptyInputScopesError\n ],\n },\n invalidPrompt: {\n code: ClientConfigurationErrorCodes.invalidPromptValue,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.invalidPromptValue\n ],\n },\n invalidClaimsRequest: {\n code: ClientConfigurationErrorCodes.invalidClaims,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.invalidClaims\n ],\n },\n tokenRequestEmptyError: {\n code: ClientConfigurationErrorCodes.tokenRequestEmpty,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.tokenRequestEmpty\n ],\n },\n logoutRequestEmptyError: {\n code: ClientConfigurationErrorCodes.logoutRequestEmpty,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.logoutRequestEmpty\n ],\n },\n invalidCodeChallengeMethod: {\n code: ClientConfigurationErrorCodes.invalidCodeChallengeMethod,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.invalidCodeChallengeMethod\n ],\n },\n invalidCodeChallengeParams: {\n code: ClientConfigurationErrorCodes.pkceParamsMissing,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.pkceParamsMissing\n ],\n },\n invalidCloudDiscoveryMetadata: {\n code: ClientConfigurationErrorCodes.invalidCloudDiscoveryMetadata,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.invalidCloudDiscoveryMetadata\n ],\n },\n invalidAuthorityMetadata: {\n code: ClientConfigurationErrorCodes.invalidAuthorityMetadata,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.invalidAuthorityMetadata\n ],\n },\n untrustedAuthority: {\n code: ClientConfigurationErrorCodes.untrustedAuthority,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.untrustedAuthority\n ],\n },\n missingSshJwk: {\n code: ClientConfigurationErrorCodes.missingSshJwk,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.missingSshJwk\n ],\n },\n missingSshKid: {\n code: ClientConfigurationErrorCodes.missingSshKid,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.missingSshKid\n ],\n },\n missingNonceAuthenticationHeader: {\n code: ClientConfigurationErrorCodes.missingNonceAuthenticationHeader,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.missingNonceAuthenticationHeader\n ],\n },\n invalidAuthenticationHeader: {\n code: ClientConfigurationErrorCodes.invalidAuthenticationHeader,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.invalidAuthenticationHeader\n ],\n },\n cannotSetOIDCOptions: {\n code: ClientConfigurationErrorCodes.cannotSetOIDCOptions,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.cannotSetOIDCOptions\n ],\n },\n cannotAllowNativeBroker: {\n code: ClientConfigurationErrorCodes.cannotAllowNativeBroker,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.cannotAllowNativeBroker\n ],\n },\n authorityMismatch: {\n code: ClientConfigurationErrorCodes.authorityMismatch,\n desc: ClientConfigurationErrorMessages[\n ClientConfigurationErrorCodes.authorityMismatch\n ],\n },\n};\n\n/**\n * Error thrown when there is an error in configuration of the MSAL.js library.\n */\nexport class ClientConfigurationError extends AuthError {\n constructor(errorCode: string) {\n super(errorCode, ClientConfigurationErrorMessages[errorCode]);\n this.name = \"ClientConfigurationError\";\n Object.setPrototypeOf(this, ClientConfigurationError.prototype);\n }\n}\n\nexport function createClientConfigurationError(\n errorCode: string\n): ClientConfigurationError {\n return new ClientConfigurationError(errorCode);\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * @hidden\n */\nexport class StringUtils {\n /**\n * Check if stringified object is empty\n * @param strObj\n */\n static isEmptyObj(strObj?: string): boolean {\n if (strObj) {\n try {\n const obj = JSON.parse(strObj);\n return Object.keys(obj).length === 0;\n } catch (e) {}\n }\n return true;\n }\n\n static startsWith(str: string, search: string): boolean {\n return str.indexOf(search) === 0;\n }\n\n static endsWith(str: string, search: string): boolean {\n return (\n str.length >= search.length &&\n str.lastIndexOf(search) === str.length - search.length\n );\n }\n\n /**\n * Parses string into an object.\n *\n * @param query\n */\n static queryStringToObject<T>(query: string): T {\n const obj: {} = {};\n const params = query.split(\"&\");\n const decode = (s: string) => decodeURIComponent(s.replace(/\\+/g, \" \"));\n params.forEach((pair) => {\n if (pair.trim()) {\n const [key, value] = pair.split(/=(.+)/g, 2); // Split on the first occurence of the '=' character\n if (key && value) {\n obj[decode(key)] = decode(value);\n }\n }\n });\n return obj as T;\n }\n\n /**\n * Trims entries in an array.\n *\n * @param arr\n */\n static trimArrayEntries(arr: Array<string>): Array<string> {\n return arr.map((entry) => entry.trim());\n }\n\n /**\n * Removes empty strings from array\n * @param arr\n */\n static removeEmptyStringsFromArray(arr: Array<string>): Array<string> {\n return arr.filter((entry) => {\n return !!entry;\n });\n }\n\n /**\n * Attempts to parse a string into JSON\n * @param str\n */\n static jsonParseHelper<T>(str: string): T | null {\n try {\n return JSON.parse(str) as T;\n } catch (e) {\n return null;\n }\n }\n\n /**\n * Tests if a given string matches a given pattern, with support for wildcards and queries.\n * @param pattern Wildcard pattern to string match. Supports \"*\" for wildcards and \"?\" for queries\n * @param input String to match against\n */\n static matchPattern(pattern: string, input: string): boolean {\n /**\n * Wildcard support: https://stackoverflow.com/a/3117248/4888559\n * Queries: replaces \"?\" in string with escaped \"\\?\" for regex test\n */\n // eslint-disable-next-line security/detect-non-literal-regexp\n const regex: RegExp = new RegExp(\n pattern\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\\*/g, \"[^ ]*\")\n .replace(/\\?/g, \"\\\\?\")\n );\n\n return regex.test(input);\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n createClientConfigurationError,\n ClientConfigurationErrorCodes,\n} from \"../error/ClientConfigurationError\";\nimport { StringUtils } from \"../utils/StringUtils\";\nimport {\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../error/ClientAuthError\";\nimport { Constants, OIDC_SCOPES } from \"../utils/Constants\";\n\n/**\n * The ScopeSet class creates a set of scopes. Scopes are case-insensitive, unique values, so the Set object in JS makes\n * the most sense to implement for this class. All scopes are trimmed and converted to lower case strings in intersection and union functions\n * to ensure uniqueness of strings.\n */\nexport class ScopeSet {\n // Scopes as a Set of strings\n private scopes: Set<string>;\n\n constructor(inputScopes: Array<string>) {\n // Filter empty string and null/undefined array items\n const scopeArr = inputScopes\n ? StringUtils.trimArrayEntries([...inputScopes])\n : [];\n const filteredInput = scopeArr\n ? StringUtils.removeEmptyStringsFromArray(scopeArr)\n : [];\n\n // Validate and filter scopes (validate function throws if validation fails)\n this.validateInputScopes(filteredInput);\n\n this.scopes = new Set<string>(); // Iterator in constructor not supported by IE11\n filteredInput.forEach((scope) => this.scopes.add(scope));\n }\n\n /**\n * Factory method to create ScopeSet from space-delimited string\n * @param inputScopeString\n * @param appClientId\n * @param scopesRequired\n */\n static fromString(inputScopeString: string): ScopeSet {\n const scopeString = inputScopeString || Constants.EMPTY_STRING;\n const inputScopes: Array<string> = scopeString.split(\" \");\n return new ScopeSet(inputScopes);\n }\n\n /**\n * Creates the set of scopes to search for in cache lookups\n * @param inputScopeString\n * @returns\n */\n static createSearchScopes(inputScopeString: Array<string>): ScopeSet {\n const scopeSet = new ScopeSet(inputScopeString);\n if (!scopeSet.containsOnlyOIDCScopes()) {\n scopeSet.removeOIDCScopes();\n } else {\n scopeSet.removeScope(Constants.OFFLINE_ACCESS_SCOPE);\n }\n\n return scopeSet;\n }\n\n /**\n * Used to validate the scopes input parameter requested by the developer.\n * @param {Array<string>} inputScopes - Developer requested permissions. Not all scopes are guaranteed to be included in the access token returned.\n * @param {boolean} scopesRequired - Boolean indicating whether the scopes array is required or not\n */\n private validateInputScopes(inputScopes: Array<string>): void {\n // Check if scopes are required but not given or is an empty array\n if (!inputScopes || inputScopes.length < 1) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.emptyInputScopesError\n );\n }\n }\n\n /**\n * Check if a given scope is present in this set of scopes.\n * @param scope\n */\n containsScope(scope: string): boolean {\n const lowerCaseScopes = this.printScopesLowerCase().split(\" \");\n const lowerCaseScopesSet = new ScopeSet(lowerCaseScopes);\n // compare lowercase scopes\n return scope\n ? lowerCaseScopesSet.scopes.has(scope.toLowerCase())\n : false;\n }\n\n /**\n * Check if a set of scopes is present in this set of scopes.\n * @param scopeSet\n */\n containsScopeSet(scopeSet: ScopeSet): boolean {\n if (!scopeSet || scopeSet.scopes.size <= 0) {\n return false;\n }\n\n return (\n this.scopes.size >= scopeSet.scopes.size &&\n scopeSet.asArray().every((scope) => this.containsScope(scope))\n );\n }\n\n /**\n * Check if set of scopes contains only the defaults\n */\n containsOnlyOIDCScopes(): boolean {\n let defaultScopeCount = 0;\n OIDC_SCOPES.forEach((defaultScope: string) => {\n if (this.containsScope(defaultScope)) {\n defaultScopeCount += 1;\n }\n });\n\n return this.scopes.size === defaultScopeCount;\n }\n\n /**\n * Appends single scope if passed\n * @param newScope\n */\n appendScope(newScope: string): void {\n if (newScope) {\n this.scopes.add(newScope.trim());\n }\n }\n\n /**\n * Appends multiple scopes if passed\n * @param newScopes\n */\n appendScopes(newScopes: Array<string>): void {\n try {\n newScopes.forEach((newScope) => this.appendScope(newScope));\n } catch (e) {\n throw createClientAuthError(\n ClientAuthErrorCodes.cannotAppendScopeSet\n );\n }\n }\n\n /**\n * Removes element from set of scopes.\n * @param scope\n */\n removeScope(scope: string): void {\n if (!scope) {\n throw createClientAuthError(\n ClientAuthErrorCodes.cannotRemoveEmptyScope\n );\n }\n this.scopes.delete(scope.trim());\n }\n\n /**\n * Removes default scopes from set of scopes\n * Primarily used to prevent cache misses if the default scopes are not returned from the server\n */\n removeOIDCScopes(): void {\n OIDC_SCOPES.forEach((defaultScope: string) => {\n this.scopes.delete(defaultScope);\n });\n }\n\n /**\n * Combines an array of scopes with the current set of scopes.\n * @param otherScopes\n */\n unionScopeSets(otherScopes: ScopeSet): Set<string> {\n if (!otherScopes) {\n throw createClientAuthError(\n ClientAuthErrorCodes.emptyInputScopeSet\n );\n }\n const unionScopes = new Set<string>(); // Iterator in constructor not supported in IE11\n otherScopes.scopes.forEach((scope) =>\n unionScopes.add(scope.toLowerCase())\n );\n this.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));\n return unionScopes;\n }\n\n /**\n * Check if scopes intersect between this set and another.\n * @param otherScopes\n */\n intersectingScopeSets(otherScopes: ScopeSet): boolean {\n if (!otherScopes) {\n throw createClientAuthError(\n ClientAuthErrorCodes.emptyInputScopeSet\n );\n }\n\n // Do not allow OIDC scopes to be the only intersecting scopes\n if (!otherScopes.containsOnlyOIDCScopes()) {\n otherScopes.removeOIDCScopes();\n }\n const unionScopes = this.unionScopeSets(otherScopes);\n const sizeOtherScopes = otherScopes.getScopeCount();\n const sizeThisScopes = this.getScopeCount();\n const sizeUnionScopes = unionScopes.size;\n return sizeUnionScopes < sizeThisScopes + sizeOtherScopes;\n }\n\n /**\n * Returns size of set of scopes.\n */\n getScopeCount(): number {\n return this.scopes.size;\n }\n\n /**\n * Returns the scopes as an array of string values\n */\n asArray(): Array<string> {\n const array: Array<string> = [];\n this.scopes.forEach((val) => array.push(val));\n return array;\n }\n\n /**\n * Prints scopes into a space-delimited string\n */\n printScopes(): string {\n if (this.scopes) {\n const scopeArr = this.asArray();\n return scopeArr.join(\" \");\n }\n return Constants.EMPTY_STRING;\n }\n\n /**\n * Prints scopes into a space-delimited lower-case string (used for caching)\n */\n printScopesLowerCase(): string {\n return this.printScopes().toLowerCase();\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n createClientAuthError,\n ClientAuthErrorCodes,\n} from \"../error/ClientAuthError\";\nimport { Separators, Constants } from \"../utils/Constants\";\n\n/**\n * Client info object which consists of two IDs. Need to add more info here.\n */\nexport type ClientInfo = {\n uid: string;\n utid: string;\n};\n\n/**\n * Function to build a client info object from server clientInfo string\n * @param rawClientInfo\n * @param crypto\n */\nexport function buildClientInfo(\n rawClientInfo: string,\n base64Decode: (input: string) => string\n): ClientInfo {\n if (!rawClientInfo) {\n throw createClientAuthError(ClientAuthErrorCodes.clientInfoEmptyError);\n }\n\n try {\n const decodedClientInfo: string = base64Decode(rawClientInfo);\n return JSON.parse(decodedClientInfo) as ClientInfo;\n } catch (e) {\n throw createClientAuthError(\n ClientAuthErrorCodes.clientInfoDecodingError\n );\n }\n}\n\n/**\n * Function to build a client info object from cached homeAccountId string\n * @param homeAccountId\n */\nexport function buildClientInfoFromHomeAccountId(\n homeAccountId: string\n): ClientInfo {\n if (!homeAccountId) {\n throw createClientAuthError(\n ClientAuthErrorCodes.clientInfoDecodingError\n );\n }\n const clientInfoParts: string[] = homeAccountId.split(\n Separators.CLIENT_INFO_SEPARATOR,\n 2\n );\n return {\n uid: clientInfoParts[0],\n utid:\n clientInfoParts.length < 2\n ? Constants.EMPTY_STRING\n : clientInfoParts[1],\n };\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { TokenClaims } from \"./TokenClaims\";\n/**\n * Account object with the following signature:\n * - homeAccountId - Home account identifier for this account object\n * - environment - Entity which issued the token represented by the domain of the issuer (e.g. login.microsoftonline.com)\n * - tenantId - Full tenant or organizational id that this account belongs to\n * - username - preferred_username claim of the id_token that represents this account\n * - localAccountId - Local, tenant-specific account identifer for this account object, usually used in legacy cases\n * - name - Full name for the account, including given name and family name\n * - idToken - raw ID token\n * - idTokenClaims - Object contains claims from ID token\n * - nativeAccountId - The user's native account ID\n * - tenantProfiles - Map of tenant profile objects for each tenant that the account has authenticated with in the browser\n */\nexport type AccountInfo = {\n homeAccountId: string;\n environment: string;\n tenantId: string;\n username: string;\n localAccountId: string;\n name?: string;\n idToken?: string;\n idTokenClaims?: TokenClaims & {\n [key: string]:\n | string\n | number\n | string[]\n | object\n | undefined\n | unknown;\n };\n nativeAccountId?: string;\n authorityType?: string;\n tenantProfiles?: Map<string, TenantProfile>;\n};\n\n/**\n * Account details that vary across tenants for the same user\n */\nexport type TenantProfile = Pick<\n AccountInfo,\n \"tenantId\" | \"localAccountId\" | \"name\"\n> & {\n /**\n * - isHomeTenant - True if this is the home tenant profile of the account, false if it's a guest tenant profile\n */\n isHomeTenant?: boolean;\n};\n\nexport type ActiveAccountFilters = {\n homeAccountId: string;\n localAccountId: string;\n tenantId?: string;\n};\n\n/**\n * Returns true if tenantId matches the utid portion of homeAccountId\n * @param tenantId\n * @param homeAccountId\n * @returns\n */\nexport function tenantIdMatchesHomeTenant(\n tenantId?: string,\n homeAccountId?: string\n): boolean {\n return (\n !!tenantId &&\n !!homeAccountId &&\n tenantId === homeAccountId.split(\".\")[1]\n );\n}\n\nexport function buildTenantProfileFromIdTokenClaims(\n homeAccountId: string,\n idTokenClaims: TokenClaims\n): TenantProfile {\n const { oid, sub, tid, name, tfp, acr } = idTokenClaims;\n\n /**\n * Since there is no way to determine if the authority is AAD or B2C, we exhaust all the possible claims that can serve as tenant ID with the following precedence:\n * tid - TenantID claim that identifies the tenant that issued the token in AAD. Expected in all AAD ID tokens, not present in B2C ID Tokens.\n * tfp - Trust Framework Policy claim that identifies the policy that was used to authenticate the user. Functions as tenant for B2C scenarios.\n * acr - Authentication Context Class Reference claim used only with older B2C policies. Fallback in case tfp is not present, but likely won't be present anyway.\n */\n const tenantId = tid || tfp || acr || \"\";\n\n return {\n tenantId: tenantId,\n localAccountId: oid || sub || \"\",\n name: name,\n isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId),\n };\n}\n\n/**\n * Replaces account info that varies by tenant profile sourced from the ID token claims passed in with the tenant-specific account info\n * @param baseAccountInfo\n * @param idTokenClaims\n * @returns\n */\nexport function updateAccountTenantProfileData(\n baseAccountInfo: AccountInfo,\n tenantProfile?: TenantProfile,\n idTokenClaims?: TokenClaims\n): AccountInfo {\n let updatedAccountInfo = baseAccountInfo;\n // Tenant Profile overrides passed in account info\n if (tenantProfile) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { isHomeTenant, ...tenantProfileOverride } = tenantProfile;\n updatedAccountInfo = { ...baseAccountInfo, ...tenantProfileOverride };\n }\n\n // ID token claims override passed in account info and tenant profile\n if (idTokenClaims) {\n // Ignore isHomeTenant, loginHint, and sid which are part of tenant profile but not base account info\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { isHomeTenant, ...claimsSourcedTenantProfile } =\n buildTenantProfileFromIdTokenClaims(\n baseAccountInfo.homeAccountId,\n idTokenClaims\n );\n\n updatedAccountInfo = {\n ...updatedAccountInfo,\n ...claimsSourcedTenantProfile,\n idTokenClaims: idTokenClaims,\n };\n\n return updatedAccountInfo;\n }\n\n return updatedAccountInfo;\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Authority types supported by MSAL.\n */\nexport const AuthorityType = {\n Default: 0,\n Adfs: 1,\n Dsts: 2,\n Ciam: 3,\n} as const;\nexport type AuthorityType = (typeof AuthorityType)[keyof typeof AuthorityType];\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Type which describes Id Token claims known by MSAL.\n */\nexport type TokenClaims = {\n /**\n * Audience\n */\n aud?: string;\n /**\n * Issuer\n */\n iss?: string;\n /**\n * Issued at\n */\n iat?: number;\n /**\n * Not valid before\n */\n nbf?: number;\n /**\n * Immutable object identifier, this ID uniquely identifies the user across applications\n */\n oid?: string;\n /**\n * Immutable subject identifier, this is a pairwise identifier - it is unique to a particular application ID\n */\n sub?: string;\n /**\n * Users' tenant or '9188040d-6c67-4c5b-b112-36a304b66dad' for personal accounts.\n */\n tid?: string;\n /**\n * Trusted Framework Policy (B2C) The name of the policy that was used to acquire the ID token.\n */\n tfp?: string;\n /**\n * Authentication Context Class Reference (B2C) Used only with older policies.\n */\n acr?: string;\n ver?: string;\n upn?: string;\n preferred_username?: string;\n login_hint?: string;\n emails?: string[];\n name?: string;\n nonce?: string;\n /**\n * Expiration\n */\n exp?: number;\n home_oid?: string;\n sid?: string;\n cloud_instance_host_name?: string;\n cnf?: {\n kid: string;\n };\n x5c_ca?: string[];\n ts?: number;\n at?: string;\n u?: string;\n p?: string;\n m?: string;\n roles?: string[];\n amr?: string[];\n idp?: string;\n auth_time?: number;\n /**\n * \tRegion of the resource tenant\n */\n tenant_region_scope?: string;\n tenant_region_sub_scope?: string;\n};\n\n/**\n * Gets tenantId from available ID token claims to set as credential realm with the following precedence:\n * 1. tid - if the token is acquired from an Azure AD tenant tid will be present\n * 2. tfp - if the token is acquired from a modern B2C tenant tfp should be present\n * 3. acr - if the token is acquired from a legacy B2C tenant acr should be present\n * Downcased to match the realm case-insensitive comparison requirements\n * @param idTokenClaims\n * @returns\n */\nexport function getTenantIdFromIdTokenClaims(\n idTokenClaims?: TokenClaims\n): string | null {\n if (idTokenClaims) {\n const tenantId =\n idTokenClaims.tid || idTokenClaims.tfp || idTokenClaims.acr;\n return tenantId || null;\n }\n return null;\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Protocol modes supported by MSAL.\n */\nexport const ProtocolMode = {\n AAD: \"AAD\",\n OIDC: \"OIDC\",\n} as const;\nexport type ProtocolMode = (typeof ProtocolMode)[keyof typeof ProtocolMode];\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { CacheAccountType, Separators } from \"../../utils/Constants\";\nimport { Authority } from \"../../authority/Authority\";\nimport { ICrypto } from \"../../crypto/ICrypto\";\nimport { ClientInfo, buildClientInfo } from \"../../account/ClientInfo\";\nimport {\n AccountInfo,\n TenantProfile,\n buildTenantProfileFromIdTokenClaims,\n} from \"../../account/AccountInfo\";\nimport {\n createClientAuthError,\n ClientAuthErrorCodes,\n} from \"../../error/ClientAuthError\";\nimport { AuthorityType } from \"../../authority/AuthorityType\";\nimport { Logger } from \"../../logger/Logger\";\nimport {\n TokenClaims,\n getTenantIdFromIdTokenClaims,\n} from \"../../account/TokenClaims\";\nimport { ProtocolMode } from \"../../authority/ProtocolMode\";\n\n/**\n * Type that defines required and optional parameters for an Account field (based on universal cache schema implemented by all MSALs).\n *\n * Key : Value Schema\n *\n * Key: <home_account_id>-<environment>-<realm*>\n *\n * Value Schema:\n * {\n * homeAccountId: home account identifier for the auth scheme,\n * environment: entity that issued the token, represented as a full host\n * realm: Full tenant or organizational identifier that the account belongs to\n * localAccountId: Original tenant-specific accountID, usually used for legacy cases\n * username: primary username that represents the user, usually corresponds to preferred_username in the v2 endpt\n * authorityType: Accounts authority type as a string\n * name: Full name for the account, including given name and family name,\n * lastModificationTime: last time this entity was modified in the cache\n * lastModificationApp:\n * nativeAccountId: Account identifier on the native device\n * tenantProfiles: Array of tenant profile objects for each tenant that the account has authenticated with in the browser\n * }\n * @internal\n */\nexport class AccountEntity {\n homeAccountId: string;\n environment: string;\n realm: string;\n localAccountId: string;\n username: string;\n authorityType: string;\n clientInfo?: string;\n name?: string;\n lastModificationTime?: string;\n lastModificationApp?: string;\n cloudGraphHostName?: string;\n msGraphHost?: string;\n nativeAccountId?: string;\n tenantProfiles?: Array<TenantProfile>;\n\n /**\n * Generate Account Id key component as per the schema: <home_account_id>-<environment>\n */\n generateAccountId(): string {\n const accountId: Array<string> = [this.homeAccountId, this.environment];\n return accountId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();\n }\n\n /**\n * Generate Account Cache Key as per the schema: <home_account_id>-<environment>-<realm*>\n */\n generateAccountKey(): string {\n return AccountEntity.generateAccountCacheKey({\n homeAccountId: this.homeAccountId,\n environment: this.environment,\n tenantId: this.realm,\n username: this.username,\n localAccountId: this.localAccountId,\n });\n }\n\n /**\n * Returns the AccountInfo interface for this account.\n */\n getAccountInfo(): AccountInfo {\n return {\n homeAccountId: this.homeAccountId,\n environment: this.environment,\n tenantId: this.realm,\n username: this.username,\n localAccountId: this.localAccountId,\n name: this.name,\n nativeAccountId: this.nativeAccountId,\n authorityType: this.authorityType,\n // Deserialize tenant profiles array into a Map\n tenantProfiles: new Map(\n (this.tenantProfiles || []).map((tenantProfile) => {\n return [tenantProfile.tenantId, tenantProfile];\n })\n ),\n };\n }\n\n /**\n * Returns true if the account entity is in single tenant format (outdated), false otherwise\n */\n isSingleTenant(): boolean {\n return !this.tenantProfiles;\n }\n\n /**\n * Generates account key from interface\n * @param accountInterface\n */\n static generateAccountCacheKey(accountInterface: AccountInfo): string {\n const homeTenantId = accountInterface.homeAccountId.split(\".\")[1];\n const accountKey = [\n accountInterface.homeAccountId,\n accountInterface.environment || \"\",\n homeTenantId || accountInterface.tenantId || \"\",\n ];\n\n return accountKey.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();\n }\n\n /**\n * Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD.\n * @param accountDetails\n */\n static createAccount(\n accountDetails: {\n homeAccountId: string;\n idTokenClaims: TokenClaims;\n clientInfo?: string;\n cloudGraphHostName?: string;\n msGraphHost?: string;\n environment?: string;\n nativeAccountId?: string;\n tenantProfiles?: Array<TenantProfile>;\n },\n authority: Authority,\n base64Decode?: (input: string) => string\n ): AccountEntity {\n const account: AccountEntity = new AccountEntity();\n\n if (authority.authorityType === AuthorityType.Adfs) {\n account.authorityType = CacheAccountType.ADFS_ACCOUNT_TYPE;\n } else if (authority.protocolMode === ProtocolMode.AAD) {\n account.authorityType = CacheAccountType.MSSTS_ACCOUNT_TYPE;\n } else {\n account.authorityType = CacheAccountType.GENERIC_ACCOUNT_TYPE;\n }\n\n let clientInfo: ClientInfo | undefined;\n\n if (accountDetails.clientInfo && base64Decode) {\n clientInfo = buildClientInfo(\n accountDetails.clientInfo,\n base64Decode\n );\n }\n\n account.clientInfo = accountDetails.clientInfo;\n account.homeAccountId = accountDetails.homeAccountId;\n account.nativeAccountId = accountDetails.nativeAccountId;\n\n const env =\n accountDetails.environment ||\n (authority && authority.getPreferredCache());\n\n if (!env) {\n throw createClientAuthError(\n ClientAuthErrorCodes.invalidCacheEnvironment\n );\n }\n\n account.environment = env;\n // non AAD scenarios can have empty realm\n account.realm =\n clientInfo?.utid ||\n getTenantIdFromIdTokenClaims(accountDetails.idTokenClaims) ||\n \"\";\n\n // How do you account for MSA CID here?\n account.localAccountId =\n clientInfo?.uid ||\n accountDetails.idTokenClaims.oid ||\n accountDetails.idTokenClaims.sub ||\n \"\";\n\n /*\n * In B2C scenarios the emails claim is used instead of preferred_username and it is an array.\n * In most cases it will contain a single email. This field should not be relied upon if a custom\n * policy is configured to return more than 1 email.\n */\n const preferredUsername =\n accountDetails.idTokenClaims.preferred_username ||\n accountDetails.idTokenClaims.upn;\n const email = accountDetails.idTokenClaims.emails\n ? accountDetails.idTokenClaims.emails[0]\n : null;\n\n account.username = preferredUsername || email || \"\";\n account.name = accountDetails.idTokenClaims.name;\n\n account.cloudGraphHostName = accountDetails.cloudGraphHostName;\n account.msGraphHost = accountDetails.msGraphHost;\n\n if (accountDetails.tenantProfiles) {\n account.tenantProfiles = accountDetails.tenantProfiles;\n } else {\n const tenantProfiles = [];\n if (accountDetails.idTokenClaims) {\n const tenantProfile = buildTenantProfileFromIdTokenClaims(\n accountDetails.homeAccountId,\n accountDetails.idTokenClaims\n );\n tenantProfiles.push(tenantProfile);\n }\n account.tenantProfiles = tenantProfiles;\n }\n\n return account;\n }\n\n /**\n * Creates an AccountEntity object from AccountInfo\n * @param accountInfo\n * @param cloudGraphHostName\n * @param msGraphHost\n * @returns\n */\n static createFromAccountInfo(\n accountInfo: AccountInfo,\n cloudGraphHostName?: string,\n msGraphHost?: string\n ): AccountEntity {\n const account: AccountEntity = new AccountEntity();\n\n account.authorityType =\n accountInfo.authorityType || CacheAccountType.GENERIC_ACCOUNT_TYPE;\n account.homeAccountId = accountInfo.homeAccountId;\n account.localAccountId = accountInfo.localAccountId;\n account.nativeAccountId = accountInfo.nativeAccountId;\n\n account.realm = accountInfo.tenantId;\n account.environment = accountInfo.environment;\n\n account.username = accountInfo.username;\n account.name = accountInfo.name;\n\n account.cloudGraphHostName = cloudGraphHostName;\n account.msGraphHost = msGraphHost;\n // Serialize tenant profiles map into an array\n account.tenantProfiles = Array.from(\n accountInfo.tenantProfiles?.values() || []\n );\n\n return account;\n }\n\n /**\n * Generate HomeAccountId from server response\n * @param serverClientInfo\n * @param authType\n */\n static generateHomeAccountId(\n serverClientInfo: string,\n authType: AuthorityType,\n logger: Logger,\n cryptoObj: ICrypto,\n idTokenClaims?: TokenClaims\n ): string {\n // since ADFS/DSTS do not have tid and does not set client_info\n if (\n !(\n authType === AuthorityType.Adfs ||\n authType === AuthorityType.Dsts\n )\n ) {\n // for cases where there is clientInfo\n if (serverClientInfo) {\n try {\n const clientInfo = buildClientInfo(\n serverClientInfo,\n cryptoObj.base64Decode\n );\n if (clientInfo.uid && clientInfo.utid) {\n return `${clientInfo.uid}.${clientInfo.utid}`;\n }\n } catch (e) {}\n }\n logger.warning(\"No client info in response\");\n }\n\n // default to \"sub\" claim\n return idTokenClaims?.sub || \"\";\n }\n\n /**\n * Validates an entity: checks for all expected params\n * @param entity\n */\n static isAccountEntity(entity: object): boolean {\n if (!entity) {\n return false;\n }\n\n return (\n entity.hasOwnProperty(\"homeAccountId\") &&\n entity.hasOwnProperty(\"environment\") &&\n entity.hasOwnProperty(\"realm\") &&\n entity.hasOwnProperty(\"localAccountId\") &&\n entity.hasOwnProperty(\"username\") &&\n entity.hasOwnProperty(\"authorityType\")\n );\n }\n\n /**\n * Helper function to determine whether 2 accountInfo objects represent the same account\n * @param accountA\n * @param accountB\n * @param compareClaims - If set to true idTokenClaims will also be compared to determine account equality\n */\n static accountInfoIsEqual(\n accountA: AccountInfo | null,\n accountB: AccountInfo | null,\n compareClaims?: boolean\n ): boolean {\n if (!accountA || !accountB) {\n return false;\n }\n\n let claimsMatch = true; // default to true so as to not fail comparison below if compareClaims: false\n if (compareClaims) {\n const accountAClaims = (accountA.idTokenClaims ||\n {}) as TokenClaims;\n const accountBClaims = (accountB.idTokenClaims ||\n {}) as TokenClaims;\n\n // issued at timestamp and nonce are expected to change each time a new id token is acquired\n claimsMatch =\n accountAClaims.iat === accountBClaims.iat &&\n accountAClaims.nonce === accountBClaims.nonce;\n }\n\n return (\n accountA.homeAccountId === accountB.homeAccountId &&\n accountA.localAccountId === accountB.localAccountId &&\n accountA.username === accountB.username &&\n accountA.tenantId === accountB.tenantId &&\n accountA.environment === accountB.environment &&\n accountA.nativeAccountId === accountB.nativeAccountId &&\n claimsMatch\n );\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ServerAuthorizationCodeResponse } from \"../response/ServerAuthorizationCodeResponse\";\nimport {\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../error/ClientAuthError\";\n\n/**\n * Parses hash string from given string. Returns empty string if no hash symbol is found.\n * @param hashString\n */\nexport function stripLeadingHashOrQuery(responseString: string): string {\n if (responseString.startsWith(\"#/\")) {\n return responseString.substring(2);\n } else if (\n responseString.startsWith(\"#\") ||\n responseString.startsWith(\"?\")\n ) {\n return responseString.substring(1);\n }\n\n return responseString;\n}\n\n/**\n * Returns URL hash as server auth code response object.\n */\nexport function getDeserializedResponse(\n responseString: string\n): ServerAuthorizationCodeResponse | null {\n // Check if given hash is empty\n if (!responseString || responseString.indexOf(\"=\") < 0) {\n return null;\n }\n try {\n // Strip the # or ? symbol if present\n const normalizedResponse = stripLeadingHashOrQuery(responseString);\n // If # symbol was not present, above will return empty string, so give original hash value\n const deserializedHash: ServerAuthorizationCodeResponse =\n Object.fromEntries(new URLSearchParams(normalizedResponse));\n\n // Check for known response properties\n if (\n deserializedHash.code ||\n deserializedHash.error ||\n deserializedHash.error_description ||\n deserializedHash.state\n ) {\n return deserializedHash;\n }\n } catch (e) {\n throw createClientAuthError(ClientAuthErrorCodes.hashNotDeserialized);\n }\n\n return null;\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n createClientConfigurationError,\n ClientConfigurationErrorCodes,\n} from \"../error/ClientConfigurationError\";\nimport { StringUtils } from \"../utils/StringUtils\";\nimport { IUri } from \"./IUri\";\nimport { AADAuthorityConstants, Constants } from \"../utils/Constants\";\nimport * as UrlUtils from \"../utils/UrlUtils\";\n\n/**\n * Url object class which can perform various transformations on url strings.\n */\nexport class UrlString {\n // internal url string field\n private _urlString: string;\n public get urlString(): string {\n return this._urlString;\n }\n\n constructor(url: string) {\n this._urlString = url;\n if (!this._urlString) {\n // Throws error if url is empty\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.urlEmptyError\n );\n }\n\n if (!url.includes(\"#\")) {\n this._urlString = UrlString.canonicalizeUri(url);\n }\n }\n\n /**\n * Ensure urls are lower case and end with a / character.\n * @param url\n */\n static canonicalizeUri(url: string): string {\n if (url) {\n let lowerCaseUrl = url.toLowerCase();\n\n if (StringUtils.endsWith(lowerCaseUrl, \"?\")) {\n lowerCaseUrl = lowerCaseUrl.slice(0, -1);\n } else if (StringUtils.endsWith(lowerCaseUrl, \"?/\")) {\n lowerCaseUrl = lowerCaseUrl.slice(0, -2);\n }\n\n if (!StringUtils.endsWith(lowerCaseUrl, \"/\")) {\n lowerCaseUrl += \"/\";\n }\n\n return lowerCaseUrl;\n }\n\n return url;\n }\n\n /**\n * Throws if urlString passed is not a valid authority URI string.\n */\n validateAsUri(): void {\n // Attempts to parse url for uri components\n let components;\n try {\n components = this.getUrlComponents();\n } catch (e) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.urlParseError\n );\n }\n\n // Throw error if URI or path segments are not parseable.\n if (!components.HostNameAndPort || !components.PathSegments) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.urlParseError\n );\n }\n\n // Throw error if uri is insecure.\n if (\n !components.Protocol ||\n components.Protocol.toLowerCase() !== \"https:\"\n ) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.authorityUriInsecure\n );\n }\n }\n\n /**\n * Given a url and a query string return the url with provided query string appended\n * @param url\n * @param queryString\n */\n static appendQueryString(url: string, queryString: string): string {\n if (!queryString) {\n return url;\n }\n\n return url.indexOf(\"?\") < 0\n ? `${url}?${queryString}`\n : `${url}&${queryString}`;\n }\n\n /**\n * Returns a url with the hash removed\n * @param url\n */\n static removeHashFromUrl(url: string): string {\n return UrlString.canonicalizeUri(url.split(\"#\")[0]);\n }\n\n /**\n * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d\n * @param href The url\n * @param tenantId The tenant id to replace\n */\n replaceTenantPath(tenantId: string): UrlString {\n const urlObject = this.getUrlComponents();\n const pathArray = urlObject.PathSegments;\n if (\n tenantId &&\n pathArray.length !== 0 &&\n (pathArray[0] === AADAuthorityConstants.COMMON ||\n pathArray[0] === AADAuthorityConstants.ORGANIZATIONS)\n ) {\n pathArray[0] = tenantId;\n }\n return UrlString.constructAuthorityUriFromObject(urlObject);\n }\n\n /**\n * Parses out the components from a url string.\n * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url.\n */\n getUrlComponents(): IUri {\n // https://gist.github.com/curtisz/11139b2cfcaef4a261e0\n const regEx = RegExp(\n \"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\\\?([^#]*))?(#(.*))?\"\n );\n\n // If url string does not match regEx, we throw an error\n const match = this.urlString.match(regEx);\n if (!match) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.urlParseError\n );\n }\n\n // Url component object\n const urlComponents = {\n Protocol: match[1],\n HostNameAndPort: match[4],\n AbsolutePath: match[5],\n QueryString: match[7],\n } as IUri;\n\n let pathSegments = urlComponents.AbsolutePath.split(\"/\");\n pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements\n urlComponents.PathSegments = pathSegments;\n\n if (\n urlComponents.QueryString &&\n urlComponents.QueryString.endsWith(\"/\")\n ) {\n urlComponents.QueryString = urlComponents.QueryString.substring(\n 0,\n urlComponents.QueryString.length - 1\n );\n }\n return urlComponents;\n }\n\n static getDomainFromUrl(url: string): string {\n const regEx = RegExp(\"^([^:/?#]+://)?([^/?#]*)\");\n\n const match = url.match(regEx);\n\n if (!match) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.urlParseError\n );\n }\n\n return match[2];\n }\n\n static getAbsoluteUrl(relativeUrl: string, baseUrl: string): string {\n if (relativeUrl[0] === Constants.FORWARD_SLASH) {\n const url = new UrlString(baseUrl);\n const baseComponents = url.getUrlComponents();\n\n return (\n baseComponents.Protocol +\n \"//\" +\n baseComponents.HostNameAndPort +\n relativeUrl\n );\n }\n\n return relativeUrl;\n }\n\n static constructAuthorityUriFromObject(urlObject: IUri): UrlString {\n return new UrlString(\n urlObject.Protocol +\n \"//\" +\n urlObject.HostNameAndPort +\n \"/\" +\n urlObject.PathSegments.join(\"/\")\n );\n }\n\n /**\n * Check if the hash of the URL string contains known properties\n * @deprecated This API will be removed in a future version\n */\n static hashContainsKnownProperties(response: string): boolean {\n return !!UrlUtils.getDeserializedResponse(response);\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Logger } from \"../logger/Logger\";\nimport { UrlString } from \"../url/UrlString\";\nimport { AuthorityMetadataSource } from \"../utils/Constants\";\nimport { StaticAuthorityOptions } from \"./AuthorityOptions\";\nimport { CloudDiscoveryMetadata } from \"./CloudDiscoveryMetadata\";\nimport { CloudInstanceDiscoveryResponse } from \"./CloudInstanceDiscoveryResponse\";\nimport { OpenIdConfigResponse } from \"./OpenIdConfigResponse\";\n\ntype RawMetadata = {\n endpointMetadata: { [key: string]: OpenIdConfigResponse };\n instanceDiscoveryMetadata: CloudInstanceDiscoveryResponse;\n};\n\nexport const rawMetdataJSON: RawMetadata = {\n endpointMetadata: {\n \"login.microsoftonline.com\": {\n token_endpoint:\n \"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token\",\n jwks_uri:\n \"https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys\",\n issuer: \"https://login.microsoftonline.com/{tenantid}/v2.0\",\n authorization_endpoint:\n \"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize\",\n end_session_endpoint:\n \"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/logout\",\n },\n \"login.chinacloudapi.cn\": {\n token_endpoint:\n \"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/token\",\n jwks_uri:\n \"https://login.chinacloudapi.cn/{tenantid}/discovery/v2.0/keys\",\n issuer: \"https://login.partner.microsoftonline.cn/{tenantid}/v2.0\",\n authorization_endpoint:\n \"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/authorize\",\n end_session_endpoint:\n \"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/logout\",\n },\n \"login.microsoftonline.us\": {\n token_endpoint:\n \"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/token\",\n jwks_uri:\n \"https://login.microsoftonline.us/{tenantid}/discovery/v2.0/keys\",\n issuer: \"https://login.microsoftonline.us/{tenantid}/v2.0\",\n authorization_endpoint:\n \"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/authorize\",\n end_session_endpoint:\n \"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/logout\",\n },\n },\n instanceDiscoveryMetadata: {\n tenant_discovery_endpoint:\n \"https://{canonicalAuthority}/v2.0/.well-known/openid-configuration\",\n metadata: [\n {\n preferred_network: \"login.microsoftonline.com\",\n preferred_cache: \"login.windows.net\",\n aliases: [\n \"login.microsoftonline.com\",\n \"login.windows.net\",\n \"login.microsoft.com\",\n \"sts.windows.net\",\n ],\n },\n {\n preferred_network: \"login.partner.microsoftonline.cn\",\n preferred_cache: \"login.partner.microsoftonline.cn\",\n aliases: [\n \"login.partner.microsoftonline.cn\",\n \"login.chinacloudapi.cn\",\n ],\n },\n {\n preferred_network: \"login.microsoftonline.de\",\n preferred_cache: \"login.microsoftonline.de\",\n aliases: [\"login.microsoftonline.de\"],\n },\n {\n preferred_network: \"login.microsoftonline.us\",\n preferred_cache: \"login.microsoftonline.us\",\n aliases: [\n \"login.microsoftonline.us\",\n \"login.usgovcloudapi.net\",\n ],\n },\n {\n preferred_network: \"login-us.microsoftonline.com\",\n preferred_cache: \"login-us.microsoftonline.com\",\n aliases: [\"login-us.microsoftonline.com\"],\n },\n ],\n },\n};\n\nexport const EndpointMetadata = rawMetdataJSON.endpointMetadata;\nexport const InstanceDiscoveryMetadata =\n rawMetdataJSON.instanceDiscoveryMetadata;\n\nexport const InstanceDiscoveryMetadataAliases: Set<String> = new Set();\nInstanceDiscoveryMetadata.metadata.forEach(\n (metadataEntry: CloudDiscoveryMetadata) => {\n metadataEntry.aliases.forEach((alias: string) => {\n InstanceDiscoveryMetadataAliases.add(alias);\n });\n }\n);\n\n/**\n * Attempts to get an aliases array from the static authority metadata sources based on the canonical authority host\n * @param staticAuthorityOptions\n * @param logger\n * @returns\n */\nexport function getAliasesFromStaticSources(\n staticAuthorityOptions: StaticAuthorityOptions,\n logger?: Logger\n): string[] {\n let staticAliases: string[] | undefined;\n const canonicalAuthority = staticAuthorityOptions.canonicalAuthority;\n if (canonicalAuthority) {\n const authorityHost = new UrlString(\n canonicalAuthority\n ).getUrlComponents().HostNameAndPort;\n staticAliases =\n getAliasesFromMetadata(\n authorityHost,\n staticAuthorityOptions.cloudDiscoveryMetadata?.metadata,\n AuthorityMetadataSource.CONFIG,\n logger\n ) ||\n getAliasesFromMetadata(\n authorityHost,\n InstanceDiscoveryMetadata.metadata,\n AuthorityMetadataSource.HARDCODED_VALUES,\n logger\n ) ||\n staticAuthorityOptions.knownAuthorities;\n }\n\n return staticAliases || [];\n}\n\n/**\n * Returns aliases for from the raw cloud discovery metadata passed in\n * @param authorityHost\n * @param rawCloudDiscoveryMetadata\n * @returns\n */\nexport function getAliasesFromMetadata(\n authorityHost?: string,\n cloudDiscoveryMetadata?: CloudDiscoveryMetadata[],\n source?: AuthorityMetadataSource,\n logger?: Logger\n): string[] | null {\n logger?.trace(`getAliasesFromMetadata called with source: ${source}`);\n if (authorityHost && cloudDiscoveryMetadata) {\n const metadata = getCloudDiscoveryMetadataFromNetworkResponse(\n cloudDiscoveryMetadata,\n authorityHost\n );\n\n if (metadata) {\n logger?.trace(\n `getAliasesFromMetadata: found cloud discovery metadata in ${source}, returning aliases`\n );\n return metadata.aliases;\n } else {\n logger?.trace(\n `getAliasesFromMetadata: did not find cloud discovery metadata in ${source}`\n );\n }\n }\n\n return null;\n}\n\n/**\n * Get cloud discovery metadata for common authorities\n */\nexport function getCloudDiscoveryMetadataFromHardcodedValues(\n authorityHost: string\n): CloudDiscoveryMetadata | null {\n const metadata = getCloudDiscoveryMetadataFromNetworkResponse(\n InstanceDiscoveryMetadata.metadata,\n authorityHost\n );\n return metadata;\n}\n\n/**\n * Searches instance discovery network response for the entry that contains the host in the aliases list\n * @param response\n * @param authority\n */\nexport function getCloudDiscoveryMetadataFromNetworkResponse(\n response: CloudDiscoveryMetadata[],\n authorityHost: string\n): CloudDiscoveryMetadata | null {\n for (let i = 0; i < response.length; i++) {\n const metadata = response[i];\n if (metadata.aliases.includes(authorityHost)) {\n return metadata;\n }\n }\n\n return null;\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AccountFilter,\n CredentialFilter,\n ValidCredentialType,\n AppMetadataFilter,\n AppMetadataCache,\n TokenKeys,\n TenantProfileFilter,\n} from \"./utils/CacheTypes\";\nimport { CacheRecord } from \"./entities/CacheRecord\";\nimport {\n CredentialType,\n APP_METADATA,\n THE_FAMILY_ID,\n AUTHORITY_METADATA_CONSTANTS,\n AuthenticationScheme,\n Separators,\n} from \"../utils/Constants\";\nimport { CredentialEntity } from \"./entities/CredentialEntity\";\nimport { generateCredentialKey } from \"./utils/CacheHelpers\";\nimport { ScopeSet } from \"../request/ScopeSet\";\nimport { AccountEntity } from \"./entities/AccountEntity\";\nimport { AccessTokenEntity } from \"./entities/AccessTokenEntity\";\nimport { IdTokenEntity } from \"./entities/IdTokenEntity\";\nimport { RefreshTokenEntity } from \"./entities/RefreshTokenEntity\";\nimport { ICacheManager } from \"./interface/ICacheManager\";\nimport {\n createClientAuthError,\n ClientAuthErrorCodes,\n} from \"../error/ClientAuthError\";\nimport {\n AccountInfo,\n TenantProfile,\n tenantIdMatchesHomeTenant,\n updateAccountTenantProfileData,\n} from \"../account/AccountInfo\";\nimport { AppMetadataEntity } from \"./entities/AppMetadataEntity\";\nimport { ServerTelemetryEntity } from \"./entities/ServerTelemetryEntity\";\nimport { ThrottlingEntity } from \"./entities/ThrottlingEntity\";\nimport { extractTokenClaims } from \"../account/AuthToken\";\nimport { ICrypto } from \"../crypto/ICrypto\";\nimport { AuthorityMetadataEntity } from \"./entities/AuthorityMetadataEntity\";\nimport { BaseAuthRequest } from \"../request/BaseAuthRequest\";\nimport { Logger } from \"../logger/Logger\";\nimport { name, version } from \"../packageMetadata\";\nimport { StoreInCache } from \"../request/StoreInCache\";\nimport { getAliasesFromStaticSources } from \"../authority/AuthorityMetadata\";\nimport { StaticAuthorityOptions } from \"../authority/AuthorityOptions\";\nimport { TokenClaims } from \"../account/TokenClaims\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\n\n/**\n * Interface class which implement cache storage functions used by MSAL to perform validity checks, and store tokens.\n * @internal\n */\nexport abstract class CacheManager implements ICacheManager {\n protected clientId: string;\n protected cryptoImpl: ICrypto;\n // Instance of logger for functions defined in the msal-common layer\n private commonLogger: Logger;\n private staticAuthorityOptions?: StaticAuthorityOptions;\n\n constructor(\n clientId: string,\n cryptoImpl: ICrypto,\n logger: Logger,\n staticAuthorityOptions?: StaticAuthorityOptions\n ) {\n this.clientId = clientId;\n this.cryptoImpl = cryptoImpl;\n this.commonLogger = logger.clone(name, version);\n this.staticAuthorityOptions = staticAuthorityOptions;\n }\n\n /**\n * fetch the account entity from the platform cache\n * @param accountKey\n */\n abstract getAccount(\n accountKey: string,\n logger?: Logger\n ): AccountEntity | null;\n\n /**\n * Returns deserialized account if found in the cache, otherwiser returns null\n */\n abstract getCachedAccountEntity(accountKey: string): AccountEntity | null;\n\n /**\n * set account entity in the platform cache\n * @param account\n */\n abstract setAccount(account: AccountEntity): void;\n\n /**\n * remove account entity from the platform cache if it's outdated\n */\n abstract removeOutdatedAccount(accountKey: string): void;\n\n /**\n * fetch the idToken entity from the platform cache\n * @param idTokenKey\n */\n abstract getIdTokenCredential(idTokenKey: string): IdTokenEntity | null;\n\n /**\n * set idToken entity to the platform cache\n * @param idToken\n */\n abstract setIdTokenCredential(idToken: IdTokenEntity): void;\n\n /**\n * fetch the idToken entity from the platform cache\n * @param accessTokenKey\n */\n abstract getAccessTokenCredential(\n accessTokenKey: string\n ): AccessTokenEntity | null;\n\n /**\n * set idToken entity to the platform cache\n * @param accessToken\n */\n abstract setAccessTokenCredential(accessToken: AccessTokenEntity): void;\n\n /**\n * fetch the idToken entity from the platform cache\n * @param refreshTokenKey\n */\n abstract getRefreshTokenCredential(\n refreshTokenKey: string\n ): RefreshTokenEntity | null;\n\n /**\n * set idToken entity to the platform cache\n * @param refreshToken\n */\n abstract setRefreshTokenCredential(refreshToken: RefreshTokenEntity): void;\n\n /**\n * fetch appMetadata entity from the platform cache\n * @param appMetadataKey\n */\n abstract getAppMetadata(appMetadataKey: string): AppMetadataEntity | null;\n\n /**\n * set appMetadata entity to the platform cache\n * @param appMetadata\n */\n abstract setAppMetadata(appMetadata: AppMetadataEntity): void;\n\n /**\n * fetch server telemetry entity from the platform cache\n * @param serverTelemetryKey\n */\n abstract getServerTelemetry(\n serverTelemetryKey: string\n ): ServerTelemetryEntity | null;\n\n /**\n * set server telemetry entity to the platform cache\n * @param serverTelemetryKey\n * @param serverTelemetry\n */\n abstract setServerTelemetry(\n serverTelemetryKey: string,\n serverTelemetry: ServerTelemetryEntity\n ): void;\n\n /**\n * fetch cloud discovery metadata entity from the platform cache\n * @param key\n */\n abstract getAuthorityMetadata(key: string): AuthorityMetadataEntity | null;\n\n /**\n *\n */\n abstract getAuthorityMetadataKeys(): Array<string>;\n\n /**\n * set cloud discovery metadata entity to the platform cache\n * @param key\n * @param value\n */\n abstract setAuthorityMetadata(\n key: string,\n value: AuthorityMetadataEntity\n ): void;\n\n /**\n * fetch throttling entity from the platform cache\n * @param throttlingCacheKey\n */\n abstract getThrottlingCache(\n throttlingCacheKey: string\n ): ThrottlingEntity | null;\n\n /**\n * set throttling entity to the platform cache\n * @param throttlingCacheKey\n * @param throttlingCache\n */\n abstract setThrottlingCache(\n throttlingCacheKey: string,\n throttlingCache: ThrottlingEntity\n ): void;\n\n /**\n * Function to remove an item from cache given its key.\n * @param key\n */\n abstract removeItem(key: string): void;\n\n /**\n * Function which returns boolean whether cache contains a specific key.\n * @param key\n */\n abstract containsKey(key: string, type?: string): boolean;\n\n /**\n * Function which retrieves all current keys from the cache.\n */\n abstract getKeys(): string[];\n\n /**\n * Function which retrieves all account keys from the cache\n */\n abstract getAccountKeys(): string[];\n\n /**\n * Function which retrieves all token keys from the cache\n */\n abstract getTokenKeys(): TokenKeys;\n\n /**\n * Function which clears cache.\n */\n abstract clear(): Promise<void>;\n\n /**\n * Function which updates an outdated credential cache key\n */\n abstract updateCredentialCacheKey(\n currentCacheKey: string,\n credential: ValidCredentialType\n ): string;\n\n /**\n * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.\n * @param accountFilter - (Optional) filter to narrow down the accounts returned\n * @returns Array of AccountInfo objects in cache\n */\n getAllAccounts(accountFilter?: AccountFilter): AccountInfo[] {\n return this.buildTenantProfiles(\n this.getAccountsFilteredBy(accountFilter || {}),\n accountFilter\n );\n }\n\n /**\n * Gets first tenanted AccountInfo object found based on provided filters\n */\n getAccountInfoFilteredBy(accountFilter: AccountFilter): AccountInfo | null {\n const allAccounts = this.getAllAccounts(accountFilter);\n if (allAccounts.length > 1) {\n // If one or more accounts are found, prioritize accounts that have an ID token\n const sortedAccounts = allAccounts.sort((account) => {\n return account.idTokenClaims ? -1 : 1;\n });\n return sortedAccounts[0];\n } else if (allAccounts.length === 1) {\n // If only one account is found, return it regardless of whether a matching ID token was found\n return allAccounts[0];\n } else {\n return null;\n }\n }\n\n /**\n * Returns a single matching\n * @param accountFilter\n * @returns\n */\n getBaseAccountInfo(accountFilter: AccountFilter): AccountInfo | null {\n const accountEntities = this.getAccountsFilteredBy(accountFilter);\n if (accountEntities.length > 0) {\n return accountEntities[0].getAccountInfo();\n } else {\n return null;\n }\n }\n\n /**\n * Matches filtered account entities with cached ID tokens that match the tenant profile-specific account filters\n * and builds the account info objects from the matching ID token's claims\n * @param cachedAccounts\n * @param accountFilter\n * @returns Array of AccountInfo objects that match account and tenant profile filters\n */\n private buildTenantProfiles(\n cachedAccounts: AccountEntity[],\n accountFilter?: AccountFilter\n ): AccountInfo[] {\n return cachedAccounts.flatMap((accountEntity) => {\n return this.getAccountInfoForTenantProfiles(\n accountEntity,\n accountFilter\n );\n });\n }\n\n private getAccountInfoForTenantProfiles(\n accountEntity: AccountEntity,\n accountFilter?: AccountFilter\n ): AccountInfo[] {\n return this.getTenantProfilesFromAccountEntity(\n accountEntity,\n accountFilter?.tenantId,\n accountFilter\n );\n }\n\n private getTenantedAccountInfoByFilter(\n accountInfo: AccountInfo,\n tokenKeys: TokenKeys,\n tenantProfile: TenantProfile,\n tenantProfileFilter?: TenantProfileFilter\n ): AccountInfo | null {\n let tenantedAccountInfo: AccountInfo | null = null;\n let idTokenClaims: TokenClaims | undefined;\n\n if (tenantProfileFilter) {\n if (\n !this.tenantProfileMatchesFilter(\n tenantProfile,\n tenantProfileFilter\n )\n ) {\n return null;\n }\n }\n\n const idToken = this.getIdToken(\n accountInfo,\n tokenKeys,\n tenantProfile.tenantId\n );\n\n if (idToken) {\n idTokenClaims = extractTokenClaims(\n idToken.secret,\n this.cryptoImpl.base64Decode\n );\n\n if (\n !this.idTokenClaimsMatchTenantProfileFilter(\n idTokenClaims,\n tenantProfileFilter\n )\n ) {\n // ID token sourced claims don't match so this tenant profile is not a match\n return null;\n }\n }\n\n // Expand tenant profile into account info based on matching tenant profile and if available matching ID token claims\n tenantedAccountInfo = updateAccountTenantProfileData(\n accountInfo,\n tenantProfile,\n idTokenClaims\n );\n\n return tenantedAccountInfo;\n }\n\n private getTenantProfilesFromAccountEntity(\n accountEntity: AccountEntity,\n targetTenantId?: string,\n tenantProfileFilter?: TenantProfileFilter\n ): AccountInfo[] {\n const accountInfo = accountEntity.getAccountInfo();\n let searchTenantProfiles: Map<string, TenantProfile> =\n accountInfo.tenantProfiles || new Map<string, TenantProfile>();\n const tokenKeys = this.getTokenKeys();\n\n // If a tenant ID was provided, only return the tenant profile for that tenant ID if it exists\n if (targetTenantId) {\n const tenantProfile = searchTenantProfiles.get(targetTenantId);\n if (tenantProfile) {\n // Reduce search field to just this tenant profile\n searchTenantProfiles = new Map<string, TenantProfile>([\n [targetTenantId, tenantProfile],\n ]);\n } else {\n // No tenant profile for search tenant ID, return empty array\n return [];\n }\n }\n\n const matchingTenantProfiles: AccountInfo[] = [];\n searchTenantProfiles.forEach((tenantProfile: TenantProfile) => {\n const tenantedAccountInfo = this.getTenantedAccountInfoByFilter(\n accountInfo,\n tokenKeys,\n tenantProfile,\n tenantProfileFilter\n );\n if (tenantedAccountInfo) {\n matchingTenantProfiles.push(tenantedAccountInfo);\n }\n });\n\n return matchingTenantProfiles;\n }\n\n private tenantProfileMatchesFilter(\n tenantProfile: TenantProfile,\n tenantProfileFilter: TenantProfileFilter\n ): boolean {\n if (\n !!tenantProfileFilter.localAccountId &&\n !this.matchLocalAccountIdFromTenantProfile(\n tenantProfile,\n tenantProfileFilter.localAccountId\n )\n ) {\n return false;\n }\n\n if (\n !!tenantProfileFilter.name &&\n !(tenantProfile.name === tenantProfileFilter.name)\n ) {\n return false;\n }\n\n if (\n tenantProfileFilter.isHomeTenant !== undefined &&\n !(tenantProfile.isHomeTenant === tenantProfileFilter.isHomeTenant)\n ) {\n return false;\n }\n\n return true;\n }\n\n private idTokenClaimsMatchTenantProfileFilter(\n idTokenClaims: TokenClaims,\n tenantProfileFilter?: TenantProfileFilter\n ): boolean {\n // Tenant Profile filtering\n if (tenantProfileFilter) {\n if (\n !!tenantProfileFilter.localAccountId &&\n !this.matchLocalAccountIdFromTokenClaims(\n idTokenClaims,\n tenantProfileFilter.localAccountId\n )\n ) {\n return false;\n }\n\n if (\n !!tenantProfileFilter.loginHint &&\n !this.matchLoginHintFromTokenClaims(\n idTokenClaims,\n tenantProfileFilter.loginHint\n )\n ) {\n return false;\n }\n\n if (\n !!tenantProfileFilter.username &&\n !this.matchUsername(\n idTokenClaims.preferred_username,\n tenantProfileFilter.username\n )\n ) {\n return false;\n }\n\n if (\n !!tenantProfileFilter.name &&\n !this.matchName(idTokenClaims, tenantProfileFilter.name)\n ) {\n return false;\n }\n\n if (\n !!tenantProfileFilter.sid &&\n !this.matchSid(idTokenClaims, tenantProfileFilter.sid)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * saves a cache record\n * @param cacheRecord\n */\n async saveCacheRecord(\n cacheRecord: CacheRecord,\n storeInCache?: StoreInCache\n ): Promise<void> {\n if (!cacheRecord) {\n throw createClientAuthError(\n ClientAuthErrorCodes.invalidCacheRecord\n );\n }\n\n if (!!cacheRecord.account) {\n this.setAccount(cacheRecord.account);\n }\n\n if (!!cacheRecord.idToken && storeInCache?.idToken !== false) {\n this.setIdTokenCredential(cacheRecord.idToken);\n }\n\n if (!!cacheRecord.accessToken && storeInCache?.accessToken !== false) {\n await this.saveAccessToken(cacheRecord.accessToken);\n }\n\n if (\n !!cacheRecord.refreshToken &&\n storeInCache?.refreshToken !== false\n ) {\n this.setRefreshTokenCredential(cacheRecord.refreshToken);\n }\n\n if (!!cacheRecord.appMetadata) {\n this.setAppMetadata(cacheRecord.appMetadata);\n }\n }\n\n /**\n * saves access token credential\n * @param credential\n */\n private async saveAccessToken(\n credential: AccessTokenEntity\n ): Promise<void> {\n const accessTokenFilter: CredentialFilter = {\n clientId: credential.clientId,\n credentialType: credential.credentialType,\n environment: credential.environment,\n homeAccountId: credential.homeAccountId,\n realm: credential.realm,\n tokenType: credential.tokenType,\n requestedClaimsHash: credential.requestedClaimsHash,\n };\n\n const tokenKeys = this.getTokenKeys();\n const currentScopes = ScopeSet.fromString(credential.target);\n\n const removedAccessTokens: Array<Promise<void>> = [];\n tokenKeys.accessToken.forEach((key) => {\n if (\n !this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)\n ) {\n return;\n }\n\n const tokenEntity = this.getAccessTokenCredential(key);\n\n if (\n tokenEntity &&\n this.credentialMatchesFilter(tokenEntity, accessTokenFilter)\n ) {\n const tokenScopeSet = ScopeSet.fromString(tokenEntity.target);\n if (tokenScopeSet.intersectingScopeSets(currentScopes)) {\n removedAccessTokens.push(this.removeAccessToken(key));\n }\n }\n });\n await Promise.all(removedAccessTokens);\n this.setAccessTokenCredential(credential);\n }\n\n /**\n * Retrieve account entities matching all provided tenant-agnostic filters; if no filter is set, get all account entities in the cache\n * Not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared\n * @param accountFilter - An object containing Account properties to filter by\n */\n getAccountsFilteredBy(accountFilter: AccountFilter): AccountEntity[] {\n const allAccountKeys = this.getAccountKeys();\n const matchingAccounts: AccountEntity[] = [];\n allAccountKeys.forEach((cacheKey) => {\n if (!this.isAccountKey(cacheKey, accountFilter.homeAccountId)) {\n // Don't parse value if the key doesn't match the account filters\n return;\n }\n\n const entity: AccountEntity | null = this.getAccount(\n cacheKey,\n this.commonLogger\n );\n\n // Match base account fields\n\n if (!entity) {\n return;\n }\n\n if (\n !!accountFilter.homeAccountId &&\n !this.matchHomeAccountId(entity, accountFilter.homeAccountId)\n ) {\n return;\n }\n\n if (\n !!accountFilter.username &&\n !this.matchUsername(entity.username, accountFilter.username)\n ) {\n return;\n }\n\n if (\n !!accountFilter.environment &&\n !this.matchEnvironment(entity, accountFilter.environment)\n ) {\n return;\n }\n\n if (\n !!accountFilter.realm &&\n !this.matchRealm(entity, accountFilter.realm)\n ) {\n return;\n }\n\n if (\n !!accountFilter.nativeAccountId &&\n !this.matchNativeAccountId(\n entity,\n accountFilter.nativeAccountId\n )\n ) {\n return;\n }\n\n if (\n !!accountFilter.authorityType &&\n !this.matchAuthorityType(entity, accountFilter.authorityType)\n ) {\n return;\n }\n\n // If at least one tenant profile matches the tenant profile filter, add the account to the list of matching accounts\n const tenantProfileFilter: TenantProfileFilter = {\n localAccountId: accountFilter?.localAccountId,\n name: accountFilter?.name,\n };\n\n const matchingTenantProfiles = entity.tenantProfiles?.filter(\n (tenantProfile: TenantProfile) => {\n return this.tenantProfileMatchesFilter(\n tenantProfile,\n tenantProfileFilter\n );\n }\n );\n\n if (matchingTenantProfiles && matchingTenantProfiles.length === 0) {\n // No tenant profile for this account matches filter, don't add to list of matching accounts\n return;\n }\n\n matchingAccounts.push(entity);\n });\n\n return matchingAccounts;\n }\n\n /**\n * Returns true if the given key matches our account key schema. Also matches homeAccountId and/or tenantId if provided\n * @param key\n * @param homeAccountId\n * @param tenantId\n * @returns\n */\n isAccountKey(\n key: string,\n homeAccountId?: string,\n tenantId?: string\n ): boolean {\n if (key.split(Separators.CACHE_KEY_SEPARATOR).length < 3) {\n // Account cache keys contain 3 items separated by '-' (each item may also contain '-')\n return false;\n }\n\n if (\n homeAccountId &&\n !key.toLowerCase().includes(homeAccountId.toLowerCase())\n ) {\n return false;\n }\n\n if (tenantId && !key.toLowerCase().includes(tenantId.toLowerCase())) {\n return false;\n }\n\n // Do not check environment as aliasing can cause false negatives\n\n return true;\n }\n\n /**\n * Returns true if the given key matches our credential key schema.\n * @param key\n */\n isCredentialKey(key: string): boolean {\n if (key.split(Separators.CACHE_KEY_SEPARATOR).length < 6) {\n // Credential cache keys contain 6 items separated by '-' (each item may also contain '-')\n return false;\n }\n\n const lowerCaseKey = key.toLowerCase();\n // Credential keys must indicate what credential type they represent\n if (\n lowerCaseKey.indexOf(CredentialType.ID_TOKEN.toLowerCase()) ===\n -1 &&\n lowerCaseKey.indexOf(CredentialType.ACCESS_TOKEN.toLowerCase()) ===\n -1 &&\n lowerCaseKey.indexOf(\n CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()\n ) === -1 &&\n lowerCaseKey.indexOf(CredentialType.REFRESH_TOKEN.toLowerCase()) ===\n -1\n ) {\n return false;\n }\n\n if (\n lowerCaseKey.indexOf(CredentialType.REFRESH_TOKEN.toLowerCase()) >\n -1\n ) {\n // Refresh tokens must contain the client id or family id\n const clientIdValidation = `${CredentialType.REFRESH_TOKEN}${Separators.CACHE_KEY_SEPARATOR}${this.clientId}${Separators.CACHE_KEY_SEPARATOR}`;\n const familyIdValidation = `${CredentialType.REFRESH_TOKEN}${Separators.CACHE_KEY_SEPARATOR}${THE_FAMILY_ID}${Separators.CACHE_KEY_SEPARATOR}`;\n if (\n lowerCaseKey.indexOf(clientIdValidation.toLowerCase()) === -1 &&\n lowerCaseKey.indexOf(familyIdValidation.toLowerCase()) === -1\n ) {\n return false;\n }\n } else if (lowerCaseKey.indexOf(this.clientId.toLowerCase()) === -1) {\n // Tokens must contain the clientId\n return false;\n }\n\n return true;\n }\n\n /**\n * Returns whether or not the given credential entity matches the filter\n * @param entity\n * @param filter\n * @returns\n */\n credentialMatchesFilter(\n entity: ValidCredentialType,\n filter: CredentialFilter\n ): boolean {\n if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) {\n return false;\n }\n\n if (\n !!filter.userAssertionHash &&\n !this.matchUserAssertionHash(entity, filter.userAssertionHash)\n ) {\n return false;\n }\n\n /*\n * homeAccountId can be undefined, and we want to filter out cached items that have a homeAccountId of \"\"\n * because we don't want a client_credential request to return a cached token that has a homeAccountId\n */\n if (\n typeof filter.homeAccountId === \"string\" &&\n !this.matchHomeAccountId(entity, filter.homeAccountId)\n ) {\n return false;\n }\n\n if (\n !!filter.environment &&\n !this.matchEnvironment(entity, filter.environment)\n ) {\n return false;\n }\n\n if (!!filter.realm && !this.matchRealm(entity, filter.realm)) {\n return false;\n }\n\n if (\n !!filter.credentialType &&\n !this.matchCredentialType(entity, filter.credentialType)\n ) {\n return false;\n }\n\n if (!!filter.familyId && !this.matchFamilyId(entity, filter.familyId)) {\n return false;\n }\n\n /*\n * idTokens do not have \"target\", target specific refreshTokens do exist for some types of authentication\n * Resource specific refresh tokens case will be added when the support is deemed necessary\n */\n if (!!filter.target && !this.matchTarget(entity, filter.target)) {\n return false;\n }\n\n // If request OR cached entity has requested Claims Hash, check if they match\n if (filter.requestedClaimsHash || entity.requestedClaimsHash) {\n // Don't match if either is undefined or they are different\n if (entity.requestedClaimsHash !== filter.requestedClaimsHash) {\n return false;\n }\n }\n\n // Access Token with Auth Scheme specific matching\n if (\n entity.credentialType ===\n CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME\n ) {\n if (\n !!filter.tokenType &&\n !this.matchTokenType(entity, filter.tokenType)\n ) {\n return false;\n }\n\n // KeyId (sshKid) in request must match cached SSH certificate keyId because SSH cert is bound to a specific key\n if (filter.tokenType === AuthenticationScheme.SSH) {\n if (filter.keyId && !this.matchKeyId(entity, filter.keyId)) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * retrieve appMetadata matching all provided filters; if no filter is set, get all appMetadata\n * @param filter\n */\n getAppMetadataFilteredBy(filter: AppMetadataFilter): AppMetadataCache {\n return this.getAppMetadataFilteredByInternal(\n filter.environment,\n filter.clientId\n );\n }\n\n /**\n * Support function to help match appMetadata\n * @param environment\n * @param clientId\n */\n private getAppMetadataFilteredByInternal(\n environment?: string,\n clientId?: string\n ): AppMetadataCache {\n const allCacheKeys = this.getKeys();\n const matchingAppMetadata: AppMetadataCache = {};\n\n allCacheKeys.forEach((cacheKey) => {\n // don't parse any non-appMetadata type cache entities\n if (!this.isAppMetadata(cacheKey)) {\n return;\n }\n\n // Attempt retrieval\n const entity = this.getAppMetadata(cacheKey);\n\n if (!entity) {\n return;\n }\n\n if (!!environment && !this.matchEnvironment(entity, environment)) {\n return;\n }\n\n if (!!clientId && !this.matchClientId(entity, clientId)) {\n return;\n }\n\n matchingAppMetadata[cacheKey] = entity;\n });\n\n return matchingAppMetadata;\n }\n\n /**\n * retrieve authorityMetadata that contains a matching alias\n * @param filter\n */\n getAuthorityMetadataByAlias(host: string): AuthorityMetadataEntity | null {\n const allCacheKeys = this.getAuthorityMetadataKeys();\n let matchedEntity = null;\n\n allCacheKeys.forEach((cacheKey) => {\n // don't parse any non-authorityMetadata type cache entities\n if (\n !this.isAuthorityMetadata(cacheKey) ||\n cacheKey.indexOf(this.clientId) === -1\n ) {\n return;\n }\n\n // Attempt retrieval\n const entity = this.getAuthorityMetadata(cacheKey);\n\n if (!entity) {\n return;\n }\n\n if (entity.aliases.indexOf(host) === -1) {\n return;\n }\n\n matchedEntity = entity;\n });\n\n return matchedEntity;\n }\n\n /**\n * Removes all accounts and related tokens from cache.\n */\n async removeAllAccounts(): Promise<void> {\n const allAccountKeys = this.getAccountKeys();\n const removedAccounts: Array<Promise<void>> = [];\n\n allAccountKeys.forEach((cacheKey) => {\n removedAccounts.push(this.removeAccount(cacheKey));\n });\n\n await Promise.all(removedAccounts);\n }\n\n /**\n * Removes the account and related tokens for a given account key\n * @param account\n */\n async removeAccount(accountKey: string): Promise<void> {\n const account = this.getAccount(accountKey, this.commonLogger);\n if (!account) {\n return;\n }\n await this.removeAccountContext(account);\n this.removeItem(accountKey);\n }\n\n /**\n * Removes credentials associated with the provided account\n * @param account\n */\n async removeAccountContext(account: AccountEntity): Promise<void> {\n const allTokenKeys = this.getTokenKeys();\n const accountId = account.generateAccountId();\n const removedCredentials: Array<Promise<void>> = [];\n\n allTokenKeys.idToken.forEach((key) => {\n if (key.indexOf(accountId) === 0) {\n this.removeIdToken(key);\n }\n });\n\n allTokenKeys.accessToken.forEach((key) => {\n if (key.indexOf(accountId) === 0) {\n removedCredentials.push(this.removeAccessToken(key));\n }\n });\n\n allTokenKeys.refreshToken.forEach((key) => {\n if (key.indexOf(accountId) === 0) {\n this.removeRefreshToken(key);\n }\n });\n\n await Promise.all(removedCredentials);\n }\n\n /**\n * Migrates a single-tenant account and all it's associated alternate cross-tenant account objects in the\n * cache into a condensed multi-tenant account object with tenant profiles.\n * @param accountKey\n * @param accountEntity\n * @param logger\n * @returns\n */\n protected updateOutdatedCachedAccount(\n accountKey: string,\n accountEntity: AccountEntity | null,\n logger?: Logger\n ): AccountEntity | null {\n // Only update if account entity is defined and has no tenantProfiles object (is outdated)\n if (accountEntity && accountEntity.isSingleTenant()) {\n this.commonLogger?.verbose(\n \"updateOutdatedCachedAccount: Found a single-tenant (outdated) account entity in the cache, migrating to multi-tenant account entity\"\n );\n\n // Get keys of all accounts belonging to user\n const matchingAccountKeys = this.getAccountKeys().filter(\n (key: string) => {\n return key.startsWith(accountEntity.homeAccountId);\n }\n );\n\n // Get all account entities belonging to user\n const accountsToMerge: AccountEntity[] = [];\n matchingAccountKeys.forEach((key: string) => {\n const account = this.getCachedAccountEntity(key);\n if (account) {\n accountsToMerge.push(account);\n }\n });\n\n // Set base account to home account if available, any account if not\n const baseAccount =\n accountsToMerge.find((account) => {\n return tenantIdMatchesHomeTenant(\n account.realm,\n account.homeAccountId\n );\n }) || accountsToMerge[0];\n\n // Populate tenant profiles built from each account entity belonging to the user\n baseAccount.tenantProfiles = accountsToMerge.map(\n (account: AccountEntity) => {\n return {\n tenantId: account.realm,\n localAccountId: account.localAccountId,\n name: account.name,\n isHomeTenant: tenantIdMatchesHomeTenant(\n account.realm,\n account.homeAccountId\n ),\n };\n }\n );\n\n const updatedAccount = CacheManager.toObject(new AccountEntity(), {\n ...baseAccount,\n });\n\n const newAccountKey = updatedAccount.generateAccountKey();\n\n // Clear cache of legacy account objects that have been collpsed into tenant profiles\n matchingAccountKeys.forEach((key: string) => {\n if (key !== newAccountKey) {\n this.removeOutdatedAccount(accountKey);\n }\n });\n\n // Cache updated account object\n this.setAccount(updatedAccount);\n logger?.verbose(\"Updated an outdated account entity in the cache\");\n return updatedAccount;\n }\n\n // No update is necessary\n return accountEntity;\n }\n\n /**\n * returns a boolean if the given credential is removed\n * @param credential\n */\n async removeAccessToken(key: string): Promise<void> {\n const credential = this.getAccessTokenCredential(key);\n if (!credential) {\n return;\n }\n\n // Remove Token Binding Key from key store for PoP Tokens Credentials\n if (\n credential.credentialType.toLowerCase() ===\n CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()\n ) {\n if (credential.tokenType === AuthenticationScheme.POP) {\n const accessTokenWithAuthSchemeEntity =\n credential as AccessTokenEntity;\n const kid = accessTokenWithAuthSchemeEntity.keyId;\n\n if (kid) {\n try {\n await this.cryptoImpl.removeTokenBindingKey(kid);\n } catch (error) {\n throw createClientAuthError(\n ClientAuthErrorCodes.bindingKeyNotRemoved\n );\n }\n }\n }\n }\n\n return this.removeItem(key);\n }\n\n /**\n * Removes all app metadata objects from cache.\n */\n removeAppMetadata(): boolean {\n const allCacheKeys = this.getKeys();\n allCacheKeys.forEach((cacheKey) => {\n if (this.isAppMetadata(cacheKey)) {\n this.removeItem(cacheKey);\n }\n });\n\n return true;\n }\n\n /**\n * Retrieve AccountEntity from cache\n * @param account\n */\n readAccountFromCache(account: AccountInfo): AccountEntity | null {\n const accountKey: string =\n AccountEntity.generateAccountCacheKey(account);\n return this.getAccount(accountKey, this.commonLogger);\n }\n\n /**\n * Retrieve IdTokenEntity from cache\n * @param account {AccountInfo}\n * @param tokenKeys {?TokenKeys}\n * @param targetRealm {?string}\n * @param performanceClient {?IPerformanceClient}\n * @param correlationId {?string}\n */\n getIdToken(\n account: AccountInfo,\n tokenKeys?: TokenKeys,\n targetRealm?: string,\n performanceClient?: IPerformanceClient,\n correlationId?: string\n ): IdTokenEntity | null {\n this.commonLogger.trace(\"CacheManager - getIdToken called\");\n const idTokenFilter: CredentialFilter = {\n homeAccountId: account.homeAccountId,\n environment: account.environment,\n credentialType: CredentialType.ID_TOKEN,\n clientId: this.clientId,\n realm: targetRealm,\n };\n\n const idTokenMap: Map<string, IdTokenEntity> = this.getIdTokensByFilter(\n idTokenFilter,\n tokenKeys\n );\n\n const numIdTokens = idTokenMap.size;\n\n if (numIdTokens < 1) {\n this.commonLogger.info(\"CacheManager:getIdToken - No token found\");\n return null;\n } else if (numIdTokens > 1) {\n let tokensToBeRemoved: Map<string, IdTokenEntity> = idTokenMap;\n // Multiple tenant profiles and no tenant specified, pick home account\n if (!targetRealm) {\n const homeIdTokenMap: Map<string, IdTokenEntity> = new Map<\n string,\n IdTokenEntity\n >();\n idTokenMap.forEach((idToken, key) => {\n if (idToken.realm === account.tenantId) {\n homeIdTokenMap.set(key, idToken);\n }\n });\n const numHomeIdTokens = homeIdTokenMap.size;\n if (numHomeIdTokens < 1) {\n this.commonLogger.info(\n \"CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result\"\n );\n return idTokenMap.values().next().value;\n } else if (numHomeIdTokens === 1) {\n this.commonLogger.info(\n \"CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile\"\n );\n return homeIdTokenMap.values().next().value;\n } else {\n // Multiple ID tokens for home tenant profile, remove all and return null\n tokensToBeRemoved = homeIdTokenMap;\n }\n }\n // Multiple tokens for a single tenant profile, remove all and return null\n this.commonLogger.info(\n \"CacheManager:getIdToken - Multiple matching ID tokens found, clearing them\"\n );\n tokensToBeRemoved.forEach((idToken, key) => {\n this.removeIdToken(key);\n });\n if (performanceClient && correlationId) {\n performanceClient.addFields(\n { multiMatchedID: idTokenMap.size },\n correlationId\n );\n }\n return null;\n }\n\n this.commonLogger.info(\"CacheManager:getIdToken - Returning ID token\");\n return idTokenMap.values().next().value;\n }\n\n /**\n * Gets all idTokens matching the given filter\n * @param filter\n * @returns\n */\n getIdTokensByFilter(\n filter: CredentialFilter,\n tokenKeys?: TokenKeys\n ): Map<string, IdTokenEntity> {\n const idTokenKeys =\n (tokenKeys && tokenKeys.idToken) || this.getTokenKeys().idToken;\n\n const idTokens: Map<string, IdTokenEntity> = new Map<\n string,\n IdTokenEntity\n >();\n idTokenKeys.forEach((key) => {\n if (\n !this.idTokenKeyMatchesFilter(key, {\n clientId: this.clientId,\n ...filter,\n })\n ) {\n return;\n }\n const idToken = this.getIdTokenCredential(key);\n if (idToken && this.credentialMatchesFilter(idToken, filter)) {\n idTokens.set(key, idToken);\n }\n });\n\n return idTokens;\n }\n\n /**\n * Validate the cache key against filter before retrieving and parsing cache value\n * @param key\n * @param filter\n * @returns\n */\n idTokenKeyMatchesFilter(\n inputKey: string,\n filter: CredentialFilter\n ): boolean {\n const key = inputKey.toLowerCase();\n if (\n filter.clientId &&\n key.indexOf(filter.clientId.toLowerCase()) === -1\n ) {\n return false;\n }\n\n if (\n filter.homeAccountId &&\n key.indexOf(filter.homeAccountId.toLowerCase()) === -1\n ) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Removes idToken from the cache\n * @param key\n */\n removeIdToken(key: string): void {\n this.removeItem(key);\n }\n\n /**\n * Removes refresh token from the cache\n * @param key\n */\n removeRefreshToken(key: string): void {\n this.removeItem(key);\n }\n\n /**\n * Retrieve AccessTokenEntity from cache\n * @param account {AccountInfo}\n * @param request {BaseAuthRequest}\n * @param tokenKeys {?TokenKeys}\n * @param performanceClient {?IPerformanceClient}\n * @param correlationId {?string}\n */\n getAccessToken(\n account: AccountInfo,\n request: BaseAuthRequest,\n tokenKeys?: TokenKeys,\n targetRealm?: string,\n performanceClient?: IPerformanceClient,\n correlationId?: string\n ): AccessTokenEntity | null {\n this.commonLogger.trace(\"CacheManager - getAccessToken called\");\n const scopes = ScopeSet.createSearchScopes(request.scopes);\n const authScheme =\n request.authenticationScheme || AuthenticationScheme.BEARER;\n /*\n * Distinguish between Bearer and PoP/SSH token cache types\n * Cast to lowercase to handle \"bearer\" from ADFS\n */\n const credentialType =\n authScheme &&\n authScheme.toLowerCase() !==\n AuthenticationScheme.BEARER.toLowerCase()\n ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME\n : CredentialType.ACCESS_TOKEN;\n\n const accessTokenFilter: CredentialFilter = {\n homeAccountId: account.homeAccountId,\n environment: account.environment,\n credentialType: credentialType,\n clientId: this.clientId,\n realm: targetRealm || account.tenantId,\n target: scopes,\n tokenType: authScheme,\n keyId: request.sshKid,\n requestedClaimsHash: request.requestedClaimsHash,\n };\n\n const accessTokenKeys =\n (tokenKeys && tokenKeys.accessToken) ||\n this.getTokenKeys().accessToken;\n const accessTokens: AccessTokenEntity[] = [];\n\n accessTokenKeys.forEach((key) => {\n // Validate key\n if (\n this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)\n ) {\n const accessToken = this.getAccessTokenCredential(key);\n\n // Validate value\n if (\n accessToken &&\n this.credentialMatchesFilter(accessToken, accessTokenFilter)\n ) {\n accessTokens.push(accessToken);\n }\n }\n });\n\n const numAccessTokens = accessTokens.length;\n if (numAccessTokens < 1) {\n this.commonLogger.info(\n \"CacheManager:getAccessToken - No token found\"\n );\n return null;\n } else if (numAccessTokens > 1) {\n this.commonLogger.info(\n \"CacheManager:getAccessToken - Multiple access tokens found, clearing them\"\n );\n accessTokens.forEach((accessToken) => {\n void this.removeAccessToken(generateCredentialKey(accessToken));\n });\n if (performanceClient && correlationId) {\n performanceClient.addFields(\n { multiMatchedAT: accessTokens.length },\n correlationId\n );\n }\n return null;\n }\n\n this.commonLogger.info(\n \"CacheManager:getAccessToken - Returning access token\"\n );\n return accessTokens[0];\n }\n\n /**\n * Validate the cache key against filter before retrieving and parsing cache value\n * @param key\n * @param filter\n * @param keyMustContainAllScopes\n * @returns\n */\n accessTokenKeyMatchesFilter(\n inputKey: string,\n filter: CredentialFilter,\n keyMustContainAllScopes: boolean\n ): boolean {\n const key = inputKey.toLowerCase();\n if (\n filter.clientId &&\n key.indexOf(filter.clientId.toLowerCase()) === -1\n ) {\n return false;\n }\n\n if (\n filter.homeAccountId &&\n key.indexOf(filter.homeAccountId.toLowerCase()) === -1\n ) {\n return false;\n }\n\n if (filter.realm && key.indexOf(filter.realm.toLowerCase()) === -1) {\n return false;\n }\n\n if (\n filter.requestedClaimsHash &&\n key.indexOf(filter.requestedClaimsHash.toLowerCase()) === -1\n ) {\n return false;\n }\n\n if (filter.target) {\n const scopes = filter.target.asArray();\n for (let i = 0; i < scopes.length; i++) {\n if (\n keyMustContainAllScopes &&\n !key.includes(scopes[i].toLowerCase())\n ) {\n // When performing a cache lookup a missing scope would be a cache miss\n return false;\n } else if (\n !keyMustContainAllScopes &&\n key.includes(scopes[i].toLowerCase())\n ) {\n // When performing a cache write, any token with a subset of requested scopes should be replaced\n return true;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Gets all access tokens matching the filter\n * @param filter\n * @returns\n */\n getAccessTokensByFilter(filter: CredentialFilter): AccessTokenEntity[] {\n const tokenKeys = this.getTokenKeys();\n\n const accessTokens: AccessTokenEntity[] = [];\n tokenKeys.accessToken.forEach((key) => {\n if (!this.accessTokenKeyMatchesFilter(key, filter, true)) {\n return;\n }\n\n const accessToken = this.getAccessTokenCredential(key);\n if (\n accessToken &&\n this.credentialMatchesFilter(accessToken, filter)\n ) {\n accessTokens.push(accessToken);\n }\n });\n\n return accessTokens;\n }\n\n /**\n * Helper to retrieve the appropriate refresh token from cache\n * @param account {AccountInfo}\n * @param familyRT {boolean}\n * @param tokenKeys {?TokenKeys}\n * @param performanceClient {?IPerformanceClient}\n * @param correlationId {?string}\n */\n getRefreshToken(\n account: AccountInfo,\n familyRT: boolean,\n tokenKeys?: TokenKeys,\n performanceClient?: IPerformanceClient,\n correlationId?: string\n ): RefreshTokenEntity | null {\n this.commonLogger.trace(\"CacheManager - getRefreshToken called\");\n const id = familyRT ? THE_FAMILY_ID : undefined;\n const refreshTokenFilter: CredentialFilter = {\n homeAccountId: account.homeAccountId,\n environment: account.environment,\n credentialType: CredentialType.REFRESH_TOKEN,\n clientId: this.clientId,\n familyId: id,\n };\n\n const refreshTokenKeys =\n (tokenKeys && tokenKeys.refreshToken) ||\n this.getTokenKeys().refreshToken;\n const refreshTokens: RefreshTokenEntity[] = [];\n\n refreshTokenKeys.forEach((key) => {\n // Validate key\n if (this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) {\n const refreshToken = this.getRefreshTokenCredential(key);\n // Validate value\n if (\n refreshToken &&\n this.credentialMatchesFilter(\n refreshToken,\n refreshTokenFilter\n )\n ) {\n refreshTokens.push(refreshToken);\n }\n }\n });\n\n const numRefreshTokens = refreshTokens.length;\n if (numRefreshTokens < 1) {\n this.commonLogger.info(\n \"CacheManager:getRefreshToken - No refresh token found.\"\n );\n return null;\n }\n // address the else case after remove functions address environment aliases\n\n if (numRefreshTokens > 1 && performanceClient && correlationId) {\n performanceClient.addFields(\n { multiMatchedRT: numRefreshTokens },\n correlationId\n );\n }\n\n this.commonLogger.info(\n \"CacheManager:getRefreshToken - returning refresh token\"\n );\n return refreshTokens[0] as RefreshTokenEntity;\n }\n\n /**\n * Validate the cache key against filter before retrieving and parsing cache value\n * @param key\n * @param filter\n */\n refreshTokenKeyMatchesFilter(\n inputKey: string,\n filter: CredentialFilter\n ): boolean {\n const key = inputKey.toLowerCase();\n if (\n filter.familyId &&\n key.indexOf(filter.familyId.toLowerCase()) === -1\n ) {\n return false;\n }\n\n // If familyId is used, clientId is not in the key\n if (\n !filter.familyId &&\n filter.clientId &&\n key.indexOf(filter.clientId.toLowerCase()) === -1\n ) {\n return false;\n }\n\n if (\n filter.homeAccountId &&\n key.indexOf(filter.homeAccountId.toLowerCase()) === -1\n ) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Retrieve AppMetadataEntity from cache\n */\n readAppMetadataFromCache(environment: string): AppMetadataEntity | null {\n const appMetadataFilter: AppMetadataFilter = {\n environment,\n clientId: this.clientId,\n };\n\n const appMetadata: AppMetadataCache =\n this.getAppMetadataFilteredBy(appMetadataFilter);\n const appMetadataEntries: AppMetadataEntity[] = Object.keys(\n appMetadata\n ).map((key) => appMetadata[key]);\n\n const numAppMetadata = appMetadataEntries.length;\n if (numAppMetadata < 1) {\n return null;\n } else if (numAppMetadata > 1) {\n throw createClientAuthError(\n ClientAuthErrorCodes.multipleMatchingAppMetadata\n );\n }\n\n return appMetadataEntries[0] as AppMetadataEntity;\n }\n\n /**\n * Return the family_id value associated with FOCI\n * @param environment\n * @param clientId\n */\n isAppMetadataFOCI(environment: string): boolean {\n const appMetadata = this.readAppMetadataFromCache(environment);\n return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID);\n }\n\n /**\n * helper to match account ids\n * @param value\n * @param homeAccountId\n */\n private matchHomeAccountId(\n entity: AccountEntity | CredentialEntity,\n homeAccountId: string\n ): boolean {\n return !!(\n typeof entity.homeAccountId === \"string\" &&\n homeAccountId === entity.homeAccountId\n );\n }\n\n /**\n * helper to match account ids\n * @param entity\n * @param localAccountId\n * @returns\n */\n private matchLocalAccountIdFromTokenClaims(\n tokenClaims: TokenClaims,\n localAccountId: string\n ): boolean {\n const idTokenLocalAccountId = tokenClaims.oid || tokenClaims.sub;\n return localAccountId === idTokenLocalAccountId;\n }\n\n private matchLocalAccountIdFromTenantProfile(\n tenantProfile: TenantProfile,\n localAccountId: string\n ): boolean {\n return tenantProfile.localAccountId === localAccountId;\n }\n\n /**\n * helper to match names\n * @param entity\n * @param name\n * @returns true if the downcased name properties are present and match in the filter and the entity\n */\n private matchName(claims: TokenClaims, name: string): boolean {\n return !!(name.toLowerCase() === claims.name?.toLowerCase());\n }\n\n /**\n * helper to match usernames\n * @param entity\n * @param username\n * @returns\n */\n private matchUsername(\n cachedUsername?: string,\n filterUsername?: string\n ): boolean {\n return !!(\n cachedUsername &&\n typeof cachedUsername === \"string\" &&\n filterUsername?.toLowerCase() === cachedUsername.toLowerCase()\n );\n }\n\n /**\n * helper to match assertion\n * @param value\n * @param oboAssertion\n */\n private matchUserAssertionHash(\n entity: CredentialEntity,\n userAssertionHash: string\n ): boolean {\n return !!(\n entity.userAssertionHash &&\n userAssertionHash === entity.userAssertionHash\n );\n }\n\n /**\n * helper to match environment\n * @param value\n * @param environment\n */\n private matchEnvironment(\n entity: AccountEntity | CredentialEntity | AppMetadataEntity,\n environment: string\n ): boolean {\n // Check static authority options first for cases where authority metadata has not been resolved and cached yet\n if (this.staticAuthorityOptions) {\n const staticAliases = getAliasesFromStaticSources(\n this.staticAuthorityOptions,\n this.commonLogger\n );\n if (\n staticAliases.includes(environment) &&\n staticAliases.includes(entity.environment)\n ) {\n return true;\n }\n }\n\n // Query metadata cache if no static authority configuration has aliases that match enviroment\n const cloudMetadata = this.getAuthorityMetadataByAlias(environment);\n if (\n cloudMetadata &&\n cloudMetadata.aliases.indexOf(entity.environment) > -1\n ) {\n return true;\n }\n return false;\n }\n\n /**\n * helper to match credential type\n * @param entity\n * @param credentialType\n */\n private matchCredentialType(\n entity: CredentialEntity,\n credentialType: string\n ): boolean {\n return (\n entity.credentialType &&\n credentialType.toLowerCase() === entity.credentialType.toLowerCase()\n );\n }\n\n /**\n * helper to match client ids\n * @param entity\n * @param clientId\n */\n private matchClientId(\n entity: CredentialEntity | AppMetadataEntity,\n clientId: string\n ): boolean {\n return !!(entity.clientId && clientId === entity.clientId);\n }\n\n /**\n * helper to match family ids\n * @param entity\n * @param familyId\n */\n private matchFamilyId(\n entity: CredentialEntity | AppMetadataEntity,\n familyId: string\n ): boolean {\n return !!(entity.familyId && familyId === entity.familyId);\n }\n\n /**\n * helper to match realm\n * @param entity\n * @param realm\n */\n private matchRealm(\n entity: AccountEntity | CredentialEntity,\n realm: string\n ): boolean {\n return !!(entity.realm?.toLowerCase() === realm.toLowerCase());\n }\n\n /**\n * helper to match nativeAccountId\n * @param entity\n * @param nativeAccountId\n * @returns boolean indicating the match result\n */\n private matchNativeAccountId(\n entity: AccountEntity,\n nativeAccountId: string\n ): boolean {\n return !!(\n entity.nativeAccountId && nativeAccountId === entity.nativeAccountId\n );\n }\n\n /**\n * helper to match loginHint which can be either:\n * 1. login_hint ID token claim\n * 2. username in cached account object\n * 3. upn in ID token claims\n * @param entity\n * @param loginHint\n * @returns\n */\n private matchLoginHintFromTokenClaims(\n tokenClaims: TokenClaims,\n loginHint: string\n ): boolean {\n if (tokenClaims.login_hint === loginHint) {\n return true;\n }\n\n if (tokenClaims.preferred_username === loginHint) {\n return true;\n }\n\n if (tokenClaims.upn === loginHint) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Helper to match sid\n * @param entity\n * @param sid\n * @returns true if the sid claim is present and matches the filter\n */\n private matchSid(idTokenClaims: TokenClaims, sid: string): boolean {\n return idTokenClaims.sid === sid;\n }\n\n private matchAuthorityType(\n entity: AccountEntity,\n authorityType: string\n ): boolean {\n return !!(\n entity.authorityType &&\n authorityType.toLowerCase() === entity.authorityType.toLowerCase()\n );\n }\n\n /**\n * Returns true if the target scopes are a subset of the current entity's scopes, false otherwise.\n * @param entity\n * @param target\n */\n private matchTarget(entity: CredentialEntity, target: ScopeSet): boolean {\n const isNotAccessTokenCredential =\n entity.credentialType !== CredentialType.ACCESS_TOKEN &&\n entity.credentialType !==\n CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;\n\n if (isNotAccessTokenCredential || !entity.target) {\n return false;\n }\n\n const entityScopeSet: ScopeSet = ScopeSet.fromString(entity.target);\n\n return entityScopeSet.containsScopeSet(target);\n }\n\n /**\n * Returns true if the credential's tokenType or Authentication Scheme matches the one in the request, false otherwise\n * @param entity\n * @param tokenType\n */\n private matchTokenType(\n entity: CredentialEntity,\n tokenType: AuthenticationScheme\n ): boolean {\n return !!(entity.tokenType && entity.tokenType === tokenType);\n }\n\n /**\n * Returns true if the credential's keyId matches the one in the request, false otherwise\n * @param entity\n * @param tokenType\n */\n private matchKeyId(entity: CredentialEntity, keyId: string): boolean {\n return !!(entity.keyId && entity.keyId === keyId);\n }\n\n /**\n * returns if a given cache entity is of the type appmetadata\n * @param key\n */\n private isAppMetadata(key: string): boolean {\n return key.indexOf(APP_METADATA) !== -1;\n }\n\n /**\n * returns if a given cache entity is of the type authoritymetadata\n * @param key\n */\n protected isAuthorityMetadata(key: string): boolean {\n return key.indexOf(AUTHORITY_METADATA_CONSTANTS.CACHE_KEY) !== -1;\n }\n\n /**\n * returns cache key used for cloud instance metadata\n */\n generateAuthorityMetadataCacheKey(authority: string): string {\n return `${AUTHORITY_METADATA_CONSTANTS.CACHE_KEY}-${this.clientId}-${authority}`;\n }\n\n /**\n * Helper to convert serialized data to object\n * @param obj\n * @param json\n */\n static toObject<T>(obj: T, json: object): T {\n for (const propertyName in json) {\n obj[propertyName] = json[propertyName];\n }\n return obj;\n }\n}\n\n/** @internal */\nexport class DefaultStorageClass extends CacheManager {\n setAccount(): void {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getAccount(): AccountEntity {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getCachedAccountEntity(): AccountEntity | null {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n setIdTokenCredential(): void {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getIdTokenCredential(): IdTokenEntity {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n setAccessTokenCredential(): void {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getAccessTokenCredential(): AccessTokenEntity {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n setRefreshTokenCredential(): void {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getRefreshTokenCredential(): RefreshTokenEntity {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n setAppMetadata(): void {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getAppMetadata(): AppMetadataEntity {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n setServerTelemetry(): void {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getServerTelemetry(): ServerTelemetryEntity {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n setAuthorityMetadata(): void {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getAuthorityMetadata(): AuthorityMetadataEntity | null {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getAuthorityMetadataKeys(): Array<string> {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n setThrottlingCache(): void {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getThrottlingCache(): ThrottlingEntity {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n removeItem(): boolean {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n containsKey(): boolean {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getKeys(): string[] {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getAccountKeys(): string[] {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n getTokenKeys(): TokenKeys {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n async clear(): Promise<void> {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n updateCredentialCacheKey(): string {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n removeOutdatedAccount(): void {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { INetworkModule } from \"../network/INetworkModule\";\nimport { DEFAULT_CRYPTO_IMPLEMENTATION, ICrypto } from \"../crypto/ICrypto\";\nimport { ILoggerCallback, Logger, LogLevel } from \"../logger/Logger\";\nimport { Constants } from \"../utils/Constants\";\nimport { version } from \"../packageMetadata\";\nimport { Authority } from \"../authority/Authority\";\nimport { AzureCloudInstance } from \"../authority/AuthorityOptions\";\nimport { CacheManager, DefaultStorageClass } from \"../cache/CacheManager\";\nimport { ServerTelemetryManager } from \"../telemetry/server/ServerTelemetryManager\";\nimport { ICachePlugin } from \"../cache/interface/ICachePlugin\";\nimport { ISerializableTokenCache } from \"../cache/interface/ISerializableTokenCache\";\nimport { ClientCredentials } from \"../account/ClientCredentials\";\nimport { ProtocolMode } from \"../authority/ProtocolMode\";\nimport {\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../error/ClientAuthError\";\n\n// Token renewal offset default in seconds\nconst DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;\n\n/**\n * Use the configuration object to configure MSAL Modules and initialize the base interfaces for MSAL.\n *\n * This object allows you to configure important elements of MSAL functionality:\n * - authOptions - Authentication for application\n * - cryptoInterface - Implementation of crypto functions\n * - libraryInfo - Library metadata\n * - telemetry - Telemetry options and data\n * - loggerOptions - Logging for application\n * - networkInterface - Network implementation\n * - storageInterface - Storage implementation\n * - systemOptions - Additional library options\n * - clientCredentials - Credentials options for confidential clients\n * @internal\n */\nexport type ClientConfiguration = {\n authOptions: AuthOptions;\n systemOptions?: SystemOptions;\n loggerOptions?: LoggerOptions;\n cacheOptions?: CacheOptions;\n storageInterface?: CacheManager;\n networkInterface?: INetworkModule;\n cryptoInterface?: ICrypto;\n clientCredentials?: ClientCredentials;\n libraryInfo?: LibraryInfo;\n telemetry?: TelemetryOptions;\n serverTelemetryManager?: ServerTelemetryManager | null;\n persistencePlugin?: ICachePlugin | null;\n serializableCache?: ISerializableTokenCache | null;\n};\n\nexport type CommonClientConfiguration = {\n authOptions: Required<AuthOptions>;\n systemOptions: Required<SystemOptions>;\n loggerOptions: Required<LoggerOptions>;\n cacheOptions: Required<CacheOptions>;\n storageInterface: CacheManager;\n networkInterface: INetworkModule;\n cryptoInterface: Required<ICrypto>;\n libraryInfo: LibraryInfo;\n telemetry: Required<TelemetryOptions>;\n serverTelemetryManager: ServerTelemetryManager | null;\n clientCredentials: ClientCredentials;\n persistencePlugin: ICachePlugin | null;\n serializableCache: ISerializableTokenCache | null;\n};\n\n/**\n * Use this to configure the auth options in the ClientConfiguration object\n *\n * - clientId - Client ID of your app registered with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview in Microsoft Identity Platform\n * - authority - You can configure a specific authority, defaults to \" \" or \"https://login.microsoftonline.com/common\"\n * - knownAuthorities - An array of URIs that are known to be valid. Used in B2C scenarios.\n * - cloudDiscoveryMetadata - A string containing the cloud discovery response. Used in AAD scenarios.\n * - clientCapabilities - Array of capabilities which will be added to the claims.access_token.xms_cc request property on every network request.\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 * @internal\n */\nexport type AuthOptions = {\n clientId: string;\n authority: Authority;\n clientCapabilities?: Array<string>;\n azureCloudOptions?: AzureCloudOptions;\n skipAuthorityMetadataCache?: boolean;\n};\n\n/**\n * Use this to configure token renewal info in the Configuration object\n *\n * - tokenRenewalOffsetSeconds - Sets the window of offset needed to renew the token before expiry\n */\nexport type SystemOptions = {\n tokenRenewalOffsetSeconds?: number;\n preventCorsPreflight?: boolean;\n};\n\n/**\n * Use this to configure the logging that MSAL does, by configuring logger options in the Configuration object\n *\n * - loggerCallback - Callback for logger\n * - piiLoggingEnabled - Sets whether pii logging is enabled\n * - logLevel - Sets the level at which logging happens\n * - correlationId - Sets the correlationId printed by the logger\n */\nexport type LoggerOptions = {\n loggerCallback?: ILoggerCallback;\n piiLoggingEnabled?: boolean;\n logLevel?: LogLevel;\n correlationId?: string;\n};\n\n/**\n * Use this to configure credential cache preferences in the ClientConfiguration object\n *\n * - claimsBasedCachingEnabled - Sets whether tokens should be cached based on the claims hash. Default is false.\n */\nexport type CacheOptions = {\n claimsBasedCachingEnabled?: boolean;\n};\n\n/**\n * Library-specific options\n */\nexport type LibraryInfo = {\n sku: string;\n version: string;\n cpu: string;\n os: string;\n};\n\n/**\n * AzureCloudInstance specific options\n *\n * - azureCloudInstance - string enum providing short notation for soverign and public cloud authorities\n * - tenant - provision to provide the tenant info\n */\nexport type AzureCloudOptions = {\n azureCloudInstance: AzureCloudInstance;\n tenant?: string;\n};\n\nexport type TelemetryOptions = {\n application: ApplicationTelemetry;\n};\n\n/**\n * Telemetry information sent on request\n * - appName: Unique string name of an application\n * - appVersion: Version of the application using MSAL\n */\nexport type ApplicationTelemetry = {\n appName: string;\n appVersion: string;\n};\n\nexport const DEFAULT_SYSTEM_OPTIONS: Required<SystemOptions> = {\n tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,\n preventCorsPreflight: false,\n};\n\nconst DEFAULT_LOGGER_IMPLEMENTATION: Required<LoggerOptions> = {\n loggerCallback: () => {\n // allow users to not set loggerCallback\n },\n piiLoggingEnabled: false,\n logLevel: LogLevel.Info,\n correlationId: Constants.EMPTY_STRING,\n};\n\nconst DEFAULT_CACHE_OPTIONS: Required<CacheOptions> = {\n claimsBasedCachingEnabled: false,\n};\n\nconst DEFAULT_NETWORK_IMPLEMENTATION: INetworkModule = {\n async sendGetRequestAsync<T>(): Promise<T> {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n async sendPostRequestAsync<T>(): Promise<T> {\n throw createClientAuthError(ClientAuthErrorCodes.methodNotImplemented);\n },\n};\n\nconst DEFAULT_LIBRARY_INFO: LibraryInfo = {\n sku: Constants.SKU,\n version: version,\n cpu: Constants.EMPTY_STRING,\n os: Constants.EMPTY_STRING,\n};\n\nconst DEFAULT_CLIENT_CREDENTIALS: ClientCredentials = {\n clientSecret: Constants.EMPTY_STRING,\n clientAssertion: undefined,\n};\n\nconst DEFAULT_AZURE_CLOUD_OPTIONS: AzureCloudOptions = {\n azureCloudInstance: AzureCloudInstance.None,\n tenant: `${Constants.DEFAULT_COMMON_TENANT}`,\n};\n\nconst DEFAULT_TELEMETRY_OPTIONS: Required<TelemetryOptions> = {\n application: {\n appName: \"\",\n appVersion: \"\",\n },\n};\n\n/**\n * Function that sets the default options when not explicitly configured from app developer\n *\n * @param Configuration\n *\n * @returns Configuration\n */\nexport function buildClientConfiguration({\n authOptions: userAuthOptions,\n systemOptions: userSystemOptions,\n loggerOptions: userLoggerOption,\n cacheOptions: userCacheOptions,\n storageInterface: storageImplementation,\n networkInterface: networkImplementation,\n cryptoInterface: cryptoImplementation,\n clientCredentials: clientCredentials,\n libraryInfo: libraryInfo,\n telemetry: telemetry,\n serverTelemetryManager: serverTelemetryManager,\n persistencePlugin: persistencePlugin,\n serializableCache: serializableCache,\n}: ClientConfiguration): CommonClientConfiguration {\n const loggerOptions = {\n ...DEFAULT_LOGGER_IMPLEMENTATION,\n ...userLoggerOption,\n };\n\n return {\n authOptions: buildAuthOptions(userAuthOptions),\n systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions },\n loggerOptions: loggerOptions,\n cacheOptions: { ...DEFAULT_CACHE_OPTIONS, ...userCacheOptions },\n storageInterface:\n storageImplementation ||\n new DefaultStorageClass(\n userAuthOptions.clientId,\n DEFAULT_CRYPTO_IMPLEMENTATION,\n new Logger(loggerOptions)\n ),\n networkInterface:\n networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,\n cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,\n clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,\n libraryInfo: { ...DEFAULT_LIBRARY_INFO, ...libraryInfo },\n telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry },\n serverTelemetryManager: serverTelemetryManager || null,\n persistencePlugin: persistencePlugin || null,\n serializableCache: serializableCache || null,\n };\n}\n\n/**\n * Construct authoptions from the client and platform passed values\n * @param authOptions\n */\nfunction buildAuthOptions(authOptions: AuthOptions): Required<AuthOptions> {\n return {\n clientCapabilities: [],\n azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS,\n skipAuthorityMetadataCache: false,\n ...authOptions,\n };\n}\n\n/**\n * Returns true if config has protocolMode set to ProtocolMode.OIDC, false otherwise\n * @param ClientConfiguration\n */\nexport function isOidcProtocolMode(config: ClientConfiguration): boolean {\n return (\n config.authOptions.authority.options.protocolMode === ProtocolMode.OIDC\n );\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AuthError } from \"./AuthError\";\n\n/**\n * Error thrown when there is an error with the server code, for example, unavailability.\n */\nexport class ServerError extends AuthError {\n constructor(errorCode?: string, errorMessage?: string, subError?: string) {\n super(errorCode, errorMessage, subError);\n this.name = \"ServerError\";\n\n Object.setPrototypeOf(this, ServerError.prototype);\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { NetworkResponse } from \"./NetworkManager\";\nimport { ServerAuthorizationTokenResponse } from \"../response/ServerAuthorizationTokenResponse\";\nimport {\n HeaderNames,\n ThrottlingConstants,\n Constants,\n} from \"../utils/Constants\";\nimport { CacheManager } from \"../cache/CacheManager\";\nimport { ServerError } from \"../error/ServerError\";\nimport { RequestThumbprint } from \"./RequestThumbprint\";\nimport { ThrottlingEntity } from \"../cache/entities/ThrottlingEntity\";\nimport { BaseAuthRequest } from \"../request/BaseAuthRequest\";\n\n/** @internal */\nexport class ThrottlingUtils {\n /**\n * Prepares a RequestThumbprint to be stored as a key.\n * @param thumbprint\n */\n static generateThrottlingStorageKey(thumbprint: RequestThumbprint): string {\n return `${ThrottlingConstants.THROTTLING_PREFIX}.${JSON.stringify(\n thumbprint\n )}`;\n }\n\n /**\n * Performs necessary throttling checks before a network request.\n * @param cacheManager\n * @param thumbprint\n */\n static preProcess(\n cacheManager: CacheManager,\n thumbprint: RequestThumbprint\n ): void {\n const key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint);\n const value = cacheManager.getThrottlingCache(key);\n\n if (value) {\n if (value.throttleTime < Date.now()) {\n cacheManager.removeItem(key);\n return;\n }\n throw new ServerError(\n value.errorCodes?.join(\" \") || Constants.EMPTY_STRING,\n value.errorMessage,\n value.subError\n );\n }\n }\n\n /**\n * Performs necessary throttling checks after a network request.\n * @param cacheManager\n * @param thumbprint\n * @param response\n */\n static postProcess(\n cacheManager: CacheManager,\n thumbprint: RequestThumbprint,\n response: NetworkResponse<ServerAuthorizationTokenResponse>\n ): void {\n if (\n ThrottlingUtils.checkResponseStatus(response) ||\n ThrottlingUtils.checkResponseForRetryAfter(response)\n ) {\n const thumbprintValue: ThrottlingEntity = {\n throttleTime: ThrottlingUtils.calculateThrottleTime(\n parseInt(response.headers[HeaderNames.RETRY_AFTER])\n ),\n error: response.body.error,\n errorCodes: response.body.error_codes,\n errorMessage: response.body.error_description,\n subError: response.body.suberror,\n };\n cacheManager.setThrottlingCache(\n ThrottlingUtils.generateThrottlingStorageKey(thumbprint),\n thumbprintValue\n );\n }\n }\n\n /**\n * Checks a NetworkResponse object's status codes against 429 or 5xx\n * @param response\n */\n static checkResponseStatus(\n response: NetworkResponse<ServerAuthorizationTokenResponse>\n ): boolean {\n return (\n response.status === 429 ||\n (response.status >= 500 && response.status < 600)\n );\n }\n\n /**\n * Checks a NetworkResponse object's RetryAfter header\n * @param response\n */\n static checkResponseForRetryAfter(\n response: NetworkResponse<ServerAuthorizationTokenResponse>\n ): boolean {\n if (response.headers) {\n return (\n response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) &&\n (response.status < 200 || response.status >= 300)\n );\n }\n return false;\n }\n\n /**\n * Calculates the Unix-time value for a throttle to expire given throttleTime in seconds.\n * @param throttleTime\n */\n static calculateThrottleTime(throttleTime: number): number {\n const time = throttleTime <= 0 ? 0 : throttleTime;\n\n const currentSeconds = Date.now() / 1000;\n return Math.floor(\n Math.min(\n currentSeconds +\n (time || ThrottlingConstants.DEFAULT_THROTTLE_TIME_SECONDS),\n currentSeconds +\n ThrottlingConstants.DEFAULT_MAX_THROTTLE_TIME_SECONDS\n ) * 1000\n );\n }\n\n static removeThrottle(\n cacheManager: CacheManager,\n clientId: string,\n request: BaseAuthRequest,\n homeAccountIdentifier?: string\n ): void {\n const thumbprint: RequestThumbprint = {\n clientId: clientId,\n authority: request.authority,\n scopes: request.scopes,\n homeAccountIdentifier: homeAccountIdentifier,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid,\n };\n\n const key = this.generateThrottlingStorageKey(thumbprint);\n cacheManager.removeItem(key);\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { INetworkModule, NetworkRequestOptions } from \"./INetworkModule\";\nimport { RequestThumbprint } from \"./RequestThumbprint\";\nimport { ThrottlingUtils } from \"./ThrottlingUtils\";\nimport { CacheManager } from \"../cache/CacheManager\";\nimport { AuthError } from \"../error/AuthError\";\nimport {\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../error/ClientAuthError\";\nimport { ServerAuthorizationTokenResponse } from \"../response/ServerAuthorizationTokenResponse\";\n\nexport type NetworkResponse<T> = {\n headers: Record<string, string>;\n body: T;\n status: number;\n};\n\nexport type UrlToHttpRequestOptions = {\n protocol: string;\n hostname: string;\n hash: string;\n search: string;\n pathname: string;\n path: string;\n href: string;\n port?: number;\n auth?: string;\n};\n\n/** @internal */\nexport class NetworkManager {\n private networkClient: INetworkModule;\n private cacheManager: CacheManager;\n\n constructor(networkClient: INetworkModule, cacheManager: CacheManager) {\n this.networkClient = networkClient;\n this.cacheManager = cacheManager;\n }\n\n /**\n * Wraps sendPostRequestAsync with necessary preflight and postflight logic\n * @param thumbprint\n * @param tokenEndpoint\n * @param options\n */\n async sendPostRequest<T extends ServerAuthorizationTokenResponse>(\n thumbprint: RequestThumbprint,\n tokenEndpoint: string,\n options: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n ThrottlingUtils.preProcess(this.cacheManager, thumbprint);\n\n let response;\n try {\n response = await this.networkClient.sendPostRequestAsync<T>(\n tokenEndpoint,\n options\n );\n } catch (e) {\n if (e instanceof AuthError) {\n throw e;\n } else {\n throw createClientAuthError(ClientAuthErrorCodes.networkError);\n }\n }\n\n ThrottlingUtils.postProcess(this.cacheManager, thumbprint, response);\n\n return response;\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport type CcsCredential = {\n credential: string;\n type: CcsCredentialType;\n};\n\nexport const CcsCredentialType = {\n HOME_ACCOUNT_ID: \"home_account_id\",\n UPN: \"UPN\",\n} as const;\nexport type CcsCredentialType =\n (typeof CcsCredentialType)[keyof typeof CcsCredentialType];\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport const CLIENT_ID = \"client_id\";\nexport const REDIRECT_URI = \"redirect_uri\";\nexport const RESPONSE_TYPE = \"response_type\";\nexport const RESPONSE_MODE = \"response_mode\";\nexport const GRANT_TYPE = \"grant_type\";\nexport const CLAIMS = \"claims\";\nexport const SCOPE = \"scope\";\nexport const ERROR = \"error\";\nexport const ERROR_DESCRIPTION = \"error_description\";\nexport const ACCESS_TOKEN = \"access_token\";\nexport const ID_TOKEN = \"id_token\";\nexport const REFRESH_TOKEN = \"refresh_token\";\nexport const EXPIRES_IN = \"expires_in\";\nexport const REFRESH_TOKEN_EXPIRES_IN = \"refresh_token_expires_in\";\nexport const STATE = \"state\";\nexport const NONCE = \"nonce\";\nexport const PROMPT = \"prompt\";\nexport const SESSION_STATE = \"session_state\";\nexport const CLIENT_INFO = \"client_info\";\nexport const CODE = \"code\";\nexport const CODE_CHALLENGE = \"code_challenge\";\nexport const CODE_CHALLENGE_METHOD = \"code_challenge_method\";\nexport const CODE_VERIFIER = \"code_verifier\";\nexport const CLIENT_REQUEST_ID = \"client-request-id\";\nexport const X_CLIENT_SKU = \"x-client-SKU\";\nexport const X_CLIENT_VER = \"x-client-VER\";\nexport const X_CLIENT_OS = \"x-client-OS\";\nexport const X_CLIENT_CPU = \"x-client-CPU\";\nexport const X_CLIENT_CURR_TELEM = \"x-client-current-telemetry\";\nexport const X_CLIENT_LAST_TELEM = \"x-client-last-telemetry\";\nexport const X_MS_LIB_CAPABILITY = \"x-ms-lib-capability\";\nexport const X_APP_NAME = \"x-app-name\";\nexport const X_APP_VER = \"x-app-ver\";\nexport const POST_LOGOUT_URI = \"post_logout_redirect_uri\";\nexport const ID_TOKEN_HINT = \"id_token_hint\";\nexport const DEVICE_CODE = \"device_code\";\nexport const CLIENT_SECRET = \"client_secret\";\nexport const CLIENT_ASSERTION = \"client_assertion\";\nexport const CLIENT_ASSERTION_TYPE = \"client_assertion_type\";\nexport const TOKEN_TYPE = \"token_type\";\nexport const REQ_CNF = \"req_cnf\";\nexport const OBO_ASSERTION = \"assertion\";\nexport const REQUESTED_TOKEN_USE = \"requested_token_use\";\nexport const ON_BEHALF_OF = \"on_behalf_of\";\nexport const FOCI = \"foci\";\nexport const CCS_HEADER = \"X-AnchorMailbox\";\nexport const RETURN_SPA_CODE = \"return_spa_code\";\nexport const NATIVE_BROKER = \"nativebroker\";\nexport const LOGOUT_HINT = \"logout_hint\";\nexport const SID = \"sid\";\nexport const LOGIN_HINT = \"login_hint\";\nexport const DOMAIN_HINT = \"domain_hint\";\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n createClientConfigurationError,\n ClientConfigurationErrorCodes,\n} from \"../error/ClientConfigurationError\";\nimport { PromptValue, CodeChallengeMethodValues } from \"../utils/Constants\";\nimport { StringDict } from \"../utils/MsalTypes\";\n\n/**\n * Validates server consumable params from the \"request\" objects\n */\nexport class RequestValidator {\n /**\n * Utility to check if the `redirectUri` in the request is a non-null value\n * @param redirectUri\n */\n static validateRedirectUri(redirectUri: string): void {\n if (!redirectUri) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.redirectUriEmpty\n );\n }\n }\n\n /**\n * Utility to validate prompt sent by the user in the request\n * @param prompt\n */\n static validatePrompt(prompt: string): void {\n const promptValues = [];\n\n for (const value in PromptValue) {\n promptValues.push(PromptValue[value]);\n }\n\n if (promptValues.indexOf(prompt) < 0) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.invalidPromptValue\n );\n }\n }\n\n static validateClaims(claims: string): void {\n try {\n JSON.parse(claims);\n } catch (e) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.invalidClaims\n );\n }\n }\n\n /**\n * Utility to validate code_challenge and code_challenge_method\n * @param codeChallenge\n * @param codeChallengeMethod\n */\n static validateCodeChallengeParams(\n codeChallenge: string,\n codeChallengeMethod: string\n ): void {\n if (!codeChallenge || !codeChallengeMethod) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.pkceParamsMissing\n );\n } else {\n this.validateCodeChallengeMethod(codeChallengeMethod);\n }\n }\n\n /**\n * Utility to validate code_challenge_method\n * @param codeChallengeMethod\n */\n static validateCodeChallengeMethod(codeChallengeMethod: string): void {\n if (\n [\n CodeChallengeMethodValues.PLAIN,\n CodeChallengeMethodValues.S256,\n ].indexOf(codeChallengeMethod) < 0\n ) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.invalidCodeChallengeMethod\n );\n }\n }\n\n /**\n * Removes unnecessary, duplicate, and empty string query parameters from extraQueryParameters\n * @param request\n */\n static sanitizeEQParams(\n eQParams: StringDict,\n queryParams: Map<string, string>\n ): StringDict {\n if (!eQParams) {\n return {};\n }\n\n // Remove any query parameters already included in SSO params\n queryParams.forEach((_value, key) => {\n if (eQParams[key]) {\n delete eQParams[key];\n }\n });\n\n // remove empty string parameters\n return Object.fromEntries(\n Object.entries(eQParams).filter((kv) => kv[1] !== \"\")\n );\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n Constants,\n ResponseMode,\n CLIENT_INFO,\n AuthenticationScheme,\n ClaimsRequestKeys,\n PasswordGrantConstants,\n OIDC_DEFAULT_SCOPES,\n ThrottlingConstants,\n HeaderNames,\n} from \"../utils/Constants\";\nimport * as AADServerParamKeys from \"../constants/AADServerParamKeys\";\nimport { ScopeSet } from \"./ScopeSet\";\nimport {\n createClientConfigurationError,\n ClientConfigurationErrorCodes,\n} from \"../error/ClientConfigurationError\";\nimport { StringDict } from \"../utils/MsalTypes\";\nimport { RequestValidator } from \"./RequestValidator\";\nimport {\n ApplicationTelemetry,\n LibraryInfo,\n} from \"../config/ClientConfiguration\";\nimport { ServerTelemetryManager } from \"../telemetry/server/ServerTelemetryManager\";\nimport { ClientInfo } from \"../account/ClientInfo\";\n\n/** @internal */\nexport class RequestParameterBuilder {\n private parameters: Map<string, string>;\n\n constructor() {\n this.parameters = new Map<string, string>();\n }\n\n /**\n * add response_type = code\n */\n addResponseTypeCode(): void {\n this.parameters.set(\n AADServerParamKeys.RESPONSE_TYPE,\n encodeURIComponent(Constants.CODE_RESPONSE_TYPE)\n );\n }\n\n /**\n * add response_type = token id_token\n */\n addResponseTypeForTokenAndIdToken(): void {\n this.parameters.set(\n AADServerParamKeys.RESPONSE_TYPE,\n encodeURIComponent(\n `${Constants.TOKEN_RESPONSE_TYPE} ${Constants.ID_TOKEN_RESPONSE_TYPE}`\n )\n );\n }\n\n /**\n * add response_mode. defaults to query.\n * @param responseMode\n */\n addResponseMode(responseMode?: ResponseMode): void {\n this.parameters.set(\n AADServerParamKeys.RESPONSE_MODE,\n encodeURIComponent(responseMode ? responseMode : ResponseMode.QUERY)\n );\n }\n\n /**\n * Add flag to indicate STS should attempt to use WAM if available\n */\n addNativeBroker(): void {\n this.parameters.set(\n AADServerParamKeys.NATIVE_BROKER,\n encodeURIComponent(\"1\")\n );\n }\n\n /**\n * add scopes. set addOidcScopes to false to prevent default scopes in non-user scenarios\n * @param scopeSet\n * @param addOidcScopes\n */\n addScopes(\n scopes: string[],\n addOidcScopes: boolean = true,\n defaultScopes: Array<string> = OIDC_DEFAULT_SCOPES\n ): void {\n // Always add openid to the scopes when adding OIDC scopes\n if (\n addOidcScopes &&\n !defaultScopes.includes(\"openid\") &&\n !scopes.includes(\"openid\")\n ) {\n defaultScopes.push(\"openid\");\n }\n const requestScopes = addOidcScopes\n ? [...(scopes || []), ...defaultScopes]\n : scopes || [];\n const scopeSet = new ScopeSet(requestScopes);\n this.parameters.set(\n AADServerParamKeys.SCOPE,\n encodeURIComponent(scopeSet.printScopes())\n );\n }\n\n /**\n * add clientId\n * @param clientId\n */\n addClientId(clientId: string): void {\n this.parameters.set(\n AADServerParamKeys.CLIENT_ID,\n encodeURIComponent(clientId)\n );\n }\n\n /**\n * add redirect_uri\n * @param redirectUri\n */\n addRedirectUri(redirectUri: string): void {\n RequestValidator.validateRedirectUri(redirectUri);\n this.parameters.set(\n AADServerParamKeys.REDIRECT_URI,\n encodeURIComponent(redirectUri)\n );\n }\n\n /**\n * add post logout redirectUri\n * @param redirectUri\n */\n addPostLogoutRedirectUri(redirectUri: string): void {\n RequestValidator.validateRedirectUri(redirectUri);\n this.parameters.set(\n AADServerParamKeys.POST_LOGOUT_URI,\n encodeURIComponent(redirectUri)\n );\n }\n\n /**\n * add id_token_hint to logout request\n * @param idTokenHint\n */\n addIdTokenHint(idTokenHint: string): void {\n this.parameters.set(\n AADServerParamKeys.ID_TOKEN_HINT,\n encodeURIComponent(idTokenHint)\n );\n }\n\n /**\n * add domain_hint\n * @param domainHint\n */\n addDomainHint(domainHint: string): void {\n this.parameters.set(\n AADServerParamKeys.DOMAIN_HINT,\n encodeURIComponent(domainHint)\n );\n }\n\n /**\n * add login_hint\n * @param loginHint\n */\n addLoginHint(loginHint: string): void {\n this.parameters.set(\n AADServerParamKeys.LOGIN_HINT,\n encodeURIComponent(loginHint)\n );\n }\n\n /**\n * Adds the CCS (Cache Credential Service) query parameter for login_hint\n * @param loginHint\n */\n addCcsUpn(loginHint: string): void {\n this.parameters.set(\n HeaderNames.CCS_HEADER,\n encodeURIComponent(`UPN:${loginHint}`)\n );\n }\n\n /**\n * Adds the CCS (Cache Credential Service) query parameter for account object\n * @param loginHint\n */\n addCcsOid(clientInfo: ClientInfo): void {\n this.parameters.set(\n HeaderNames.CCS_HEADER,\n encodeURIComponent(`Oid:${clientInfo.uid}@${clientInfo.utid}`)\n );\n }\n\n /**\n * add sid\n * @param sid\n */\n addSid(sid: string): void {\n this.parameters.set(AADServerParamKeys.SID, encodeURIComponent(sid));\n }\n\n /**\n * add claims\n * @param claims\n */\n addClaims(claims?: string, clientCapabilities?: Array<string>): void {\n const mergedClaims = this.addClientCapabilitiesToClaims(\n claims,\n clientCapabilities\n );\n RequestValidator.validateClaims(mergedClaims);\n this.parameters.set(\n AADServerParamKeys.CLAIMS,\n encodeURIComponent(mergedClaims)\n );\n }\n\n /**\n * add correlationId\n * @param correlationId\n */\n addCorrelationId(correlationId: string): void {\n this.parameters.set(\n AADServerParamKeys.CLIENT_REQUEST_ID,\n encodeURIComponent(correlationId)\n );\n }\n\n /**\n * add library info query params\n * @param libraryInfo\n */\n addLibraryInfo(libraryInfo: LibraryInfo): void {\n // Telemetry Info\n this.parameters.set(AADServerParamKeys.X_CLIENT_SKU, libraryInfo.sku);\n this.parameters.set(\n AADServerParamKeys.X_CLIENT_VER,\n libraryInfo.version\n );\n if (libraryInfo.os) {\n this.parameters.set(AADServerParamKeys.X_CLIENT_OS, libraryInfo.os);\n }\n if (libraryInfo.cpu) {\n this.parameters.set(\n AADServerParamKeys.X_CLIENT_CPU,\n libraryInfo.cpu\n );\n }\n }\n\n /**\n * Add client telemetry parameters\n * @param appTelemetry\n */\n addApplicationTelemetry(appTelemetry: ApplicationTelemetry): void {\n if (appTelemetry?.appName) {\n this.parameters.set(\n AADServerParamKeys.X_APP_NAME,\n appTelemetry.appName\n );\n }\n\n if (appTelemetry?.appVersion) {\n this.parameters.set(\n AADServerParamKeys.X_APP_VER,\n appTelemetry.appVersion\n );\n }\n }\n\n /**\n * add prompt\n * @param prompt\n */\n addPrompt(prompt: string): void {\n RequestValidator.validatePrompt(prompt);\n this.parameters.set(\n `${AADServerParamKeys.PROMPT}`,\n encodeURIComponent(prompt)\n );\n }\n\n /**\n * add state\n * @param state\n */\n addState(state: string): void {\n if (state) {\n this.parameters.set(\n AADServerParamKeys.STATE,\n encodeURIComponent(state)\n );\n }\n }\n\n /**\n * add nonce\n * @param nonce\n */\n addNonce(nonce: string): void {\n this.parameters.set(\n AADServerParamKeys.NONCE,\n encodeURIComponent(nonce)\n );\n }\n\n /**\n * add code_challenge and code_challenge_method\n * - throw if either of them are not passed\n * @param codeChallenge\n * @param codeChallengeMethod\n */\n addCodeChallengeParams(\n codeChallenge: string,\n codeChallengeMethod: string\n ): void {\n RequestValidator.validateCodeChallengeParams(\n codeChallenge,\n codeChallengeMethod\n );\n if (codeChallenge && codeChallengeMethod) {\n this.parameters.set(\n AADServerParamKeys.CODE_CHALLENGE,\n encodeURIComponent(codeChallenge)\n );\n this.parameters.set(\n AADServerParamKeys.CODE_CHALLENGE_METHOD,\n encodeURIComponent(codeChallengeMethod)\n );\n } else {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.pkceParamsMissing\n );\n }\n }\n\n /**\n * add the `authorization_code` passed by the user to exchange for a token\n * @param code\n */\n addAuthorizationCode(code: string): void {\n this.parameters.set(AADServerParamKeys.CODE, encodeURIComponent(code));\n }\n\n /**\n * add the `authorization_code` passed by the user to exchange for a token\n * @param code\n */\n addDeviceCode(code: string): void {\n this.parameters.set(\n AADServerParamKeys.DEVICE_CODE,\n encodeURIComponent(code)\n );\n }\n\n /**\n * add the `refreshToken` passed by the user\n * @param refreshToken\n */\n addRefreshToken(refreshToken: string): void {\n this.parameters.set(\n AADServerParamKeys.REFRESH_TOKEN,\n encodeURIComponent(refreshToken)\n );\n }\n\n /**\n * add the `code_verifier` passed by the user to exchange for a token\n * @param codeVerifier\n */\n addCodeVerifier(codeVerifier: string): void {\n this.parameters.set(\n AADServerParamKeys.CODE_VERIFIER,\n encodeURIComponent(codeVerifier)\n );\n }\n\n /**\n * add client_secret\n * @param clientSecret\n */\n addClientSecret(clientSecret: string): void {\n this.parameters.set(\n AADServerParamKeys.CLIENT_SECRET,\n encodeURIComponent(clientSecret)\n );\n }\n\n /**\n * add clientAssertion for confidential client flows\n * @param clientAssertion\n */\n addClientAssertion(clientAssertion: string): void {\n if (clientAssertion) {\n this.parameters.set(\n AADServerParamKeys.CLIENT_ASSERTION,\n encodeURIComponent(clientAssertion)\n );\n }\n }\n\n /**\n * add clientAssertionType for confidential client flows\n * @param clientAssertionType\n */\n addClientAssertionType(clientAssertionType: string): void {\n if (clientAssertionType) {\n this.parameters.set(\n AADServerParamKeys.CLIENT_ASSERTION_TYPE,\n encodeURIComponent(clientAssertionType)\n );\n }\n }\n\n /**\n * add OBO assertion for confidential client flows\n * @param clientAssertion\n */\n addOboAssertion(oboAssertion: string): void {\n this.parameters.set(\n AADServerParamKeys.OBO_ASSERTION,\n encodeURIComponent(oboAssertion)\n );\n }\n\n /**\n * add grant type\n * @param grantType\n */\n addRequestTokenUse(tokenUse: string): void {\n this.parameters.set(\n AADServerParamKeys.REQUESTED_TOKEN_USE,\n encodeURIComponent(tokenUse)\n );\n }\n\n /**\n * add grant type\n * @param grantType\n */\n addGrantType(grantType: string): void {\n this.parameters.set(\n AADServerParamKeys.GRANT_TYPE,\n encodeURIComponent(grantType)\n );\n }\n\n /**\n * add client info\n *\n */\n addClientInfo(): void {\n this.parameters.set(CLIENT_INFO, \"1\");\n }\n\n /**\n * add extraQueryParams\n * @param eQParams\n */\n addExtraQueryParameters(eQParams: StringDict): void {\n const sanitizedEQParams = RequestValidator.sanitizeEQParams(\n eQParams,\n this.parameters\n );\n Object.keys(sanitizedEQParams).forEach((key) => {\n this.parameters.set(key, eQParams[key]);\n });\n }\n\n addClientCapabilitiesToClaims(\n claims?: string,\n clientCapabilities?: Array<string>\n ): string {\n let mergedClaims: object;\n\n // Parse provided claims into JSON object or initialize empty object\n if (!claims) {\n mergedClaims = {};\n } else {\n try {\n mergedClaims = JSON.parse(claims);\n } catch (e) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.invalidClaims\n );\n }\n }\n\n if (clientCapabilities && clientCapabilities.length > 0) {\n if (!mergedClaims.hasOwnProperty(ClaimsRequestKeys.ACCESS_TOKEN)) {\n // Add access_token key to claims object\n mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN] = {};\n }\n\n // Add xms_cc claim with provided clientCapabilities to access_token key\n mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][\n ClaimsRequestKeys.XMS_CC\n ] = {\n values: clientCapabilities,\n };\n }\n\n return JSON.stringify(mergedClaims);\n }\n\n /**\n * adds `username` for Password Grant flow\n * @param username\n */\n addUsername(username: string): void {\n this.parameters.set(\n PasswordGrantConstants.username,\n encodeURIComponent(username)\n );\n }\n\n /**\n * adds `password` for Password Grant flow\n * @param password\n */\n addPassword(password: string): void {\n this.parameters.set(\n PasswordGrantConstants.password,\n encodeURIComponent(password)\n );\n }\n\n /**\n * add pop_jwk to query params\n * @param cnfString\n */\n addPopToken(cnfString: string): void {\n if (cnfString) {\n this.parameters.set(\n AADServerParamKeys.TOKEN_TYPE,\n AuthenticationScheme.POP\n );\n this.parameters.set(\n AADServerParamKeys.REQ_CNF,\n encodeURIComponent(cnfString)\n );\n }\n }\n\n /**\n * add SSH JWK and key ID to query params\n */\n addSshJwk(sshJwkString: string): void {\n if (sshJwkString) {\n this.parameters.set(\n AADServerParamKeys.TOKEN_TYPE,\n AuthenticationScheme.SSH\n );\n this.parameters.set(\n AADServerParamKeys.REQ_CNF,\n encodeURIComponent(sshJwkString)\n );\n }\n }\n\n /**\n * add server telemetry fields\n * @param serverTelemetryManager\n */\n addServerTelemetry(serverTelemetryManager: ServerTelemetryManager): void {\n this.parameters.set(\n AADServerParamKeys.X_CLIENT_CURR_TELEM,\n serverTelemetryManager.generateCurrentRequestHeaderValue()\n );\n this.parameters.set(\n AADServerParamKeys.X_CLIENT_LAST_TELEM,\n serverTelemetryManager.generateLastRequestHeaderValue()\n );\n }\n\n /**\n * Adds parameter that indicates to the server that throttling is supported\n */\n addThrottling(): void {\n this.parameters.set(\n AADServerParamKeys.X_MS_LIB_CAPABILITY,\n ThrottlingConstants.X_MS_LIB_CAPABILITY_VALUE\n );\n }\n\n /**\n * Adds logout_hint parameter for \"silent\" logout which prevent server account picker\n */\n addLogoutHint(logoutHint: string): void {\n this.parameters.set(\n AADServerParamKeys.LOGOUT_HINT,\n encodeURIComponent(logoutHint)\n );\n }\n\n /**\n * Utility to create a URL from the params map\n */\n createQueryString(): string {\n const queryParameterArray: Array<string> = new Array<string>();\n\n this.parameters.forEach((value, key) => {\n queryParameterArray.push(`${key}=${value}`);\n });\n\n return queryParameterArray.join(\"&\");\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Tenant Discovery Response which contains the relevant OAuth endpoints and data needed for authentication and authorization.\n */\nexport type OpenIdConfigResponse = {\n authorization_endpoint: string;\n token_endpoint: string;\n end_session_endpoint?: string;\n issuer: string;\n jwks_uri: string;\n};\n\nexport function isOpenIdConfigResponse(response: object): boolean {\n return (\n response.hasOwnProperty(\"authorization_endpoint\") &&\n response.hasOwnProperty(\"token_endpoint\") &&\n response.hasOwnProperty(\"issuer\") &&\n response.hasOwnProperty(\"jwks_uri\")\n );\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { CloudDiscoveryMetadata } from \"./CloudDiscoveryMetadata\";\n\n/**\n * The OpenID Configuration Endpoint Response type. Used by the authority class to get relevant OAuth endpoints.\n */\nexport type CloudInstanceDiscoveryResponse = {\n tenant_discovery_endpoint: string;\n metadata: Array<CloudDiscoveryMetadata>;\n};\n\nexport function isCloudInstanceDiscoveryResponse(response: object): boolean {\n return (\n response.hasOwnProperty(\"tenant_discovery_endpoint\") &&\n response.hasOwnProperty(\"metadata\")\n );\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * The OpenID Configuration Endpoint Response type. Used by the authority class to get relevant OAuth endpoints.\n */\nexport type CloudInstanceDiscoveryErrorResponse = {\n error: String;\n error_description: String;\n error_codes?: Array<Number>;\n timestamp?: String;\n trace_id?: String;\n correlation_id?: String;\n error_uri?: String;\n};\n\nexport function isCloudInstanceDiscoveryErrorResponse(\n response: object\n): boolean {\n return (\n response.hasOwnProperty(\"error\") &&\n response.hasOwnProperty(\"error_description\")\n );\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Enumeration of operations that are instrumented by have their performance measured by the PerformanceClient.\n *\n * @export\n * @enum {number}\n */\nexport const PerformanceEvents = {\n /**\n * acquireTokenByCode API (msal-browser and msal-node).\n * Used to acquire tokens by trading an authorization code against the token endpoint.\n */\n AcquireTokenByCode: \"acquireTokenByCode\",\n\n /**\n * acquireTokenByRefreshToken API (msal-browser and msal-node).\n * Used to renew an access token using a refresh token against the token endpoint.\n */\n AcquireTokenByRefreshToken: \"acquireTokenByRefreshToken\",\n\n /**\n * acquireTokenSilent API (msal-browser and msal-node).\n * Used to silently acquire a new access token (from the cache or the network).\n */\n AcquireTokenSilent: \"acquireTokenSilent\",\n\n /**\n * acquireTokenSilentAsync (msal-browser).\n * Internal API for acquireTokenSilent.\n */\n AcquireTokenSilentAsync: \"acquireTokenSilentAsync\",\n\n /**\n * acquireTokenPopup (msal-browser).\n * Used to acquire a new access token interactively through pop ups\n */\n AcquireTokenPopup: \"acquireTokenPopup\",\n\n /**\n * getPublicKeyThumbprint API in CryptoOpts class (msal-browser).\n * Used to generate a public/private keypair and generate a public key thumbprint for pop requests.\n */\n CryptoOptsGetPublicKeyThumbprint: \"cryptoOptsGetPublicKeyThumbprint\",\n\n /**\n * signJwt API in CryptoOpts class (msal-browser).\n * Used to signed a pop token.\n */\n CryptoOptsSignJwt: \"cryptoOptsSignJwt\",\n\n /**\n * acquireToken API in the SilentCacheClient class (msal-browser).\n * Used to read access tokens from the cache.\n */\n SilentCacheClientAcquireToken: \"silentCacheClientAcquireToken\",\n\n /**\n * acquireToken API in the SilentIframeClient class (msal-browser).\n * Used to acquire a new set of tokens from the authorize endpoint in a hidden iframe.\n */\n SilentIframeClientAcquireToken: \"silentIframeClientAcquireToken\",\n\n /**\n * acquireToken API in SilentRereshClient (msal-browser).\n * Used to acquire a new set of tokens from the token endpoint using a refresh token.\n */\n SilentRefreshClientAcquireToken: \"silentRefreshClientAcquireToken\",\n\n /**\n * ssoSilent API (msal-browser).\n * Used to silently acquire an authorization code and set of tokens using a hidden iframe.\n */\n SsoSilent: \"ssoSilent\",\n\n /**\n * getDiscoveredAuthority API in StandardInteractionClient class (msal-browser).\n * Used to load authority metadata for a request.\n */\n StandardInteractionClientGetDiscoveredAuthority:\n \"standardInteractionClientGetDiscoveredAuthority\",\n\n /**\n * acquireToken APIs in msal-browser.\n * Used to make an /authorize endpoint call with native brokering enabled.\n */\n FetchAccountIdWithNativeBroker: \"fetchAccountIdWithNativeBroker\",\n\n /**\n * acquireToken API in NativeInteractionClient class (msal-browser).\n * Used to acquire a token from Native component when native brokering is enabled.\n */\n NativeInteractionClientAcquireToken: \"nativeInteractionClientAcquireToken\",\n /**\n * Time spent creating default headers for requests to token endpoint\n */\n BaseClientCreateTokenRequestHeaders: \"baseClientCreateTokenRequestHeaders\",\n /**\n * Time spent sending/waiting for the response of a request to the token endpoint\n */\n RefreshTokenClientExecutePostToTokenEndpoint:\n \"refreshTokenClientExecutePostToTokenEndpoint\",\n AuthorizationCodeClientExecutePostToTokenEndpoint:\n \"authorizationCodeClientExecutePostToTokenEndpoint\",\n /**\n * Used to measure the time taken for completing embedded-broker handshake (PW-Broker).\n */\n BrokerHandhshake: \"brokerHandshake\",\n /**\n * acquireTokenByRefreshToken API in BrokerClientApplication (PW-Broker) .\n */\n AcquireTokenByRefreshTokenInBroker: \"acquireTokenByRefreshTokenInBroker\",\n /**\n * Time taken for token acquisition by broker\n */\n AcquireTokenByBroker: \"acquireTokenByBroker\",\n\n /**\n * Time spent on the network for refresh token acquisition\n */\n RefreshTokenClientExecuteTokenRequest:\n \"refreshTokenClientExecuteTokenRequest\",\n\n /**\n * Time taken for acquiring refresh token , records RT size\n */\n RefreshTokenClientAcquireToken: \"refreshTokenClientAcquireToken\",\n\n /**\n * Time taken for acquiring cached refresh token\n */\n RefreshTokenClientAcquireTokenWithCachedRefreshToken:\n \"refreshTokenClientAcquireTokenWithCachedRefreshToken\",\n\n /**\n * acquireTokenByRefreshToken API in RefreshTokenClient (msal-common).\n */\n RefreshTokenClientAcquireTokenByRefreshToken:\n \"refreshTokenClientAcquireTokenByRefreshToken\",\n\n /**\n * Helper function to create token request body in RefreshTokenClient (msal-common).\n */\n RefreshTokenClientCreateTokenRequestBody:\n \"refreshTokenClientCreateTokenRequestBody\",\n\n /**\n * acquireTokenFromCache (msal-browser).\n * Internal API for acquiring token from cache\n */\n AcquireTokenFromCache: \"acquireTokenFromCache\",\n SilentFlowClientAcquireCachedToken: \"silentFlowClientAcquireCachedToken\",\n SilentFlowClientGenerateResultFromCacheRecord:\n \"silentFlowClientGenerateResultFromCacheRecord\",\n\n /**\n * acquireTokenBySilentIframe (msal-browser).\n * Internal API for acquiring token by silent Iframe\n */\n AcquireTokenBySilentIframe: \"acquireTokenBySilentIframe\",\n\n /**\n * Internal API for initializing base request in BaseInteractionClient (msal-browser)\n */\n InitializeBaseRequest: \"initializeBaseRequest\",\n\n /**\n * Internal API for initializing silent request in SilentCacheClient (msal-browser)\n */\n InitializeSilentRequest: \"initializeSilentRequest\",\n\n InitializeClientApplication: \"initializeClientApplication\",\n\n /**\n * Helper function in SilentIframeClient class (msal-browser).\n */\n SilentIframeClientTokenHelper: \"silentIframeClientTokenHelper\",\n\n /**\n * SilentHandler\n */\n SilentHandlerInitiateAuthRequest: \"silentHandlerInitiateAuthRequest\",\n SilentHandlerMonitorIframeForHash: \"silentHandlerMonitorIframeForHash\",\n SilentHandlerLoadFrame: \"silentHandlerLoadFrame\",\n SilentHandlerLoadFrameSync: \"silentHandlerLoadFrameSync\",\n\n /**\n * Helper functions in StandardInteractionClient class (msal-browser)\n */\n StandardInteractionClientCreateAuthCodeClient:\n \"standardInteractionClientCreateAuthCodeClient\",\n StandardInteractionClientGetClientConfiguration:\n \"standardInteractionClientGetClientConfiguration\",\n StandardInteractionClientInitializeAuthorizationRequest:\n \"standardInteractionClientInitializeAuthorizationRequest\",\n StandardInteractionClientInitializeAuthorizationCodeRequest:\n \"standardInteractionClientInitializeAuthorizationCodeRequest\",\n\n /**\n * getAuthCodeUrl API (msal-browser and msal-node).\n */\n GetAuthCodeUrl: \"getAuthCodeUrl\",\n\n /**\n * Functions from InteractionHandler (msal-browser)\n */\n HandleCodeResponseFromServer: \"handleCodeResponseFromServer\",\n HandleCodeResponse: \"handleCodeResponse\",\n UpdateTokenEndpointAuthority: \"updateTokenEndpointAuthority\",\n\n /**\n * APIs in Authorization Code Client (msal-common)\n */\n AuthClientAcquireToken: \"authClientAcquireToken\",\n AuthClientExecuteTokenRequest: \"authClientExecuteTokenRequest\",\n AuthClientCreateTokenRequestBody: \"authClientCreateTokenRequestBody\",\n AuthClientCreateQueryString: \"authClientCreateQueryString\",\n\n /**\n * Generate functions in PopTokenGenerator (msal-common)\n */\n PopTokenGenerateCnf: \"popTokenGenerateCnf\",\n PopTokenGenerateKid: \"popTokenGenerateKid\",\n\n /**\n * handleServerTokenResponse API in ResponseHandler (msal-common)\n */\n HandleServerTokenResponse: \"handleServerTokenResponse\",\n DeserializeResponse: \"deserializeResponse\",\n\n /**\n * Authority functions\n */\n AuthorityFactoryCreateDiscoveredInstance:\n \"authorityFactoryCreateDiscoveredInstance\",\n AuthorityResolveEndpointsAsync: \"authorityResolveEndpointsAsync\",\n AuthorityResolveEndpointsFromLocalSources:\n \"authorityResolveEndpointsFromLocalSources\",\n AuthorityGetCloudDiscoveryMetadataFromNetwork:\n \"authorityGetCloudDiscoveryMetadataFromNetwork\",\n AuthorityUpdateCloudDiscoveryMetadata:\n \"authorityUpdateCloudDiscoveryMetadata\",\n AuthorityGetEndpointMetadataFromNetwork:\n \"authorityGetEndpointMetadataFromNetwork\",\n AuthorityUpdateEndpointMetadata: \"authorityUpdateEndpointMetadata\",\n AuthorityUpdateMetadataWithRegionalInformation:\n \"authorityUpdateMetadataWithRegionalInformation\",\n\n /**\n * Region Discovery functions\n */\n RegionDiscoveryDetectRegion: \"regionDiscoveryDetectRegion\",\n RegionDiscoveryGetRegionFromIMDS: \"regionDiscoveryGetRegionFromIMDS\",\n RegionDiscoveryGetCurrentVersion: \"regionDiscoveryGetCurrentVersion\",\n\n AcquireTokenByCodeAsync: \"acquireTokenByCodeAsync\",\n\n GetEndpointMetadataFromNetwork: \"getEndpointMetadataFromNetwork\",\n GetCloudDiscoveryMetadataFromNetworkMeasurement:\n \"getCloudDiscoveryMetadataFromNetworkMeasurement\",\n\n HandleRedirectPromiseMeasurement: \"handleRedirectPromiseMeasurement\",\n\n UpdateCloudDiscoveryMetadataMeasurement:\n \"updateCloudDiscoveryMetadataMeasurement\",\n\n UsernamePasswordClientAcquireToken: \"usernamePasswordClientAcquireToken\",\n\n NativeMessageHandlerHandshake: \"nativeMessageHandlerHandshake\",\n\n NativeGenerateAuthResult: \"nativeGenerateAuthResult\",\n\n RemoveHiddenIframe: \"removeHiddenIframe\",\n\n /**\n * Cache operations\n */\n ClearTokensAndKeysWithClaims: \"clearTokensAndKeysWithClaims\",\n CacheManagerGetRefreshToken: \"cacheManagerGetRefreshToken\",\n\n /**\n * Crypto Operations\n */\n GeneratePkceCodes: \"generatePkceCodes\",\n GenerateCodeVerifier: \"generateCodeVerifier\",\n GenerateCodeChallengeFromVerifier: \"generateCodeChallengeFromVerifier\",\n Sha256Digest: \"sha256Digest\",\n GetRandomValues: \"getRandomValues\",\n} as const;\nexport type PerformanceEvents =\n (typeof PerformanceEvents)[keyof typeof PerformanceEvents];\n\n/**\n * State of the performance event.\n *\n * @export\n * @enum {number}\n */\nexport const PerformanceEventStatus = {\n NotStarted: 0,\n InProgress: 1,\n Completed: 2,\n} as const;\nexport type PerformanceEventStatus =\n (typeof PerformanceEventStatus)[keyof typeof PerformanceEventStatus];\n\nexport type SubMeasurement = {\n name: string;\n startTimeMs: number;\n};\n\n/**\n * Performance measurement taken by the library, including metadata about the request and application.\n *\n * @export\n * @typedef {PerformanceEvent}\n */\nexport type PerformanceEvent = {\n /**\n * Unique id for the event\n *\n * @type {string}\n */\n eventId: string;\n\n /**\n * State of the perforance measure.\n *\n * @type {PerformanceEventStatus}\n */\n status: PerformanceEventStatus;\n\n /**\n * Login authority used for the request\n *\n * @type {string}\n */\n authority: string;\n\n /**\n * Client id for the application\n *\n * @type {string}\n */\n clientId: string;\n\n /**\n * Correlation ID used for the request\n *\n * @type {string}\n */\n correlationId: string;\n\n /**\n * End-to-end duration in milliseconds.\n * @date 3/22/2022 - 3:40:05 PM\n *\n * @type {number}\n */\n durationMs?: number;\n\n /**\n * Visibility of the page when the event completed.\n * Read from: https://developer.mozilla.org/docs/Web/API/Page_Visibility_API\n *\n * @type {?(string | null)}\n */\n endPageVisibility?: string | null;\n\n /**\n * Whether the result was retrieved from the cache.\n *\n * @type {(boolean | null)}\n */\n fromCache?: boolean | null;\n\n /**\n * Event name (usually in the form of classNameFunctionName)\n *\n * @type {string}\n */\n name: string;\n\n /**\n * Visibility of the page when the event completed.\n * Read from: https://developer.mozilla.org/docs/Web/API/Page_Visibility_API\n *\n * @type {?(string | null)}\n */\n startPageVisibility?: string | null;\n\n /**\n * Unix millisecond timestamp when the event was initiated.\n *\n * @type {number}\n */\n startTimeMs: number;\n\n /**\n * Whether or the operation completed successfully.\n *\n * @type {(boolean | null)}\n */\n success?: boolean | null;\n\n /**\n * Add specific error code in case of failure\n *\n * @type {string}\n */\n errorCode?: string;\n\n /**\n * Add specific sub error code in case of failure\n *\n * @type {string}\n */\n subErrorCode?: string;\n\n /**\n * Name of the library used for the operation.\n *\n * @type {string}\n */\n libraryName: string;\n\n /**\n * Version of the library used for the operation.\n *\n * @type {string}\n */\n libraryVersion: string;\n\n /**\n * Whether the response is from a native component (e.g., WAM)\n *\n * @type {?boolean}\n */\n isNativeBroker?: boolean;\n\n /**\n * Request ID returned from the response\n *\n * @type {?string}\n */\n requestId?: string;\n\n /**\n * Cache lookup policy\n *\n * @type {?number}\n */\n cacheLookupPolicy?: number | undefined;\n\n /**\n * Cache Outcome\n * @type {?number}\n */\n cacheOutcome?: number;\n\n /**\n * Amount of time spent in the JS queue in milliseconds.\n *\n * @type {?number}\n */\n queuedTimeMs?: number;\n\n /**\n * Sub-measurements for internal use. To be deleted before flushing.\n */\n incompleteSubMeasurements?: Map<string, SubMeasurement>;\n\n visibilityChangeCount?: number;\n incompleteSubsCount?: number;\n /**\n * Amount of times queued in the JS event queue.\n *\n * @type {?number}\n */\n queuedCount?: number;\n /**\n * Amount of manually completed queue events.\n *\n * @type {?number}\n */\n queuedManuallyCompletedCount?: number;\n\n /**\n * Size of the id token\n *\n * @type {number}\n */\n idTokenSize?: number;\n\n /**\n *\n * Size of the access token\n *\n * @type {number}\n */\n\n accessTokenSize?: number;\n\n /**\n *\n * Size of the refresh token\n *\n * @type {number}\n */\n\n refreshTokenSize?: number | undefined;\n\n /**\n * Application name as specified by the app.\n *\n * @type {?string}\n */\n appName?: string;\n\n /**\n * Application version as specified by the app.\n *\n * @type {?string}\n */\n appVersion?: string;\n\n /**\n * The following are fields that may be emitted in native broker scenarios\n */\n extensionId?: string;\n extensionVersion?: string;\n matsBrokerVersion?: string;\n matsAccountJoinOnStart?: string;\n matsAccountJoinOnEnd?: string;\n matsDeviceJoin?: string;\n matsPromptBehavior?: string;\n matsApiErrorCode?: number;\n matsUiVisible?: boolean;\n matsSilentCode?: number;\n matsSilentBiSubCode?: number;\n matsSilentMessage?: string;\n matsSilentStatus?: number;\n matsHttpStatus?: number;\n matsHttpEventCount?: number;\n httpVerToken?: string;\n\n /**\n * Native broker fields\n */\n allowNativeBroker?: boolean;\n extensionInstalled?: boolean;\n extensionHandshakeTimeoutMs?: number;\n extensionHandshakeTimedOut?: boolean;\n\n /**\n * Nested App Auth Fields\n */\n nestedAppAuthRequest?: boolean;\n\n /**\n * Multiple matched access/id/refresh tokens in the cache\n */\n multiMatchedAT?: number;\n multiMatchedID?: number;\n multiMatchedRT?: number;\n};\n\nexport const IntFields: ReadonlySet<string> = new Set([\n \"accessTokenSize\",\n \"durationMs\",\n \"idTokenSize\",\n \"matsSilentStatus\",\n \"matsHttpStatus\",\n \"refreshTokenSize\",\n \"queuedTimeMs\",\n \"startTimeMs\",\n \"status\",\n \"multiMatchedAT\",\n \"multiMatchedID\",\n \"multiMatchedRT\",\n]);\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Logger } from \"../logger/Logger\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\n\n/**\n * Wraps a function with a performance measurement.\n * Usage: invoke(functionToCall, performanceClient, \"EventName\", \"correlationId\")(...argsToPassToFunction)\n * @param callback\n * @param eventName\n * @param logger\n * @param telemetryClient\n * @param correlationId\n * @returns\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const invoke = <T extends Array<any>, U>(\n callback: (...args: T) => U,\n eventName: string,\n logger: Logger,\n telemetryClient?: IPerformanceClient,\n correlationId?: string\n) => {\n return (...args: T): U => {\n logger.trace(`Executing function ${eventName}`);\n const inProgressEvent = telemetryClient?.startMeasurement(\n eventName,\n correlationId\n );\n try {\n const result = callback(...args);\n inProgressEvent?.end({\n success: true,\n });\n logger.trace(`Returning result from ${eventName}`);\n return result;\n } catch (e) {\n logger.trace(`Error occurred in ${eventName}`);\n try {\n logger.trace(JSON.stringify(e));\n } catch (e) {\n logger.trace(\"Unable to print error message.\");\n }\n inProgressEvent?.end({\n success: false,\n });\n throw e;\n }\n };\n};\n\n/**\n * Wraps an async function with a performance measurement.\n * Usage: invokeAsync(functionToCall, performanceClient, \"EventName\", \"correlationId\")(...argsToPassToFunction)\n * @param callback\n * @param eventName\n * @param logger\n * @param telemetryClient\n * @param correlationId\n * @returns\n * @internal\n *\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const invokeAsync = <T extends Array<any>, U>(\n callback: (...args: T) => Promise<U>,\n eventName: string,\n logger: Logger,\n telemetryClient?: IPerformanceClient,\n correlationId?: string\n) => {\n return (...args: T): Promise<U> => {\n logger.trace(`Executing function ${eventName}`);\n const inProgressEvent = telemetryClient?.startMeasurement(\n eventName,\n correlationId\n );\n telemetryClient?.setPreQueueTime(eventName, correlationId);\n return callback(...args)\n .then((response) => {\n logger.trace(`Returning result from ${eventName}`);\n inProgressEvent?.end({\n success: true,\n });\n return response;\n })\n .catch((e) => {\n logger.trace(`Error occurred in ${eventName}`);\n try {\n logger.trace(JSON.stringify(e));\n } catch (e) {\n logger.trace(\"Unable to print error message.\");\n }\n inProgressEvent?.end({\n success: false,\n });\n throw e;\n });\n };\n};\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { INetworkModule } from \"../network/INetworkModule\";\nimport { NetworkResponse } from \"../network/NetworkManager\";\nimport { IMDSBadResponse } from \"../response/IMDSBadResponse\";\nimport {\n Constants,\n RegionDiscoverySources,\n ResponseCodes,\n} from \"../utils/Constants\";\nimport { RegionDiscoveryMetadata } from \"./RegionDiscoveryMetadata\";\nimport { ImdsOptions } from \"./ImdsOptions\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\nimport { invokeAsync } from \"../utils/FunctionWrappers\";\nimport { Logger } from \"../logger/Logger\";\n\nexport class RegionDiscovery {\n // Network interface to make requests with.\n protected networkInterface: INetworkModule;\n // Logger\n private logger: Logger;\n // Performance client\n protected performanceClient: IPerformanceClient | undefined;\n // CorrelationId\n protected correlationId: string | undefined;\n // Options for the IMDS endpoint request\n protected static IMDS_OPTIONS: ImdsOptions = {\n headers: {\n Metadata: \"true\",\n },\n };\n\n constructor(\n networkInterface: INetworkModule,\n logger: Logger,\n performanceClient?: IPerformanceClient,\n correlationId?: string\n ) {\n this.networkInterface = networkInterface;\n this.logger = logger;\n this.performanceClient = performanceClient;\n this.correlationId = correlationId;\n }\n\n /**\n * Detect the region from the application's environment.\n *\n * @returns Promise<string | null>\n */\n public async detectRegion(\n environmentRegion: string | undefined,\n regionDiscoveryMetadata: RegionDiscoveryMetadata\n ): Promise<string | null> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.RegionDiscoveryDetectRegion,\n this.correlationId\n );\n\n // Initialize auto detected region with the region from the envrionment\n let autodetectedRegionName = environmentRegion;\n\n // Check if a region was detected from the environment, if not, attempt to get the region from IMDS\n if (!autodetectedRegionName) {\n const options = RegionDiscovery.IMDS_OPTIONS;\n\n try {\n const localIMDSVersionResponse = await invokeAsync(\n this.getRegionFromIMDS.bind(this),\n PerformanceEvents.RegionDiscoveryGetRegionFromIMDS,\n this.logger,\n this.performanceClient,\n this.correlationId\n )(Constants.IMDS_VERSION, options);\n if (\n localIMDSVersionResponse.status ===\n ResponseCodes.httpSuccess\n ) {\n autodetectedRegionName = localIMDSVersionResponse.body;\n regionDiscoveryMetadata.region_source =\n RegionDiscoverySources.IMDS;\n }\n\n // If the response using the local IMDS version failed, try to fetch the current version of IMDS and retry.\n if (\n localIMDSVersionResponse.status ===\n ResponseCodes.httpBadRequest\n ) {\n const currentIMDSVersion = await invokeAsync(\n this.getCurrentVersion.bind(this),\n PerformanceEvents.RegionDiscoveryGetCurrentVersion,\n this.logger,\n this.performanceClient,\n this.correlationId\n )(options);\n if (!currentIMDSVersion) {\n regionDiscoveryMetadata.region_source =\n RegionDiscoverySources.FAILED_AUTO_DETECTION;\n return null;\n }\n\n const currentIMDSVersionResponse = await invokeAsync(\n this.getRegionFromIMDS.bind(this),\n PerformanceEvents.RegionDiscoveryGetRegionFromIMDS,\n this.logger,\n this.performanceClient,\n this.correlationId\n )(currentIMDSVersion, options);\n if (\n currentIMDSVersionResponse.status ===\n ResponseCodes.httpSuccess\n ) {\n autodetectedRegionName =\n currentIMDSVersionResponse.body;\n regionDiscoveryMetadata.region_source =\n RegionDiscoverySources.IMDS;\n }\n }\n } catch (e) {\n regionDiscoveryMetadata.region_source =\n RegionDiscoverySources.FAILED_AUTO_DETECTION;\n return null;\n }\n } else {\n regionDiscoveryMetadata.region_source =\n RegionDiscoverySources.ENVIRONMENT_VARIABLE;\n }\n\n // If no region was auto detected from the environment or from the IMDS endpoint, mark the attempt as a FAILED_AUTO_DETECTION\n if (!autodetectedRegionName) {\n regionDiscoveryMetadata.region_source =\n RegionDiscoverySources.FAILED_AUTO_DETECTION;\n }\n\n return autodetectedRegionName || null;\n }\n\n /**\n * Make the call to the IMDS endpoint\n *\n * @param imdsEndpointUrl\n * @returns Promise<NetworkResponse<string>>\n */\n private async getRegionFromIMDS(\n version: string,\n options: ImdsOptions\n ): Promise<NetworkResponse<string>> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.RegionDiscoveryGetRegionFromIMDS,\n this.correlationId\n );\n return this.networkInterface.sendGetRequestAsync<string>(\n `${Constants.IMDS_ENDPOINT}?api-version=${version}&format=text`,\n options,\n Constants.IMDS_TIMEOUT\n );\n }\n\n /**\n * Get the most recent version of the IMDS endpoint available\n *\n * @returns Promise<string | null>\n */\n private async getCurrentVersion(\n options: ImdsOptions\n ): Promise<string | null> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.RegionDiscoveryGetCurrentVersion,\n this.correlationId\n );\n try {\n const response =\n await this.networkInterface.sendGetRequestAsync<IMDSBadResponse>(\n `${Constants.IMDS_ENDPOINT}?format=json`,\n options\n );\n\n // When IMDS endpoint is called without the api version query param, bad request response comes back with latest version.\n if (\n response.status === ResponseCodes.httpBadRequest &&\n response.body &&\n response.body[\"newest-versions\"] &&\n response.body[\"newest-versions\"].length > 0\n ) {\n return response.body[\"newest-versions\"][0];\n }\n\n return null;\n } catch (e) {\n return null;\n }\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AuthorityType } from \"./AuthorityType\";\nimport {\n isOpenIdConfigResponse,\n OpenIdConfigResponse,\n} from \"./OpenIdConfigResponse\";\nimport { UrlString } from \"../url/UrlString\";\nimport { IUri } from \"../url/IUri\";\nimport {\n createClientAuthError,\n ClientAuthErrorCodes,\n} from \"../error/ClientAuthError\";\nimport { INetworkModule } from \"../network/INetworkModule\";\nimport {\n AADAuthorityConstants,\n AuthorityMetadataSource,\n Constants,\n RegionDiscoveryOutcomes,\n} from \"../utils/Constants\";\nimport {\n EndpointMetadata,\n getCloudDiscoveryMetadataFromHardcodedValues,\n getCloudDiscoveryMetadataFromNetworkResponse,\n InstanceDiscoveryMetadataAliases,\n} from \"./AuthorityMetadata\";\nimport {\n createClientConfigurationError,\n ClientConfigurationErrorCodes,\n} from \"../error/ClientConfigurationError\";\nimport { ProtocolMode } from \"./ProtocolMode\";\nimport { ICacheManager } from \"../cache/interface/ICacheManager\";\nimport { AuthorityMetadataEntity } from \"../cache/entities/AuthorityMetadataEntity\";\nimport {\n AuthorityOptions,\n AzureCloudInstance,\n StaticAuthorityOptions,\n} from \"./AuthorityOptions\";\nimport {\n CloudInstanceDiscoveryResponse,\n isCloudInstanceDiscoveryResponse,\n} from \"./CloudInstanceDiscoveryResponse\";\nimport {\n CloudInstanceDiscoveryErrorResponse,\n isCloudInstanceDiscoveryErrorResponse,\n} from \"./CloudInstanceDiscoveryErrorResponse\";\nimport { CloudDiscoveryMetadata } from \"./CloudDiscoveryMetadata\";\nimport { RegionDiscovery } from \"./RegionDiscovery\";\nimport { RegionDiscoveryMetadata } from \"./RegionDiscoveryMetadata\";\nimport { ImdsOptions } from \"./ImdsOptions\";\nimport { AzureCloudOptions } from \"../config/ClientConfiguration\";\nimport { Logger } from \"../logger/Logger\";\nimport { AuthError } from \"../error/AuthError\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\nimport { invokeAsync } from \"../utils/FunctionWrappers\";\nimport * as CacheHelpers from \"../cache/utils/CacheHelpers\";\n\n/**\n * The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the\n * endpoint. It will store the pertinent config data in this object for use during token calls.\n * @internal\n */\nexport class Authority {\n // Canonical authority url string\n private _canonicalAuthority: UrlString;\n // Canonicaly authority url components\n private _canonicalAuthorityUrlComponents: IUri | null;\n // Network interface to make requests with.\n protected networkInterface: INetworkModule;\n // Cache Manager to cache network responses\n protected cacheManager: ICacheManager;\n // Protocol mode to construct endpoints\n private authorityOptions: AuthorityOptions;\n // Authority metadata\n private metadata: AuthorityMetadataEntity;\n // Region discovery service\n private regionDiscovery: RegionDiscovery;\n // Region discovery metadata\n public regionDiscoveryMetadata: RegionDiscoveryMetadata;\n // Logger object\n private logger: Logger;\n // Performance client\n protected performanceClient: IPerformanceClient | undefined;\n // Correlation Id\n protected correlationId: string;\n // Reserved tenant domain names that will not be replaced with tenant id\n private static reservedTenantDomains: Set<string> = new Set([\n \"{tenant}\",\n \"{tenantid}\",\n AADAuthorityConstants.COMMON,\n AADAuthorityConstants.CONSUMERS,\n AADAuthorityConstants.ORGANIZATIONS,\n ]);\n\n constructor(\n authority: string,\n networkInterface: INetworkModule,\n cacheManager: ICacheManager,\n authorityOptions: AuthorityOptions,\n logger: Logger,\n correlationId: string,\n performanceClient?: IPerformanceClient\n ) {\n this.canonicalAuthority = authority;\n this._canonicalAuthority.validateAsUri();\n this.networkInterface = networkInterface;\n this.cacheManager = cacheManager;\n this.authorityOptions = authorityOptions;\n this.regionDiscoveryMetadata = {\n region_used: undefined,\n region_source: undefined,\n region_outcome: undefined,\n };\n this.logger = logger;\n this.performanceClient = performanceClient;\n this.correlationId = correlationId;\n this.regionDiscovery = new RegionDiscovery(\n networkInterface,\n this.logger,\n this.performanceClient,\n this.correlationId\n );\n }\n\n /**\n * Get {@link AuthorityType}\n * @param authorityUri {@link IUri}\n * @private\n */\n private getAuthorityType(authorityUri: IUri): AuthorityType {\n // CIAM auth url pattern is being standardized as: <tenant>.ciamlogin.com\n if (authorityUri.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) {\n return AuthorityType.Ciam;\n }\n\n const pathSegments = authorityUri.PathSegments;\n if (pathSegments.length) {\n switch (pathSegments[0].toLowerCase()) {\n case Constants.ADFS:\n return AuthorityType.Adfs;\n case Constants.DSTS:\n return AuthorityType.Dsts;\n default:\n break;\n }\n }\n return AuthorityType.Default;\n }\n\n // See above for AuthorityType\n public get authorityType(): AuthorityType {\n return this.getAuthorityType(this.canonicalAuthorityUrlComponents);\n }\n\n /**\n * ProtocolMode enum representing the way endpoints are constructed.\n */\n public get protocolMode(): ProtocolMode {\n return this.authorityOptions.protocolMode;\n }\n\n /**\n * Returns authorityOptions which can be used to reinstantiate a new authority instance\n */\n public get options(): AuthorityOptions {\n return this.authorityOptions;\n }\n\n /**\n * A URL that is the authority set by the developer\n */\n public get canonicalAuthority(): string {\n return this._canonicalAuthority.urlString;\n }\n\n /**\n * Sets canonical authority.\n */\n public set canonicalAuthority(url: string) {\n this._canonicalAuthority = new UrlString(url);\n this._canonicalAuthority.validateAsUri();\n this._canonicalAuthorityUrlComponents = null;\n }\n\n /**\n * Get authority components.\n */\n public get canonicalAuthorityUrlComponents(): IUri {\n if (!this._canonicalAuthorityUrlComponents) {\n this._canonicalAuthorityUrlComponents =\n this._canonicalAuthority.getUrlComponents();\n }\n\n return this._canonicalAuthorityUrlComponents;\n }\n\n /**\n * Get hostname and port i.e. login.microsoftonline.com\n */\n public get hostnameAndPort(): string {\n return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();\n }\n\n /**\n * Get tenant for authority.\n */\n public get tenant(): string {\n return this.canonicalAuthorityUrlComponents.PathSegments[0];\n }\n\n /**\n * OAuth /authorize endpoint for requests\n */\n public get authorizationEndpoint(): string {\n if (this.discoveryComplete()) {\n return this.replacePath(this.metadata.authorization_endpoint);\n } else {\n throw createClientAuthError(\n ClientAuthErrorCodes.endpointResolutionError\n );\n }\n }\n\n /**\n * OAuth /token endpoint for requests\n */\n public get tokenEndpoint(): string {\n if (this.discoveryComplete()) {\n return this.replacePath(this.metadata.token_endpoint);\n } else {\n throw createClientAuthError(\n ClientAuthErrorCodes.endpointResolutionError\n );\n }\n }\n\n public get deviceCodeEndpoint(): string {\n if (this.discoveryComplete()) {\n return this.replacePath(\n this.metadata.token_endpoint.replace(\"/token\", \"/devicecode\")\n );\n } else {\n throw createClientAuthError(\n ClientAuthErrorCodes.endpointResolutionError\n );\n }\n }\n\n /**\n * OAuth logout endpoint for requests\n */\n public get endSessionEndpoint(): string {\n if (this.discoveryComplete()) {\n // ROPC policies may not have end_session_endpoint set\n if (!this.metadata.end_session_endpoint) {\n throw createClientAuthError(\n ClientAuthErrorCodes.endSessionEndpointNotSupported\n );\n }\n return this.replacePath(this.metadata.end_session_endpoint);\n } else {\n throw createClientAuthError(\n ClientAuthErrorCodes.endpointResolutionError\n );\n }\n }\n\n /**\n * OAuth issuer for requests\n */\n public get selfSignedJwtAudience(): string {\n if (this.discoveryComplete()) {\n return this.replacePath(this.metadata.issuer);\n } else {\n throw createClientAuthError(\n ClientAuthErrorCodes.endpointResolutionError\n );\n }\n }\n\n /**\n * Jwks_uri for token signing keys\n */\n public get jwksUri(): string {\n if (this.discoveryComplete()) {\n return this.replacePath(this.metadata.jwks_uri);\n } else {\n throw createClientAuthError(\n ClientAuthErrorCodes.endpointResolutionError\n );\n }\n }\n\n /**\n * Returns a flag indicating that tenant name can be replaced in authority {@link IUri}\n * @param authorityUri {@link IUri}\n * @private\n */\n private canReplaceTenant(authorityUri: IUri): boolean {\n return (\n authorityUri.PathSegments.length === 1 &&\n !Authority.reservedTenantDomains.has(\n authorityUri.PathSegments[0]\n ) &&\n this.getAuthorityType(authorityUri) === AuthorityType.Default &&\n this.protocolMode === ProtocolMode.AAD\n );\n }\n\n /**\n * Replaces tenant in url path with current tenant. Defaults to common.\n * @param urlString\n */\n private replaceTenant(urlString: string): string {\n return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);\n }\n\n /**\n * Replaces path such as tenant or policy with the current tenant or policy.\n * @param urlString\n */\n private replacePath(urlString: string): string {\n let endpoint = urlString;\n const cachedAuthorityUrl = new UrlString(\n this.metadata.canonical_authority\n );\n const cachedAuthorityUrlComponents =\n cachedAuthorityUrl.getUrlComponents();\n const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments;\n const currentAuthorityParts =\n this.canonicalAuthorityUrlComponents.PathSegments;\n\n currentAuthorityParts.forEach((currentPart, index) => {\n let cachedPart = cachedAuthorityParts[index];\n if (\n index === 0 &&\n this.canReplaceTenant(cachedAuthorityUrlComponents)\n ) {\n const tenantId = new UrlString(\n this.metadata.authorization_endpoint\n ).getUrlComponents().PathSegments[0];\n /**\n * Check if AAD canonical authority contains tenant domain name, for example \"testdomain.onmicrosoft.com\",\n * by comparing its first path segment to the corresponding authorization endpoint path segment, which is\n * always resolved with tenant id by OIDC.\n */\n if (cachedPart !== tenantId) {\n this.logger.verbose(\n `Replacing tenant domain name ${cachedPart} with id ${tenantId}`\n );\n cachedPart = tenantId;\n }\n }\n if (currentPart !== cachedPart) {\n endpoint = endpoint.replace(\n `/${cachedPart}/`,\n `/${currentPart}/`\n );\n }\n });\n\n return this.replaceTenant(endpoint);\n }\n\n /**\n * The default open id configuration endpoint for any canonical authority.\n */\n protected get defaultOpenIdConfigurationEndpoint(): string {\n const canonicalAuthorityHost = this.hostnameAndPort;\n if (\n this.canonicalAuthority.endsWith(\"v2.0/\") ||\n this.authorityType === AuthorityType.Adfs ||\n (this.protocolMode !== ProtocolMode.AAD &&\n !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost))\n ) {\n return `${this.canonicalAuthority}.well-known/openid-configuration`;\n }\n return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;\n }\n\n /**\n * Boolean that returns whethr or not tenant discovery has been completed.\n */\n discoveryComplete(): boolean {\n return !!this.metadata;\n }\n\n /**\n * Perform endpoint discovery to discover aliases, preferred_cache, preferred_network\n * and the /authorize, /token and logout endpoints.\n */\n public async resolveEndpointsAsync(): Promise<void> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthorityResolveEndpointsAsync,\n this.correlationId\n );\n\n const metadataEntity = this.getCurrentMetadataEntity();\n\n const cloudDiscoverySource = await invokeAsync(\n this.updateCloudDiscoveryMetadata.bind(this),\n PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata,\n this.logger,\n this.performanceClient,\n this.correlationId\n )(metadataEntity);\n this.canonicalAuthority = this.canonicalAuthority.replace(\n this.hostnameAndPort,\n metadataEntity.preferred_network\n );\n const endpointSource = await invokeAsync(\n this.updateEndpointMetadata.bind(this),\n PerformanceEvents.AuthorityUpdateEndpointMetadata,\n this.logger,\n this.performanceClient,\n this.correlationId\n )(metadataEntity);\n this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, {\n source: endpointSource,\n });\n this.performanceClient?.addFields(\n {\n cloudDiscoverySource: cloudDiscoverySource,\n authorityEndpointSource: endpointSource,\n },\n this.correlationId\n );\n }\n\n /**\n * Returns metadata entity from cache if it exists, otherwiser returns a new metadata entity built\n * from the configured canonical authority\n * @returns\n */\n private getCurrentMetadataEntity(): AuthorityMetadataEntity {\n let metadataEntity: AuthorityMetadataEntity | null =\n this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort);\n\n if (!metadataEntity) {\n metadataEntity = {\n aliases: [],\n preferred_cache: this.hostnameAndPort,\n preferred_network: this.hostnameAndPort,\n canonical_authority: this.canonicalAuthority,\n authorization_endpoint: \"\",\n token_endpoint: \"\",\n end_session_endpoint: \"\",\n issuer: \"\",\n aliasesFromNetwork: false,\n endpointsFromNetwork: false,\n expiresAt: CacheHelpers.generateAuthorityMetadataExpiresAt(),\n jwks_uri: \"\",\n };\n }\n return metadataEntity;\n }\n\n /**\n * Updates cached metadata based on metadata source and sets the instance's metadata\n * property to the same value\n * @param metadataEntity\n * @param cloudDiscoverySource\n * @param endpointMetadataResult\n */\n private updateCachedMetadata(\n metadataEntity: AuthorityMetadataEntity,\n cloudDiscoverySource: AuthorityMetadataSource | null,\n endpointMetadataResult: {\n source: AuthorityMetadataSource;\n metadata?: OpenIdConfigResponse;\n } | null\n ): void {\n if (\n cloudDiscoverySource !== AuthorityMetadataSource.CACHE &&\n endpointMetadataResult?.source !== AuthorityMetadataSource.CACHE\n ) {\n // Reset the expiration time unless both values came from a successful cache lookup\n metadataEntity.expiresAt =\n CacheHelpers.generateAuthorityMetadataExpiresAt();\n metadataEntity.canonical_authority = this.canonicalAuthority;\n }\n\n const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(\n metadataEntity.preferred_cache\n );\n this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity);\n this.metadata = metadataEntity;\n }\n\n /**\n * Update AuthorityMetadataEntity with new endpoints and return where the information came from\n * @param metadataEntity\n */\n private async updateEndpointMetadata(\n metadataEntity: AuthorityMetadataEntity\n ): Promise<AuthorityMetadataSource> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthorityUpdateEndpointMetadata,\n this.correlationId\n );\n\n const localMetadata =\n this.updateEndpointMetadataFromLocalSources(metadataEntity);\n\n // Further update may be required for hardcoded metadata if regional metadata is preferred\n if (localMetadata) {\n if (\n localMetadata.source ===\n AuthorityMetadataSource.HARDCODED_VALUES\n ) {\n // If the user prefers to use an azure region replace the global endpoints with regional information.\n if (\n this.authorityOptions.azureRegionConfiguration?.azureRegion\n ) {\n if (localMetadata.metadata) {\n const hardcodedMetadata = await invokeAsync(\n this.updateMetadataWithRegionalInformation.bind(\n this\n ),\n PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation,\n this.logger,\n this.performanceClient,\n this.correlationId\n )(localMetadata.metadata);\n CacheHelpers.updateAuthorityEndpointMetadata(\n metadataEntity,\n hardcodedMetadata,\n false\n );\n metadataEntity.canonical_authority =\n this.canonicalAuthority;\n }\n }\n }\n return localMetadata.source;\n }\n\n // Get metadata from network if local sources aren't available\n let metadata = await invokeAsync(\n this.getEndpointMetadataFromNetwork.bind(this),\n PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork,\n this.logger,\n this.performanceClient,\n this.correlationId\n )();\n if (metadata) {\n // If the user prefers to use an azure region replace the global endpoints with regional information.\n if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {\n metadata = await invokeAsync(\n this.updateMetadataWithRegionalInformation.bind(this),\n PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation,\n this.logger,\n this.performanceClient,\n this.correlationId\n )(metadata);\n }\n\n CacheHelpers.updateAuthorityEndpointMetadata(\n metadataEntity,\n metadata,\n true\n );\n return AuthorityMetadataSource.NETWORK;\n } else {\n // Metadata could not be obtained from the config, cache, network or hardcoded values\n throw createClientAuthError(\n ClientAuthErrorCodes.openIdConfigError,\n this.defaultOpenIdConfigurationEndpoint\n );\n }\n }\n\n /**\n * Updates endpoint metadata from local sources and returns where the information was retrieved from and the metadata config\n * response if the source is hardcoded metadata\n * @param metadataEntity\n * @returns\n */\n private updateEndpointMetadataFromLocalSources(\n metadataEntity: AuthorityMetadataEntity\n ): {\n source: AuthorityMetadataSource;\n metadata?: OpenIdConfigResponse;\n } | null {\n this.logger.verbose(\n \"Attempting to get endpoint metadata from authority configuration\"\n );\n const configMetadata = this.getEndpointMetadataFromConfig();\n if (configMetadata) {\n this.logger.verbose(\n \"Found endpoint metadata in authority configuration\"\n );\n CacheHelpers.updateAuthorityEndpointMetadata(\n metadataEntity,\n configMetadata,\n false\n );\n return {\n source: AuthorityMetadataSource.CONFIG,\n };\n }\n\n this.logger.verbose(\n \"Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values.\"\n );\n\n // skipAuthorityMetadataCache is used to bypass hardcoded authority metadata and force a network metadata cache lookup and network metadata request if no cached response is available.\n if (this.authorityOptions.skipAuthorityMetadataCache) {\n this.logger.verbose(\n \"Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache.\"\n );\n } else {\n const hardcodedMetadata =\n this.getEndpointMetadataFromHardcodedValues();\n if (hardcodedMetadata) {\n CacheHelpers.updateAuthorityEndpointMetadata(\n metadataEntity,\n hardcodedMetadata,\n false\n );\n return {\n source: AuthorityMetadataSource.HARDCODED_VALUES,\n metadata: hardcodedMetadata,\n };\n } else {\n this.logger.verbose(\n \"Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.\"\n );\n }\n }\n\n // Check cached metadata entity expiration status\n const metadataEntityExpired =\n CacheHelpers.isAuthorityMetadataExpired(metadataEntity);\n if (\n this.isAuthoritySameType(metadataEntity) &&\n metadataEntity.endpointsFromNetwork &&\n !metadataEntityExpired\n ) {\n // No need to update\n this.logger.verbose(\"Found endpoint metadata in the cache.\");\n return { source: AuthorityMetadataSource.CACHE };\n } else if (metadataEntityExpired) {\n this.logger.verbose(\"The metadata entity is expired.\");\n }\n\n return null;\n }\n\n /**\n * Compares the number of url components after the domain to determine if the cached\n * authority metadata can be used for the requested authority. Protects against same domain different\n * authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy\n * @param metadataEntity\n */\n private isAuthoritySameType(\n metadataEntity: AuthorityMetadataEntity\n ): boolean {\n const cachedAuthorityUrl = new UrlString(\n metadataEntity.canonical_authority\n );\n const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;\n\n return (\n cachedParts.length ===\n this.canonicalAuthorityUrlComponents.PathSegments.length\n );\n }\n\n /**\n * Parse authorityMetadata config option\n */\n private getEndpointMetadataFromConfig(): OpenIdConfigResponse | null {\n if (this.authorityOptions.authorityMetadata) {\n try {\n return JSON.parse(\n this.authorityOptions.authorityMetadata\n ) as OpenIdConfigResponse;\n } catch (e) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.invalidAuthorityMetadata\n );\n }\n }\n\n return null;\n }\n\n /**\n * Gets OAuth endpoints from the given OpenID configuration endpoint.\n *\n * @param hasHardcodedMetadata boolean\n */\n private async getEndpointMetadataFromNetwork(): Promise<OpenIdConfigResponse | null> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork,\n this.correlationId\n );\n\n const options: ImdsOptions = {};\n\n /*\n * TODO: Add a timeout if the authority exists in our library's\n * hardcoded list of metadata\n */\n\n const openIdConfigurationEndpoint =\n this.defaultOpenIdConfigurationEndpoint;\n this.logger.verbose(\n `Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${openIdConfigurationEndpoint}`\n );\n\n try {\n const response =\n await this.networkInterface.sendGetRequestAsync<OpenIdConfigResponse>(\n openIdConfigurationEndpoint,\n options\n );\n const isValidResponse = isOpenIdConfigResponse(response.body);\n if (isValidResponse) {\n return response.body;\n } else {\n this.logger.verbose(\n `Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`\n );\n return null;\n }\n } catch (e) {\n this.logger.verbose(\n `Authority.getEndpointMetadataFromNetwork: ${e}`\n );\n return null;\n }\n }\n\n /**\n * Get OAuth endpoints for common authorities.\n */\n private getEndpointMetadataFromHardcodedValues(): OpenIdConfigResponse | null {\n if (this.hostnameAndPort in EndpointMetadata) {\n return EndpointMetadata[this.hostnameAndPort];\n }\n\n return null;\n }\n\n /**\n * Update the retrieved metadata with regional information.\n * User selected Azure region will be used if configured.\n */\n private async updateMetadataWithRegionalInformation(\n metadata: OpenIdConfigResponse\n ): Promise<OpenIdConfigResponse> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation,\n this.correlationId\n );\n\n const userConfiguredAzureRegion =\n this.authorityOptions.azureRegionConfiguration?.azureRegion;\n\n if (userConfiguredAzureRegion) {\n if (\n userConfiguredAzureRegion !==\n Constants.AZURE_REGION_AUTO_DISCOVER_FLAG\n ) {\n this.regionDiscoveryMetadata.region_outcome =\n RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;\n this.regionDiscoveryMetadata.region_used =\n userConfiguredAzureRegion;\n return Authority.replaceWithRegionalInformation(\n metadata,\n userConfiguredAzureRegion\n );\n }\n\n const autodetectedRegionName = await invokeAsync(\n this.regionDiscovery.detectRegion.bind(this.regionDiscovery),\n PerformanceEvents.RegionDiscoveryDetectRegion,\n this.logger,\n this.performanceClient,\n this.correlationId\n )(\n this.authorityOptions.azureRegionConfiguration\n ?.environmentRegion,\n this.regionDiscoveryMetadata\n );\n\n if (autodetectedRegionName) {\n this.regionDiscoveryMetadata.region_outcome =\n RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;\n this.regionDiscoveryMetadata.region_used =\n autodetectedRegionName;\n return Authority.replaceWithRegionalInformation(\n metadata,\n autodetectedRegionName\n );\n }\n\n this.regionDiscoveryMetadata.region_outcome =\n RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;\n }\n\n return metadata;\n }\n\n /**\n * Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache\n * and returns where the information was retrieved from\n * @param metadataEntity\n * @returns AuthorityMetadataSource\n */\n private async updateCloudDiscoveryMetadata(\n metadataEntity: AuthorityMetadataEntity\n ): Promise<AuthorityMetadataSource> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata,\n this.correlationId\n );\n const localMetadataSource =\n this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity);\n if (localMetadataSource) {\n return localMetadataSource;\n }\n\n // Fallback to network as metadata source\n const metadata = await invokeAsync(\n this.getCloudDiscoveryMetadataFromNetwork.bind(this),\n PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork,\n this.logger,\n this.performanceClient,\n this.correlationId\n )();\n\n if (metadata) {\n CacheHelpers.updateCloudDiscoveryMetadata(\n metadataEntity,\n metadata,\n true\n );\n return AuthorityMetadataSource.NETWORK;\n }\n\n // Metadata could not be obtained from the config, cache, network or hardcoded values\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.untrustedAuthority\n );\n }\n\n private updateCloudDiscoveryMetadataFromLocalSources(\n metadataEntity: AuthorityMetadataEntity\n ): AuthorityMetadataSource | null {\n this.logger.verbose(\n \"Attempting to get cloud discovery metadata from authority configuration\"\n );\n this.logger.verbosePii(\n `Known Authorities: ${\n this.authorityOptions.knownAuthorities ||\n Constants.NOT_APPLICABLE\n }`\n );\n this.logger.verbosePii(\n `Authority Metadata: ${\n this.authorityOptions.authorityMetadata ||\n Constants.NOT_APPLICABLE\n }`\n );\n this.logger.verbosePii(\n `Canonical Authority: ${\n metadataEntity.canonical_authority || Constants.NOT_APPLICABLE\n }`\n );\n const metadata = this.getCloudDiscoveryMetadataFromConfig();\n if (metadata) {\n this.logger.verbose(\n \"Found cloud discovery metadata in authority configuration\"\n );\n CacheHelpers.updateCloudDiscoveryMetadata(\n metadataEntity,\n metadata,\n false\n );\n return AuthorityMetadataSource.CONFIG;\n }\n\n // If the cached metadata came from config but that config was not passed to this instance, we must go to hardcoded values\n this.logger.verbose(\n \"Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values.\"\n );\n\n if (this.options.skipAuthorityMetadataCache) {\n this.logger.verbose(\n \"Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache.\"\n );\n } else {\n const hardcodedMetadata =\n getCloudDiscoveryMetadataFromHardcodedValues(\n this.hostnameAndPort\n );\n if (hardcodedMetadata) {\n this.logger.verbose(\n \"Found cloud discovery metadata from hardcoded values.\"\n );\n CacheHelpers.updateCloudDiscoveryMetadata(\n metadataEntity,\n hardcodedMetadata,\n false\n );\n return AuthorityMetadataSource.HARDCODED_VALUES;\n }\n\n this.logger.verbose(\n \"Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.\"\n );\n }\n\n const metadataEntityExpired =\n CacheHelpers.isAuthorityMetadataExpired(metadataEntity);\n if (\n this.isAuthoritySameType(metadataEntity) &&\n metadataEntity.aliasesFromNetwork &&\n !metadataEntityExpired\n ) {\n this.logger.verbose(\"Found cloud discovery metadata in the cache.\");\n // No need to update\n return AuthorityMetadataSource.CACHE;\n } else if (metadataEntityExpired) {\n this.logger.verbose(\"The metadata entity is expired.\");\n }\n\n return null;\n }\n\n /**\n * Parse cloudDiscoveryMetadata config or check knownAuthorities\n */\n private getCloudDiscoveryMetadataFromConfig(): CloudDiscoveryMetadata | null {\n // CIAM does not support cloud discovery metadata\n if (this.authorityType === AuthorityType.Ciam) {\n this.logger.verbose(\n \"CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host.\"\n );\n return Authority.createCloudDiscoveryMetadataFromHost(\n this.hostnameAndPort\n );\n }\n\n // Check if network response was provided in config\n if (this.authorityOptions.cloudDiscoveryMetadata) {\n this.logger.verbose(\n \"The cloud discovery metadata has been provided as a network response, in the config.\"\n );\n try {\n this.logger.verbose(\n \"Attempting to parse the cloud discovery metadata.\"\n );\n const parsedResponse = JSON.parse(\n this.authorityOptions.cloudDiscoveryMetadata\n ) as CloudInstanceDiscoveryResponse;\n const metadata = getCloudDiscoveryMetadataFromNetworkResponse(\n parsedResponse.metadata,\n this.hostnameAndPort\n );\n this.logger.verbose(\"Parsed the cloud discovery metadata.\");\n if (metadata) {\n this.logger.verbose(\n \"There is returnable metadata attached to the parsed cloud discovery metadata.\"\n );\n return metadata;\n } else {\n this.logger.verbose(\n \"There is no metadata attached to the parsed cloud discovery metadata.\"\n );\n }\n } catch (e) {\n this.logger.verbose(\n \"Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error.\"\n );\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.invalidCloudDiscoveryMetadata\n );\n }\n }\n\n // If cloudDiscoveryMetadata is empty or does not contain the host, check knownAuthorities\n if (this.isInKnownAuthorities()) {\n this.logger.verbose(\n \"The host is included in knownAuthorities. Creating new cloud discovery metadata from the host.\"\n );\n return Authority.createCloudDiscoveryMetadataFromHost(\n this.hostnameAndPort\n );\n }\n\n return null;\n }\n\n /**\n * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config\n *\n * @param hasHardcodedMetadata boolean\n */\n private async getCloudDiscoveryMetadataFromNetwork(): Promise<CloudDiscoveryMetadata | null> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork,\n this.correlationId\n );\n const instanceDiscoveryEndpoint = `${Constants.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;\n const options: ImdsOptions = {};\n\n /*\n * TODO: Add a timeout if the authority exists in our library's\n * hardcoded list of metadata\n */\n\n let match = null;\n try {\n const response = await this.networkInterface.sendGetRequestAsync<\n | CloudInstanceDiscoveryResponse\n | CloudInstanceDiscoveryErrorResponse\n >(instanceDiscoveryEndpoint, options);\n let typedResponseBody:\n | CloudInstanceDiscoveryResponse\n | CloudInstanceDiscoveryErrorResponse;\n let metadata: Array<CloudDiscoveryMetadata>;\n if (isCloudInstanceDiscoveryResponse(response.body)) {\n typedResponseBody =\n response.body as CloudInstanceDiscoveryResponse;\n metadata = typedResponseBody.metadata;\n\n this.logger.verbosePii(\n `tenant_discovery_endpoint is: ${typedResponseBody.tenant_discovery_endpoint}`\n );\n } else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {\n this.logger.warning(\n `A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${response.status}`\n );\n\n typedResponseBody =\n response.body as CloudInstanceDiscoveryErrorResponse;\n if (typedResponseBody.error === Constants.INVALID_INSTANCE) {\n this.logger.error(\n \"The CloudInstanceDiscoveryErrorResponse error is invalid_instance.\"\n );\n return null;\n }\n\n this.logger.warning(\n `The CloudInstanceDiscoveryErrorResponse error is ${typedResponseBody.error}`\n );\n this.logger.warning(\n `The CloudInstanceDiscoveryErrorResponse error description is ${typedResponseBody.error_description}`\n );\n\n this.logger.warning(\n \"Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []\"\n );\n metadata = [];\n } else {\n this.logger.error(\n \"AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse\"\n );\n return null;\n }\n\n this.logger.verbose(\n \"Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request.\"\n );\n match = getCloudDiscoveryMetadataFromNetworkResponse(\n metadata,\n this.hostnameAndPort\n );\n } catch (error) {\n if (error instanceof AuthError) {\n this.logger.error(\n `There was a network error while attempting to get the cloud discovery instance metadata.\\nError: ${error.errorCode}\\nError Description: ${error.errorMessage}`\n );\n } else {\n const typedError = error as Error;\n this.logger.error(\n `A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\\nError: ${typedError.name}\\nError Description: ${typedError.message}`\n );\n }\n\n return null;\n }\n\n // Custom Domain scenario, host is trusted because Instance Discovery call succeeded\n if (!match) {\n this.logger.warning(\n \"The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request.\"\n );\n this.logger.verbose(\n \"Creating custom Authority for custom domain scenario.\"\n );\n\n match = Authority.createCloudDiscoveryMetadataFromHost(\n this.hostnameAndPort\n );\n }\n return match;\n }\n\n /**\n * Helper function to determine if this host is included in the knownAuthorities config option\n */\n private isInKnownAuthorities(): boolean {\n const matches = this.authorityOptions.knownAuthorities.filter(\n (authority) => {\n return (\n authority &&\n UrlString.getDomainFromUrl(authority).toLowerCase() ===\n this.hostnameAndPort\n );\n }\n );\n return matches.length > 0;\n }\n\n /**\n * helper function to populate the authority based on azureCloudOptions\n * @param authorityString\n * @param azureCloudOptions\n */\n static generateAuthority(\n authorityString: string,\n azureCloudOptions?: AzureCloudOptions\n ): string {\n let authorityAzureCloudInstance;\n\n if (\n azureCloudOptions &&\n azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None\n ) {\n const tenant = azureCloudOptions.tenant\n ? azureCloudOptions.tenant\n : Constants.DEFAULT_COMMON_TENANT;\n authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;\n }\n\n return authorityAzureCloudInstance\n ? authorityAzureCloudInstance\n : authorityString;\n }\n\n /**\n * Creates cloud discovery metadata object from a given host\n * @param host\n */\n static createCloudDiscoveryMetadataFromHost(\n host: string\n ): CloudDiscoveryMetadata {\n return {\n preferred_network: host,\n preferred_cache: host,\n aliases: [host],\n };\n }\n\n /**\n * helper function to generate environment from authority object\n */\n getPreferredCache(): string {\n if (this.discoveryComplete()) {\n return this.metadata.preferred_cache;\n } else {\n throw createClientAuthError(\n ClientAuthErrorCodes.endpointResolutionError\n );\n }\n }\n\n /**\n * Returns whether or not the provided host is an alias of this authority instance\n * @param host\n */\n isAlias(host: string): boolean {\n return this.metadata.aliases.indexOf(host) > -1;\n }\n\n /**\n * Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery\n * @param host\n */\n isAliasOfKnownMicrosoftAuthority(host: string): boolean {\n return InstanceDiscoveryMetadataAliases.has(host);\n }\n\n /**\n * Checks whether the provided host is that of a public cloud authority\n *\n * @param authority string\n * @returns bool\n */\n static isPublicCloudAuthority(host: string): boolean {\n return Constants.KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;\n }\n\n /**\n * Rebuild the authority string with the region\n *\n * @param host string\n * @param region string\n */\n static buildRegionalAuthorityString(\n host: string,\n region: string,\n queryString?: string\n ): string {\n // Create and validate a Url string object with the initial authority string\n const authorityUrlInstance = new UrlString(host);\n authorityUrlInstance.validateAsUri();\n\n const authorityUrlParts = authorityUrlInstance.getUrlComponents();\n\n let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;\n\n if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) {\n hostNameAndPort = `${region}.${Constants.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;\n }\n\n // Include the query string portion of the url\n const url = UrlString.constructAuthorityUriFromObject({\n ...authorityUrlInstance.getUrlComponents(),\n HostNameAndPort: hostNameAndPort,\n }).urlString;\n\n // Add the query string if a query string was provided\n if (queryString) return `${url}?${queryString}`;\n\n return url;\n }\n\n /**\n * Replace the endpoints in the metadata object with their regional equivalents.\n *\n * @param metadata OpenIdConfigResponse\n * @param azureRegion string\n */\n static replaceWithRegionalInformation(\n metadata: OpenIdConfigResponse,\n azureRegion: string\n ): OpenIdConfigResponse {\n const regionalMetadata = { ...metadata };\n regionalMetadata.authorization_endpoint =\n Authority.buildRegionalAuthorityString(\n regionalMetadata.authorization_endpoint,\n azureRegion\n );\n\n regionalMetadata.token_endpoint =\n Authority.buildRegionalAuthorityString(\n regionalMetadata.token_endpoint,\n azureRegion\n );\n\n if (regionalMetadata.end_session_endpoint) {\n regionalMetadata.end_session_endpoint =\n Authority.buildRegionalAuthorityString(\n regionalMetadata.end_session_endpoint,\n azureRegion\n );\n }\n\n return regionalMetadata;\n }\n\n /**\n * Transform CIAM_AUTHORIY as per the below rules:\n * If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it\n *\n * NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com`\n * `ciamlogin.com` can also change in the future and we should accommodate the same\n *\n * @param authority\n */\n static transformCIAMAuthority(authority: string): string {\n let ciamAuthority = authority;\n const authorityUrl = new UrlString(authority);\n const authorityUrlComponents = authorityUrl.getUrlComponents();\n\n // check if transformation is needed\n if (\n authorityUrlComponents.PathSegments.length === 0 &&\n authorityUrlComponents.HostNameAndPort.endsWith(\n Constants.CIAM_AUTH_URL\n )\n ) {\n const tenantIdOrDomain =\n authorityUrlComponents.HostNameAndPort.split(\".\")[0];\n ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${Constants.AAD_TENANT_DOMAIN_SUFFIX}`;\n }\n\n return ciamAuthority;\n }\n}\n\n/**\n * Extract tenantId from authority\n */\nexport function getTenantFromAuthorityString(\n authority: string\n): string | undefined {\n const authorityUrl = new UrlString(authority);\n const authorityUrlComponents = authorityUrl.getUrlComponents();\n /**\n * For credential matching purposes, tenantId is the last path segment of the authority URL:\n * AAD Authority - domain/tenantId -> Credentials are cached with realm = tenantId\n * B2C Authority - domain/{tenantId}?/.../policy -> Credentials are cached with realm = policy\n * tenantId is downcased because B2C policies can have mixed case but tfp claim is downcased\n */\n const tenantId =\n authorityUrlComponents.PathSegments.slice(-1)[0].toLowerCase();\n\n switch (tenantId) {\n case AADAuthorityConstants.COMMON:\n case AADAuthorityConstants.ORGANIZATIONS:\n case AADAuthorityConstants.CONSUMERS:\n return undefined;\n default:\n return tenantId;\n }\n}\n\nexport function formatAuthorityUri(authorityUri: string): string {\n return authorityUri.endsWith(Constants.FORWARD_SLASH)\n ? authorityUri\n : `${authorityUri}${Constants.FORWARD_SLASH}`;\n}\n\nexport function buildStaticAuthorityOptions(\n authOptions: Partial<AuthorityOptions>\n): StaticAuthorityOptions {\n const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata;\n let cloudDiscoveryMetadata: CloudInstanceDiscoveryResponse | undefined =\n undefined;\n if (rawCloudDiscoveryMetadata) {\n try {\n cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata);\n } catch (e) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.invalidCloudDiscoveryMetadata\n );\n }\n }\n return {\n canonicalAuthority: authOptions.authority\n ? formatAuthorityUri(authOptions.authority)\n : undefined,\n knownAuthorities: authOptions.knownAuthorities,\n cloudDiscoveryMetadata: cloudDiscoveryMetadata,\n };\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Authority, formatAuthorityUri } from \"./Authority\";\nimport { INetworkModule } from \"../network/INetworkModule\";\nimport {\n createClientAuthError,\n ClientAuthErrorCodes,\n} from \"../error/ClientAuthError\";\nimport { ICacheManager } from \"../cache/interface/ICacheManager\";\nimport { AuthorityOptions } from \"./AuthorityOptions\";\nimport { Logger } from \"../logger/Logger\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\nimport { invokeAsync } from \"../utils/FunctionWrappers\";\n\n/**\n * Create an authority object of the correct type based on the url\n * Performs basic authority validation - checks to see if the authority is of a valid type (i.e. aad, b2c, adfs)\n *\n * Also performs endpoint discovery.\n *\n * @param authorityUri\n * @param networkClient\n * @param protocolMode\n * @internal\n */\nexport async function createDiscoveredInstance(\n authorityUri: string,\n networkClient: INetworkModule,\n cacheManager: ICacheManager,\n authorityOptions: AuthorityOptions,\n logger: Logger,\n correlationId: string,\n performanceClient?: IPerformanceClient\n): Promise<Authority> {\n performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthorityFactoryCreateDiscoveredInstance,\n correlationId\n );\n const authorityUriFinal = Authority.transformCIAMAuthority(\n formatAuthorityUri(authorityUri)\n );\n\n // Initialize authority and perform discovery endpoint check.\n const acquireTokenAuthority: Authority = new Authority(\n authorityUriFinal,\n networkClient,\n cacheManager,\n authorityOptions,\n logger,\n correlationId,\n performanceClient\n );\n\n try {\n await invokeAsync(\n acquireTokenAuthority.resolveEndpointsAsync.bind(\n acquireTokenAuthority\n ),\n PerformanceEvents.AuthorityResolveEndpointsAsync,\n logger,\n performanceClient,\n correlationId\n )();\n return acquireTokenAuthority;\n } catch (e) {\n throw createClientAuthError(\n ClientAuthErrorCodes.endpointResolutionError\n );\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n ClientConfiguration,\n buildClientConfiguration,\n CommonClientConfiguration,\n} from \"../config/ClientConfiguration\";\nimport { INetworkModule } from \"../network/INetworkModule\";\nimport { NetworkManager, NetworkResponse } from \"../network/NetworkManager\";\nimport { ICrypto } from \"../crypto/ICrypto\";\nimport { Authority } from \"../authority/Authority\";\nimport { Logger } from \"../logger/Logger\";\nimport { Constants, HeaderNames } from \"../utils/Constants\";\nimport { ServerAuthorizationTokenResponse } from \"../response/ServerAuthorizationTokenResponse\";\nimport { CacheManager } from \"../cache/CacheManager\";\nimport { ServerTelemetryManager } from \"../telemetry/server/ServerTelemetryManager\";\nimport { RequestThumbprint } from \"../network/RequestThumbprint\";\nimport { version, name } from \"../packageMetadata\";\nimport { CcsCredential, CcsCredentialType } from \"../account/CcsCredential\";\nimport { buildClientInfoFromHomeAccountId } from \"../account/ClientInfo\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\nimport { RequestParameterBuilder } from \"../request/RequestParameterBuilder\";\nimport { BaseAuthRequest } from \"../request/BaseAuthRequest\";\nimport { createDiscoveredInstance } from \"../authority/AuthorityFactory\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\n\n/**\n * Base application class which will construct requests to send to and handle responses from the Microsoft STS using the authorization code flow.\n * @internal\n */\nexport abstract class BaseClient {\n // Logger object\n public logger: Logger;\n\n // Application config\n protected config: CommonClientConfiguration;\n\n // Crypto Interface\n protected cryptoUtils: ICrypto;\n\n // Storage Interface\n protected cacheManager: CacheManager;\n\n // Network Interface\n protected networkClient: INetworkModule;\n\n // Server Telemetry Manager\n protected serverTelemetryManager: ServerTelemetryManager | null;\n\n // Network Manager\n protected networkManager: NetworkManager;\n\n // Default authority object\n public authority: Authority;\n\n // Performance telemetry client\n protected performanceClient?: IPerformanceClient;\n\n protected constructor(\n configuration: ClientConfiguration,\n performanceClient?: IPerformanceClient\n ) {\n // Set the configuration\n this.config = buildClientConfiguration(configuration);\n\n // Initialize the logger\n this.logger = new Logger(this.config.loggerOptions, name, version);\n\n // Initialize crypto\n this.cryptoUtils = this.config.cryptoInterface;\n\n // Initialize storage interface\n this.cacheManager = this.config.storageInterface;\n\n // Set the network interface\n this.networkClient = this.config.networkInterface;\n\n // Set the NetworkManager\n this.networkManager = new NetworkManager(\n this.networkClient,\n this.cacheManager\n );\n\n // Set TelemetryManager\n this.serverTelemetryManager = this.config.serverTelemetryManager;\n\n // set Authority\n this.authority = this.config.authOptions.authority;\n\n // set performance telemetry client\n this.performanceClient = performanceClient;\n }\n\n /**\n * Creates default headers for requests to token endpoint\n */\n protected createTokenRequestHeaders(\n ccsCred?: CcsCredential\n ): Record<string, string> {\n const headers: Record<string, string> = {};\n headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE;\n if (!this.config.systemOptions.preventCorsPreflight && ccsCred) {\n switch (ccsCred.type) {\n case CcsCredentialType.HOME_ACCOUNT_ID:\n try {\n const clientInfo = buildClientInfoFromHomeAccountId(\n ccsCred.credential\n );\n headers[\n HeaderNames.CCS_HEADER\n ] = `Oid:${clientInfo.uid}@${clientInfo.utid}`;\n } catch (e) {\n this.logger.verbose(\n \"Could not parse home account ID for CCS Header: \" +\n e\n );\n }\n break;\n case CcsCredentialType.UPN:\n headers[\n HeaderNames.CCS_HEADER\n ] = `UPN: ${ccsCred.credential}`;\n break;\n }\n }\n return headers;\n }\n\n /**\n * Http post to token endpoint\n * @param tokenEndpoint\n * @param queryString\n * @param headers\n * @param thumbprint\n */\n protected async executePostToTokenEndpoint(\n tokenEndpoint: string,\n queryString: string,\n headers: Record<string, string>,\n thumbprint: RequestThumbprint,\n correlationId: string,\n queuedEvent?: string\n ): Promise<NetworkResponse<ServerAuthorizationTokenResponse>> {\n if (queuedEvent) {\n this.performanceClient?.addQueueMeasurement(\n queuedEvent,\n correlationId\n );\n }\n\n const response =\n await this.networkManager.sendPostRequest<ServerAuthorizationTokenResponse>(\n thumbprint,\n tokenEndpoint,\n { body: queryString, headers: headers }\n );\n this.performanceClient?.addFields(\n {\n refreshTokenSize: response.body.refresh_token?.length || 0,\n httpVerToken:\n response.headers?.[HeaderNames.X_MS_HTTP_VERSION] || \"\",\n },\n correlationId\n );\n\n if (\n this.config.serverTelemetryManager &&\n response.status < 500 &&\n response.status !== 429\n ) {\n // Telemetry data successfully logged by server, clear Telemetry cache\n this.config.serverTelemetryManager.clearTelemetryCache();\n }\n\n return response;\n }\n\n /**\n * Updates the authority object of the client. Endpoint discovery must be completed.\n * @param updatedAuthority\n */\n async updateAuthority(\n cloudInstanceHostname: string,\n correlationId: string\n ): Promise<void> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.UpdateTokenEndpointAuthority,\n correlationId\n );\n const cloudInstanceAuthorityUri = `https://${cloudInstanceHostname}/${this.authority.tenant}/`;\n const cloudInstanceAuthority = await createDiscoveredInstance(\n cloudInstanceAuthorityUri,\n this.networkClient,\n this.cacheManager,\n this.authority.options,\n this.logger,\n correlationId,\n this.performanceClient\n );\n this.authority = cloudInstanceAuthority;\n }\n\n /**\n * Creates query string for the /token request\n * @param request\n */\n createTokenQueryParameters(request: BaseAuthRequest): string {\n const parameterBuilder = new RequestParameterBuilder();\n\n if (request.tokenQueryParameters) {\n parameterBuilder.addExtraQueryParameters(\n request.tokenQueryParameters\n );\n }\n\n return parameterBuilder.createQueryString();\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n// Codes defined by MSAL\nexport const noTokensFound = \"no_tokens_found\";\nexport const nativeAccountUnavailable = \"native_account_unavailable\";\nexport const refreshTokenExpired = \"refresh_token_expired\";\n\n// Codes potentially returned by server\nexport const interactionRequired = \"interaction_required\";\nexport const consentRequired = \"consent_required\";\nexport const loginRequired = \"login_required\";\nexport const badToken = \"bad_token\";\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants } from \"../utils/Constants\";\nimport { AuthError } from \"./AuthError\";\nimport * as InteractionRequiredAuthErrorCodes from \"./InteractionRequiredAuthErrorCodes\";\nexport { InteractionRequiredAuthErrorCodes };\n\n/**\n * InteractionRequiredServerErrorMessage contains string constants used by error codes and messages returned by the server indicating interaction is required\n */\nexport const InteractionRequiredServerErrorMessage = [\n InteractionRequiredAuthErrorCodes.interactionRequired,\n InteractionRequiredAuthErrorCodes.consentRequired,\n InteractionRequiredAuthErrorCodes.loginRequired,\n InteractionRequiredAuthErrorCodes.badToken,\n];\n\nexport const InteractionRequiredAuthSubErrorMessage = [\n \"message_only\",\n \"additional_action\",\n \"basic_action\",\n \"user_password_expired\",\n \"consent_required\",\n \"bad_token\",\n];\n\nconst InteractionRequiredAuthErrorMessages = {\n [InteractionRequiredAuthErrorCodes.noTokensFound]:\n \"No refresh token found in the cache. Please sign-in.\",\n [InteractionRequiredAuthErrorCodes.nativeAccountUnavailable]:\n \"The requested account is not available in the native broker. It may have been deleted or logged out. Please sign-in again using an interactive API.\",\n [InteractionRequiredAuthErrorCodes.refreshTokenExpired]:\n \"Refresh token has expired.\",\n [InteractionRequiredAuthErrorCodes.badToken]:\n \"Identity provider returned bad_token due to an expired or invalid refresh token. Please invoke an interactive API to resolve.\",\n};\n\n/**\n * Interaction required errors defined by the SDK\n * @deprecated Use InteractionRequiredAuthErrorCodes instead\n */\nexport const InteractionRequiredAuthErrorMessage = {\n noTokensFoundError: {\n code: InteractionRequiredAuthErrorCodes.noTokensFound,\n desc: InteractionRequiredAuthErrorMessages[\n InteractionRequiredAuthErrorCodes.noTokensFound\n ],\n },\n native_account_unavailable: {\n code: InteractionRequiredAuthErrorCodes.nativeAccountUnavailable,\n desc: InteractionRequiredAuthErrorMessages[\n InteractionRequiredAuthErrorCodes.nativeAccountUnavailable\n ],\n },\n bad_token: {\n code: InteractionRequiredAuthErrorCodes.badToken,\n desc: InteractionRequiredAuthErrorMessages[\n InteractionRequiredAuthErrorCodes.badToken\n ],\n },\n};\n\n/**\n * Error thrown when user interaction is required.\n */\nexport class InteractionRequiredAuthError extends AuthError {\n /**\n * The time the error occured at\n */\n timestamp: string;\n\n /**\n * TraceId associated with the error\n */\n traceId: string;\n\n /**\n * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/claims-challenge.md\n *\n * A string with extra claims needed for the token request to succeed\n * web site: redirect the user to the authorization page and set the extra claims\n * web api: include the claims in the WWW-Authenticate header that are sent back to the client so that it knows to request a token with the extra claims\n * desktop application or browser context: include the claims when acquiring the token interactively\n * app to app context (client_credentials): include the claims in the AcquireTokenByClientCredential request\n */\n claims: string;\n\n constructor(\n errorCode?: string,\n errorMessage?: string,\n subError?: string,\n timestamp?: string,\n traceId?: string,\n correlationId?: string,\n claims?: string\n ) {\n super(errorCode, errorMessage, subError);\n Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype);\n\n this.timestamp = timestamp || Constants.EMPTY_STRING;\n this.traceId = traceId || Constants.EMPTY_STRING;\n this.correlationId = correlationId || Constants.EMPTY_STRING;\n this.claims = claims || Constants.EMPTY_STRING;\n this.name = \"InteractionRequiredAuthError\";\n }\n}\n\n/**\n * Helper function used to determine if an error thrown by the server requires interaction to resolve\n * @param errorCode\n * @param errorString\n * @param subError\n */\nexport function isInteractionRequiredError(\n errorCode?: string,\n errorString?: string,\n subError?: string\n): boolean {\n const isInteractionRequiredErrorCode =\n !!errorCode &&\n InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;\n const isInteractionRequiredSubError =\n !!subError &&\n InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;\n const isInteractionRequiredErrorDesc =\n !!errorString &&\n InteractionRequiredServerErrorMessage.some((irErrorCode) => {\n return errorString.indexOf(irErrorCode) > -1;\n });\n\n return (\n isInteractionRequiredErrorCode ||\n isInteractionRequiredErrorDesc ||\n isInteractionRequiredSubError\n );\n}\n\n/**\n * Creates an InteractionRequiredAuthError\n */\nexport function createInteractionRequiredAuthError(\n errorCode: string\n): InteractionRequiredAuthError {\n return new InteractionRequiredAuthError(\n errorCode,\n InteractionRequiredAuthErrorMessages[errorCode]\n );\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IdTokenEntity } from \"./IdTokenEntity\";\nimport { AccessTokenEntity } from \"./AccessTokenEntity\";\nimport { RefreshTokenEntity } from \"./RefreshTokenEntity\";\nimport { AccountEntity } from \"./AccountEntity\";\nimport { AppMetadataEntity } from \"./AppMetadataEntity\";\n\n/** @internal */\nexport class CacheRecord {\n account: AccountEntity | null;\n idToken: IdTokenEntity | null;\n accessToken: AccessTokenEntity | null;\n refreshToken: RefreshTokenEntity | null;\n appMetadata: AppMetadataEntity | null;\n\n constructor(\n accountEntity?: AccountEntity | null,\n idTokenEntity?: IdTokenEntity | null,\n accessTokenEntity?: AccessTokenEntity | null,\n refreshTokenEntity?: RefreshTokenEntity | null,\n appMetadataEntity?: AppMetadataEntity | null\n ) {\n this.account = accountEntity || null;\n this.idToken = idTokenEntity || null;\n this.accessToken = accessTokenEntity || null;\n this.refreshToken = refreshTokenEntity || null;\n this.appMetadata = appMetadataEntity || null;\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { Constants } from \"./Constants\";\nimport { ICrypto } from \"../crypto/ICrypto\";\nimport {\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../error/ClientAuthError\";\n\n/**\n * Type which defines the object that is stringified, encoded and sent in the state value.\n * Contains the following:\n * - id - unique identifier for this request\n * - ts - timestamp for the time the request was made. Used to ensure that token expiration is not calculated incorrectly.\n * - platformState - string value sent from the platform.\n */\nexport type LibraryStateObject = {\n id: string;\n meta?: Record<string, string>;\n};\n\n/**\n * Type which defines the stringified and encoded object sent to the service in the authorize request.\n */\nexport type RequestStateObject = {\n userRequestState: string;\n libraryState: LibraryStateObject;\n};\n\n/**\n * Class which provides helpers for OAuth 2.0 protocol specific values\n */\nexport class ProtocolUtils {\n /**\n * Appends user state with random guid, or returns random guid.\n * @param userState\n * @param randomGuid\n */\n static setRequestState(\n cryptoObj: ICrypto,\n userState?: string,\n meta?: Record<string, string>\n ): string {\n const libraryState = ProtocolUtils.generateLibraryState(\n cryptoObj,\n meta\n );\n return userState\n ? `${libraryState}${Constants.RESOURCE_DELIM}${userState}`\n : libraryState;\n }\n\n /**\n * Generates the state value used by the common library.\n * @param randomGuid\n * @param cryptoObj\n */\n static generateLibraryState(\n cryptoObj: ICrypto,\n meta?: Record<string, string>\n ): string {\n if (!cryptoObj) {\n throw createClientAuthError(ClientAuthErrorCodes.noCryptoObject);\n }\n\n // Create a state object containing a unique id and the timestamp of the request creation\n const stateObj: LibraryStateObject = {\n id: cryptoObj.createNewGuid(),\n };\n\n if (meta) {\n stateObj.meta = meta;\n }\n\n const stateString = JSON.stringify(stateObj);\n\n return cryptoObj.base64Encode(stateString);\n }\n\n /**\n * Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user.\n * @param state\n * @param cryptoObj\n */\n static parseRequestState(\n cryptoObj: ICrypto,\n state: string\n ): RequestStateObject {\n if (!cryptoObj) {\n throw createClientAuthError(ClientAuthErrorCodes.noCryptoObject);\n }\n\n if (!state) {\n throw createClientAuthError(ClientAuthErrorCodes.invalidState);\n }\n\n try {\n // Split the state between library state and user passed state and decode them separately\n const splitState = state.split(Constants.RESOURCE_DELIM);\n const libraryState = splitState[0];\n const userState =\n splitState.length > 1\n ? splitState.slice(1).join(Constants.RESOURCE_DELIM)\n : Constants.EMPTY_STRING;\n const libraryStateString = cryptoObj.base64Decode(libraryState);\n const libraryStateObj = JSON.parse(\n libraryStateString\n ) as LibraryStateObject;\n return {\n userRequestState: userState || Constants.EMPTY_STRING,\n libraryState: libraryStateObj,\n };\n } catch (e) {\n throw createClientAuthError(ClientAuthErrorCodes.invalidState);\n }\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ICrypto, SignedHttpRequestParameters } from \"./ICrypto\";\nimport { TimeUtils } from \"../utils/TimeUtils\";\nimport { UrlString } from \"../url/UrlString\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\nimport { invokeAsync } from \"../utils/FunctionWrappers\";\nimport { Logger } from \"../logger/Logger\";\n\n/**\n * See eSTS docs for more info.\n * - A kid element, with the value containing an RFC 7638-compliant JWK thumbprint that is base64 encoded.\n * - xms_ksl element, representing the storage location of the key's secret component on the client device. One of two values:\n * - sw: software storage\n * - uhw: hardware storage\n */\ntype ReqCnf = {\n kid: string;\n xms_ksl: KeyLocation;\n};\n\nexport type ReqCnfData = {\n kid: string;\n reqCnfString: string;\n reqCnfHash: string;\n};\n\nconst KeyLocation = {\n SW: \"sw\",\n UHW: \"uhw\",\n} as const;\nexport type KeyLocation = (typeof KeyLocation)[keyof typeof KeyLocation];\n\n/** @internal */\nexport class PopTokenGenerator {\n private cryptoUtils: ICrypto;\n private performanceClient?: IPerformanceClient;\n\n constructor(cryptoUtils: ICrypto, performanceClient?: IPerformanceClient) {\n this.cryptoUtils = cryptoUtils;\n this.performanceClient = performanceClient;\n }\n\n /**\n * Generates the req_cnf validated at the RP in the POP protocol for SHR parameters\n * and returns an object containing the keyid, the full req_cnf string and the req_cnf string hash\n * @param request\n * @returns\n */\n async generateCnf(\n request: SignedHttpRequestParameters,\n logger: Logger\n ): Promise<ReqCnfData> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.PopTokenGenerateCnf,\n request.correlationId\n );\n\n const reqCnf = await invokeAsync(\n this.generateKid.bind(this),\n PerformanceEvents.PopTokenGenerateCnf,\n logger,\n this.performanceClient,\n request.correlationId\n )(request);\n const reqCnfString: string = this.cryptoUtils.base64Encode(\n JSON.stringify(reqCnf)\n );\n\n return {\n kid: reqCnf.kid,\n reqCnfString,\n reqCnfHash: await this.cryptoUtils.hashString(reqCnfString),\n };\n }\n\n /**\n * Generates key_id for a SHR token request\n * @param request\n * @returns\n */\n async generateKid(request: SignedHttpRequestParameters): Promise<ReqCnf> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.PopTokenGenerateKid,\n request.correlationId\n );\n\n const kidThumbprint = await this.cryptoUtils.getPublicKeyThumbprint(\n request\n );\n\n return {\n kid: kidThumbprint,\n xms_ksl: KeyLocation.SW,\n };\n }\n\n /**\n * Signs the POP access_token with the local generated key-pair\n * @param accessToken\n * @param request\n * @returns\n */\n async signPopToken(\n accessToken: string,\n keyId: string,\n request: SignedHttpRequestParameters\n ): Promise<string> {\n return this.signPayload(accessToken, keyId, request);\n }\n\n /**\n * Utility function to generate the signed JWT for an access_token\n * @param payload\n * @param kid\n * @param request\n * @param claims\n * @returns\n */\n async signPayload(\n payload: string,\n keyId: string,\n request: SignedHttpRequestParameters,\n claims?: object\n ): Promise<string> {\n // Deconstruct request to extract SHR parameters\n const {\n resourceRequestMethod,\n resourceRequestUri,\n shrClaims,\n shrNonce,\n shrOptions,\n } = request;\n\n const resourceUrlString = resourceRequestUri\n ? new UrlString(resourceRequestUri)\n : undefined;\n const resourceUrlComponents = resourceUrlString?.getUrlComponents();\n return this.cryptoUtils.signJwt(\n {\n at: payload,\n ts: TimeUtils.nowSeconds(),\n m: resourceRequestMethod?.toUpperCase(),\n u: resourceUrlComponents?.HostNameAndPort,\n nonce: shrNonce || this.cryptoUtils.createNewGuid(),\n p: resourceUrlComponents?.AbsolutePath,\n q: resourceUrlComponents?.QueryString\n ? [[], resourceUrlComponents.QueryString]\n : undefined,\n client_claims: shrClaims || undefined,\n ...claims,\n },\n keyId,\n shrOptions,\n request.correlationId\n );\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ISerializableTokenCache } from \"../interface/ISerializableTokenCache\";\n\n/**\n * This class instance helps track the memory changes facilitating\n * decisions to read from and write to the persistent cache\n */ export class TokenCacheContext {\n /**\n * boolean indicating cache change\n */\n hasChanged: boolean;\n /**\n * serializable token cache interface\n */\n cache: ISerializableTokenCache;\n\n constructor(tokenCache: ISerializableTokenCache, hasChanged: boolean) {\n this.cache = tokenCache;\n this.hasChanged = hasChanged;\n }\n\n /**\n * boolean which indicates the changes in cache\n */\n get cacheHasChanged(): boolean {\n return this.hasChanged;\n }\n\n /**\n * function to retrieve the token cache\n */\n get tokenCache(): ISerializableTokenCache {\n return this.cache;\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ServerAuthorizationTokenResponse } from \"./ServerAuthorizationTokenResponse\";\nimport { ICrypto } from \"../crypto/ICrypto\";\nimport {\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../error/ClientAuthError\";\nimport { ServerAuthorizationCodeResponse } from \"./ServerAuthorizationCodeResponse\";\nimport { Logger } from \"../logger/Logger\";\nimport { ServerError } from \"../error/ServerError\";\nimport { ScopeSet } from \"../request/ScopeSet\";\nimport { AuthenticationResult } from \"./AuthenticationResult\";\nimport { AccountEntity } from \"../cache/entities/AccountEntity\";\nimport { Authority } from \"../authority/Authority\";\nimport { IdTokenEntity } from \"../cache/entities/IdTokenEntity\";\nimport { AccessTokenEntity } from \"../cache/entities/AccessTokenEntity\";\nimport { RefreshTokenEntity } from \"../cache/entities/RefreshTokenEntity\";\nimport {\n InteractionRequiredAuthError,\n isInteractionRequiredError,\n} from \"../error/InteractionRequiredAuthError\";\nimport { CacheRecord } from \"../cache/entities/CacheRecord\";\nimport { CacheManager } from \"../cache/CacheManager\";\nimport { ProtocolUtils, RequestStateObject } from \"../utils/ProtocolUtils\";\nimport {\n AuthenticationScheme,\n Constants,\n THE_FAMILY_ID,\n HttpStatus,\n} from \"../utils/Constants\";\nimport { PopTokenGenerator } from \"../crypto/PopTokenGenerator\";\nimport { AppMetadataEntity } from \"../cache/entities/AppMetadataEntity\";\nimport { ICachePlugin } from \"../cache/interface/ICachePlugin\";\nimport { TokenCacheContext } from \"../cache/persistence/TokenCacheContext\";\nimport { ISerializableTokenCache } from \"../cache/interface/ISerializableTokenCache\";\nimport { AuthorizationCodePayload } from \"./AuthorizationCodePayload\";\nimport { BaseAuthRequest } from \"../request/BaseAuthRequest\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\nimport { checkMaxAge, extractTokenClaims } from \"../account/AuthToken\";\nimport {\n TokenClaims,\n getTenantIdFromIdTokenClaims,\n} from \"../account/TokenClaims\";\nimport {\n AccountInfo,\n buildTenantProfileFromIdTokenClaims,\n updateAccountTenantProfileData,\n} from \"../account/AccountInfo\";\nimport * as CacheHelpers from \"../cache/utils/CacheHelpers\";\n\n/**\n * Class that handles response parsing.\n * @internal\n */\nexport class ResponseHandler {\n private clientId: string;\n private cacheStorage: CacheManager;\n private cryptoObj: ICrypto;\n private logger: Logger;\n private homeAccountIdentifier: string;\n private serializableCache: ISerializableTokenCache | null;\n private persistencePlugin: ICachePlugin | null;\n private performanceClient?: IPerformanceClient;\n\n constructor(\n clientId: string,\n cacheStorage: CacheManager,\n cryptoObj: ICrypto,\n logger: Logger,\n serializableCache: ISerializableTokenCache | null,\n persistencePlugin: ICachePlugin | null,\n performanceClient?: IPerformanceClient\n ) {\n this.clientId = clientId;\n this.cacheStorage = cacheStorage;\n this.cryptoObj = cryptoObj;\n this.logger = logger;\n this.serializableCache = serializableCache;\n this.persistencePlugin = persistencePlugin;\n this.performanceClient = performanceClient;\n }\n\n /**\n * Function which validates server authorization code response.\n * @param serverResponseHash\n * @param requestState\n * @param cryptoObj\n */\n validateServerAuthorizationCodeResponse(\n serverResponse: ServerAuthorizationCodeResponse,\n requestState: string\n ): void {\n if (!serverResponse.state || !requestState) {\n throw serverResponse.state\n ? createClientAuthError(\n ClientAuthErrorCodes.stateNotFound,\n \"Cached State\"\n )\n : createClientAuthError(\n ClientAuthErrorCodes.stateNotFound,\n \"Server State\"\n );\n }\n\n let decodedServerResponseState: string;\n let decodedRequestState: string;\n\n try {\n decodedServerResponseState = decodeURIComponent(\n serverResponse.state\n );\n } catch (e) {\n throw createClientAuthError(\n ClientAuthErrorCodes.invalidState,\n serverResponse.state\n );\n }\n\n try {\n decodedRequestState = decodeURIComponent(requestState);\n } catch (e) {\n throw createClientAuthError(\n ClientAuthErrorCodes.invalidState,\n serverResponse.state\n );\n }\n\n if (decodedServerResponseState !== decodedRequestState) {\n throw createClientAuthError(ClientAuthErrorCodes.stateMismatch);\n }\n\n // Check for error\n if (\n serverResponse.error ||\n serverResponse.error_description ||\n serverResponse.suberror\n ) {\n if (\n isInteractionRequiredError(\n serverResponse.error,\n serverResponse.error_description,\n serverResponse.suberror\n )\n ) {\n throw new InteractionRequiredAuthError(\n serverResponse.error || \"\",\n serverResponse.error_description,\n serverResponse.suberror,\n serverResponse.timestamp || \"\",\n serverResponse.trace_id || \"\",\n serverResponse.correlation_id || \"\",\n serverResponse.claims || \"\"\n );\n }\n\n throw new ServerError(\n serverResponse.error || \"\",\n serverResponse.error_description,\n serverResponse.suberror\n );\n }\n }\n\n /**\n * Function which validates server authorization token response.\n * @param serverResponse\n * @param refreshAccessToken\n */\n validateTokenResponse(\n serverResponse: ServerAuthorizationTokenResponse,\n refreshAccessToken?: boolean\n ): void {\n // Check for error\n if (\n serverResponse.error ||\n serverResponse.error_description ||\n serverResponse.suberror\n ) {\n const errString = `${serverResponse.error_codes} - [${serverResponse.timestamp}]: ${serverResponse.error_description} - Correlation ID: ${serverResponse.correlation_id} - Trace ID: ${serverResponse.trace_id}`;\n const serverError = new ServerError(\n serverResponse.error,\n errString,\n serverResponse.suberror\n );\n\n // check if 500 error\n if (\n refreshAccessToken &&\n serverResponse.status &&\n serverResponse.status >= HttpStatus.SERVER_ERROR_RANGE_START &&\n serverResponse.status <= HttpStatus.SERVER_ERROR_RANGE_END\n ) {\n this.logger.warning(\n `executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.\\n${serverError}`\n );\n\n // don't throw an exception, but alert the user via a log that the token was unable to be refreshed\n return;\n // check if 400 error\n } else if (\n refreshAccessToken &&\n serverResponse.status &&\n serverResponse.status >= HttpStatus.CLIENT_ERROR_RANGE_START &&\n serverResponse.status <= HttpStatus.CLIENT_ERROR_RANGE_END\n ) {\n this.logger.warning(\n `executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.\\n${serverError}`\n );\n\n // don't throw an exception, but alert the user via a log that the token was unable to be refreshed\n return;\n }\n\n if (\n isInteractionRequiredError(\n serverResponse.error,\n serverResponse.error_description,\n serverResponse.suberror\n )\n ) {\n throw new InteractionRequiredAuthError(\n serverResponse.error,\n serverResponse.error_description,\n serverResponse.suberror,\n serverResponse.timestamp || Constants.EMPTY_STRING,\n serverResponse.trace_id || Constants.EMPTY_STRING,\n serverResponse.correlation_id || Constants.EMPTY_STRING,\n serverResponse.claims || Constants.EMPTY_STRING\n );\n }\n\n throw serverError;\n }\n }\n\n /**\n * Returns a constructed token response based on given string. Also manages the cache updates and cleanups.\n * @param serverTokenResponse\n * @param authority\n */\n async handleServerTokenResponse(\n serverTokenResponse: ServerAuthorizationTokenResponse,\n authority: Authority,\n reqTimestamp: number,\n request: BaseAuthRequest,\n authCodePayload?: AuthorizationCodePayload,\n userAssertionHash?: string,\n handlingRefreshTokenResponse?: boolean,\n forceCacheRefreshTokenResponse?: boolean,\n serverRequestId?: string\n ): Promise<AuthenticationResult> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.HandleServerTokenResponse,\n serverTokenResponse.correlation_id\n );\n\n // create an idToken object (not entity)\n let idTokenClaims: TokenClaims | undefined;\n if (serverTokenResponse.id_token) {\n idTokenClaims = extractTokenClaims(\n serverTokenResponse.id_token || Constants.EMPTY_STRING,\n this.cryptoObj.base64Decode\n );\n\n // token nonce check (TODO: Add a warning if no nonce is given?)\n if (authCodePayload && authCodePayload.nonce) {\n if (idTokenClaims.nonce !== authCodePayload.nonce) {\n throw createClientAuthError(\n ClientAuthErrorCodes.nonceMismatch\n );\n }\n }\n\n // token max_age check\n if (request.maxAge || request.maxAge === 0) {\n const authTime = idTokenClaims.auth_time;\n if (!authTime) {\n throw createClientAuthError(\n ClientAuthErrorCodes.authTimeNotFound\n );\n }\n\n checkMaxAge(authTime, request.maxAge);\n }\n }\n\n // generate homeAccountId\n this.homeAccountIdentifier = AccountEntity.generateHomeAccountId(\n serverTokenResponse.client_info || Constants.EMPTY_STRING,\n authority.authorityType,\n this.logger,\n this.cryptoObj,\n idTokenClaims\n );\n\n // save the response tokens\n let requestStateObj: RequestStateObject | undefined;\n if (!!authCodePayload && !!authCodePayload.state) {\n requestStateObj = ProtocolUtils.parseRequestState(\n this.cryptoObj,\n authCodePayload.state\n );\n }\n\n // Add keyId from request to serverTokenResponse if defined\n serverTokenResponse.key_id =\n serverTokenResponse.key_id || request.sshKid || undefined;\n\n const cacheRecord = this.generateCacheRecord(\n serverTokenResponse,\n authority,\n reqTimestamp,\n request,\n idTokenClaims,\n userAssertionHash,\n authCodePayload\n );\n let cacheContext;\n try {\n if (this.persistencePlugin && this.serializableCache) {\n this.logger.verbose(\n \"Persistence enabled, calling beforeCacheAccess\"\n );\n cacheContext = new TokenCacheContext(\n this.serializableCache,\n true\n );\n await this.persistencePlugin.beforeCacheAccess(cacheContext);\n }\n /*\n * When saving a refreshed tokens to the cache, it is expected that the account that was used is present in the cache.\n * If not present, we should return null, as it's the case that another application called removeAccount in between\n * the calls to getAllAccounts and acquireTokenSilent. We should not overwrite that removal, unless explicitly flagged by\n * the developer, as in the case of refresh token flow used in ADAL Node to MSAL Node migration.\n */\n if (\n handlingRefreshTokenResponse &&\n !forceCacheRefreshTokenResponse &&\n cacheRecord.account\n ) {\n const key = cacheRecord.account.generateAccountKey();\n const account = this.cacheStorage.getAccount(key, this.logger);\n if (!account) {\n this.logger.warning(\n \"Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache\"\n );\n return await ResponseHandler.generateAuthenticationResult(\n this.cryptoObj,\n authority,\n cacheRecord,\n false,\n request,\n idTokenClaims,\n requestStateObj,\n undefined,\n serverRequestId\n );\n }\n }\n await this.cacheStorage.saveCacheRecord(\n cacheRecord,\n request.storeInCache\n );\n } finally {\n if (\n this.persistencePlugin &&\n this.serializableCache &&\n cacheContext\n ) {\n this.logger.verbose(\n \"Persistence enabled, calling afterCacheAccess\"\n );\n await this.persistencePlugin.afterCacheAccess(cacheContext);\n }\n }\n\n return ResponseHandler.generateAuthenticationResult(\n this.cryptoObj,\n authority,\n cacheRecord,\n false,\n request,\n idTokenClaims,\n requestStateObj,\n serverTokenResponse,\n serverRequestId\n );\n }\n\n /**\n * Generates CacheRecord\n * @param serverTokenResponse\n * @param idTokenObj\n * @param authority\n */\n private generateCacheRecord(\n serverTokenResponse: ServerAuthorizationTokenResponse,\n authority: Authority,\n reqTimestamp: number,\n request: BaseAuthRequest,\n idTokenClaims?: TokenClaims,\n userAssertionHash?: string,\n authCodePayload?: AuthorizationCodePayload\n ): CacheRecord {\n const env = authority.getPreferredCache();\n if (!env) {\n throw createClientAuthError(\n ClientAuthErrorCodes.invalidCacheEnvironment\n );\n }\n\n const claimsTenantId = getTenantIdFromIdTokenClaims(idTokenClaims);\n\n // IdToken: non AAD scenarios can have empty realm\n let cachedIdToken: IdTokenEntity | undefined;\n let cachedAccount: AccountEntity | undefined;\n if (serverTokenResponse.id_token && !!idTokenClaims) {\n cachedIdToken = CacheHelpers.createIdTokenEntity(\n this.homeAccountIdentifier,\n env,\n serverTokenResponse.id_token,\n this.clientId,\n claimsTenantId || \"\"\n );\n\n cachedAccount = buildAccountToCache(\n this.cacheStorage,\n authority,\n this.homeAccountIdentifier,\n idTokenClaims,\n this.cryptoObj.base64Decode,\n serverTokenResponse.client_info,\n env,\n claimsTenantId,\n authCodePayload,\n undefined, // nativeAccountId\n this.logger\n );\n }\n\n // AccessToken\n let cachedAccessToken: AccessTokenEntity | null = null;\n if (serverTokenResponse.access_token) {\n // If scopes not returned in server response, use request scopes\n const responseScopes = serverTokenResponse.scope\n ? ScopeSet.fromString(serverTokenResponse.scope)\n : new ScopeSet(request.scopes || []);\n\n /*\n * Use timestamp calculated before request\n * Server may return timestamps as strings, parse to numbers if so.\n */\n const expiresIn: number =\n (typeof serverTokenResponse.expires_in === \"string\"\n ? parseInt(serverTokenResponse.expires_in, 10)\n : serverTokenResponse.expires_in) || 0;\n const extExpiresIn: number =\n (typeof serverTokenResponse.ext_expires_in === \"string\"\n ? parseInt(serverTokenResponse.ext_expires_in, 10)\n : serverTokenResponse.ext_expires_in) || 0;\n const refreshIn: number | undefined =\n (typeof serverTokenResponse.refresh_in === \"string\"\n ? parseInt(serverTokenResponse.refresh_in, 10)\n : serverTokenResponse.refresh_in) || undefined;\n const tokenExpirationSeconds = reqTimestamp + expiresIn;\n const extendedTokenExpirationSeconds =\n tokenExpirationSeconds + extExpiresIn;\n const refreshOnSeconds =\n refreshIn && refreshIn > 0\n ? reqTimestamp + refreshIn\n : undefined;\n\n // non AAD scenarios can have empty realm\n cachedAccessToken = CacheHelpers.createAccessTokenEntity(\n this.homeAccountIdentifier,\n env,\n serverTokenResponse.access_token,\n this.clientId,\n claimsTenantId || authority.tenant,\n responseScopes.printScopes(),\n tokenExpirationSeconds,\n extendedTokenExpirationSeconds,\n this.cryptoObj.base64Decode,\n refreshOnSeconds,\n serverTokenResponse.token_type,\n userAssertionHash,\n serverTokenResponse.key_id,\n request.claims,\n request.requestedClaimsHash\n );\n }\n\n // refreshToken\n let cachedRefreshToken: RefreshTokenEntity | null = null;\n if (serverTokenResponse.refresh_token) {\n let rtExpiresOn: number | undefined;\n if (serverTokenResponse.refresh_token_expires_in) {\n const rtExpiresIn: number =\n typeof serverTokenResponse.refresh_token_expires_in ===\n \"string\"\n ? parseInt(\n serverTokenResponse.refresh_token_expires_in,\n 10\n )\n : serverTokenResponse.refresh_token_expires_in;\n rtExpiresOn = reqTimestamp + rtExpiresIn;\n }\n cachedRefreshToken = CacheHelpers.createRefreshTokenEntity(\n this.homeAccountIdentifier,\n env,\n serverTokenResponse.refresh_token,\n this.clientId,\n serverTokenResponse.foci,\n userAssertionHash,\n rtExpiresOn\n );\n }\n\n // appMetadata\n let cachedAppMetadata: AppMetadataEntity | null = null;\n if (serverTokenResponse.foci) {\n cachedAppMetadata = {\n clientId: this.clientId,\n environment: env,\n familyId: serverTokenResponse.foci,\n };\n }\n\n return new CacheRecord(\n cachedAccount,\n cachedIdToken,\n cachedAccessToken,\n cachedRefreshToken,\n cachedAppMetadata\n );\n }\n\n /**\n * Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache.\n *\n * Optionally takes a state string that is set as-is in the response.\n *\n * @param cacheRecord\n * @param idTokenObj\n * @param fromTokenCache\n * @param stateString\n */\n static async generateAuthenticationResult(\n cryptoObj: ICrypto,\n authority: Authority,\n cacheRecord: CacheRecord,\n fromTokenCache: boolean,\n request: BaseAuthRequest,\n idTokenClaims?: TokenClaims,\n requestState?: RequestStateObject,\n serverTokenResponse?: ServerAuthorizationTokenResponse,\n requestId?: string\n ): Promise<AuthenticationResult> {\n let accessToken: string = Constants.EMPTY_STRING;\n let responseScopes: Array<string> = [];\n let expiresOn: Date | null = null;\n let extExpiresOn: Date | undefined;\n let refreshOn: Date | undefined;\n let familyId: string = Constants.EMPTY_STRING;\n\n if (cacheRecord.accessToken) {\n if (\n cacheRecord.accessToken.tokenType === AuthenticationScheme.POP\n ) {\n const popTokenGenerator: PopTokenGenerator =\n new PopTokenGenerator(cryptoObj);\n const { secret, keyId } = cacheRecord.accessToken;\n\n if (!keyId) {\n throw createClientAuthError(\n ClientAuthErrorCodes.keyIdMissing\n );\n }\n\n accessToken = await popTokenGenerator.signPopToken(\n secret,\n keyId,\n request\n );\n } else {\n accessToken = cacheRecord.accessToken.secret;\n }\n responseScopes = ScopeSet.fromString(\n cacheRecord.accessToken.target\n ).asArray();\n expiresOn = new Date(\n Number(cacheRecord.accessToken.expiresOn) * 1000\n );\n extExpiresOn = new Date(\n Number(cacheRecord.accessToken.extendedExpiresOn) * 1000\n );\n if (cacheRecord.accessToken.refreshOn) {\n refreshOn = new Date(\n Number(cacheRecord.accessToken.refreshOn) * 1000\n );\n }\n }\n\n if (cacheRecord.appMetadata) {\n familyId =\n cacheRecord.appMetadata.familyId === THE_FAMILY_ID\n ? THE_FAMILY_ID\n : \"\";\n }\n const uid = idTokenClaims?.oid || idTokenClaims?.sub || \"\";\n const tid = idTokenClaims?.tid || \"\";\n\n // for hybrid + native bridge enablement, send back the native account Id\n if (serverTokenResponse?.spa_accountid && !!cacheRecord.account) {\n cacheRecord.account.nativeAccountId =\n serverTokenResponse?.spa_accountid;\n }\n\n const accountInfo: AccountInfo | null = cacheRecord.account\n ? updateAccountTenantProfileData(\n cacheRecord.account.getAccountInfo(),\n undefined, // tenantProfile optional\n idTokenClaims\n )\n : null;\n\n return {\n authority: authority.canonicalAuthority,\n uniqueId: uid,\n tenantId: tid,\n scopes: responseScopes,\n account: accountInfo,\n idToken: cacheRecord?.idToken?.secret || \"\",\n idTokenClaims: idTokenClaims || {},\n accessToken: accessToken,\n fromCache: fromTokenCache,\n expiresOn: expiresOn,\n extExpiresOn: extExpiresOn,\n refreshOn: refreshOn,\n correlationId: request.correlationId,\n requestId: requestId || Constants.EMPTY_STRING,\n familyId: familyId,\n tokenType:\n cacheRecord.accessToken?.tokenType || Constants.EMPTY_STRING,\n state: requestState\n ? requestState.userRequestState\n : Constants.EMPTY_STRING,\n cloudGraphHostName:\n cacheRecord.account?.cloudGraphHostName ||\n Constants.EMPTY_STRING,\n msGraphHost:\n cacheRecord.account?.msGraphHost || Constants.EMPTY_STRING,\n code: serverTokenResponse?.spa_code,\n fromNativeBroker: false,\n };\n }\n}\n\nexport function buildAccountToCache(\n cacheStorage: CacheManager,\n authority: Authority,\n homeAccountId: string,\n idTokenClaims: TokenClaims,\n base64Decode: (input: string) => string,\n clientInfo?: string,\n environment?: string,\n claimsTenantId?: string | null,\n authCodePayload?: AuthorizationCodePayload,\n nativeAccountId?: string,\n logger?: Logger\n): AccountEntity {\n logger?.verbose(\"setCachedAccount called\");\n\n // Check if base account is already cached\n const accountKeys = cacheStorage.getAccountKeys();\n const baseAccountKey = accountKeys.find((accountKey: string) => {\n return accountKey.startsWith(homeAccountId);\n });\n\n let cachedAccount: AccountEntity | null = null;\n if (baseAccountKey) {\n cachedAccount = cacheStorage.getAccount(baseAccountKey, logger);\n }\n\n const baseAccount =\n cachedAccount ||\n AccountEntity.createAccount(\n {\n homeAccountId,\n idTokenClaims,\n clientInfo,\n environment,\n cloudGraphHostName: authCodePayload?.cloud_graph_host_name,\n msGraphHost: authCodePayload?.msgraph_host,\n nativeAccountId: nativeAccountId,\n },\n authority,\n base64Decode\n );\n\n const tenantProfiles = baseAccount.tenantProfiles || [];\n\n if (\n claimsTenantId &&\n !tenantProfiles.find((tenantProfile) => {\n return tenantProfile.tenantId === claimsTenantId;\n })\n ) {\n const newTenantProfile = buildTenantProfileFromIdTokenClaims(\n homeAccountId,\n idTokenClaims\n );\n tenantProfiles.push(newTenantProfile);\n }\n baseAccount.tenantProfiles = tenantProfiles;\n\n return baseAccount;\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { BaseClient } from \"./BaseClient\";\nimport { CommonAuthorizationUrlRequest } from \"../request/CommonAuthorizationUrlRequest\";\nimport { CommonAuthorizationCodeRequest } from \"../request/CommonAuthorizationCodeRequest\";\nimport { Authority } from \"../authority/Authority\";\nimport { RequestParameterBuilder } from \"../request/RequestParameterBuilder\";\nimport {\n GrantType,\n AuthenticationScheme,\n PromptValue,\n Separators,\n HeaderNames,\n} from \"../utils/Constants\";\nimport * as AADServerParamKeys from \"../constants/AADServerParamKeys\";\nimport {\n ClientConfiguration,\n isOidcProtocolMode,\n} from \"../config/ClientConfiguration\";\nimport { ServerAuthorizationTokenResponse } from \"../response/ServerAuthorizationTokenResponse\";\nimport { NetworkResponse } from \"../network/NetworkManager\";\nimport { ResponseHandler } from \"../response/ResponseHandler\";\nimport { AuthenticationResult } from \"../response/AuthenticationResult\";\nimport { StringUtils } from \"../utils/StringUtils\";\nimport {\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../error/ClientAuthError\";\nimport { UrlString } from \"../url/UrlString\";\nimport { ServerAuthorizationCodeResponse } from \"../response/ServerAuthorizationCodeResponse\";\nimport { CommonEndSessionRequest } from \"../request/CommonEndSessionRequest\";\nimport { PopTokenGenerator } from \"../crypto/PopTokenGenerator\";\nimport { RequestThumbprint } from \"../network/RequestThumbprint\";\nimport { AuthorizationCodePayload } from \"../response/AuthorizationCodePayload\";\nimport { TimeUtils } from \"../utils/TimeUtils\";\nimport { AccountInfo } from \"../account/AccountInfo\";\nimport {\n buildClientInfoFromHomeAccountId,\n buildClientInfo,\n} from \"../account/ClientInfo\";\nimport { CcsCredentialType, CcsCredential } from \"../account/CcsCredential\";\nimport {\n createClientConfigurationError,\n ClientConfigurationErrorCodes,\n} from \"../error/ClientConfigurationError\";\nimport { RequestValidator } from \"../request/RequestValidator\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\nimport { invokeAsync } from \"../utils/FunctionWrappers\";\n\n/**\n * Oauth2.0 Authorization Code client\n * @internal\n */\nexport class AuthorizationCodeClient extends BaseClient {\n // Flag to indicate if client is for hybrid spa auth code redemption\n protected includeRedirectUri: boolean = true;\n private oidcDefaultScopes;\n\n constructor(\n configuration: ClientConfiguration,\n performanceClient?: IPerformanceClient\n ) {\n super(configuration, performanceClient);\n this.oidcDefaultScopes =\n this.config.authOptions.authority.options.OIDCOptions?.defaultScopes;\n }\n\n /**\n * Creates the URL of the authorization request letting the user input credentials and consent to the\n * application. The URL target 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 * acquireToken(AuthorizationCodeRequest)\n * @param request\n */\n async getAuthCodeUrl(\n request: CommonAuthorizationUrlRequest\n ): Promise<string> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.GetAuthCodeUrl,\n request.correlationId\n );\n\n const queryString = await invokeAsync(\n this.createAuthCodeUrlQueryString.bind(this),\n PerformanceEvents.AuthClientCreateQueryString,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request);\n\n return UrlString.appendQueryString(\n this.authority.authorizationEndpoint,\n queryString\n );\n }\n\n /**\n * API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the\n * authorization_code_grant\n * @param request\n */\n async acquireToken(\n request: CommonAuthorizationCodeRequest,\n authCodePayload?: AuthorizationCodePayload\n ): Promise<AuthenticationResult> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthClientAcquireToken,\n request.correlationId\n );\n\n if (!request.code) {\n throw createClientAuthError(\n ClientAuthErrorCodes.requestCannotBeMade\n );\n }\n\n const reqTimestamp = TimeUtils.nowSeconds();\n const response = await invokeAsync(\n this.executeTokenRequest.bind(this),\n PerformanceEvents.AuthClientExecuteTokenRequest,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(this.authority, request);\n\n // Retrieve requestId from response headers\n const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];\n\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin,\n this.performanceClient\n );\n\n // Validate response. This function throws a server error if an error is returned by the server.\n responseHandler.validateTokenResponse(response.body);\n\n return invokeAsync(\n responseHandler.handleServerTokenResponse.bind(responseHandler),\n PerformanceEvents.HandleServerTokenResponse,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(\n response.body,\n this.authority,\n reqTimestamp,\n request,\n authCodePayload,\n undefined,\n undefined,\n undefined,\n requestId\n );\n }\n\n /**\n * Handles the hash fragment response from public client code request. Returns a code response used by\n * the client to exchange for a token in acquireToken.\n * @param hashFragment\n */\n handleFragmentResponse(\n serverParams: ServerAuthorizationCodeResponse,\n cachedState: string\n ): AuthorizationCodePayload {\n // Handle responses.\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n null,\n null\n );\n\n // Get code response\n responseHandler.validateServerAuthorizationCodeResponse(\n serverParams,\n cachedState\n );\n\n // throw when there is no auth code in the response\n if (!serverParams.code) {\n throw createClientAuthError(\n ClientAuthErrorCodes.authorizationCodeMissingFromServerResponse\n );\n }\n\n return serverParams as AuthorizationCodePayload;\n }\n\n /**\n * Used to log out the current user, and redirect the user to the postLogoutRedirectUri.\n * Default behaviour is to redirect the user to `window.location.href`.\n * @param authorityUri\n */\n getLogoutUri(logoutRequest: CommonEndSessionRequest): string {\n // Throw error if logoutRequest is null/undefined\n if (!logoutRequest) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.logoutRequestEmpty\n );\n }\n const queryString = this.createLogoutUrlQueryString(logoutRequest);\n\n // Construct logout URI\n return UrlString.appendQueryString(\n this.authority.endSessionEndpoint,\n queryString\n );\n }\n\n /**\n * Executes POST request to token endpoint\n * @param authority\n * @param request\n */\n private async executeTokenRequest(\n authority: Authority,\n request: CommonAuthorizationCodeRequest\n ): Promise<NetworkResponse<ServerAuthorizationTokenResponse>> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthClientExecuteTokenRequest,\n request.correlationId\n );\n\n const queryParametersString = this.createTokenQueryParameters(request);\n const endpoint = UrlString.appendQueryString(\n authority.tokenEndpoint,\n queryParametersString\n );\n\n const requestBody = await invokeAsync(\n this.createTokenRequestBody.bind(this),\n PerformanceEvents.AuthClientCreateTokenRequestBody,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request);\n\n let ccsCredential: CcsCredential | undefined = undefined;\n if (request.clientInfo) {\n try {\n const clientInfo = buildClientInfo(\n request.clientInfo,\n this.cryptoUtils.base64Decode\n );\n ccsCredential = {\n credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,\n type: CcsCredentialType.HOME_ACCOUNT_ID,\n };\n } catch (e) {\n this.logger.verbose(\n \"Could not parse client info for CCS Header: \" + e\n );\n }\n }\n const headers: Record<string, string> = this.createTokenRequestHeaders(\n ccsCredential || request.ccsCredential\n );\n\n const thumbprint: RequestThumbprint = {\n clientId:\n request.tokenBodyParameters?.clientId ||\n this.config.authOptions.clientId,\n authority: authority.canonicalAuthority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid,\n };\n\n return invokeAsync(\n this.executePostToTokenEndpoint.bind(this),\n PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(\n endpoint,\n requestBody,\n headers,\n thumbprint,\n request.correlationId,\n PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint\n );\n }\n\n /**\n * Generates a map for all the params to be sent to the service\n * @param request\n */\n private async createTokenRequestBody(\n request: CommonAuthorizationCodeRequest\n ): Promise<string> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthClientCreateTokenRequestBody,\n request.correlationId\n );\n\n const parameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addClientId(\n request.tokenBodyParameters?.[AADServerParamKeys.CLIENT_ID] ||\n this.config.authOptions.clientId\n );\n\n /*\n * For hybrid spa flow, there will be a code but no verifier\n * In this scenario, don't include redirect uri as auth code will not be bound to redirect URI\n */\n if (!this.includeRedirectUri) {\n // Just validate\n RequestValidator.validateRedirectUri(request.redirectUri);\n } else {\n // Validate and include redirect uri\n parameterBuilder.addRedirectUri(request.redirectUri);\n }\n\n // Add scope array, parameter builder will add default scopes and dedupe\n parameterBuilder.addScopes(\n request.scopes,\n true,\n this.oidcDefaultScopes\n );\n\n // add code: user set, not validated\n parameterBuilder.addAuthorizationCode(request.code);\n\n // Add library metadata\n parameterBuilder.addLibraryInfo(this.config.libraryInfo);\n parameterBuilder.addApplicationTelemetry(\n this.config.telemetry.application\n );\n parameterBuilder.addThrottling();\n\n if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {\n parameterBuilder.addServerTelemetry(this.serverTelemetryManager);\n }\n\n // add code_verifier if passed\n if (request.codeVerifier) {\n parameterBuilder.addCodeVerifier(request.codeVerifier);\n }\n\n if (this.config.clientCredentials.clientSecret) {\n parameterBuilder.addClientSecret(\n this.config.clientCredentials.clientSecret\n );\n }\n\n if (this.config.clientCredentials.clientAssertion) {\n const clientAssertion =\n this.config.clientCredentials.clientAssertion;\n parameterBuilder.addClientAssertion(clientAssertion.assertion);\n parameterBuilder.addClientAssertionType(\n clientAssertion.assertionType\n );\n }\n\n parameterBuilder.addGrantType(GrantType.AUTHORIZATION_CODE_GRANT);\n parameterBuilder.addClientInfo();\n\n if (request.authenticationScheme === AuthenticationScheme.POP) {\n const popTokenGenerator = new PopTokenGenerator(\n this.cryptoUtils,\n this.performanceClient\n );\n\n const reqCnfData = await invokeAsync(\n popTokenGenerator.generateCnf.bind(popTokenGenerator),\n PerformanceEvents.PopTokenGenerateCnf,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request, this.logger);\n // SPA PoP requires full Base64Url encoded req_cnf string (unhashed)\n parameterBuilder.addPopToken(reqCnfData.reqCnfString);\n } else if (request.authenticationScheme === AuthenticationScheme.SSH) {\n if (request.sshJwk) {\n parameterBuilder.addSshJwk(request.sshJwk);\n } else {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.missingSshJwk\n );\n }\n }\n\n const correlationId =\n request.correlationId ||\n this.config.cryptoInterface.createNewGuid();\n parameterBuilder.addCorrelationId(correlationId);\n\n if (\n !StringUtils.isEmptyObj(request.claims) ||\n (this.config.authOptions.clientCapabilities &&\n this.config.authOptions.clientCapabilities.length > 0)\n ) {\n parameterBuilder.addClaims(\n request.claims,\n this.config.authOptions.clientCapabilities\n );\n }\n\n let ccsCred: CcsCredential | undefined = undefined;\n if (request.clientInfo) {\n try {\n const clientInfo = buildClientInfo(\n request.clientInfo,\n this.cryptoUtils.base64Decode\n );\n ccsCred = {\n credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,\n type: CcsCredentialType.HOME_ACCOUNT_ID,\n };\n } catch (e) {\n this.logger.verbose(\n \"Could not parse client info for CCS Header: \" + e\n );\n }\n } else {\n ccsCred = request.ccsCredential;\n }\n\n // Adds these as parameters in the request instead of headers to prevent CORS preflight request\n if (this.config.systemOptions.preventCorsPreflight && ccsCred) {\n switch (ccsCred.type) {\n case CcsCredentialType.HOME_ACCOUNT_ID:\n try {\n const clientInfo = buildClientInfoFromHomeAccountId(\n ccsCred.credential\n );\n parameterBuilder.addCcsOid(clientInfo);\n } catch (e) {\n this.logger.verbose(\n \"Could not parse home account ID for CCS Header: \" +\n e\n );\n }\n break;\n case CcsCredentialType.UPN:\n parameterBuilder.addCcsUpn(ccsCred.credential);\n break;\n }\n }\n\n if (request.tokenBodyParameters) {\n parameterBuilder.addExtraQueryParameters(\n request.tokenBodyParameters\n );\n }\n\n // Add hybrid spa parameters if not already provided\n if (\n request.enableSpaAuthorizationCode &&\n (!request.tokenBodyParameters ||\n !request.tokenBodyParameters[\n AADServerParamKeys.RETURN_SPA_CODE\n ])\n ) {\n parameterBuilder.addExtraQueryParameters({\n [AADServerParamKeys.RETURN_SPA_CODE]: \"1\",\n });\n }\n\n return parameterBuilder.createQueryString();\n }\n\n /**\n * This API validates the `AuthorizationCodeUrlRequest` and creates a URL\n * @param request\n */\n private async createAuthCodeUrlQueryString(\n request: CommonAuthorizationUrlRequest\n ): Promise<string> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.AuthClientCreateQueryString,\n request.correlationId\n );\n\n const parameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addClientId(\n request.extraQueryParameters?.[AADServerParamKeys.CLIENT_ID] ||\n this.config.authOptions.clientId\n );\n\n const requestScopes = [\n ...(request.scopes || []),\n ...(request.extraScopesToConsent || []),\n ];\n parameterBuilder.addScopes(requestScopes, true, this.oidcDefaultScopes);\n\n // validate the redirectUri (to be a non null value)\n parameterBuilder.addRedirectUri(request.redirectUri);\n\n // generate the correlationId if not set by the user and add\n const correlationId =\n request.correlationId ||\n this.config.cryptoInterface.createNewGuid();\n parameterBuilder.addCorrelationId(correlationId);\n\n // add response_mode. If not passed in it defaults to query.\n parameterBuilder.addResponseMode(request.responseMode);\n\n // add response_type = code\n parameterBuilder.addResponseTypeCode();\n\n // add library info parameters\n parameterBuilder.addLibraryInfo(this.config.libraryInfo);\n if (!isOidcProtocolMode(this.config)) {\n parameterBuilder.addApplicationTelemetry(\n this.config.telemetry.application\n );\n }\n\n // add client_info=1\n parameterBuilder.addClientInfo();\n\n if (request.codeChallenge && request.codeChallengeMethod) {\n parameterBuilder.addCodeChallengeParams(\n request.codeChallenge,\n request.codeChallengeMethod\n );\n }\n\n if (request.prompt) {\n parameterBuilder.addPrompt(request.prompt);\n }\n\n if (request.domainHint) {\n parameterBuilder.addDomainHint(request.domainHint);\n }\n\n // Add sid or loginHint with preference for login_hint claim (in request) -> sid -> loginHint (upn/email) -> username of AccountInfo object\n if (request.prompt !== PromptValue.SELECT_ACCOUNT) {\n // AAD will throw if prompt=select_account is passed with an account hint\n if (request.sid && request.prompt === PromptValue.NONE) {\n // SessionID is only used in silent calls\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: Prompt is none, adding sid from request\"\n );\n parameterBuilder.addSid(request.sid);\n } else if (request.account) {\n const accountSid = this.extractAccountSid(request.account);\n const accountLoginHintClaim = this.extractLoginHint(\n request.account\n );\n // If login_hint claim is present, use it over sid/username\n if (accountLoginHintClaim) {\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: login_hint claim present on account\"\n );\n parameterBuilder.addLoginHint(accountLoginHintClaim);\n try {\n const clientInfo = buildClientInfoFromHomeAccountId(\n request.account.homeAccountId\n );\n parameterBuilder.addCcsOid(clientInfo);\n } catch (e) {\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header\"\n );\n }\n } else if (accountSid && request.prompt === PromptValue.NONE) {\n /*\n * If account and loginHint are provided, we will check account first for sid before adding loginHint\n * SessionId is only used in silent calls\n */\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: Prompt is none, adding sid from account\"\n );\n parameterBuilder.addSid(accountSid);\n try {\n const clientInfo = buildClientInfoFromHomeAccountId(\n request.account.homeAccountId\n );\n parameterBuilder.addCcsOid(clientInfo);\n } catch (e) {\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header\"\n );\n }\n } else if (request.loginHint) {\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: Adding login_hint from request\"\n );\n parameterBuilder.addLoginHint(request.loginHint);\n parameterBuilder.addCcsUpn(request.loginHint);\n } else if (request.account.username) {\n // Fallback to account username if provided\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: Adding login_hint from account\"\n );\n parameterBuilder.addLoginHint(request.account.username);\n try {\n const clientInfo = buildClientInfoFromHomeAccountId(\n request.account.homeAccountId\n );\n parameterBuilder.addCcsOid(clientInfo);\n } catch (e) {\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header\"\n );\n }\n }\n } else if (request.loginHint) {\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: No account, adding login_hint from request\"\n );\n parameterBuilder.addLoginHint(request.loginHint);\n parameterBuilder.addCcsUpn(request.loginHint);\n }\n } else {\n this.logger.verbose(\n \"createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints\"\n );\n }\n\n if (request.nonce) {\n parameterBuilder.addNonce(request.nonce);\n }\n\n if (request.state) {\n parameterBuilder.addState(request.state);\n }\n\n if (\n request.claims ||\n (this.config.authOptions.clientCapabilities &&\n this.config.authOptions.clientCapabilities.length > 0)\n ) {\n parameterBuilder.addClaims(\n request.claims,\n this.config.authOptions.clientCapabilities\n );\n }\n\n if (request.extraQueryParameters) {\n parameterBuilder.addExtraQueryParameters(\n request.extraQueryParameters\n );\n }\n\n if (request.nativeBroker) {\n // signal ests that this is a WAM call\n parameterBuilder.addNativeBroker();\n\n // pass the req_cnf for POP\n if (request.authenticationScheme === AuthenticationScheme.POP) {\n const popTokenGenerator = new PopTokenGenerator(\n this.cryptoUtils\n );\n // to reduce the URL length, it is recommended to send the hash of the req_cnf instead of the whole string\n const reqCnfData = await invokeAsync(\n popTokenGenerator.generateCnf.bind(popTokenGenerator),\n PerformanceEvents.PopTokenGenerateCnf,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request, this.logger);\n parameterBuilder.addPopToken(reqCnfData.reqCnfHash);\n }\n }\n\n return parameterBuilder.createQueryString();\n }\n\n /**\n * This API validates the `EndSessionRequest` and creates a URL\n * @param request\n */\n private createLogoutUrlQueryString(\n request: CommonEndSessionRequest\n ): string {\n const parameterBuilder = new RequestParameterBuilder();\n\n if (request.postLogoutRedirectUri) {\n parameterBuilder.addPostLogoutRedirectUri(\n request.postLogoutRedirectUri\n );\n }\n\n if (request.correlationId) {\n parameterBuilder.addCorrelationId(request.correlationId);\n }\n\n if (request.idTokenHint) {\n parameterBuilder.addIdTokenHint(request.idTokenHint);\n }\n\n if (request.state) {\n parameterBuilder.addState(request.state);\n }\n\n if (request.logoutHint) {\n parameterBuilder.addLogoutHint(request.logoutHint);\n }\n\n if (request.extraQueryParameters) {\n parameterBuilder.addExtraQueryParameters(\n request.extraQueryParameters\n );\n }\n\n return parameterBuilder.createQueryString();\n }\n\n /**\n * Helper to get sid from account. Returns null if idTokenClaims are not present or sid is not present.\n * @param account\n */\n private extractAccountSid(account: AccountInfo): string | null {\n return account.idTokenClaims?.sid || null;\n }\n\n private extractLoginHint(account: AccountInfo): string | null {\n return account.idTokenClaims?.login_hint || null;\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n ClientConfiguration,\n isOidcProtocolMode,\n} from \"../config/ClientConfiguration\";\nimport { BaseClient } from \"./BaseClient\";\nimport { CommonRefreshTokenRequest } from \"../request/CommonRefreshTokenRequest\";\nimport { Authority } from \"../authority/Authority\";\nimport { ServerAuthorizationTokenResponse } from \"../response/ServerAuthorizationTokenResponse\";\nimport { RequestParameterBuilder } from \"../request/RequestParameterBuilder\";\nimport {\n GrantType,\n AuthenticationScheme,\n Errors,\n HeaderNames,\n} from \"../utils/Constants\";\nimport * as AADServerParamKeys from \"../constants/AADServerParamKeys\";\nimport { ResponseHandler } from \"../response/ResponseHandler\";\nimport { AuthenticationResult } from \"../response/AuthenticationResult\";\nimport { PopTokenGenerator } from \"../crypto/PopTokenGenerator\";\nimport { StringUtils } from \"../utils/StringUtils\";\nimport { RequestThumbprint } from \"../network/RequestThumbprint\";\nimport { NetworkResponse } from \"../network/NetworkManager\";\nimport { CommonSilentFlowRequest } from \"../request/CommonSilentFlowRequest\";\nimport {\n createClientConfigurationError,\n ClientConfigurationErrorCodes,\n} from \"../error/ClientConfigurationError\";\nimport {\n createClientAuthError,\n ClientAuthErrorCodes,\n} from \"../error/ClientAuthError\";\nimport { ServerError } from \"../error/ServerError\";\nimport { TimeUtils } from \"../utils/TimeUtils\";\nimport { UrlString } from \"../url/UrlString\";\nimport { CcsCredentialType } from \"../account/CcsCredential\";\nimport { buildClientInfoFromHomeAccountId } from \"../account/ClientInfo\";\nimport {\n InteractionRequiredAuthError,\n InteractionRequiredAuthErrorCodes,\n createInteractionRequiredAuthError,\n} from \"../error/InteractionRequiredAuthError\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\nimport { invoke, invokeAsync } from \"../utils/FunctionWrappers\";\nimport { generateCredentialKey } from \"../cache/utils/CacheHelpers\";\n\nconst DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS = 300; // 5 Minutes\n\n/**\n * OAuth2.0 refresh token client\n * @internal\n */\nexport class RefreshTokenClient extends BaseClient {\n constructor(\n configuration: ClientConfiguration,\n performanceClient?: IPerformanceClient\n ) {\n super(configuration, performanceClient);\n }\n public async acquireToken(\n request: CommonRefreshTokenRequest\n ): Promise<AuthenticationResult> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.RefreshTokenClientAcquireToken,\n request.correlationId\n );\n\n const reqTimestamp = TimeUtils.nowSeconds();\n const response = await invokeAsync(\n this.executeTokenRequest.bind(this),\n PerformanceEvents.RefreshTokenClientExecuteTokenRequest,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request, this.authority);\n\n // Retrieve requestId from response headers\n const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin\n );\n responseHandler.validateTokenResponse(response.body);\n\n return invokeAsync(\n responseHandler.handleServerTokenResponse.bind(responseHandler),\n PerformanceEvents.HandleServerTokenResponse,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(\n response.body,\n this.authority,\n reqTimestamp,\n request,\n undefined,\n undefined,\n true,\n request.forceCache,\n requestId\n );\n }\n\n /**\n * Gets cached refresh token and attaches to request, then calls acquireToken API\n * @param request\n */\n public async acquireTokenByRefreshToken(\n request: CommonSilentFlowRequest\n ): Promise<AuthenticationResult> {\n // Cannot renew token if no request object is given.\n if (!request) {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.tokenRequestEmpty\n );\n }\n\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken,\n request.correlationId\n );\n\n // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases\n if (!request.account) {\n throw createClientAuthError(\n ClientAuthErrorCodes.noAccountInSilentRequest\n );\n }\n\n // try checking if FOCI is enabled for the given application\n const isFOCI = this.cacheManager.isAppMetadataFOCI(\n request.account.environment\n );\n\n // if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest\n if (isFOCI) {\n try {\n return await invokeAsync(\n this.acquireTokenWithCachedRefreshToken.bind(this),\n PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request, true);\n } catch (e) {\n const noFamilyRTInCache =\n e instanceof InteractionRequiredAuthError &&\n e.errorCode ===\n InteractionRequiredAuthErrorCodes.noTokensFound;\n const clientMismatchErrorWithFamilyRT =\n e instanceof ServerError &&\n e.errorCode === Errors.INVALID_GRANT_ERROR &&\n e.subError === Errors.CLIENT_MISMATCH_ERROR;\n\n // if family Refresh Token (FRT) cache acquisition fails or if client_mismatch error is seen with FRT, reattempt with application Refresh Token (ART)\n if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) {\n return invokeAsync(\n this.acquireTokenWithCachedRefreshToken.bind(this),\n PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request, false);\n // throw in all other cases\n } else {\n throw e;\n }\n }\n }\n // fall back to application refresh token acquisition\n return invokeAsync(\n this.acquireTokenWithCachedRefreshToken.bind(this),\n PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request, false);\n }\n\n /**\n * makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached\n * @param request\n */\n private async acquireTokenWithCachedRefreshToken(\n request: CommonSilentFlowRequest,\n foci: boolean\n ) {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken,\n request.correlationId\n );\n\n // fetches family RT or application RT based on FOCI value\n const refreshToken = invoke(\n this.cacheManager.getRefreshToken.bind(this.cacheManager),\n PerformanceEvents.CacheManagerGetRefreshToken,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(\n request.account,\n foci,\n undefined,\n this.performanceClient,\n request.correlationId\n );\n\n if (!refreshToken) {\n throw createInteractionRequiredAuthError(\n InteractionRequiredAuthErrorCodes.noTokensFound\n );\n }\n\n if (\n refreshToken.expiresOn &&\n TimeUtils.isTokenExpired(\n refreshToken.expiresOn,\n request.refreshTokenExpirationOffsetSeconds ||\n DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS\n )\n ) {\n throw createInteractionRequiredAuthError(\n InteractionRequiredAuthErrorCodes.refreshTokenExpired\n );\n }\n // attach cached RT size to the current measurement\n\n const refreshTokenRequest: CommonRefreshTokenRequest = {\n ...request,\n refreshToken: refreshToken.secret,\n authenticationScheme:\n request.authenticationScheme || AuthenticationScheme.BEARER,\n ccsCredential: {\n credential: request.account.homeAccountId,\n type: CcsCredentialType.HOME_ACCOUNT_ID,\n },\n };\n\n try {\n return await invokeAsync(\n this.acquireToken.bind(this),\n PerformanceEvents.RefreshTokenClientAcquireToken,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(refreshTokenRequest);\n } catch (e) {\n if (\n e instanceof InteractionRequiredAuthError &&\n e.subError === InteractionRequiredAuthErrorCodes.badToken\n ) {\n // Remove bad refresh token from cache\n this.logger.verbose(\n \"acquireTokenWithRefreshToken: bad refresh token, removing from cache\"\n );\n const badRefreshTokenKey = generateCredentialKey(refreshToken);\n this.cacheManager.removeRefreshToken(badRefreshTokenKey);\n }\n\n throw e;\n }\n }\n\n /**\n * Constructs the network message and makes a NW call to the underlying secure token service\n * @param request\n * @param authority\n */\n private async executeTokenRequest(\n request: CommonRefreshTokenRequest,\n authority: Authority\n ): Promise<NetworkResponse<ServerAuthorizationTokenResponse>> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.RefreshTokenClientExecuteTokenRequest,\n request.correlationId\n );\n\n const queryParametersString = this.createTokenQueryParameters(request);\n const endpoint = UrlString.appendQueryString(\n authority.tokenEndpoint,\n queryParametersString\n );\n\n const requestBody = await invokeAsync(\n this.createTokenRequestBody.bind(this),\n PerformanceEvents.RefreshTokenClientCreateTokenRequestBody,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request);\n const headers: Record<string, string> = this.createTokenRequestHeaders(\n request.ccsCredential\n );\n const thumbprint: RequestThumbprint = {\n clientId:\n request.tokenBodyParameters?.clientId ||\n this.config.authOptions.clientId,\n authority: authority.canonicalAuthority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid,\n };\n\n return invokeAsync(\n this.executePostToTokenEndpoint.bind(this),\n PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(\n endpoint,\n requestBody,\n headers,\n thumbprint,\n request.correlationId,\n PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint\n );\n }\n\n /**\n * Helper function to create the token request body\n * @param request\n */\n private async createTokenRequestBody(\n request: CommonRefreshTokenRequest\n ): Promise<string> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.RefreshTokenClientCreateTokenRequestBody,\n request.correlationId\n );\n\n const correlationId = request.correlationId;\n const parameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addClientId(\n request.tokenBodyParameters?.[AADServerParamKeys.CLIENT_ID] ||\n this.config.authOptions.clientId\n );\n\n if (request.redirectUri) {\n parameterBuilder.addRedirectUri(request.redirectUri);\n }\n\n parameterBuilder.addScopes(\n request.scopes,\n true,\n this.config.authOptions.authority.options.OIDCOptions?.defaultScopes\n );\n\n parameterBuilder.addGrantType(GrantType.REFRESH_TOKEN_GRANT);\n\n parameterBuilder.addClientInfo();\n\n parameterBuilder.addLibraryInfo(this.config.libraryInfo);\n parameterBuilder.addApplicationTelemetry(\n this.config.telemetry.application\n );\n parameterBuilder.addThrottling();\n\n if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {\n parameterBuilder.addServerTelemetry(this.serverTelemetryManager);\n }\n\n parameterBuilder.addCorrelationId(correlationId);\n\n parameterBuilder.addRefreshToken(request.refreshToken);\n\n if (this.config.clientCredentials.clientSecret) {\n parameterBuilder.addClientSecret(\n this.config.clientCredentials.clientSecret\n );\n }\n\n if (this.config.clientCredentials.clientAssertion) {\n const clientAssertion =\n this.config.clientCredentials.clientAssertion;\n parameterBuilder.addClientAssertion(clientAssertion.assertion);\n parameterBuilder.addClientAssertionType(\n clientAssertion.assertionType\n );\n }\n\n if (request.authenticationScheme === AuthenticationScheme.POP) {\n const popTokenGenerator = new PopTokenGenerator(\n this.cryptoUtils,\n this.performanceClient\n );\n const reqCnfData = await invokeAsync(\n popTokenGenerator.generateCnf.bind(popTokenGenerator),\n PerformanceEvents.PopTokenGenerateCnf,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(request, this.logger);\n // SPA PoP requires full Base64Url encoded req_cnf string (unhashed)\n parameterBuilder.addPopToken(reqCnfData.reqCnfString);\n } else if (request.authenticationScheme === AuthenticationScheme.SSH) {\n if (request.sshJwk) {\n parameterBuilder.addSshJwk(request.sshJwk);\n } else {\n throw createClientConfigurationError(\n ClientConfigurationErrorCodes.missingSshJwk\n );\n }\n }\n\n if (\n !StringUtils.isEmptyObj(request.claims) ||\n (this.config.authOptions.clientCapabilities &&\n this.config.authOptions.clientCapabilities.length > 0)\n ) {\n parameterBuilder.addClaims(\n request.claims,\n this.config.authOptions.clientCapabilities\n );\n }\n\n if (\n this.config.systemOptions.preventCorsPreflight &&\n request.ccsCredential\n ) {\n switch (request.ccsCredential.type) {\n case CcsCredentialType.HOME_ACCOUNT_ID:\n try {\n const clientInfo = buildClientInfoFromHomeAccountId(\n request.ccsCredential.credential\n );\n parameterBuilder.addCcsOid(clientInfo);\n } catch (e) {\n this.logger.verbose(\n \"Could not parse home account ID for CCS Header: \" +\n e\n );\n }\n break;\n case CcsCredentialType.UPN:\n parameterBuilder.addCcsUpn(\n request.ccsCredential.credential\n );\n break;\n }\n }\n\n if (request.tokenBodyParameters) {\n parameterBuilder.addExtraQueryParameters(\n request.tokenBodyParameters\n );\n }\n\n return parameterBuilder.createQueryString();\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { BaseClient } from \"./BaseClient\";\nimport { ClientConfiguration } from \"../config/ClientConfiguration\";\nimport { CommonSilentFlowRequest } from \"../request/CommonSilentFlowRequest\";\nimport { AuthenticationResult } from \"../response/AuthenticationResult\";\nimport { TimeUtils } from \"../utils/TimeUtils\";\nimport { RefreshTokenClient } from \"./RefreshTokenClient\";\nimport {\n ClientAuthError,\n ClientAuthErrorCodes,\n createClientAuthError,\n} from \"../error/ClientAuthError\";\nimport { ResponseHandler } from \"../response/ResponseHandler\";\nimport { CacheRecord } from \"../cache/entities/CacheRecord\";\nimport { CacheOutcome } from \"../utils/Constants\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\nimport { StringUtils } from \"../utils/StringUtils\";\nimport { checkMaxAge, extractTokenClaims } from \"../account/AuthToken\";\nimport { TokenClaims } from \"../account/TokenClaims\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\nimport { invokeAsync } from \"../utils/FunctionWrappers\";\nimport { getTenantFromAuthorityString } from \"../authority/Authority\";\n\n/** @internal */\nexport class SilentFlowClient extends BaseClient {\n constructor(\n configuration: ClientConfiguration,\n performanceClient?: IPerformanceClient\n ) {\n super(configuration, performanceClient);\n }\n\n /**\n * Retrieves a token from cache if it is still valid, or uses the cached refresh token to renew\n * the given token and returns the renewed token\n * @param request\n */\n async acquireToken(\n request: CommonSilentFlowRequest\n ): Promise<AuthenticationResult> {\n try {\n const [authResponse, cacheOutcome] = await this.acquireCachedToken(\n request\n );\n\n // if the token is not expired but must be refreshed; get a new one in the background\n if (cacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {\n this.logger.info(\n \"SilentFlowClient:acquireCachedToken - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.\"\n );\n\n // refresh the access token in the background\n const refreshTokenClient = new RefreshTokenClient(\n this.config,\n this.performanceClient\n );\n\n refreshTokenClient\n .acquireTokenByRefreshToken(request)\n .catch(() => {\n // do nothing, this is running in the background and no action is to be taken upon success or failure\n });\n }\n\n // return the cached token\n return authResponse;\n } catch (e) {\n if (\n e instanceof ClientAuthError &&\n e.errorCode === ClientAuthErrorCodes.tokenRefreshRequired\n ) {\n const refreshTokenClient = new RefreshTokenClient(\n this.config,\n this.performanceClient\n );\n return refreshTokenClient.acquireTokenByRefreshToken(request);\n } else {\n throw e;\n }\n }\n }\n\n /**\n * Retrieves token from cache or throws an error if it must be refreshed.\n * @param request\n */\n async acquireCachedToken(\n request: CommonSilentFlowRequest\n ): Promise<[AuthenticationResult, CacheOutcome]> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.SilentFlowClientAcquireCachedToken,\n request.correlationId\n );\n let lastCacheOutcome: CacheOutcome = CacheOutcome.NOT_APPLICABLE;\n\n if (\n request.forceRefresh ||\n (!this.config.cacheOptions.claimsBasedCachingEnabled &&\n !StringUtils.isEmptyObj(request.claims))\n ) {\n // Must refresh due to present force_refresh flag.\n this.setCacheOutcome(\n CacheOutcome.FORCE_REFRESH_OR_CLAIMS,\n request.correlationId\n );\n throw createClientAuthError(\n ClientAuthErrorCodes.tokenRefreshRequired\n );\n }\n\n // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases\n if (!request.account) {\n throw createClientAuthError(\n ClientAuthErrorCodes.noAccountInSilentRequest\n );\n }\n\n const requestTenantId =\n request.account.tenantId ||\n getTenantFromAuthorityString(request.authority);\n const tokenKeys = this.cacheManager.getTokenKeys();\n const cachedAccessToken = this.cacheManager.getAccessToken(\n request.account,\n request,\n tokenKeys,\n requestTenantId,\n this.performanceClient,\n request.correlationId\n );\n\n if (!cachedAccessToken) {\n // must refresh due to non-existent access_token\n this.setCacheOutcome(\n CacheOutcome.NO_CACHED_ACCESS_TOKEN,\n request.correlationId\n );\n throw createClientAuthError(\n ClientAuthErrorCodes.tokenRefreshRequired\n );\n } else if (\n TimeUtils.wasClockTurnedBack(cachedAccessToken.cachedAt) ||\n TimeUtils.isTokenExpired(\n cachedAccessToken.expiresOn,\n this.config.systemOptions.tokenRenewalOffsetSeconds\n )\n ) {\n // must refresh due to the expires_in value\n this.setCacheOutcome(\n CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED,\n request.correlationId\n );\n throw createClientAuthError(\n ClientAuthErrorCodes.tokenRefreshRequired\n );\n } else if (\n cachedAccessToken.refreshOn &&\n TimeUtils.isTokenExpired(cachedAccessToken.refreshOn, 0)\n ) {\n // must refresh (in the background) due to the refresh_in value\n lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;\n\n // don't throw ClientAuthError.createRefreshRequiredError(), return cached token instead\n }\n\n const environment =\n request.authority || this.authority.getPreferredCache();\n const cacheRecord: CacheRecord = {\n account: this.cacheManager.readAccountFromCache(request.account),\n accessToken: cachedAccessToken,\n idToken: this.cacheManager.getIdToken(\n request.account,\n tokenKeys,\n requestTenantId,\n this.performanceClient,\n request.correlationId\n ),\n refreshToken: null,\n appMetadata:\n this.cacheManager.readAppMetadataFromCache(environment),\n };\n\n this.setCacheOutcome(lastCacheOutcome, request.correlationId);\n\n if (this.config.serverTelemetryManager) {\n this.config.serverTelemetryManager.incrementCacheHits();\n }\n\n return [\n await invokeAsync(\n this.generateResultFromCacheRecord.bind(this),\n PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord,\n this.logger,\n this.performanceClient,\n request.correlationId\n )(cacheRecord, request),\n lastCacheOutcome,\n ];\n }\n\n private setCacheOutcome(\n cacheOutcome: CacheOutcome,\n correlationId: string\n ): void {\n this.serverTelemetryManager?.setCacheOutcome(cacheOutcome);\n this.performanceClient?.addFields(\n {\n cacheOutcome: cacheOutcome,\n },\n correlationId\n );\n if (cacheOutcome !== CacheOutcome.NOT_APPLICABLE) {\n this.logger.info(\n `Token refresh is required due to cache outcome: ${cacheOutcome}`\n );\n }\n }\n\n /**\n * Helper function to build response object from the CacheRecord\n * @param cacheRecord\n */\n private async generateResultFromCacheRecord(\n cacheRecord: CacheRecord,\n request: CommonSilentFlowRequest\n ): Promise<AuthenticationResult> {\n this.performanceClient?.addQueueMeasurement(\n PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord,\n request.correlationId\n );\n let idTokenClaims: TokenClaims | undefined;\n if (cacheRecord.idToken) {\n idTokenClaims = extractTokenClaims(\n cacheRecord.idToken.secret,\n this.config.cryptoInterface.base64Decode\n );\n }\n\n // token max_age check\n if (request.maxAge || request.maxAge === 0) {\n const authTime = idTokenClaims?.auth_time;\n if (!authTime) {\n throw createClientAuthError(\n ClientAuthErrorCodes.authTimeNotFound\n );\n }\n\n checkMaxAge(authTime, request.maxAge);\n }\n\n return ResponseHandler.generateAuthenticationResult(\n this.cryptoUtils,\n this.authority,\n cacheRecord,\n true,\n request,\n idTokenClaims\n );\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n SERVER_TELEM_CONSTANTS,\n Separators,\n CacheOutcome,\n Constants,\n RegionDiscoverySources,\n RegionDiscoveryOutcomes,\n} from \"../../utils/Constants\";\nimport { CacheManager } from \"../../cache/CacheManager\";\nimport { AuthError } from \"../../error/AuthError\";\nimport { ServerTelemetryRequest } from \"./ServerTelemetryRequest\";\nimport { ServerTelemetryEntity } from \"../../cache/entities/ServerTelemetryEntity\";\nimport { RegionDiscoveryMetadata } from \"../../authority/RegionDiscoveryMetadata\";\n\n/** @internal */\nexport class ServerTelemetryManager {\n private cacheManager: CacheManager;\n private apiId: number;\n private correlationId: string;\n private telemetryCacheKey: string;\n private wrapperSKU: String;\n private wrapperVer: String;\n private regionUsed: string | undefined;\n private regionSource: RegionDiscoverySources | undefined;\n private regionOutcome: RegionDiscoveryOutcomes | undefined;\n private cacheOutcome: CacheOutcome = CacheOutcome.NOT_APPLICABLE;\n\n constructor(\n telemetryRequest: ServerTelemetryRequest,\n cacheManager: CacheManager\n ) {\n this.cacheManager = cacheManager;\n this.apiId = telemetryRequest.apiId;\n this.correlationId = telemetryRequest.correlationId;\n this.wrapperSKU = telemetryRequest.wrapperSKU || Constants.EMPTY_STRING;\n this.wrapperVer = telemetryRequest.wrapperVer || Constants.EMPTY_STRING;\n\n this.telemetryCacheKey =\n SERVER_TELEM_CONSTANTS.CACHE_KEY +\n Separators.CACHE_KEY_SEPARATOR +\n telemetryRequest.clientId;\n }\n\n /**\n * API to add MSER Telemetry to request\n */\n generateCurrentRequestHeaderValue(): string {\n const request = `${this.apiId}${SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR}${this.cacheOutcome}`;\n const platformFields = [this.wrapperSKU, this.wrapperVer].join(\n SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR\n );\n const regionDiscoveryFields = this.getRegionDiscoveryFields();\n const requestWithRegionDiscoveryFields = [\n request,\n regionDiscoveryFields,\n ].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);\n\n return [\n SERVER_TELEM_CONSTANTS.SCHEMA_VERSION,\n requestWithRegionDiscoveryFields,\n platformFields,\n ].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);\n }\n\n /**\n * API to add MSER Telemetry for the last failed request\n */\n generateLastRequestHeaderValue(): string {\n const lastRequests = this.getLastRequests();\n\n const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);\n const failedRequests = lastRequests.failedRequests\n .slice(0, 2 * maxErrors)\n .join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);\n const errors = lastRequests.errors\n .slice(0, maxErrors)\n .join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);\n const errorCount = lastRequests.errors.length;\n\n // Indicate whether this header contains all data or partial data\n const overflow =\n maxErrors < errorCount\n ? SERVER_TELEM_CONSTANTS.OVERFLOW_TRUE\n : SERVER_TELEM_CONSTANTS.OVERFLOW_FALSE;\n const platformFields = [errorCount, overflow].join(\n SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR\n );\n\n return [\n SERVER_TELEM_CONSTANTS.SCHEMA_VERSION,\n lastRequests.cacheHits,\n failedRequests,\n errors,\n platformFields,\n ].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);\n }\n\n /**\n * API to cache token failures for MSER data capture\n * @param error\n */\n cacheFailedRequest(error: unknown): void {\n const lastRequests = this.getLastRequests();\n if (\n lastRequests.errors.length >=\n SERVER_TELEM_CONSTANTS.MAX_CACHED_ERRORS\n ) {\n // Remove a cached error to make room, first in first out\n lastRequests.failedRequests.shift(); // apiId\n lastRequests.failedRequests.shift(); // correlationId\n lastRequests.errors.shift();\n }\n\n lastRequests.failedRequests.push(this.apiId, this.correlationId);\n\n if (error instanceof Error && !!error && error.toString()) {\n if (error instanceof AuthError) {\n if (error.subError) {\n lastRequests.errors.push(error.subError);\n } else if (error.errorCode) {\n lastRequests.errors.push(error.errorCode);\n } else {\n lastRequests.errors.push(error.toString());\n }\n } else {\n lastRequests.errors.push(error.toString());\n }\n } else {\n lastRequests.errors.push(SERVER_TELEM_CONSTANTS.UNKNOWN_ERROR);\n }\n\n this.cacheManager.setServerTelemetry(\n this.telemetryCacheKey,\n lastRequests\n );\n\n return;\n }\n\n /**\n * Update server telemetry cache entry by incrementing cache hit counter\n */\n incrementCacheHits(): number {\n const lastRequests = this.getLastRequests();\n lastRequests.cacheHits += 1;\n\n this.cacheManager.setServerTelemetry(\n this.telemetryCacheKey,\n lastRequests\n );\n return lastRequests.cacheHits;\n }\n\n /**\n * Get the server telemetry entity from cache or initialize a new one\n */\n getLastRequests(): ServerTelemetryEntity {\n const initialValue: ServerTelemetryEntity = {\n failedRequests: [],\n errors: [],\n cacheHits: 0,\n };\n const lastRequests = this.cacheManager.getServerTelemetry(\n this.telemetryCacheKey\n ) as ServerTelemetryEntity;\n\n return lastRequests || initialValue;\n }\n\n /**\n * Remove server telemetry cache entry\n */\n clearTelemetryCache(): void {\n const lastRequests = this.getLastRequests();\n const numErrorsFlushed =\n ServerTelemetryManager.maxErrorsToSend(lastRequests);\n const errorCount = lastRequests.errors.length;\n if (numErrorsFlushed === errorCount) {\n // All errors were sent on last request, clear Telemetry cache\n this.cacheManager.removeItem(this.telemetryCacheKey);\n } else {\n // Partial data was flushed to server, construct a new telemetry cache item with errors that were not flushed\n const serverTelemEntity: ServerTelemetryEntity = {\n failedRequests: lastRequests.failedRequests.slice(\n numErrorsFlushed * 2\n ), // failedRequests contains 2 items for each error\n errors: lastRequests.errors.slice(numErrorsFlushed),\n cacheHits: 0,\n };\n\n this.cacheManager.setServerTelemetry(\n this.telemetryCacheKey,\n serverTelemEntity\n );\n }\n }\n\n /**\n * Returns the maximum number of errors that can be flushed to the server in the next network request\n * @param serverTelemetryEntity\n */\n static maxErrorsToSend(\n serverTelemetryEntity: ServerTelemetryEntity\n ): number {\n let i;\n let maxErrors = 0;\n let dataSize = 0;\n const errorCount = serverTelemetryEntity.errors.length;\n for (i = 0; i < errorCount; i++) {\n // failedRequests parameter contains pairs of apiId and correlationId, multiply index by 2 to preserve pairs\n const apiId =\n serverTelemetryEntity.failedRequests[2 * i] ||\n Constants.EMPTY_STRING;\n const correlationId =\n serverTelemetryEntity.failedRequests[2 * i + 1] ||\n Constants.EMPTY_STRING;\n const errorCode =\n serverTelemetryEntity.errors[i] || Constants.EMPTY_STRING;\n\n // Count number of characters that would be added to header, each character is 1 byte. Add 3 at the end to account for separators\n dataSize +=\n apiId.toString().length +\n correlationId.toString().length +\n errorCode.length +\n 3;\n\n if (dataSize < SERVER_TELEM_CONSTANTS.MAX_LAST_HEADER_BYTES) {\n // Adding this entry to the header would still keep header size below the limit\n maxErrors += 1;\n } else {\n break;\n }\n }\n\n return maxErrors;\n }\n\n /**\n * Get the region discovery fields\n *\n * @returns string\n */\n getRegionDiscoveryFields(): string {\n const regionDiscoveryFields: string[] = [];\n\n regionDiscoveryFields.push(this.regionUsed || Constants.EMPTY_STRING);\n regionDiscoveryFields.push(this.regionSource || Constants.EMPTY_STRING);\n regionDiscoveryFields.push(\n this.regionOutcome || Constants.EMPTY_STRING\n );\n\n return regionDiscoveryFields.join(\",\");\n }\n\n /**\n * Update the region discovery metadata\n *\n * @param regionDiscoveryMetadata\n * @returns void\n */\n updateRegionDiscoveryMetadata(\n regionDiscoveryMetadata: RegionDiscoveryMetadata\n ): void {\n this.regionUsed = regionDiscoveryMetadata.region_used;\n this.regionSource = regionDiscoveryMetadata.region_source;\n this.regionOutcome = regionDiscoveryMetadata.region_outcome;\n }\n\n /**\n * Set cache outcome\n */\n setCacheOutcome(cacheOutcome: CacheOutcome): void {\n this.cacheOutcome = cacheOutcome;\n }\n}\n", "/*! @azure/msal-common v14.6.1 2024-01-23 */\n'use strict';\nexport { AuthorizationCodeClient } from './client/AuthorizationCodeClient.mjs';\nexport { RefreshTokenClient } from './client/RefreshTokenClient.mjs';\nexport { SilentFlowClient } from './client/SilentFlowClient.mjs';\nexport { BaseClient } from './client/BaseClient.mjs';\nexport { DEFAULT_SYSTEM_OPTIONS } from './config/ClientConfiguration.mjs';\nexport { buildTenantProfileFromIdTokenClaims, tenantIdMatchesHomeTenant, updateAccountTenantProfileData } from './account/AccountInfo.mjs';\nimport * as AuthToken from './account/AuthToken.mjs';\nexport { AuthToken };\nexport { getTenantIdFromIdTokenClaims } from './account/TokenClaims.mjs';\nexport { CcsCredentialType } from './account/CcsCredential.mjs';\nexport { buildClientInfo, buildClientInfoFromHomeAccountId } from './account/ClientInfo.mjs';\nexport { Authority, buildStaticAuthorityOptions, formatAuthorityUri } from './authority/Authority.mjs';\nexport { AzureCloudInstance } from './authority/AuthorityOptions.mjs';\nimport * as AuthorityFactory from './authority/AuthorityFactory.mjs';\nexport { AuthorityFactory };\nexport { AuthorityType } from './authority/AuthorityType.mjs';\nexport { ProtocolMode } from './authority/ProtocolMode.mjs';\nexport { CacheManager, DefaultStorageClass } from './cache/CacheManager.mjs';\nexport { CacheRecord } from './cache/entities/CacheRecord.mjs';\nimport * as CacheHelpers from './cache/utils/CacheHelpers.mjs';\nexport { CacheHelpers };\nexport { AccountEntity } from './cache/entities/AccountEntity.mjs';\nexport { TokenCacheContext } from './cache/persistence/TokenCacheContext.mjs';\nexport { StubbedNetworkModule } from './network/INetworkModule.mjs';\nexport { NetworkManager } from './network/NetworkManager.mjs';\nexport { ThrottlingUtils } from './network/ThrottlingUtils.mjs';\nexport { UrlString } from './url/UrlString.mjs';\nexport { DEFAULT_CRYPTO_IMPLEMENTATION } from './crypto/ICrypto.mjs';\nexport { JoseHeader } from './crypto/JoseHeader.mjs';\nexport { RequestParameterBuilder } from './request/RequestParameterBuilder.mjs';\nexport { ResponseHandler, buildAccountToCache } from './response/ResponseHandler.mjs';\nexport { ScopeSet } from './request/ScopeSet.mjs';\nexport { AuthenticationHeaderParser } from './request/AuthenticationHeaderParser.mjs';\nexport { LogLevel, Logger } from './logger/Logger.mjs';\nexport { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, createInteractionRequiredAuthError } from './error/InteractionRequiredAuthError.mjs';\nexport { AuthError, AuthErrorMessage, createAuthError } from './error/AuthError.mjs';\nexport { ServerError } from './error/ServerError.mjs';\nexport { ClientAuthError, ClientAuthErrorMessage, createClientAuthError } from './error/ClientAuthError.mjs';\nexport { ClientConfigurationError, ClientConfigurationErrorMessage, createClientConfigurationError } from './error/ClientConfigurationError.mjs';\nexport { AADAuthorityConstants, AuthenticationScheme, CacheAccountType, CacheOutcome, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, Errors, GrantType, HeaderNames, HttpStatus, JsonWebTokenTypes, OIDC_DEFAULT_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, ResponseMode, ServerResponseType, THE_FAMILY_ID, ThrottlingConstants } from './utils/Constants.mjs';\nimport * as AADServerParamKeys from './constants/AADServerParamKeys.mjs';\nexport { AADServerParamKeys };\nexport { StringUtils } from './utils/StringUtils.mjs';\nexport { ProtocolUtils } from './utils/ProtocolUtils.mjs';\nexport { TimeUtils } from './utils/TimeUtils.mjs';\nimport * as UrlUtils from './utils/UrlUtils.mjs';\nexport { UrlUtils };\nexport { invoke, invokeAsync } from './utils/FunctionWrappers.mjs';\nexport { ServerTelemetryManager } from './telemetry/server/ServerTelemetryManager.mjs';\nexport { IntFields, PerformanceEventStatus, PerformanceEvents } from './telemetry/performance/PerformanceEvent.mjs';\nexport { PerformanceClient } from './telemetry/performance/PerformanceClient.mjs';\nexport { StubPerformanceClient } from './telemetry/performance/StubPerformanceClient.mjs';\nexport { PopTokenGenerator } from './crypto/PopTokenGenerator.mjs';\nexport { version } from './packageMetadata.mjs';\nimport * as InteractionRequiredAuthErrorCodes from './error/InteractionRequiredAuthErrorCodes.mjs';\nexport { InteractionRequiredAuthErrorCodes };\nimport * as AuthErrorCodes from './error/AuthErrorCodes.mjs';\nexport { AuthErrorCodes };\nimport * as ClientAuthErrorCodes from './error/ClientAuthErrorCodes.mjs';\nexport { ClientAuthErrorCodes };\nimport * as ClientConfigurationErrorCodes from './error/ClientConfigurationErrorCodes.mjs';\nexport { ClientConfigurationErrorCodes };\n//# sourceMappingURL=index.mjs.map\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AccountCache,\n IdTokenCache,\n AccessTokenCache,\n RefreshTokenCache,\n AppMetadataCache,\n AccountEntity,\n IdTokenEntity,\n AccessTokenEntity,\n RefreshTokenEntity,\n CacheManager,\n CredentialType,\n AuthenticationScheme,\n} from \"@azure/msal-common\";\nimport {\n JsonCache,\n InMemoryCache,\n SerializedAccountEntity,\n SerializedIdTokenEntity,\n SerializedAccessTokenEntity,\n SerializedRefreshTokenEntity,\n SerializedAppMetadataEntity,\n} from \"./SerializerTypes.js\";\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 = !jsonFile ? {} : JSON.parse(jsonFile);\n return deserializedCache;\n }\n\n /**\n * Deserializes accounts to AccountEntity objects\n * @param accounts\n */\n static deserializeAccounts(\n accounts: Record<string, SerializedAccountEntity>\n ): 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 tenantProfiles: serializedAcc.tenantProfiles?.map(\n (serializedTenantProfile) => {\n return JSON.parse(serializedTenantProfile);\n }\n ),\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(\n idTokens: Record<string, SerializedIdTokenEntity>\n ): IdTokenCache {\n const idObjects: IdTokenCache = {};\n if (idTokens) {\n Object.keys(idTokens).map(function (key) {\n const serializedIdT = idTokens[key];\n const idToken: IdTokenEntity = {\n homeAccountId: serializedIdT.home_account_id,\n environment: serializedIdT.environment,\n credentialType:\n serializedIdT.credential_type as CredentialType,\n clientId: serializedIdT.client_id,\n secret: serializedIdT.secret,\n realm: serializedIdT.realm,\n };\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(\n accessTokens: Record<string, SerializedAccessTokenEntity>\n ): AccessTokenCache {\n const atObjects: AccessTokenCache = {};\n if (accessTokens) {\n Object.keys(accessTokens).map(function (key) {\n const serializedAT = accessTokens[key];\n const accessToken: AccessTokenEntity = {\n homeAccountId: serializedAT.home_account_id,\n environment: serializedAT.environment,\n credentialType:\n serializedAT.credential_type as CredentialType,\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 as AuthenticationScheme,\n requestedClaims: serializedAT.requestedClaims,\n requestedClaimsHash: serializedAT.requestedClaimsHash,\n userAssertionHash: serializedAT.userAssertionHash,\n };\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(\n refreshTokens: Record<string, SerializedRefreshTokenEntity>\n ): RefreshTokenCache {\n const rtObjects: RefreshTokenCache = {};\n if (refreshTokens) {\n Object.keys(refreshTokens).map(function (key) {\n const serializedRT = refreshTokens[key];\n const refreshToken: RefreshTokenEntity = {\n homeAccountId: serializedRT.home_account_id,\n environment: serializedRT.environment,\n credentialType:\n serializedRT.credential_type as CredentialType,\n clientId: serializedRT.client_id,\n secret: serializedRT.secret,\n familyId: serializedRT.family_id,\n target: serializedRT.target,\n realm: serializedRT.realm,\n };\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(\n appMetadata: Record<string, SerializedAppMetadataEntity>\n ): AppMetadataCache {\n const appMetadataObjects: AppMetadataCache = {};\n if (appMetadata) {\n Object.keys(appMetadata).map(function (key) {\n const serializedAmdt = appMetadata[key];\n appMetadataObjects[key] = {\n clientId: serializedAmdt.client_id,\n environment: serializedAmdt.environment,\n familyId: serializedAmdt.family_id,\n };\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\n/**\n * http methods\n */\nexport const HttpMethod = {\n GET: \"get\",\n POST: \"post\",\n} as const;\nexport type HttpMethod = (typeof HttpMethod)[keyof typeof HttpMethod];\n\nexport const ProxyStatus = {\n SUCCESS_RANGE_START: 200,\n SUCCESS_RANGE_END: 299,\n SERVER_ERROR: 500,\n} as const;\nexport type ProxyStatus = (typeof ProxyStatus)[keyof typeof ProxyStatus];\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:\n \"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 const ApiId = {\n acquireTokenSilent: 62,\n acquireTokenByUsernamePassword: 371,\n acquireTokenByDeviceCode: 671,\n acquireTokenByClientCredential: 771,\n acquireTokenByCode: 871,\n acquireTokenByRefreshToken: 872,\n};\nexport type ApiId = (typeof ApiId)[keyof typeof ApiId];\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, UrlToHttpRequestOptions } from \"@azure/msal-common\";\n\nexport class NetworkUtils {\n static getNetworkResponse<T>(\n headers: Record<string, string>,\n body: T,\n statusCode: number\n ): NetworkResponse<T> {\n return {\n headers: headers,\n body: body,\n status: statusCode,\n };\n }\n\n /*\n * Utility function that converts a URL object into an ordinary options object as expected by the\n * http.request and https.request APIs.\n * https://github.com/nodejs/node/blob/main/lib/internal/url.js#L1090\n */\n static urlToHttpOptions(url: URL): UrlToHttpRequestOptions {\n const options: UrlToHttpRequestOptions = {\n protocol: url.protocol,\n hostname:\n url.hostname && url.hostname.startsWith(\"[\")\n ? url.hostname.slice(1, -1)\n : url.hostname,\n hash: url.hash,\n search: url.search,\n pathname: url.pathname,\n path: `${url.pathname || \"\"}${url.search || \"\"}`,\n href: url.href,\n };\n if (url.port !== \"\") {\n options.port = Number(url.port);\n }\n if (url.username || url.password) {\n options.auth = `${decodeURIComponent(\n url.username\n )}:${decodeURIComponent(url.password)}`;\n }\n return options;\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 HttpStatus,\n} from \"@azure/msal-common\";\nimport { HttpMethod, Constants, ProxyStatus } from \"../utils/Constants.js\";\nimport { NetworkUtils } from \"../utils/NetworkUtils.js\";\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 private proxyUrl: string;\n private customAgentOptions: http.AgentOptions | https.AgentOptions;\n\n constructor(\n proxyUrl?: string,\n customAgentOptions?: http.AgentOptions | https.AgentOptions\n ) {\n this.proxyUrl = proxyUrl || \"\";\n this.customAgentOptions = customAgentOptions || {};\n }\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 (this.proxyUrl) {\n return networkRequestViaProxy(\n url,\n this.proxyUrl,\n HttpMethod.GET,\n options,\n this.customAgentOptions as http.AgentOptions\n );\n } else {\n return networkRequestViaHttps(\n url,\n HttpMethod.GET,\n options,\n this.customAgentOptions as https.AgentOptions\n );\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 (this.proxyUrl) {\n return networkRequestViaProxy(\n url,\n this.proxyUrl,\n HttpMethod.POST,\n options,\n this.customAgentOptions as http.AgentOptions,\n cancellationToken\n );\n } else {\n return networkRequestViaHttps(\n url,\n HttpMethod.POST,\n options,\n this.customAgentOptions as https.AgentOptions,\n cancellationToken\n );\n }\n }\n}\n\nconst networkRequestViaProxy = <T>(\n destinationUrlString: string,\n proxyUrlString: string,\n httpMethod: string,\n options?: NetworkRequestOptions,\n agentOptions?: http.AgentOptions,\n timeout?: number\n): Promise<NetworkResponse<T>> => {\n const destinationUrl = new URL(destinationUrlString);\n const proxyUrl = new URL(proxyUrlString);\n\n // \"method: connect\" must be used to establish a connection to the proxy\n const headers = options?.headers || ({} as Record<string, string>);\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 if (agentOptions && Object.keys(agentOptions).length) {\n tunnelRequestOptions.agent = new http.Agent(agentOptions);\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 =\n `${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 =\n response?.statusCode || ProxyStatus.SERVER_ERROR;\n if (\n proxyStatusCode < ProxyStatus.SUCCESS_RANGE_START ||\n proxyStatusCode > ProxyStatus.SUCCESS_RANGE_END\n ) {\n request.destroy();\n socket.destroy();\n reject(\n new Error(\n `Error connecting to proxy. Http status code: ${\n response.statusCode\n }. Http status message: ${\n response?.statusMessage || \"Unknown\"\n }`\n )\n );\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(\n dataStringArray[0].split(\" \")[1]\n );\n // remove \"HTTP/1.1\" and the status code to get the status message\n const statusMessage = dataStringArray[0]\n .split(\" \")\n .slice(2)\n .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(\n 1,\n dataStringArray.length - 2\n );\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(\n httpStatusCode,\n statusMessage,\n parsedHeaders,\n body\n ) as T,\n httpStatusCode\n );\n\n if (\n (httpStatusCode < HttpStatus.SUCCESS_RANGE_START ||\n httpStatusCode > HttpStatus.SUCCESS_RANGE_END) &&\n // do not destroy the request for the device code flow\n networkResponse.body[\"error\"] !==\n Constants.AUTHORIZATION_PENDING\n ) {\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 urlString: string,\n httpMethod: string,\n options?: NetworkRequestOptions,\n agentOptions?: https.AgentOptions,\n timeout?: number\n): Promise<NetworkResponse<T>> => {\n const isPostRequest = httpMethod === HttpMethod.POST;\n const body: string = options?.body || \"\";\n\n const url = new URL(urlString);\n const headers = options?.headers || ({} as Record<string, string>);\n const customOptions: https.RequestOptions = {\n method: httpMethod,\n headers: headers,\n ...NetworkUtils.urlToHttpOptions(url),\n };\n\n if (timeout) {\n customOptions.timeout = timeout;\n }\n\n if (agentOptions && Object.keys(agentOptions).length) {\n customOptions.agent = new https.Agent(agentOptions);\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(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(\n statusCode,\n statusMessage,\n parsedHeaders,\n body\n ) as T,\n statusCode\n );\n\n if (\n (statusCode < HttpStatus.SUCCESS_RANGE_START ||\n statusCode > HttpStatus.SUCCESS_RANGE_END) &&\n // do not destroy the request for the device code flow\n networkResponse.body[\"error\"] !==\n Constants.AUTHORIZATION_PENDING\n ) {\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 = (\n statusCode: number,\n statusMessage: string | undefined,\n headers: Record<string, string>,\n body: string\n) => {\n /*\n * Informational responses (100 \u2013 199)\n * Successful responses (200 \u2013 299)\n * Redirection messages (300 \u2013 399)\n * Client error responses (400 \u2013 499)\n * Server error responses (500 \u2013 599)\n */\n\n let parsedBody;\n try {\n parsedBody = JSON.parse(body);\n } catch (error) {\n let errorType;\n let errorDescriptionHelper;\n if (\n statusCode >= HttpStatus.CLIENT_ERROR_RANGE_START &&\n statusCode <= HttpStatus.CLIENT_ERROR_RANGE_END\n ) {\n errorType = \"client_error\";\n errorDescriptionHelper = \"A client\";\n } else if (\n statusCode >= HttpStatus.SERVER_ERROR_RANGE_START &&\n statusCode <= HttpStatus.SERVER_ERROR_RANGE_END\n ) {\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: ${\n statusMessage || \"Unknown\"\n }\\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 INativeBrokerPlugin,\n} from \"@azure/msal-common\";\nimport { HttpClient } from \"../network/HttpClient.js\";\nimport http from \"http\";\nimport https from \"https\";\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 claimsBasedCachingEnabled?: boolean;\n};\n\n/**\n * Use this to configure the below broker options:\n * - nativeBrokerPlugin - Native broker implementation (should be imported from msal-node-extensions)\n *\n * Note: These options are only available for PublicClientApplications using the Authorization Code Flow\n * @public\n */\nexport type BrokerOptions = {\n nativeBrokerPlugin?: INativeBrokerPlugin;\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 customAgentOptions?: http.AgentOptions | https.AgentOptions;\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 * - broker: this is where you configure broker options\n * - cache: this is where you configure cache location\n * - system: this is where you can configure the network client, logger\n * - telemetry: this is where you can configure telemetry options\n * @public\n */\nexport type Configuration = {\n auth: NodeAuthOptions;\n broker?: BrokerOptions;\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 claimsBasedCachingEnabled: false,\n};\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 customAgentOptions: {} as http.AgentOptions | https.AgentOptions,\n};\n\nconst DEFAULT_TELEMETRY_OPTIONS: Required<NodeTelemetryOptions> = {\n application: {\n appName: Constants.EMPTY_STRING,\n appVersion: Constants.EMPTY_STRING,\n },\n};\n\n/** @internal */\nexport type NodeConfiguration = {\n auth: Required<NodeAuthOptions>;\n broker: BrokerOptions;\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 * @internal\n */\nexport function buildAppConfiguration({\n auth,\n broker,\n cache,\n system,\n telemetry,\n}: Configuration): NodeConfiguration {\n const systemOptions: Required<NodeSystemOptions> = {\n ...DEFAULT_SYSTEM_OPTIONS,\n networkClient: new HttpClient(\n system?.proxyUrl,\n system?.customAgentOptions as http.AgentOptions | https.AgentOptions\n ),\n loggerOptions: system?.loggerOptions || DEFAULT_LOGGER_OPTIONS,\n };\n\n return {\n auth: { ...DEFAULT_AUTH_OPTIONS, ...auth },\n broker: { ...broker },\n cache: { ...DEFAULT_CACHE_OPTIONS, ...cache },\n system: { ...systemOptions, ...system },\n telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry },\n };\n}\n", "import crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}", "export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;", "import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;", "import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;", "import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;", "export { default as v1 } from './v1.js';\nexport { default as v3 } from './v3.js';\nexport { default as v4 } from './v4.js';\nexport { default as v5 } from './v5.js';\nexport { default as NIL } from './nil.js';\nexport { default as version } from './version.js';\nexport { default as validate } from './validate.js';\nexport { default as stringify } from './stringify.js';\nexport { default as parse } from './parse.js';", "/*\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 =\n /^[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.js\";\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.createHash(Hash.SHA256).update(buffer).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.js\";\nimport { EncodingUtils } from \"../utils/EncodingUtils.js\";\nimport { HashUtils } from \"./HashUtils.js\";\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 * 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.js\";\nimport { EncodingUtils } from \"../utils/EncodingUtils.js\";\nimport { PkceGenerator } from \"./PkceGenerator.js\";\nimport { HashUtils } from \"./HashUtils.js\";\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 {\n TokenKeys,\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 StaticAuthorityOptions,\n CacheHelpers,\n} from \"@azure/msal-common\";\n\nimport { Deserializer } from \"./serializer/Deserializer.js\";\nimport { Serializer } from \"./serializer/Serializer.js\";\nimport {\n InMemoryCache,\n JsonCache,\n CacheKVStore,\n} from \"./serializer/SerializerTypes.js\";\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(\n logger: Logger,\n clientId: string,\n cryptoImpl: ICrypto,\n staticAuthorityOptions?: StaticAuthorityOptions\n ) {\n super(clientId, cryptoImpl, logger, staticAuthorityOptions);\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 const value = cache[key];\n if (typeof value !== \"object\") {\n continue;\n }\n if (value instanceof AccountEntity) {\n inMemoryCache.accounts[key] = value as AccountEntity;\n } else if (CacheHelpers.isIdTokenEntity(value)) {\n inMemoryCache.idTokens[key] = value as IdTokenEntity;\n } else if (CacheHelpers.isAccessTokenEntity(value)) {\n inMemoryCache.accessTokens[key] = value as AccessTokenEntity;\n } else if (CacheHelpers.isRefreshTokenEntity(value)) {\n inMemoryCache.refreshTokens[key] = value as RefreshTokenEntity;\n } else if (CacheHelpers.isAppMetadataEntity(key, value)) {\n inMemoryCache.appMetadata[key] = value 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 // 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 getAccountKeys(): string[] {\n const inMemoryCache = this.getInMemoryCache();\n const accountKeys = Object.keys(inMemoryCache.accounts);\n\n return accountKeys;\n }\n\n getTokenKeys(): TokenKeys {\n const inMemoryCache = this.getInMemoryCache();\n const tokenKeys = {\n idToken: Object.keys(inMemoryCache.idTokens),\n accessToken: Object.keys(inMemoryCache.accessTokens),\n refreshToken: Object.keys(inMemoryCache.refreshTokens),\n };\n\n return tokenKeys;\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 accountEntity = this.getCachedAccountEntity(accountKey);\n if (accountEntity && AccountEntity.isAccountEntity(accountEntity)) {\n return this.updateOutdatedCachedAccount(accountKey, accountEntity);\n }\n return null;\n }\n\n /**\n * Reads account from cache, builds it into an account entity and returns it.\n * @param accountKey\n * @returns\n */\n getCachedAccountEntity(accountKey: string): AccountEntity | null {\n const cachedAccount = this.getItem(accountKey);\n return cachedAccount\n ? Object.assign(new AccountEntity(), this.getItem(accountKey))\n : 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 (CacheHelpers.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 = CacheHelpers.generateCredentialKey(idToken);\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 (CacheHelpers.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 = CacheHelpers.generateCredentialKey(accessToken);\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(\n refreshTokenKey: string\n ): RefreshTokenEntity | null {\n const refreshToken = this.getItem(\n refreshTokenKey\n ) as RefreshTokenEntity;\n if (CacheHelpers.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 =\n CacheHelpers.generateCredentialKey(refreshToken);\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(\n appMetadataKey\n ) as AppMetadataEntity;\n if (CacheHelpers.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 = CacheHelpers.generateAppMetadataKey(appMetadata);\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(\n serverTelemetrykey: string\n ): ServerTelemetryEntity | null {\n const serverTelemetryEntity: ServerTelemetryEntity = this.getItem(\n serverTelemetrykey\n ) as ServerTelemetryEntity;\n if (\n serverTelemetryEntity &&\n CacheHelpers.isServerTelemetryEntity(\n serverTelemetrykey,\n serverTelemetryEntity\n )\n ) {\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(\n serverTelemetryKey: string,\n serverTelemetry: ServerTelemetryEntity\n ): 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(\n key\n ) as AuthorityMetadataEntity;\n if (\n authorityMetadataEntity &&\n CacheHelpers.isAuthorityMetadataEntity(key, authorityMetadataEntity)\n ) {\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(\n throttlingCacheKey\n ) as ThrottlingEntity;\n if (\n throttlingCache &&\n CacheHelpers.isThrottlingEntity(throttlingCacheKey, throttlingCache)\n ) {\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(\n throttlingCacheKey: string,\n throttlingCache: ThrottlingEntity\n ): 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 * Remove account entity from the platform cache if it's outdated\n * @param accountKey\n */\n removeOutdatedAccount(accountKey: string): void {\n this.removeItem(accountKey);\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(\n currentCacheKey: string,\n credential: ValidCredentialType\n ): string {\n const updatedCacheKey = CacheHelpers.generateCredentialKey(credential);\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(\n `Updated an outdated ${credential.credentialType} cache key`\n );\n return updatedCacheKey;\n } else {\n this.logger.error(\n `Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`\n );\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.js\";\nimport {\n AccountEntity,\n AccountInfo,\n Logger,\n ISerializableTokenCache,\n ICachePlugin,\n TokenCacheContext,\n} from \"@azure/msal-common\";\nimport {\n InMemoryCache,\n JsonCache,\n SerializedAccountEntity,\n SerializedAccessTokenEntity,\n SerializedRefreshTokenEntity,\n SerializedIdTokenEntity,\n SerializedAppMetadataEntity,\n CacheKVStore,\n} from \"./serializer/SerializerTypes.js\";\nimport { Deserializer } from \"./serializer/Deserializer.js\";\nimport { Serializer } from \"./serializer/Serializer.js\";\nimport { ITokenCache } from \"./ITokenCache.js\";\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 private storage: NodeStorage;\n private cacheHasChanged: boolean;\n private cacheSnapshot: string;\n private readonly persistence: ICachePlugin;\n private logger: Logger;\n\n constructor(\n storage: NodeStorage,\n logger: Logger,\n cachePlugin?: ICachePlugin\n ) {\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 (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 (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 this.logger.trace(\"getAllAccounts called\");\n let cacheContext;\n try {\n if (this.persistence) {\n cacheContext = new TokenCacheContext(this, true);\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(\n homeAccountId: string\n ): Promise<AccountInfo | null> {\n const allAccounts = await this.getAllAccounts();\n if (homeAccountId && allAccounts && allAccounts.length) {\n return (\n allAccounts.filter(\n (accountObj) => accountObj.homeAccountId === homeAccountId\n )[0] || null\n );\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(\n localAccountId: string\n ): Promise<AccountInfo | null> {\n const allAccounts = await this.getAllAccounts();\n if (localAccountId && allAccounts && allAccounts.length) {\n return (\n allAccounts.filter(\n (accountObj) => accountObj.localAccountId === localAccountId\n )[0] || null\n );\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(\n AccountEntity.generateAccountCacheKey(account)\n );\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(\n oldState: JsonCache,\n currentState: JsonCache\n ): 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 =\n typeof oldState[newKey] !== \"undefined\" &&\n oldState[newKey] !== null;\n\n if (\n newValueNotNull &&\n newValueIsObject &&\n newValueIsNotArray &&\n oldStateNotUndefinedOrNull\n ) {\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\n ? this.mergeRemovalsDict<SerializedAccountEntity>(\n oldState.Account,\n newState.Account\n )\n : oldState.Account;\n const accessTokens = oldState.AccessToken\n ? this.mergeRemovalsDict<SerializedAccessTokenEntity>(\n oldState.AccessToken,\n newState.AccessToken\n )\n : oldState.AccessToken;\n const refreshTokens = oldState.RefreshToken\n ? this.mergeRemovalsDict<SerializedRefreshTokenEntity>(\n oldState.RefreshToken,\n newState.RefreshToken\n )\n : oldState.RefreshToken;\n const idTokens = oldState.IdToken\n ? this.mergeRemovalsDict<SerializedIdTokenEntity>(\n oldState.IdToken,\n newState.IdToken\n )\n : oldState.IdToken;\n const appMetadata = oldState.AppMetadata\n ? this.mergeRemovalsDict<SerializedAppMetadataEntity>(\n oldState.AppMetadata,\n newState.AppMetadata\n )\n : 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>(\n oldState: Record<string, T>,\n newState?: Record<string, T>\n ): 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 = \"2.6.2\";\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(\n NodeAuthErrorMessage.invalidLoopbackAddressType.code,\n `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`\n );\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(\n NodeAuthErrorMessage.unableToLoadRedirectUri.code,\n `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`\n );\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(\n NodeAuthErrorMessage.noAuthCodeInResponse.code,\n `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`\n );\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(\n NodeAuthErrorMessage.noLoopbackServerExists.code,\n `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`\n );\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(\n NodeAuthErrorMessage.loopbackServerAlreadyExists.code,\n `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`\n );\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(\n NodeAuthErrorMessage.loopbackServerTimeout.code,\n `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`\n );\n }\n\n /**\n * Creates an error thrown when the state is not present.\n */\n static createStateNotFoundError(): NodeAuthError {\n return new NodeAuthError(\n NodeAuthErrorMessage.stateNotFoundError.code,\n NodeAuthErrorMessage.stateNotFoundError.desc\n );\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AuthenticationResult,\n Authority,\n BaseClient,\n CcsCredentialType,\n ClientConfiguration,\n CommonUsernamePasswordRequest,\n GrantType,\n NetworkResponse,\n RequestParameterBuilder,\n RequestThumbprint,\n ResponseHandler,\n ServerAuthorizationTokenResponse,\n StringUtils,\n TimeUtils,\n UrlString,\n} from \"@azure/msal-common\";\n\n/**\n * Oauth2.0 Password grant client\n * Note: We are only supporting public clients for password grant and for purely testing purposes\n */\nexport class UsernamePasswordClient extends BaseClient {\n constructor(configuration: ClientConfiguration) {\n super(configuration);\n }\n\n /**\n * API to acquire a token by passing the username and password to the service in exchage of credentials\n * password_grant\n * @param request\n */\n async acquireToken(\n request: CommonUsernamePasswordRequest\n ): Promise<AuthenticationResult | null> {\n this.logger.info(\"in acquireToken call in username-password client\");\n\n const reqTimestamp = TimeUtils.nowSeconds();\n const response = await this.executeTokenRequest(\n this.authority,\n request\n );\n\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin\n );\n\n // Validate response. This function throws a server error if an error is returned by the server.\n responseHandler.validateTokenResponse(response.body);\n const tokenResponse = responseHandler.handleServerTokenResponse(\n response.body,\n this.authority,\n reqTimestamp,\n request\n );\n\n return tokenResponse;\n }\n\n /**\n * Executes POST request to token endpoint\n * @param authority\n * @param request\n */\n private async executeTokenRequest(\n authority: Authority,\n request: CommonUsernamePasswordRequest\n ): Promise<NetworkResponse<ServerAuthorizationTokenResponse>> {\n const queryParametersString = this.createTokenQueryParameters(request);\n const endpoint = UrlString.appendQueryString(\n authority.tokenEndpoint,\n queryParametersString\n );\n const requestBody = this.createTokenRequestBody(request);\n const headers: Record<string, string> = this.createTokenRequestHeaders({\n credential: request.username,\n type: CcsCredentialType.UPN,\n });\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: authority.canonicalAuthority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid,\n };\n\n return this.executePostToTokenEndpoint(\n endpoint,\n requestBody,\n headers,\n thumbprint,\n request.correlationId\n );\n }\n\n /**\n * Generates a map for all the params to be sent to the service\n * @param request\n */\n private createTokenRequestBody(\n request: CommonUsernamePasswordRequest\n ): string {\n const parameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addClientId(this.config.authOptions.clientId);\n parameterBuilder.addUsername(request.username);\n parameterBuilder.addPassword(request.password);\n\n parameterBuilder.addScopes(request.scopes);\n\n parameterBuilder.addResponseTypeForTokenAndIdToken();\n\n parameterBuilder.addGrantType(GrantType.RESOURCE_OWNER_PASSWORD_GRANT);\n parameterBuilder.addClientInfo();\n\n parameterBuilder.addLibraryInfo(this.config.libraryInfo);\n parameterBuilder.addApplicationTelemetry(\n this.config.telemetry.application\n );\n parameterBuilder.addThrottling();\n\n if (this.serverTelemetryManager) {\n parameterBuilder.addServerTelemetry(this.serverTelemetryManager);\n }\n\n const correlationId =\n request.correlationId ||\n this.config.cryptoInterface.createNewGuid();\n parameterBuilder.addCorrelationId(correlationId);\n\n if (this.config.clientCredentials.clientSecret) {\n parameterBuilder.addClientSecret(\n this.config.clientCredentials.clientSecret\n );\n }\n\n if (this.config.clientCredentials.clientAssertion) {\n const clientAssertion =\n this.config.clientCredentials.clientAssertion;\n parameterBuilder.addClientAssertion(clientAssertion.assertion);\n parameterBuilder.addClientAssertionType(\n clientAssertion.assertionType\n );\n }\n\n if (\n !StringUtils.isEmptyObj(request.claims) ||\n (this.config.authOptions.clientCapabilities &&\n this.config.authOptions.clientCapabilities.length > 0)\n ) {\n parameterBuilder.addClaims(\n request.claims,\n this.config.authOptions.clientCapabilities\n );\n }\n\n if (\n this.config.systemOptions.preventCorsPreflight &&\n request.username\n ) {\n parameterBuilder.addCcsUpn(request.username);\n }\n\n return parameterBuilder.createQueryString();\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 AuthenticationScheme,\n ResponseMode,\n AuthorityOptions,\n OIDC_DEFAULT_SCOPES,\n AzureRegionConfiguration,\n AuthError,\n AzureCloudOptions,\n AuthorizationCodePayload,\n Constants,\n StringUtils,\n createClientAuthError,\n ClientAuthErrorCodes,\n buildStaticAuthorityOptions,\n} from \"@azure/msal-common\";\nimport {\n Configuration,\n buildAppConfiguration,\n NodeConfiguration,\n} from \"../config/Configuration.js\";\nimport { CryptoProvider } from \"../crypto/CryptoProvider.js\";\nimport { NodeStorage } from \"../cache/NodeStorage.js\";\nimport { Constants as NodeConstants, ApiId } from \"../utils/Constants.js\";\nimport { TokenCache } from \"../cache/TokenCache.js\";\nimport { ClientAssertion } from \"./ClientAssertion.js\";\nimport { AuthorizationUrlRequest } from \"../request/AuthorizationUrlRequest.js\";\nimport { AuthorizationCodeRequest } from \"../request/AuthorizationCodeRequest.js\";\nimport { RefreshTokenRequest } from \"../request/RefreshTokenRequest.js\";\nimport { SilentFlowRequest } from \"../request/SilentFlowRequest.js\";\nimport { version, name } from \"../packageMetadata.js\";\nimport { UsernamePasswordRequest } from \"../request/UsernamePasswordRequest.js\";\nimport { NodeAuthError } from \"../error/NodeAuthError.js\";\nimport { UsernamePasswordClient } from \"./UsernamePasswordClient.js\";\n\n/**\n * Base abstract class for all ClientApplications - public and confidential\n * @public\n */\nexport abstract class ClientApplication {\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(\n this.config.system.loggerOptions,\n name,\n version\n );\n this.storage = new NodeStorage(\n this.logger,\n this.config.auth.clientId,\n this.cryptoProvider,\n buildStaticAuthorityOptions(this.config.auth)\n );\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(\n \"Auth code client created\",\n validRequest.correlationId\n );\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(\n request: AuthorizationCodeRequest,\n authCodePayLoad?: AuthorizationCodePayload\n ): 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(\n ApiId.acquireTokenByCode,\n validRequest.correlationId\n );\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(\n \"Auth code client created\",\n validRequest.correlationId\n );\n return await authorizationCodeClient.acquireToken(\n validRequest,\n authCodePayLoad\n );\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(\n request: RefreshTokenRequest\n ): Promise<AuthenticationResult | null> {\n this.logger.info(\n \"acquireTokenByRefreshToken called\",\n request.correlationId\n );\n const validRequest: CommonRefreshTokenRequest = {\n ...request,\n ...(await this.initializeBaseRequest(request)),\n authenticationScheme: AuthenticationScheme.BEARER,\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(\n ApiId.acquireTokenByRefreshToken,\n validRequest.correlationId\n );\n try {\n const refreshTokenClientConfig =\n 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(\n \"Refresh token client created\",\n validRequest.correlationId\n );\n return await 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(\n request: SilentFlowRequest\n ): Promise<AuthenticationResult> {\n const validRequest: CommonSilentFlowRequest = {\n ...request,\n ...(await this.initializeBaseRequest(request)),\n forceRefresh: request.forceRefresh || false,\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(\n ApiId.acquireTokenSilent,\n validRequest.correlationId,\n validRequest.forceRefresh\n );\n try {\n const silentFlowClientConfig =\n 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(\n \"Silent flow client created\",\n validRequest.correlationId\n );\n return await silentFlowClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e as AuthError);\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(\n request: UsernamePasswordRequest\n ): Promise<AuthenticationResult | null> {\n this.logger.info(\n \"acquireTokenByUsernamePassword called\",\n request.correlationId\n );\n const validRequest: CommonUsernamePasswordRequest = {\n ...request,\n ...(await this.initializeBaseRequest(request)),\n };\n const serverTelemetryManager = this.initializeServerTelemetryManager(\n ApiId.acquireTokenByUsernamePassword,\n validRequest.correlationId\n );\n try {\n const usernamePasswordClientConfig =\n await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n undefined,\n request.azureCloudOptions\n );\n const usernamePasswordClient = new UsernamePasswordClient(\n usernamePasswordClientConfig\n );\n this.logger.verbose(\n \"Username password client created\",\n validRequest.correlationId\n );\n return await 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 createClientAuthError(ClientAuthErrorCodes.stateMismatch);\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\n ): Promise<ClientConfiguration> {\n this.logger.verbose(\n \"buildOauthClientConfiguration called\",\n requestCorrelationId\n );\n\n // precedence - azureCloudInstance + tenant >> authority and request >> config\n const userAzureCloudOptions = azureCloudOptions\n ? azureCloudOptions\n : this.config.auth.azureCloudOptions;\n\n // using null assertion operator as we ensure that all config values have default values in buildConfiguration()\n const discoveredAuthority = await this.createAuthority(\n authority,\n requestCorrelationId,\n azureRegionConfiguration,\n userAzureCloudOptions\n );\n\n this.logger.info(\n `Building oauth client configuration with the following authority: ${discoveredAuthority.tokenEndpoint}.`,\n requestCorrelationId\n );\n\n serverTelemetryManager?.updateRegionDiscoveryMetadata(\n discoveredAuthority.regionDiscoveryMetadata\n );\n\n const clientConfiguration: ClientConfiguration = {\n authOptions: {\n clientId: this.config.auth.clientId,\n authority: discoveredAuthority,\n clientCapabilities: this.config.auth.clientCapabilities,\n },\n loggerOptions: {\n logLevel: this.config.system.loggerOptions.logLevel,\n loggerCallback: this.config.system.loggerOptions.loggerCallback,\n piiLoggingEnabled:\n this.config.system.loggerOptions.piiLoggingEnabled,\n correlationId: requestCorrelationId,\n },\n cacheOptions: {\n claimsBasedCachingEnabled:\n this.config.cache.claimsBasedCachingEnabled,\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\n ? this.getClientAssertion(discoveredAuthority)\n : 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): {\n assertion: string;\n assertionType: string;\n } {\n return {\n assertion: this.clientAssertion.getJwt(\n this.cryptoProvider,\n this.config.auth.clientId,\n authority.tokenEndpoint\n ),\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(\n authRequest: Partial<BaseAuthRequest>\n ): Promise<BaseAuthRequest> {\n this.logger.verbose(\n \"initializeRequestScopes called\",\n authRequest.correlationId\n );\n // Default authenticationScheme to Bearer, log that POP isn't supported yet\n if (\n authRequest.authenticationScheme &&\n authRequest.authenticationScheme === AuthenticationScheme.POP\n ) {\n this.logger.verbose(\n \"Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request\",\n authRequest.correlationId\n );\n }\n\n authRequest.authenticationScheme = AuthenticationScheme.BEARER;\n\n // Set requested claims hash if claims-based caching is enabled and claims were requested\n if (\n this.config.cache.claimsBasedCachingEnabled &&\n authRequest.claims &&\n // Checks for empty stringified object \"{}\" which doesn't qualify as requested claims\n !StringUtils.isEmptyObj(authRequest.claims)\n ) {\n authRequest.requestedClaimsHash =\n await this.cryptoProvider.hashString(authRequest.claims);\n }\n\n return {\n ...authRequest,\n scopes: [\n ...((authRequest && authRequest.scopes) || []),\n ...OIDC_DEFAULT_SCOPES,\n ],\n correlationId:\n (authRequest && authRequest.correlationId) ||\n 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(\n apiId: number,\n correlationId: string,\n forceRefresh?: boolean\n ): 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(\n authorityString: string,\n requestCorrelationId: string,\n azureRegionConfiguration?: AzureRegionConfiguration,\n azureCloudOptions?: AzureCloudOptions\n ): 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(\n authorityString,\n azureCloudOptions\n );\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:\n this.config.auth.skipAuthorityMetadataCache,\n };\n\n return AuthorityFactory.createDiscoveredInstance(\n authorityUrl,\n this.config.system.networkClient,\n this.storage,\n authorityOptions,\n this.logger,\n requestCorrelationId\n );\n }\n\n /**\n * Clear the cache\n */\n clearCache(): void {\n void this.storage.clear();\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n Constants as CommonConstants,\n ServerAuthorizationCodeResponse,\n HttpStatus,\n UrlUtils,\n} from \"@azure/msal-common\";\nimport http from \"http\";\nimport { NodeAuthError } from \"../error/NodeAuthError.js\";\nimport { Constants } from \"../utils/Constants.js\";\nimport { ILoopbackClient } from \"./ILoopbackClient.js\";\n\nexport class LoopbackClient implements ILoopbackClient {\n private server: http.Server | undefined;\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(\n successTemplate?: string,\n errorTemplate?: string\n ): Promise<ServerAuthorizationCodeResponse> {\n if (this.server) {\n throw NodeAuthError.createLoopbackServerAlreadyExistsError();\n }\n\n return new Promise<ServerAuthorizationCodeResponse>(\n (resolve, reject) => {\n this.server = http.createServer(\n (req: http.IncomingMessage, res: http.ServerResponse) => {\n const url = req.url;\n if (!url) {\n res.end(\n errorTemplate ||\n \"Error occurred loading redirectUrl\"\n );\n reject(\n NodeAuthError.createUnableToLoadRedirectUrlError()\n );\n return;\n } else if (url === CommonConstants.FORWARD_SLASH) {\n res.end(\n successTemplate ||\n \"Auth code was successfully acquired. You can close this window now.\"\n );\n return;\n }\n\n const redirectUri = this.getRedirectUri();\n const parsedUrl = new URL(url, redirectUri);\n const authCodeResponse =\n UrlUtils.getDeserializedResponse(\n parsedUrl.search\n ) || {};\n if (authCodeResponse.code) {\n res.writeHead(HttpStatus.REDIRECT, {\n location: redirectUri,\n }); // Prevent auth code from being saved in the browser history\n res.end();\n }\n resolve(authCodeResponse);\n }\n );\n this.server.listen(0); // Listen on any available port\n }\n );\n }\n\n /**\n * Get the port that the loopback server is running on\n * @returns\n */\n getRedirectUri(): string {\n if (!this.server || !this.server.listening) {\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 // Only stops accepting new connections, server will close once open/idle connections are closed.\n this.server.close();\n\n if (typeof this.server.closeAllConnections === \"function\") {\n /*\n * Close open/idle connections. This API is available in Node versions 18.2 and higher\n */\n this.server.closeAllConnections();\n }\n this.server.unref();\n this.server = undefined;\n }\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AuthErrorCodes,\n AuthenticationResult,\n BaseClient,\n ClientAuthErrorCodes,\n ClientConfiguration,\n CommonDeviceCodeRequest,\n Constants,\n DeviceCodeResponse,\n GrantType,\n RequestParameterBuilder,\n RequestThumbprint,\n ResponseHandler,\n ServerAuthorizationTokenResponse,\n ServerDeviceCodeResponse,\n StringUtils,\n TimeUtils,\n UrlString,\n createAuthError,\n createClientAuthError,\n} from \"@azure/msal-common\";\n\n/**\n * OAuth2.0 Device code client\n */\nexport class DeviceCodeClient extends BaseClient {\n constructor(configuration: ClientConfiguration) {\n super(configuration);\n }\n\n /**\n * Gets device code from device code endpoint, calls back to with device code response, and\n * polls token endpoint to exchange device code for tokens\n * @param request\n */\n public async acquireToken(\n request: CommonDeviceCodeRequest\n ): Promise<AuthenticationResult | null> {\n const deviceCodeResponse: DeviceCodeResponse = await this.getDeviceCode(\n request\n );\n request.deviceCodeCallback(deviceCodeResponse);\n const reqTimestamp = TimeUtils.nowSeconds();\n const response: ServerAuthorizationTokenResponse =\n await this.acquireTokenWithDeviceCode(request, deviceCodeResponse);\n\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin\n );\n\n // Validate response. This function throws a server error if an error is returned by the server.\n responseHandler.validateTokenResponse(response);\n return responseHandler.handleServerTokenResponse(\n response,\n this.authority,\n reqTimestamp,\n request\n );\n }\n\n /**\n * Creates device code request and executes http GET\n * @param request\n */\n private async getDeviceCode(\n request: CommonDeviceCodeRequest\n ): Promise<DeviceCodeResponse> {\n const queryParametersString = this.createExtraQueryParameters(request);\n const endpoint = UrlString.appendQueryString(\n this.authority.deviceCodeEndpoint,\n queryParametersString\n );\n const queryString = this.createQueryString(request);\n const headers = this.createTokenRequestHeaders();\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: request.authority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid,\n };\n\n return this.executePostRequestToDeviceCodeEndpoint(\n endpoint,\n queryString,\n headers,\n thumbprint\n );\n }\n\n /**\n * Creates query string for the device code request\n * @param request\n */\n createExtraQueryParameters(request: CommonDeviceCodeRequest): string {\n const parameterBuilder = new RequestParameterBuilder();\n\n if (request.extraQueryParameters) {\n parameterBuilder.addExtraQueryParameters(\n request.extraQueryParameters\n );\n }\n\n return parameterBuilder.createQueryString();\n }\n\n /**\n * Executes POST request to device code endpoint\n * @param deviceCodeEndpoint\n * @param queryString\n * @param headers\n */\n private async executePostRequestToDeviceCodeEndpoint(\n deviceCodeEndpoint: string,\n queryString: string,\n headers: Record<string, string>,\n thumbprint: RequestThumbprint\n ): Promise<DeviceCodeResponse> {\n const {\n body: {\n user_code: userCode,\n device_code: deviceCode,\n verification_uri: verificationUri,\n expires_in: expiresIn,\n interval,\n message,\n },\n } = await this.networkManager.sendPostRequest<ServerDeviceCodeResponse>(\n thumbprint,\n deviceCodeEndpoint,\n {\n body: queryString,\n headers: headers,\n }\n );\n\n return {\n userCode,\n deviceCode,\n verificationUri,\n expiresIn,\n interval,\n message,\n };\n }\n\n /**\n * Create device code endpoint query parameters and returns string\n */\n private createQueryString(request: CommonDeviceCodeRequest): string {\n const parameterBuilder: RequestParameterBuilder =\n new RequestParameterBuilder();\n\n parameterBuilder.addScopes(request.scopes);\n parameterBuilder.addClientId(this.config.authOptions.clientId);\n\n if (request.extraQueryParameters) {\n parameterBuilder.addExtraQueryParameters(\n request.extraQueryParameters\n );\n }\n\n if (\n request.claims ||\n (this.config.authOptions.clientCapabilities &&\n this.config.authOptions.clientCapabilities.length > 0)\n ) {\n parameterBuilder.addClaims(\n request.claims,\n this.config.authOptions.clientCapabilities\n );\n }\n\n return parameterBuilder.createQueryString();\n }\n\n /**\n * Breaks the polling with specific conditions.\n * @param request CommonDeviceCodeRequest\n * @param deviceCodeResponse DeviceCodeResponse\n */\n private continuePolling(\n deviceCodeExpirationTime: number,\n userSpecifiedTimeout?: number,\n userSpecifiedCancelFlag?: boolean\n ): boolean {\n if (userSpecifiedCancelFlag) {\n this.logger.error(\n \"Token request cancelled by setting DeviceCodeRequest.cancel = true\"\n );\n throw createClientAuthError(\n ClientAuthErrorCodes.deviceCodePollingCancelled\n );\n } else if (\n userSpecifiedTimeout &&\n userSpecifiedTimeout < deviceCodeExpirationTime &&\n TimeUtils.nowSeconds() > userSpecifiedTimeout\n ) {\n this.logger.error(\n `User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`\n );\n throw createClientAuthError(\n ClientAuthErrorCodes.userTimeoutReached\n );\n } else if (TimeUtils.nowSeconds() > deviceCodeExpirationTime) {\n if (userSpecifiedTimeout) {\n this.logger.verbose(\n `User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${userSpecifiedTimeout}`\n );\n }\n this.logger.error(\n `Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`\n );\n throw createClientAuthError(ClientAuthErrorCodes.deviceCodeExpired);\n }\n return true;\n }\n\n /**\n * Creates token request with device code response and polls token endpoint at interval set by the device code\n * response\n * @param request\n * @param deviceCodeResponse\n */\n private async acquireTokenWithDeviceCode(\n request: CommonDeviceCodeRequest,\n deviceCodeResponse: DeviceCodeResponse\n ): Promise<ServerAuthorizationTokenResponse> {\n const queryParametersString = this.createTokenQueryParameters(request);\n const endpoint = UrlString.appendQueryString(\n this.authority.tokenEndpoint,\n queryParametersString\n );\n const requestBody = this.createTokenRequestBody(\n request,\n deviceCodeResponse\n );\n const headers: Record<string, string> =\n this.createTokenRequestHeaders();\n\n const userSpecifiedTimeout = request.timeout\n ? TimeUtils.nowSeconds() + request.timeout\n : undefined;\n const deviceCodeExpirationTime =\n TimeUtils.nowSeconds() + deviceCodeResponse.expiresIn;\n const pollingIntervalMilli = deviceCodeResponse.interval * 1000;\n\n /*\n * Poll token endpoint while (device code is not expired AND operation has not been cancelled by\n * setting CancellationToken.cancel = true). POST request is sent at interval set by pollingIntervalMilli\n */\n while (\n this.continuePolling(\n deviceCodeExpirationTime,\n userSpecifiedTimeout,\n request.cancel\n )\n ) {\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: request.authority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid,\n };\n const response = await this.executePostToTokenEndpoint(\n endpoint,\n requestBody,\n headers,\n thumbprint,\n request.correlationId\n );\n\n if (response.body && response.body.error) {\n // user authorization is pending. Sleep for polling interval and try again\n if (response.body.error === Constants.AUTHORIZATION_PENDING) {\n this.logger.info(\n \"Authorization pending. Continue polling.\"\n );\n await TimeUtils.delay(pollingIntervalMilli);\n } else {\n // for any other error, throw\n this.logger.info(\n \"Unexpected error in polling from the server\"\n );\n throw createAuthError(\n AuthErrorCodes.postRequestFailed,\n response.body.error\n );\n }\n } else {\n this.logger.verbose(\n \"Authorization completed successfully. Polling stopped.\"\n );\n return response.body;\n }\n }\n\n /*\n * The above code should've thrown by this point, but to satisfy TypeScript,\n * and in the rare case the conditionals in continuePolling() may not catch everything...\n */\n this.logger.error(\"Polling stopped for unknown reasons.\");\n throw createClientAuthError(\n ClientAuthErrorCodes.deviceCodeUnknownError\n );\n }\n\n /**\n * Creates query parameters and converts to string.\n * @param request\n * @param deviceCodeResponse\n */\n private createTokenRequestBody(\n request: CommonDeviceCodeRequest,\n deviceCodeResponse: DeviceCodeResponse\n ): string {\n const requestParameters: RequestParameterBuilder =\n new RequestParameterBuilder();\n\n requestParameters.addScopes(request.scopes);\n requestParameters.addClientId(this.config.authOptions.clientId);\n requestParameters.addGrantType(GrantType.DEVICE_CODE_GRANT);\n requestParameters.addDeviceCode(deviceCodeResponse.deviceCode);\n const correlationId =\n request.correlationId ||\n this.config.cryptoInterface.createNewGuid();\n requestParameters.addCorrelationId(correlationId);\n requestParameters.addClientInfo();\n requestParameters.addLibraryInfo(this.config.libraryInfo);\n requestParameters.addApplicationTelemetry(\n this.config.telemetry.application\n );\n requestParameters.addThrottling();\n if (this.serverTelemetryManager) {\n requestParameters.addServerTelemetry(this.serverTelemetryManager);\n }\n\n if (\n !StringUtils.isEmptyObj(request.claims) ||\n (this.config.authOptions.clientCapabilities &&\n this.config.authOptions.clientCapabilities.length > 0)\n ) {\n requestParameters.addClaims(\n request.claims,\n this.config.authOptions.clientCapabilities\n );\n }\n return requestParameters.createQueryString();\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n ApiId,\n Constants,\n LOOPBACK_SERVER_CONSTANTS,\n} from \"../utils/Constants.js\";\nimport {\n AuthenticationResult,\n CommonDeviceCodeRequest,\n AuthError,\n ResponseMode,\n OIDC_DEFAULT_SCOPES,\n CodeChallengeMethodValues,\n Constants as CommonConstants,\n ServerError,\n NativeRequest,\n NativeSignOutRequest,\n AccountInfo,\n INativeBrokerPlugin,\n ServerAuthorizationCodeResponse,\n} from \"@azure/msal-common\";\nimport { Configuration } from \"../config/Configuration.js\";\nimport { ClientApplication } from \"./ClientApplication.js\";\nimport { IPublicClientApplication } from \"./IPublicClientApplication.js\";\nimport { DeviceCodeRequest } from \"../request/DeviceCodeRequest.js\";\nimport { AuthorizationUrlRequest } from \"../request/AuthorizationUrlRequest.js\";\nimport { AuthorizationCodeRequest } from \"../request/AuthorizationCodeRequest.js\";\nimport { InteractiveRequest } from \"../request/InteractiveRequest.js\";\nimport { NodeAuthError, NodeAuthErrorMessage } from \"../error/NodeAuthError.js\";\nimport { LoopbackClient } from \"../network/LoopbackClient.js\";\nimport { SilentFlowRequest } from \"../request/SilentFlowRequest.js\";\nimport { SignOutRequest } from \"../request/SignOutRequest.js\";\nimport { ILoopbackClient } from \"../network/ILoopbackClient.js\";\nimport { DeviceCodeClient } from \"./DeviceCodeClient.js\";\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\n extends ClientApplication\n implements IPublicClientApplication\n{\n private nativeBrokerPlugin?: INativeBrokerPlugin;\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 if (this.config.broker.nativeBrokerPlugin) {\n if (this.config.broker.nativeBrokerPlugin.isBrokerAvailable) {\n this.nativeBrokerPlugin = this.config.broker.nativeBrokerPlugin;\n this.nativeBrokerPlugin.setLogger(\n this.config.system.loggerOptions\n );\n } else {\n this.logger.warning(\n \"NativeBroker implementation was provided but the broker is unavailable.\"\n );\n }\n }\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(\n request: DeviceCodeRequest\n ): Promise<AuthenticationResult | null> {\n this.logger.info(\n \"acquireTokenByDeviceCode called\",\n request.correlationId\n );\n const validRequest: CommonDeviceCodeRequest = Object.assign(\n request,\n await this.initializeBaseRequest(request)\n );\n const serverTelemetryManager = this.initializeServerTelemetryManager(\n ApiId.acquireTokenByDeviceCode,\n validRequest.correlationId\n );\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(\n \"Device code client created\",\n validRequest.correlationId\n );\n return await deviceCodeClient.acquireToken(validRequest);\n } catch (e) {\n if (e instanceof AuthError) {\n e.setCorrelationId(validRequest.correlationId);\n }\n serverTelemetryManager.cacheFailedRequest(e as AuthError);\n throw e;\n }\n }\n\n /**\n * Acquires a token interactively via the browser by requesting an authorization code then exchanging it for a token.\n */\n async acquireTokenInteractive(\n request: InteractiveRequest\n ): Promise<AuthenticationResult> {\n const correlationId =\n request.correlationId || this.cryptoProvider.createNewGuid();\n this.logger.trace(\"acquireTokenInteractive called\", correlationId);\n const {\n openBrowser,\n successTemplate,\n errorTemplate,\n windowHandle,\n loopbackClient: customLoopbackClient,\n ...remainingProperties\n } = request;\n\n if (this.nativeBrokerPlugin) {\n const brokerRequest: NativeRequest = {\n ...remainingProperties,\n clientId: this.config.auth.clientId,\n scopes: request.scopes || OIDC_DEFAULT_SCOPES,\n redirectUri: `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}`,\n authority: request.authority || this.config.auth.authority,\n correlationId: correlationId,\n extraParameters: {\n ...remainingProperties.extraQueryParameters,\n ...remainingProperties.tokenQueryParameters,\n },\n accountId: remainingProperties.account?.nativeAccountId,\n };\n return this.nativeBrokerPlugin.acquireTokenInteractive(\n brokerRequest,\n windowHandle\n );\n }\n\n const { verifier, challenge } =\n await this.cryptoProvider.generatePkceCodes();\n\n const loopbackClient: ILoopbackClient =\n customLoopbackClient || new LoopbackClient();\n\n let authCodeResponse: ServerAuthorizationCodeResponse = {};\n let authCodeListenerError: AuthError | null = null;\n try {\n const authCodeListener = loopbackClient\n .listenForAuthCode(successTemplate, errorTemplate)\n .then((response) => {\n authCodeResponse = response;\n })\n .catch((e) => {\n // Store the promise instead of throwing so we can control when its thrown\n authCodeListenerError = e;\n });\n\n // Wait for server to be listening\n const redirectUri = await this.waitForRedirectUri(loopbackClient);\n\n const validRequest: AuthorizationUrlRequest = {\n ...remainingProperties,\n correlationId: correlationId,\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 await authCodeListener;\n if (authCodeListenerError) {\n throw authCodeListenerError;\n }\n\n if (authCodeResponse.error) {\n throw new ServerError(\n authCodeResponse.error,\n authCodeResponse.error_description,\n authCodeResponse.suberror\n );\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 await this.acquireTokenByCode(tokenRequest); // Await this so the server doesn't close prematurely\n } finally {\n loopbackClient.closeServer();\n }\n }\n\n /**\n * Returns a token retrieved either from the cache or by exchanging the refresh token for a fresh access token. If brokering is enabled the token request will be serviced by the broker.\n * @param request\n * @returns\n */\n async acquireTokenSilent(\n request: SilentFlowRequest\n ): Promise<AuthenticationResult> {\n const correlationId =\n request.correlationId || this.cryptoProvider.createNewGuid();\n this.logger.trace(\"acquireTokenSilent called\", correlationId);\n\n if (this.nativeBrokerPlugin) {\n const brokerRequest: NativeRequest = {\n ...request,\n clientId: this.config.auth.clientId,\n scopes: request.scopes || OIDC_DEFAULT_SCOPES,\n redirectUri: `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}`,\n authority: request.authority || this.config.auth.authority,\n correlationId: correlationId,\n extraParameters: request.tokenQueryParameters,\n accountId: request.account.nativeAccountId,\n forceRefresh: request.forceRefresh || false,\n };\n return this.nativeBrokerPlugin.acquireTokenSilent(brokerRequest);\n }\n\n return super.acquireTokenSilent(request);\n }\n\n /**\n * Removes cache artifacts associated with the given account\n * @param request\n * @returns\n */\n async signOut(request: SignOutRequest): Promise<void> {\n if (this.nativeBrokerPlugin && request.account.nativeAccountId) {\n const signoutRequest: NativeSignOutRequest = {\n clientId: this.config.auth.clientId,\n accountId: request.account.nativeAccountId,\n correlationId:\n request.correlationId ||\n this.cryptoProvider.createNewGuid(),\n };\n await this.nativeBrokerPlugin.signOut(signoutRequest);\n }\n\n await this.getTokenCache().removeAccount(request.account);\n }\n\n /**\n * Returns all cached accounts for this application. If brokering is enabled this request will be serviced by the broker.\n * @returns\n */\n async getAllAccounts(): Promise<AccountInfo[]> {\n if (this.nativeBrokerPlugin) {\n const correlationId = this.cryptoProvider.createNewGuid();\n return this.nativeBrokerPlugin.getAllAccounts(\n this.config.auth.clientId,\n correlationId\n );\n }\n\n return this.getTokenCache().getAllAccounts();\n }\n\n /**\n * Attempts to retrieve the redirectUri from the loopback server. If the loopback server does not start listening for requests within the timeout this will throw.\n * @param loopbackClient\n * @returns\n */\n private async waitForRedirectUri(\n loopbackClient: ILoopbackClient\n ): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let ticks = 0;\n const id = setInterval(() => {\n if (\n LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS /\n LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS <\n ticks\n ) {\n clearInterval(id);\n reject(NodeAuthError.createLoopbackServerTimeoutError());\n return;\n }\n\n try {\n const r = loopbackClient.getRedirectUri();\n clearInterval(id);\n resolve(r);\n return;\n } catch (e) {\n if (\n e instanceof AuthError &&\n e.errorCode ===\n NodeAuthErrorMessage.noLoopbackServerExists.code\n ) {\n // Loopback server is not listening yet\n ticks++;\n return;\n }\n clearInterval(id);\n reject(e);\n return;\n }\n }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);\n });\n }\n}\n", "/*global module, process*/\nvar Buffer = require('safe-buffer').Buffer;\nvar Stream = require('stream');\nvar util = require('util');\n\nfunction DataStream(data) {\n this.buffer = null;\n this.writable = true;\n this.readable = true;\n\n // No input\n if (!data) {\n this.buffer = Buffer.alloc(0);\n return this;\n }\n\n // Stream\n if (typeof data.pipe === 'function') {\n this.buffer = Buffer.alloc(0);\n data.pipe(this);\n return this;\n }\n\n // Buffer or String\n // or Object (assumedly a passworded key)\n if (data.length || typeof data === 'object') {\n this.buffer = data;\n this.writable = false;\n process.nextTick(function () {\n this.emit('end', data);\n this.readable = false;\n this.emit('close');\n }.bind(this));\n return this;\n }\n\n throw new TypeError('Unexpected data type ('+ typeof data + ')');\n}\nutil.inherits(DataStream, Stream);\n\nDataStream.prototype.write = function write(data) {\n this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]);\n this.emit('data', data);\n};\n\nDataStream.prototype.end = function end(data) {\n if (data)\n this.write(data);\n this.emit('end', data);\n this.emit('close');\n this.writable = false;\n this.readable = false;\n};\n\nmodule.exports = DataStream;\n", "/*jshint node:true */\n'use strict';\nvar Buffer = require('buffer').Buffer; // browserify\nvar SlowBuffer = require('buffer').SlowBuffer;\n\nmodule.exports = bufferEq;\n\nfunction bufferEq(a, b) {\n\n // shortcutting on type is necessary for correctness\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n return false;\n }\n\n // buffer sizes should be well-known information, so despite this\n // shortcutting, it doesn't leak any information about the *contents* of the\n // buffers.\n if (a.length !== b.length) {\n return false;\n }\n\n var c = 0;\n for (var i = 0; i < a.length; i++) {\n /*jshint bitwise:false */\n c |= a[i] ^ b[i]; // XOR\n }\n return c === 0;\n}\n\nbufferEq.install = function() {\n Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {\n return bufferEq(this, that);\n };\n};\n\nvar origBufEqual = Buffer.prototype.equal;\nvar origSlowBufEqual = SlowBuffer.prototype.equal;\nbufferEq.restore = function() {\n Buffer.prototype.equal = origBufEqual;\n SlowBuffer.prototype.equal = origSlowBufEqual;\n};\n", "'use strict';\n\nfunction getParamSize(keySize) {\n\tvar result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1);\n\treturn result;\n}\n\nvar paramBytesForAlg = {\n\tES256: getParamSize(256),\n\tES384: getParamSize(384),\n\tES512: getParamSize(521)\n};\n\nfunction getParamBytesForAlg(alg) {\n\tvar paramBytes = paramBytesForAlg[alg];\n\tif (paramBytes) {\n\t\treturn paramBytes;\n\t}\n\n\tthrow new Error('Unknown algorithm \"' + alg + '\"');\n}\n\nmodule.exports = getParamBytesForAlg;\n", "'use strict';\n\nvar Buffer = require('safe-buffer').Buffer;\n\nvar getParamBytesForAlg = require('./param-bytes-for-alg');\n\nvar MAX_OCTET = 0x80,\n\tCLASS_UNIVERSAL = 0,\n\tPRIMITIVE_BIT = 0x20,\n\tTAG_SEQ = 0x10,\n\tTAG_INT = 0x02,\n\tENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6),\n\tENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6);\n\nfunction base64Url(base64) {\n\treturn base64\n\t\t.replace(/=/g, '')\n\t\t.replace(/\\+/g, '-')\n\t\t.replace(/\\//g, '_');\n}\n\nfunction signatureAsBuffer(signature) {\n\tif (Buffer.isBuffer(signature)) {\n\t\treturn signature;\n\t} else if ('string' === typeof signature) {\n\t\treturn Buffer.from(signature, 'base64');\n\t}\n\n\tthrow new TypeError('ECDSA signature must be a Base64 string or a Buffer');\n}\n\nfunction derToJose(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\t// the DER encoded param should at most be the param size, plus a padding\n\t// zero, since due to being a signed integer\n\tvar maxEncodedParamLength = paramBytes + 1;\n\n\tvar inputLength = signature.length;\n\n\tvar offset = 0;\n\tif (signature[offset++] !== ENCODED_TAG_SEQ) {\n\t\tthrow new Error('Could not find expected \"seq\"');\n\t}\n\n\tvar seqLength = signature[offset++];\n\tif (seqLength === (MAX_OCTET | 1)) {\n\t\tseqLength = signature[offset++];\n\t}\n\n\tif (inputLength - offset < seqLength) {\n\t\tthrow new Error('\"seq\" specified length of \"' + seqLength + '\", only \"' + (inputLength - offset) + '\" remaining');\n\t}\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"r\"');\n\t}\n\n\tvar rLength = signature[offset++];\n\n\tif (inputLength - offset - 2 < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", only \"' + (inputLength - offset - 2) + '\" available');\n\t}\n\n\tif (maxEncodedParamLength < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar rOffset = offset;\n\toffset += rLength;\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"s\"');\n\t}\n\n\tvar sLength = signature[offset++];\n\n\tif (inputLength - offset !== sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", expected \"' + (inputLength - offset) + '\"');\n\t}\n\n\tif (maxEncodedParamLength < sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar sOffset = offset;\n\toffset += sLength;\n\n\tif (offset !== inputLength) {\n\t\tthrow new Error('Expected to consume entire buffer, but \"' + (inputLength - offset) + '\" bytes remain');\n\t}\n\n\tvar rPadding = paramBytes - rLength,\n\t\tsPadding = paramBytes - sLength;\n\n\tvar dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);\n\n\tfor (offset = 0; offset < rPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);\n\n\toffset = paramBytes;\n\n\tfor (var o = offset; offset < o + sPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);\n\n\tdst = dst.toString('base64');\n\tdst = base64Url(dst);\n\n\treturn dst;\n}\n\nfunction countPadding(buf, start, stop) {\n\tvar padding = 0;\n\twhile (start + padding < stop && buf[start + padding] === 0) {\n\t\t++padding;\n\t}\n\n\tvar needsSign = buf[start + padding] >= MAX_OCTET;\n\tif (needsSign) {\n\t\t--padding;\n\t}\n\n\treturn padding;\n}\n\nfunction joseToDer(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\tvar signatureBytes = signature.length;\n\tif (signatureBytes !== paramBytes * 2) {\n\t\tthrow new TypeError('\"' + alg + '\" signatures must be \"' + paramBytes * 2 + '\" bytes, saw \"' + signatureBytes + '\"');\n\t}\n\n\tvar rPadding = countPadding(signature, 0, paramBytes);\n\tvar sPadding = countPadding(signature, paramBytes, signature.length);\n\tvar rLength = paramBytes - rPadding;\n\tvar sLength = paramBytes - sPadding;\n\n\tvar rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;\n\n\tvar shortLength = rsBytes < MAX_OCTET;\n\n\tvar dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);\n\n\tvar offset = 0;\n\tdst[offset++] = ENCODED_TAG_SEQ;\n\tif (shortLength) {\n\t\t// Bit 8 has value \"0\"\n\t\t// bits 7-1 give the length.\n\t\tdst[offset++] = rsBytes;\n\t} else {\n\t\t// Bit 8 of first octet has value \"1\"\n\t\t// bits 7-1 give the number of additional length octets.\n\t\tdst[offset++] = MAX_OCTET\t| 1;\n\t\t// length, base 256\n\t\tdst[offset++] = rsBytes & 0xff;\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = rLength;\n\tif (rPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\toffset += signature.copy(dst, offset, 0, paramBytes);\n\t} else {\n\t\toffset += signature.copy(dst, offset, rPadding, paramBytes);\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = sLength;\n\tif (sPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\tsignature.copy(dst, offset, paramBytes);\n\t} else {\n\t\tsignature.copy(dst, offset, paramBytes + sPadding);\n\t}\n\n\treturn dst;\n}\n\nmodule.exports = {\n\tderToJose: derToJose,\n\tjoseToDer: joseToDer\n};\n", "var bufferEqual = require('buffer-equal-constant-time');\nvar Buffer = require('safe-buffer').Buffer;\nvar crypto = require('crypto');\nvar formatEcdsa = require('ecdsa-sig-formatter');\nvar util = require('util');\n\nvar MSG_INVALID_ALGORITHM = '\"%s\" is not a valid algorithm.\\n Supported algorithms are:\\n \"HS256\", \"HS384\", \"HS512\", \"RS256\", \"RS384\", \"RS512\", \"PS256\", \"PS384\", \"PS512\", \"ES256\", \"ES384\", \"ES512\" and \"none\".'\nvar MSG_INVALID_SECRET = 'secret must be a string or buffer';\nvar MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';\nvar MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';\n\nvar supportsKeyObjects = typeof crypto.createPublicKey === 'function';\nif (supportsKeyObjects) {\n MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';\n MSG_INVALID_SECRET += 'or a KeyObject';\n}\n\nfunction checkIsPublicKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return;\n }\n\n if (!supportsKeyObjects) {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key !== 'object') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.type !== 'string') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.asymmetricKeyType !== 'string') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.export !== 'function') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n};\n\nfunction checkIsPrivateKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return;\n }\n\n if (typeof key === 'object') {\n return;\n }\n\n throw typeError(MSG_INVALID_SIGNER_KEY);\n};\n\nfunction checkIsSecretKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return key;\n }\n\n if (!supportsKeyObjects) {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (typeof key !== 'object') {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (key.type !== 'secret') {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (typeof key.export !== 'function') {\n throw typeError(MSG_INVALID_SECRET);\n }\n}\n\nfunction fromBase64(base64) {\n return base64\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n\nfunction toBase64(base64url) {\n base64url = base64url.toString();\n\n var padding = 4 - base64url.length % 4;\n if (padding !== 4) {\n for (var i = 0; i < padding; ++i) {\n base64url += '=';\n }\n }\n\n return base64url\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n}\n\nfunction typeError(template) {\n var args = [].slice.call(arguments, 1);\n var errMsg = util.format.bind(util, template).apply(null, args);\n return new TypeError(errMsg);\n}\n\nfunction bufferOrString(obj) {\n return Buffer.isBuffer(obj) || typeof obj === 'string';\n}\n\nfunction normalizeInput(thing) {\n if (!bufferOrString(thing))\n thing = JSON.stringify(thing);\n return thing;\n}\n\nfunction createHmacSigner(bits) {\n return function sign(thing, secret) {\n checkIsSecretKey(secret);\n thing = normalizeInput(thing);\n var hmac = crypto.createHmac('sha' + bits, secret);\n var sig = (hmac.update(thing), hmac.digest('base64'))\n return fromBase64(sig);\n }\n}\n\nfunction createHmacVerifier(bits) {\n return function verify(thing, signature, secret) {\n var computedSig = createHmacSigner(bits)(thing, secret);\n return bufferEqual(Buffer.from(signature), Buffer.from(computedSig));\n }\n}\n\nfunction createKeySigner(bits) {\n return function sign(thing, privateKey) {\n checkIsPrivateKey(privateKey);\n thing = normalizeInput(thing);\n // Even though we are specifying \"RSA\" here, this works with ECDSA\n // keys as well.\n var signer = crypto.createSign('RSA-SHA' + bits);\n var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));\n return fromBase64(sig);\n }\n}\n\nfunction createKeyVerifier(bits) {\n return function verify(thing, signature, publicKey) {\n checkIsPublicKey(publicKey);\n thing = normalizeInput(thing);\n signature = toBase64(signature);\n var verifier = crypto.createVerify('RSA-SHA' + bits);\n verifier.update(thing);\n return verifier.verify(publicKey, signature, 'base64');\n }\n}\n\nfunction createPSSKeySigner(bits) {\n return function sign(thing, privateKey) {\n checkIsPrivateKey(privateKey);\n thing = normalizeInput(thing);\n var signer = crypto.createSign('RSA-SHA' + bits);\n var sig = (signer.update(thing), signer.sign({\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n }, 'base64'));\n return fromBase64(sig);\n }\n}\n\nfunction createPSSKeyVerifier(bits) {\n return function verify(thing, signature, publicKey) {\n checkIsPublicKey(publicKey);\n thing = normalizeInput(thing);\n signature = toBase64(signature);\n var verifier = crypto.createVerify('RSA-SHA' + bits);\n verifier.update(thing);\n return verifier.verify({\n key: publicKey,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n }, signature, 'base64');\n }\n}\n\nfunction createECDSASigner(bits) {\n var inner = createKeySigner(bits);\n return function sign() {\n var signature = inner.apply(null, arguments);\n signature = formatEcdsa.derToJose(signature, 'ES' + bits);\n return signature;\n };\n}\n\nfunction createECDSAVerifer(bits) {\n var inner = createKeyVerifier(bits);\n return function verify(thing, signature, publicKey) {\n signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');\n var result = inner(thing, signature, publicKey);\n return result;\n };\n}\n\nfunction createNoneSigner() {\n return function sign() {\n return '';\n }\n}\n\nfunction createNoneVerifier() {\n return function verify(thing, signature) {\n return signature === '';\n }\n}\n\nmodule.exports = function jwa(algorithm) {\n var signerFactories = {\n hs: createHmacSigner,\n rs: createKeySigner,\n ps: createPSSKeySigner,\n es: createECDSASigner,\n none: createNoneSigner,\n }\n var verifierFactories = {\n hs: createHmacVerifier,\n rs: createKeyVerifier,\n ps: createPSSKeyVerifier,\n es: createECDSAVerifer,\n none: createNoneVerifier,\n }\n var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i);\n if (!match)\n throw typeError(MSG_INVALID_ALGORITHM, algorithm);\n var algo = (match[1] || match[3]).toLowerCase();\n var bits = match[2];\n\n return {\n sign: signerFactories[algo](bits),\n verify: verifierFactories[algo](bits),\n }\n};\n", "/*global module*/\nvar Buffer = require('buffer').Buffer;\n\nmodule.exports = function toString(obj) {\n if (typeof obj === 'string')\n return obj;\n if (typeof obj === 'number' || Buffer.isBuffer(obj))\n return obj.toString();\n return JSON.stringify(obj);\n};\n", "/*global module*/\nvar Buffer = require('safe-buffer').Buffer;\nvar DataStream = require('./data-stream');\nvar jwa = require('jwa');\nvar Stream = require('stream');\nvar toString = require('./tostring');\nvar util = require('util');\n\nfunction base64url(string, encoding) {\n return Buffer\n .from(string, encoding)\n .toString('base64')\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n\nfunction jwsSecuredInput(header, payload, encoding) {\n encoding = encoding || 'utf8';\n var encodedHeader = base64url(toString(header), 'binary');\n var encodedPayload = base64url(toString(payload), encoding);\n return util.format('%s.%s', encodedHeader, encodedPayload);\n}\n\nfunction jwsSign(opts) {\n var header = opts.header;\n var payload = opts.payload;\n var secretOrKey = opts.secret || opts.privateKey;\n var encoding = opts.encoding;\n var algo = jwa(header.alg);\n var securedInput = jwsSecuredInput(header, payload, encoding);\n var signature = algo.sign(securedInput, secretOrKey);\n return util.format('%s.%s', securedInput, signature);\n}\n\nfunction SignStream(opts) {\n var secret = opts.secret||opts.privateKey||opts.key;\n var secretStream = new DataStream(secret);\n this.readable = true;\n this.header = opts.header;\n this.encoding = opts.encoding;\n this.secret = this.privateKey = this.key = secretStream;\n this.payload = new DataStream(opts.payload);\n this.secret.once('close', function () {\n if (!this.payload.writable && this.readable)\n this.sign();\n }.bind(this));\n\n this.payload.once('close', function () {\n if (!this.secret.writable && this.readable)\n this.sign();\n }.bind(this));\n}\nutil.inherits(SignStream, Stream);\n\nSignStream.prototype.sign = function sign() {\n try {\n var signature = jwsSign({\n header: this.header,\n payload: this.payload.buffer,\n secret: this.secret.buffer,\n encoding: this.encoding\n });\n this.emit('done', signature);\n this.emit('data', signature);\n this.emit('end');\n this.readable = false;\n return signature;\n } catch (e) {\n this.readable = false;\n this.emit('error', e);\n this.emit('close');\n }\n};\n\nSignStream.sign = jwsSign;\n\nmodule.exports = SignStream;\n", "/*global module*/\nvar Buffer = require('safe-buffer').Buffer;\nvar DataStream = require('./data-stream');\nvar jwa = require('jwa');\nvar Stream = require('stream');\nvar toString = require('./tostring');\nvar util = require('util');\nvar JWS_REGEX = /^[a-zA-Z0-9\\-_]+?\\.[a-zA-Z0-9\\-_]+?\\.([a-zA-Z0-9\\-_]+)?$/;\n\nfunction isObject(thing) {\n return Object.prototype.toString.call(thing) === '[object Object]';\n}\n\nfunction safeJsonParse(thing) {\n if (isObject(thing))\n return thing;\n try { return JSON.parse(thing); }\n catch (e) { return undefined; }\n}\n\nfunction headerFromJWS(jwsSig) {\n var encodedHeader = jwsSig.split('.', 1)[0];\n return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));\n}\n\nfunction securedInputFromJWS(jwsSig) {\n return jwsSig.split('.', 2).join('.');\n}\n\nfunction signatureFromJWS(jwsSig) {\n return jwsSig.split('.')[2];\n}\n\nfunction payloadFromJWS(jwsSig, encoding) {\n encoding = encoding || 'utf8';\n var payload = jwsSig.split('.')[1];\n return Buffer.from(payload, 'base64').toString(encoding);\n}\n\nfunction isValidJws(string) {\n return JWS_REGEX.test(string) && !!headerFromJWS(string);\n}\n\nfunction jwsVerify(jwsSig, algorithm, secretOrKey) {\n if (!algorithm) {\n var err = new Error(\"Missing algorithm parameter for jws.verify\");\n err.code = \"MISSING_ALGORITHM\";\n throw err;\n }\n jwsSig = toString(jwsSig);\n var signature = signatureFromJWS(jwsSig);\n var securedInput = securedInputFromJWS(jwsSig);\n var algo = jwa(algorithm);\n return algo.verify(securedInput, signature, secretOrKey);\n}\n\nfunction jwsDecode(jwsSig, opts) {\n opts = opts || {};\n jwsSig = toString(jwsSig);\n\n if (!isValidJws(jwsSig))\n return null;\n\n var header = headerFromJWS(jwsSig);\n\n if (!header)\n return null;\n\n var payload = payloadFromJWS(jwsSig);\n if (header.typ === 'JWT' || opts.json)\n payload = JSON.parse(payload, opts.encoding);\n\n return {\n header: header,\n payload: payload,\n signature: signatureFromJWS(jwsSig)\n };\n}\n\nfunction VerifyStream(opts) {\n opts = opts || {};\n var secretOrKey = opts.secret||opts.publicKey||opts.key;\n var secretStream = new DataStream(secretOrKey);\n this.readable = true;\n this.algorithm = opts.algorithm;\n this.encoding = opts.encoding;\n this.secret = this.publicKey = this.key = secretStream;\n this.signature = new DataStream(opts.signature);\n this.secret.once('close', function () {\n if (!this.signature.writable && this.readable)\n this.verify();\n }.bind(this));\n\n this.signature.once('close', function () {\n if (!this.secret.writable && this.readable)\n this.verify();\n }.bind(this));\n}\nutil.inherits(VerifyStream, Stream);\nVerifyStream.prototype.verify = function verify() {\n try {\n var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);\n var obj = jwsDecode(this.signature.buffer, this.encoding);\n this.emit('done', valid, obj);\n this.emit('data', valid);\n this.emit('end');\n this.readable = false;\n return valid;\n } catch (e) {\n this.readable = false;\n this.emit('error', e);\n this.emit('close');\n }\n};\n\nVerifyStream.decode = jwsDecode;\nVerifyStream.isValid = isValidJws;\nVerifyStream.verify = jwsVerify;\n\nmodule.exports = VerifyStream;\n", "/*global exports*/\nvar SignStream = require('./lib/sign-stream');\nvar VerifyStream = require('./lib/verify-stream');\n\nvar ALGORITHMS = [\n 'HS256', 'HS384', 'HS512',\n 'RS256', 'RS384', 'RS512',\n 'PS256', 'PS384', 'PS512',\n 'ES256', 'ES384', 'ES512'\n];\n\nexports.ALGORITHMS = ALGORITHMS;\nexports.sign = SignStream.sign;\nexports.verify = VerifyStream.verify;\nexports.decode = VerifyStream.decode;\nexports.isValid = VerifyStream.isValid;\nexports.createSign = function createSign(opts) {\n return new SignStream(opts);\n};\nexports.createVerify = function createVerify(opts) {\n return new VerifyStream(opts);\n};\n", "var jws = require('jws');\n\nmodule.exports = function (jwt, options) {\n options = options || {};\n var decoded = jws.decode(jwt, options);\n if (!decoded) { return null; }\n var payload = decoded.payload;\n\n //try parse the payload\n if(typeof payload === 'string') {\n try {\n var obj = JSON.parse(payload);\n if(obj !== null && typeof obj === 'object') {\n payload = obj;\n }\n } catch (e) { }\n }\n\n //return header if `complete` option is enabled. header includes claims\n //such as `kid` and `alg` used to select the key within a JWKS needed to\n //verify the signature\n if (options.complete === true) {\n return {\n header: decoded.header,\n payload: payload,\n signature: decoded.signature\n };\n }\n return payload;\n};\n", "var JsonWebTokenError = function (message, error) {\n Error.call(this, message);\n if(Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n this.name = 'JsonWebTokenError';\n this.message = message;\n if (error) this.inner = error;\n};\n\nJsonWebTokenError.prototype = Object.create(Error.prototype);\nJsonWebTokenError.prototype.constructor = JsonWebTokenError;\n\nmodule.exports = JsonWebTokenError;\n", "var JsonWebTokenError = require('./JsonWebTokenError');\n\nvar NotBeforeError = function (message, date) {\n JsonWebTokenError.call(this, message);\n this.name = 'NotBeforeError';\n this.date = date;\n};\n\nNotBeforeError.prototype = Object.create(JsonWebTokenError.prototype);\n\nNotBeforeError.prototype.constructor = NotBeforeError;\n\nmodule.exports = NotBeforeError;", "var JsonWebTokenError = require('./JsonWebTokenError');\n\nvar TokenExpiredError = function (message, expiredAt) {\n JsonWebTokenError.call(this, message);\n this.name = 'TokenExpiredError';\n this.expiredAt = expiredAt;\n};\n\nTokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype);\n\nTokenExpiredError.prototype.constructor = TokenExpiredError;\n\nmodule.exports = TokenExpiredError;", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "var ms = require('ms');\n\nmodule.exports = function (time, iat) {\n var timestamp = iat || Math.floor(Date.now() / 1000);\n\n if (typeof time === 'string') {\n var milliseconds = ms(time);\n if (typeof milliseconds === 'undefined') {\n return;\n }\n return Math.floor(timestamp + milliseconds / 1000);\n } else if (typeof time === 'number') {\n return timestamp + time;\n } else {\n return;\n }\n\n};", "// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n", "const debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "const {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n", "const numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n", "const debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return (\n compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n )\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (compareIdentifiers(this.prerelease[0], identifier) === 0) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n", "const SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n", "const parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "const parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n", "const SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n if (typeof (options) === 'string') {\n identifierBase = identifier\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(\n version instanceof SemVer ? version.version : version,\n options\n ).inc(release, identifier, identifierBase).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n", "const parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n const v1 = parse(version1, null, true)\n const v2 = parse(version2, null, true)\n const comparison = v1.compare(v2)\n\n if (comparison === 0) {\n return null\n }\n\n const v1Higher = comparison > 0\n const highVersion = v1Higher ? v1 : v2\n const lowVersion = v1Higher ? v2 : v1\n const highHasPre = !!highVersion.prerelease.length\n const lowHasPre = !!lowVersion.prerelease.length\n\n if (lowHasPre && !highHasPre) {\n // Going from prerelease -> no prerelease requires some special casing\n\n // If the low version has only a major, then it will always be a major\n // Some examples:\n // 1.0.0-1 -> 1.0.0\n // 1.0.0-1 -> 1.1.1\n // 1.0.0-1 -> 2.0.0\n if (!lowVersion.patch && !lowVersion.minor) {\n return 'major'\n }\n\n // Otherwise it can be determined by checking the high version\n\n if (highVersion.patch) {\n // anything higher than a patch bump would result in the wrong version\n return 'patch'\n }\n\n if (highVersion.minor) {\n // anything higher than a minor bump would result in the wrong version\n return 'minor'\n }\n\n // bumping major/minor/patch all have same result\n return 'major'\n }\n\n // add the `pre` prefix if we are going to a prerelease version\n const prefix = highHasPre ? 'pre' : ''\n\n if (v1.major !== v2.major) {\n return prefix + 'major'\n }\n\n if (v1.minor !== v2.minor) {\n return prefix + 'minor'\n }\n\n if (v1.patch !== v2.patch) {\n return prefix + 'patch'\n }\n\n // high and low are preleases\n return 'prerelease'\n}\n\nmodule.exports = diff\n", "const SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n", "const SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n", "const SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n", "const parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n", "const SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "const compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n", "const compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n", "const SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n", "const compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n", "const compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n", "const compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "const compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "const compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "const compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "const compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "const compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "const eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n", "const SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n", "'use strict'\nmodule.exports = function (Yallist) {\n Yallist.prototype[Symbol.iterator] = function* () {\n for (let walker = this.head; walker; walker = walker.next) {\n yield walker.value\n }\n }\n}\n", "'use strict'\nmodule.exports = Yallist\n\nYallist.Node = Node\nYallist.create = Yallist\n\nfunction Yallist (list) {\n var self = this\n if (!(self instanceof Yallist)) {\n self = new Yallist()\n }\n\n self.tail = null\n self.head = null\n self.length = 0\n\n if (list && typeof list.forEach === 'function') {\n list.forEach(function (item) {\n self.push(item)\n })\n } else if (arguments.length > 0) {\n for (var i = 0, l = arguments.length; i < l; i++) {\n self.push(arguments[i])\n }\n }\n\n return self\n}\n\nYallist.prototype.removeNode = function (node) {\n if (node.list !== this) {\n throw new Error('removing node which does not belong to this list')\n }\n\n var next = node.next\n var prev = node.prev\n\n if (next) {\n next.prev = prev\n }\n\n if (prev) {\n prev.next = next\n }\n\n if (node === this.head) {\n this.head = next\n }\n if (node === this.tail) {\n this.tail = prev\n }\n\n node.list.length--\n node.next = null\n node.prev = null\n node.list = null\n\n return next\n}\n\nYallist.prototype.unshiftNode = function (node) {\n if (node === this.head) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var head = this.head\n node.list = this\n node.next = head\n if (head) {\n head.prev = node\n }\n\n this.head = node\n if (!this.tail) {\n this.tail = node\n }\n this.length++\n}\n\nYallist.prototype.pushNode = function (node) {\n if (node === this.tail) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var tail = this.tail\n node.list = this\n node.prev = tail\n if (tail) {\n tail.next = node\n }\n\n this.tail = node\n if (!this.head) {\n this.head = node\n }\n this.length++\n}\n\nYallist.prototype.push = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n push(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.unshift = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n unshift(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.pop = function () {\n if (!this.tail) {\n return undefined\n }\n\n var res = this.tail.value\n this.tail = this.tail.prev\n if (this.tail) {\n this.tail.next = null\n } else {\n this.head = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.shift = function () {\n if (!this.head) {\n return undefined\n }\n\n var res = this.head.value\n this.head = this.head.next\n if (this.head) {\n this.head.prev = null\n } else {\n this.tail = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.forEach = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.head, i = 0; walker !== null; i++) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.next\n }\n}\n\nYallist.prototype.forEachReverse = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.prev\n }\n}\n\nYallist.prototype.get = function (n) {\n for (var i = 0, walker = this.head; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.next\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.getReverse = function (n) {\n for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.prev\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.map = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.head; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.next\n }\n return res\n}\n\nYallist.prototype.mapReverse = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.tail; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.prev\n }\n return res\n}\n\nYallist.prototype.reduce = function (fn, initial) {\n var acc\n var walker = this.head\n if (arguments.length > 1) {\n acc = initial\n } else if (this.head) {\n walker = this.head.next\n acc = this.head.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = 0; walker !== null; i++) {\n acc = fn(acc, walker.value, i)\n walker = walker.next\n }\n\n return acc\n}\n\nYallist.prototype.reduceReverse = function (fn, initial) {\n var acc\n var walker = this.tail\n if (arguments.length > 1) {\n acc = initial\n } else if (this.tail) {\n walker = this.tail.prev\n acc = this.tail.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = this.length - 1; walker !== null; i--) {\n acc = fn(acc, walker.value, i)\n walker = walker.prev\n }\n\n return acc\n}\n\nYallist.prototype.toArray = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.head; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.next\n }\n return arr\n}\n\nYallist.prototype.toArrayReverse = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.tail; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.prev\n }\n return arr\n}\n\nYallist.prototype.slice = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = 0, walker = this.head; walker !== null && i < from; i++) {\n walker = walker.next\n }\n for (; walker !== null && i < to; i++, walker = walker.next) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.sliceReverse = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {\n walker = walker.prev\n }\n for (; walker !== null && i > from; i--, walker = walker.prev) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.splice = function (start, deleteCount, ...nodes) {\n if (start > this.length) {\n start = this.length - 1\n }\n if (start < 0) {\n start = this.length + start;\n }\n\n for (var i = 0, walker = this.head; walker !== null && i < start; i++) {\n walker = walker.next\n }\n\n var ret = []\n for (var i = 0; walker && i < deleteCount; i++) {\n ret.push(walker.value)\n walker = this.removeNode(walker)\n }\n if (walker === null) {\n walker = this.tail\n }\n\n if (walker !== this.head && walker !== this.tail) {\n walker = walker.prev\n }\n\n for (var i = 0; i < nodes.length; i++) {\n walker = insert(this, walker, nodes[i])\n }\n return ret;\n}\n\nYallist.prototype.reverse = function () {\n var head = this.head\n var tail = this.tail\n for (var walker = head; walker !== null; walker = walker.prev) {\n var p = walker.prev\n walker.prev = walker.next\n walker.next = p\n }\n this.head = tail\n this.tail = head\n return this\n}\n\nfunction insert (self, node, value) {\n var inserted = node === self.head ?\n new Node(value, null, node, self) :\n new Node(value, node, node.next, self)\n\n if (inserted.next === null) {\n self.tail = inserted\n }\n if (inserted.prev === null) {\n self.head = inserted\n }\n\n self.length++\n\n return inserted\n}\n\nfunction push (self, item) {\n self.tail = new Node(item, self.tail, null, self)\n if (!self.head) {\n self.head = self.tail\n }\n self.length++\n}\n\nfunction unshift (self, item) {\n self.head = new Node(item, null, self.head, self)\n if (!self.tail) {\n self.tail = self.head\n }\n self.length++\n}\n\nfunction Node (value, prev, next, list) {\n if (!(this instanceof Node)) {\n return new Node(value, prev, next, list)\n }\n\n this.list = list\n this.value = value\n\n if (prev) {\n prev.next = this\n this.prev = prev\n } else {\n this.prev = null\n }\n\n if (next) {\n next.prev = this\n this.next = next\n } else {\n this.next = null\n }\n}\n\ntry {\n // add if support for Symbol.iterator is present\n require('./iterator.js')(Yallist)\n} catch (er) {}\n", "'use strict'\n\n// A linked list to keep track of recently-used-ness\nconst Yallist = require('yallist')\n\nconst MAX = Symbol('max')\nconst LENGTH = Symbol('length')\nconst LENGTH_CALCULATOR = Symbol('lengthCalculator')\nconst ALLOW_STALE = Symbol('allowStale')\nconst MAX_AGE = Symbol('maxAge')\nconst DISPOSE = Symbol('dispose')\nconst NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')\nconst LRU_LIST = Symbol('lruList')\nconst CACHE = Symbol('cache')\nconst UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')\n\nconst naiveLength = () => 1\n\n// lruList is a yallist where the head is the youngest\n// item, and the tail is the oldest. the list contains the Hit\n// objects as the entries.\n// Each Hit object has a reference to its Yallist.Node. This\n// never changes.\n//\n// cache is a Map (or PseudoMap) that matches the keys to\n// the Yallist.Node object.\nclass LRUCache {\n constructor (options) {\n if (typeof options === 'number')\n options = { max: options }\n\n if (!options)\n options = {}\n\n if (options.max && (typeof options.max !== 'number' || options.max < 0))\n throw new TypeError('max must be a non-negative number')\n // Kind of weird to have a default max of Infinity, but oh well.\n const max = this[MAX] = options.max || Infinity\n\n const lc = options.length || naiveLength\n this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc\n this[ALLOW_STALE] = options.stale || false\n if (options.maxAge && typeof options.maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n this[MAX_AGE] = options.maxAge || 0\n this[DISPOSE] = options.dispose\n this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false\n this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false\n this.reset()\n }\n\n // resize the cache when the max changes.\n set max (mL) {\n if (typeof mL !== 'number' || mL < 0)\n throw new TypeError('max must be a non-negative number')\n\n this[MAX] = mL || Infinity\n trim(this)\n }\n get max () {\n return this[MAX]\n }\n\n set allowStale (allowStale) {\n this[ALLOW_STALE] = !!allowStale\n }\n get allowStale () {\n return this[ALLOW_STALE]\n }\n\n set maxAge (mA) {\n if (typeof mA !== 'number')\n throw new TypeError('maxAge must be a non-negative number')\n\n this[MAX_AGE] = mA\n trim(this)\n }\n get maxAge () {\n return this[MAX_AGE]\n }\n\n // resize the cache when the lengthCalculator changes.\n set lengthCalculator (lC) {\n if (typeof lC !== 'function')\n lC = naiveLength\n\n if (lC !== this[LENGTH_CALCULATOR]) {\n this[LENGTH_CALCULATOR] = lC\n this[LENGTH] = 0\n this[LRU_LIST].forEach(hit => {\n hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)\n this[LENGTH] += hit.length\n })\n }\n trim(this)\n }\n get lengthCalculator () { return this[LENGTH_CALCULATOR] }\n\n get length () { return this[LENGTH] }\n get itemCount () { return this[LRU_LIST].length }\n\n rforEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].tail; walker !== null;) {\n const prev = walker.prev\n forEachStep(this, fn, walker, thisp)\n walker = prev\n }\n }\n\n forEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].head; walker !== null;) {\n const next = walker.next\n forEachStep(this, fn, walker, thisp)\n walker = next\n }\n }\n\n keys () {\n return this[LRU_LIST].toArray().map(k => k.key)\n }\n\n values () {\n return this[LRU_LIST].toArray().map(k => k.value)\n }\n\n reset () {\n if (this[DISPOSE] &&\n this[LRU_LIST] &&\n this[LRU_LIST].length) {\n this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))\n }\n\n this[CACHE] = new Map() // hash of items by key\n this[LRU_LIST] = new Yallist() // list of items in order of use recency\n this[LENGTH] = 0 // length of items in the list\n }\n\n dump () {\n return this[LRU_LIST].map(hit =>\n isStale(this, hit) ? false : {\n k: hit.key,\n v: hit.value,\n e: hit.now + (hit.maxAge || 0)\n }).toArray().filter(h => h)\n }\n\n dumpLru () {\n return this[LRU_LIST]\n }\n\n set (key, value, maxAge) {\n maxAge = maxAge || this[MAX_AGE]\n\n if (maxAge && typeof maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n\n const now = maxAge ? Date.now() : 0\n const len = this[LENGTH_CALCULATOR](value, key)\n\n if (this[CACHE].has(key)) {\n if (len > this[MAX]) {\n del(this, this[CACHE].get(key))\n return false\n }\n\n const node = this[CACHE].get(key)\n const item = node.value\n\n // dispose of the old one before overwriting\n // split out into 2 ifs for better coverage tracking\n if (this[DISPOSE]) {\n if (!this[NO_DISPOSE_ON_SET])\n this[DISPOSE](key, item.value)\n }\n\n item.now = now\n item.maxAge = maxAge\n item.value = value\n this[LENGTH] += len - item.length\n item.length = len\n this.get(key)\n trim(this)\n return true\n }\n\n const hit = new Entry(key, value, len, now, maxAge)\n\n // oversized objects fall out of cache automatically.\n if (hit.length > this[MAX]) {\n if (this[DISPOSE])\n this[DISPOSE](key, value)\n\n return false\n }\n\n this[LENGTH] += hit.length\n this[LRU_LIST].unshift(hit)\n this[CACHE].set(key, this[LRU_LIST].head)\n trim(this)\n return true\n }\n\n has (key) {\n if (!this[CACHE].has(key)) return false\n const hit = this[CACHE].get(key).value\n return !isStale(this, hit)\n }\n\n get (key) {\n return get(this, key, true)\n }\n\n peek (key) {\n return get(this, key, false)\n }\n\n pop () {\n const node = this[LRU_LIST].tail\n if (!node)\n return null\n\n del(this, node)\n return node.value\n }\n\n del (key) {\n del(this, this[CACHE].get(key))\n }\n\n load (arr) {\n // reset the cache\n this.reset()\n\n const now = Date.now()\n // A previous serialized cache has the most recent items first\n for (let l = arr.length - 1; l >= 0; l--) {\n const hit = arr[l]\n const expiresAt = hit.e || 0\n if (expiresAt === 0)\n // the item was created without expiration in a non aged cache\n this.set(hit.k, hit.v)\n else {\n const maxAge = expiresAt - now\n // dont add already expired items\n if (maxAge > 0) {\n this.set(hit.k, hit.v, maxAge)\n }\n }\n }\n }\n\n prune () {\n this[CACHE].forEach((value, key) => get(this, key, false))\n }\n}\n\nconst get = (self, key, doUse) => {\n const node = self[CACHE].get(key)\n if (node) {\n const hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n return undefined\n } else {\n if (doUse) {\n if (self[UPDATE_AGE_ON_GET])\n node.value.now = Date.now()\n self[LRU_LIST].unshiftNode(node)\n }\n }\n return hit.value\n }\n}\n\nconst isStale = (self, hit) => {\n if (!hit || (!hit.maxAge && !self[MAX_AGE]))\n return false\n\n const diff = Date.now() - hit.now\n return hit.maxAge ? diff > hit.maxAge\n : self[MAX_AGE] && (diff > self[MAX_AGE])\n}\n\nconst trim = self => {\n if (self[LENGTH] > self[MAX]) {\n for (let walker = self[LRU_LIST].tail;\n self[LENGTH] > self[MAX] && walker !== null;) {\n // We know that we're about to delete this one, and also\n // what the next least recently used key will be, so just\n // go ahead and set it now.\n const prev = walker.prev\n del(self, walker)\n walker = prev\n }\n }\n}\n\nconst del = (self, node) => {\n if (node) {\n const hit = node.value\n if (self[DISPOSE])\n self[DISPOSE](hit.key, hit.value)\n\n self[LENGTH] -= hit.length\n self[CACHE].delete(hit.key)\n self[LRU_LIST].removeNode(node)\n }\n}\n\nclass Entry {\n constructor (key, value, length, now, maxAge) {\n this.key = key\n this.value = value\n this.length = length\n this.now = now\n this.maxAge = maxAge || 0\n }\n}\n\nconst forEachStep = (self, fn, node, thisp) => {\n let hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n hit = undefined\n }\n if (hit)\n fn.call(thisp, hit.value, hit.key, self)\n}\n\nmodule.exports = LRUCache\n", "// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.format()\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range\n .trim()\n .split(/\\s+/)\n .join(' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.format()\n }\n\n format () {\n this.range = this.set\n .map((comps) => comps.join(' ').trim())\n .join('||')\n .trim()\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('lru-cache')\nconst cache = new LRU({ max: 1000 })\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr, tb) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n", "const ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "const Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n", "const Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\nmodule.exports = maxSatisfying\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\nmodule.exports = minSatisfying\n", "const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "const Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n", "const SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nmodule.exports = outside\n", "// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n", "const outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n", "const Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n", "// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let first = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!first) {\n first = version\n }\n } else {\n if (prev) {\n set.push([first, prev])\n }\n prev = null\n first = null\n }\n }\n if (first) {\n set.push([first, null])\n }\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min)\n } else if (!max && min === v[0]) {\n ranges.push('*')\n } else if (!max) {\n ranges.push(`>=${min}`)\n } else if (min === v[0]) {\n ranges.push(`<=${max}`)\n } else {\n ranges.push(`${min} - ${max}`)\n }\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n", "const Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = minimumVersionWithPreRelease\n } else {\n sub = minimumVersion\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = minimumVersion\n }\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options)\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options)\n } else {\n eqSet.add(c.semver)\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n", "// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n parse,\n valid,\n clean,\n inc,\n diff,\n major,\n minor,\n patch,\n prerelease,\n compare,\n rcompare,\n compareLoose,\n compareBuild,\n sort,\n rsort,\n gt,\n lt,\n eq,\n neq,\n gte,\n lte,\n cmp,\n coerce,\n Comparator,\n Range,\n satisfies,\n toComparators,\n maxSatisfying,\n minSatisfying,\n minVersion,\n validRange,\n outside,\n gtr,\n ltr,\n intersects,\n simplifyRange,\n subset,\n SemVer,\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n RELEASE_TYPES: constants.RELEASE_TYPES,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n", "const semver = require('semver');\n\nmodule.exports = semver.satisfies(process.version, '>=15.7.0');\n", "const semver = require('semver');\n\nmodule.exports = semver.satisfies(process.version, '>=16.9.0');\n", "const ASYMMETRIC_KEY_DETAILS_SUPPORTED = require('./asymmetricKeyDetailsSupported');\nconst RSA_PSS_KEY_DETAILS_SUPPORTED = require('./rsaPssKeyDetailsSupported');\n\nconst allowedAlgorithmsForKeys = {\n 'ec': ['ES256', 'ES384', 'ES512'],\n 'rsa': ['RS256', 'PS256', 'RS384', 'PS384', 'RS512', 'PS512'],\n 'rsa-pss': ['PS256', 'PS384', 'PS512']\n};\n\nconst allowedCurves = {\n ES256: 'prime256v1',\n ES384: 'secp384r1',\n ES512: 'secp521r1',\n};\n\nmodule.exports = function(algorithm, key) {\n if (!algorithm || !key) return;\n\n const keyType = key.asymmetricKeyType;\n if (!keyType) return;\n\n const allowedAlgorithms = allowedAlgorithmsForKeys[keyType];\n\n if (!allowedAlgorithms) {\n throw new Error(`Unknown key type \"${keyType}\".`);\n }\n\n if (!allowedAlgorithms.includes(algorithm)) {\n throw new Error(`\"alg\" parameter for \"${keyType}\" key type must be one of: ${allowedAlgorithms.join(', ')}.`)\n }\n\n /*\n * Ignore the next block from test coverage because it gets executed\n * conditionally depending on the Node version. Not ignoring it would\n * prevent us from reaching the target % of coverage for versions of\n * Node under 15.7.0.\n */\n /* istanbul ignore next */\n if (ASYMMETRIC_KEY_DETAILS_SUPPORTED) {\n switch (keyType) {\n case 'ec':\n const keyCurve = key.asymmetricKeyDetails.namedCurve;\n const allowedCurve = allowedCurves[algorithm];\n\n if (keyCurve !== allowedCurve) {\n throw new Error(`\"alg\" parameter \"${algorithm}\" requires curve \"${allowedCurve}\".`);\n }\n break;\n\n case 'rsa-pss':\n if (RSA_PSS_KEY_DETAILS_SUPPORTED) {\n const length = parseInt(algorithm.slice(-3), 10);\n const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;\n\n if (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) {\n throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of \"alg\" ${algorithm}.`);\n }\n\n if (saltLength !== undefined && saltLength > length >> 3) {\n throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of \"alg\" ${algorithm}.`)\n }\n }\n break;\n }\n }\n}\n", "var semver = require('semver');\n\nmodule.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0');\n", "const JsonWebTokenError = require('./lib/JsonWebTokenError');\nconst NotBeforeError = require('./lib/NotBeforeError');\nconst TokenExpiredError = require('./lib/TokenExpiredError');\nconst decode = require('./decode');\nconst timespan = require('./lib/timespan');\nconst validateAsymmetricKey = require('./lib/validateAsymmetricKey');\nconst PS_SUPPORTED = require('./lib/psSupported');\nconst jws = require('jws');\nconst {KeyObject, createSecretKey, createPublicKey} = require(\"crypto\");\n\nconst PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512'];\nconst EC_KEY_ALGS = ['ES256', 'ES384', 'ES512'];\nconst RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512'];\nconst HS_ALGS = ['HS256', 'HS384', 'HS512'];\n\nif (PS_SUPPORTED) {\n PUB_KEY_ALGS.splice(PUB_KEY_ALGS.length, 0, 'PS256', 'PS384', 'PS512');\n RSA_KEY_ALGS.splice(RSA_KEY_ALGS.length, 0, 'PS256', 'PS384', 'PS512');\n}\n\nmodule.exports = function (jwtString, secretOrPublicKey, options, callback) {\n if ((typeof options === 'function') && !callback) {\n callback = options;\n options = {};\n }\n\n if (!options) {\n options = {};\n }\n\n //clone this object since we are going to mutate it.\n options = Object.assign({}, options);\n\n let done;\n\n if (callback) {\n done = callback;\n } else {\n done = function(err, data) {\n if (err) throw err;\n return data;\n };\n }\n\n if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') {\n return done(new JsonWebTokenError('clockTimestamp must be a number'));\n }\n\n if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) {\n return done(new JsonWebTokenError('nonce must be a non-empty string'));\n }\n\n if (options.allowInvalidAsymmetricKeyTypes !== undefined && typeof options.allowInvalidAsymmetricKeyTypes !== 'boolean') {\n return done(new JsonWebTokenError('allowInvalidAsymmetricKeyTypes must be a boolean'));\n }\n\n const clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000);\n\n if (!jwtString){\n return done(new JsonWebTokenError('jwt must be provided'));\n }\n\n if (typeof jwtString !== 'string') {\n return done(new JsonWebTokenError('jwt must be a string'));\n }\n\n const parts = jwtString.split('.');\n\n if (parts.length !== 3){\n return done(new JsonWebTokenError('jwt malformed'));\n }\n\n let decodedToken;\n\n try {\n decodedToken = decode(jwtString, { complete: true });\n } catch(err) {\n return done(err);\n }\n\n if (!decodedToken) {\n return done(new JsonWebTokenError('invalid token'));\n }\n\n const header = decodedToken.header;\n let getSecret;\n\n if(typeof secretOrPublicKey === 'function') {\n if(!callback) {\n return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback'));\n }\n\n getSecret = secretOrPublicKey;\n }\n else {\n getSecret = function(header, secretCallback) {\n return secretCallback(null, secretOrPublicKey);\n };\n }\n\n return getSecret(header, function(err, secretOrPublicKey) {\n if(err) {\n return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message));\n }\n\n const hasSignature = parts[2].trim() !== '';\n\n if (!hasSignature && secretOrPublicKey){\n return done(new JsonWebTokenError('jwt signature is required'));\n }\n\n if (hasSignature && !secretOrPublicKey) {\n return done(new JsonWebTokenError('secret or public key must be provided'));\n }\n\n if (!hasSignature && !options.algorithms) {\n return done(new JsonWebTokenError('please specify \"none\" in \"algorithms\" to verify unsigned tokens'));\n }\n\n if (secretOrPublicKey != null && !(secretOrPublicKey instanceof KeyObject)) {\n try {\n secretOrPublicKey = createPublicKey(secretOrPublicKey);\n } catch (_) {\n try {\n secretOrPublicKey = createSecretKey(typeof secretOrPublicKey === 'string' ? Buffer.from(secretOrPublicKey) : secretOrPublicKey);\n } catch (_) {\n return done(new JsonWebTokenError('secretOrPublicKey is not valid key material'))\n }\n }\n }\n\n if (!options.algorithms) {\n if (secretOrPublicKey.type === 'secret') {\n options.algorithms = HS_ALGS;\n } else if (['rsa', 'rsa-pss'].includes(secretOrPublicKey.asymmetricKeyType)) {\n options.algorithms = RSA_KEY_ALGS\n } else if (secretOrPublicKey.asymmetricKeyType === 'ec') {\n options.algorithms = EC_KEY_ALGS\n } else {\n options.algorithms = PUB_KEY_ALGS\n }\n }\n\n if (options.algorithms.indexOf(decodedToken.header.alg) === -1) {\n return done(new JsonWebTokenError('invalid algorithm'));\n }\n\n if (header.alg.startsWith('HS') && secretOrPublicKey.type !== 'secret') {\n return done(new JsonWebTokenError((`secretOrPublicKey must be a symmetric key when using ${header.alg}`)))\n } else if (/^(?:RS|PS|ES)/.test(header.alg) && secretOrPublicKey.type !== 'public') {\n return done(new JsonWebTokenError((`secretOrPublicKey must be an asymmetric key when using ${header.alg}`)))\n }\n\n if (!options.allowInvalidAsymmetricKeyTypes) {\n try {\n validateAsymmetricKey(header.alg, secretOrPublicKey);\n } catch (e) {\n return done(e);\n }\n }\n\n let valid;\n\n try {\n valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey);\n } catch (e) {\n return done(e);\n }\n\n if (!valid) {\n return done(new JsonWebTokenError('invalid signature'));\n }\n\n const payload = decodedToken.payload;\n\n if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) {\n if (typeof payload.nbf !== 'number') {\n return done(new JsonWebTokenError('invalid nbf value'));\n }\n if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) {\n return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000)));\n }\n }\n\n if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) {\n if (typeof payload.exp !== 'number') {\n return done(new JsonWebTokenError('invalid exp value'));\n }\n if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) {\n return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000)));\n }\n }\n\n if (options.audience) {\n const audiences = Array.isArray(options.audience) ? options.audience : [options.audience];\n const target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];\n\n const match = target.some(function (targetAudience) {\n return audiences.some(function (audience) {\n return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience;\n });\n });\n\n if (!match) {\n return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or ')));\n }\n }\n\n if (options.issuer) {\n const invalid_issuer =\n (typeof options.issuer === 'string' && payload.iss !== options.issuer) ||\n (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1);\n\n if (invalid_issuer) {\n return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer));\n }\n }\n\n if (options.subject) {\n if (payload.sub !== options.subject) {\n return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject));\n }\n }\n\n if (options.jwtid) {\n if (payload.jti !== options.jwtid) {\n return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid));\n }\n }\n\n if (options.nonce) {\n if (payload.nonce !== options.nonce) {\n return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce));\n }\n }\n\n if (options.maxAge) {\n if (typeof payload.iat !== 'number') {\n return done(new JsonWebTokenError('iat required when maxAge is specified'));\n }\n\n const maxAgeTimestamp = timespan(options.maxAge, payload.iat);\n if (typeof maxAgeTimestamp === 'undefined') {\n return done(new JsonWebTokenError('\"maxAge\" should be a number of seconds or string representing a timespan eg: \"1d\", \"20h\", 60'));\n }\n if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) {\n return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000)));\n }\n }\n\n if (options.complete === true) {\n const signature = decodedToken.signature;\n\n return done(null, {\n header: header,\n payload: payload,\n signature: signature\n });\n }\n\n return done(null, payload);\n });\n};\n", "/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array ? array.length : 0,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\n/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n if (value !== value) {\n return baseFindIndex(array, baseIsNaN, fromIndex);\n }\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\n/**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\nfunction baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object),\n nativeMax = Math.max;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n // Safari 9 makes `arguments.length` enumerable in strict mode.\n var result = (isArray(value) || isArguments(value))\n ? baseTimes(value.length, String)\n : [];\n\n var length = result.length,\n skipIndexes = !!length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (key == 'length' || isIndex(key, length)))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * Checks if `value` is in `collection`. If `collection` is a string, it's\n * checked for a substring of `value`, otherwise\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * is used for equality comparisons. If `fromIndex` is negative, it's used as\n * the offset from the end of `collection`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'a': 1, 'b': 2 }, 1);\n * // => true\n *\n * _.includes('abcd', 'bc');\n * // => true\n */\nfunction includes(collection, value, fromIndex, guard) {\n collection = isArrayLike(collection) ? collection : values(collection);\n fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n var length = collection.length;\n if (fromIndex < 0) {\n fromIndex = nativeMax(length + fromIndex, 0);\n }\n return isString(collection)\n ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n}\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nfunction isArguments(value) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&\n (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);\n}\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 8-9 which returns 'object' for typed array and other constructors.\n var tag = isObject(value) ? objectToString.call(value) : '';\n return tag == funcTag || tag == genTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\nfunction isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\n/**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\nfunction values(object) {\n return object ? baseValues(object, keys(object)) : [];\n}\n\nmodule.exports = includes;\n", "/**\n * lodash 3.0.3 (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n * Available under MIT license <https://lodash.com/license>\n */\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/**\n * Checks if `value` is classified as a boolean primitive or object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\nfunction isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && objectToString.call(value) == boolTag);\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\nmodule.exports = isBoolean;\n", "/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/**\n * Checks if `value` is an integer.\n *\n * **Note:** This method is based on\n * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n * @example\n *\n * _.isInteger(3);\n * // => true\n *\n * _.isInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isInteger(Infinity);\n * // => false\n *\n * _.isInteger('3');\n * // => false\n */\nfunction isInteger(value) {\n return typeof value == 'number' && value == toInteger(value);\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = isInteger;\n", "/**\n * lodash 3.0.3 (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n * Available under MIT license <https://lodash.com/license>\n */\n\n/** `Object#toString` result references. */\nvar numberTag = '[object Number]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified\n * as numbers, use the `_.isFinite` method.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isNumber(3);\n * // => true\n *\n * _.isNumber(Number.MIN_VALUE);\n * // => true\n *\n * _.isNumber(Infinity);\n * // => true\n *\n * _.isNumber('3');\n * // => false\n */\nfunction isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && objectToString.call(value) == numberTag);\n}\n\nmodule.exports = isNumber;\n", "/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/**\n * Checks if `value` is a host object in IE < 9.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a host object, else `false`.\n */\nfunction isHostObject(value) {\n // Many host objects are `Object` objects that can coerce to strings\n // despite having improperly defined `toString` methods.\n var result = false;\n if (value != null && typeof value.toString != 'function') {\n try {\n result = !!(value + '');\n } catch (e) {}\n }\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) ||\n objectToString.call(value) != objectTag || isHostObject(value)) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (typeof Ctor == 'function' &&\n Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);\n}\n\nmodule.exports = isPlainObject;\n", "/**\n * lodash 4.0.1 (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n * Available under MIT license <https://lodash.com/license>\n */\n\n/** `Object#toString` result references. */\nvar stringTag = '[object String]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @type Function\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\nfunction isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);\n}\n\nmodule.exports = isString;\n", "/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/**\n * Creates a function that invokes `func`, with the `this` binding and arguments\n * of the created function, while it's called less than `n` times. Subsequent\n * calls to the created function return the result of the last `func` invocation.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {number} n The number of calls at which `func` is no longer invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * jQuery(element).on('click', _.before(5, addContactToList));\n * // => Allows adding up to 4 contacts to the list.\n */\nfunction before(n, func) {\n var result;\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n > 0) {\n result = func.apply(this, arguments);\n }\n if (n <= 1) {\n func = undefined;\n }\n return result;\n };\n}\n\n/**\n * Creates a function that is restricted to invoking `func` once. Repeat calls\n * to the function return the value of the first invocation. The `func` is\n * invoked with the `this` binding and arguments of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var initialize = _.once(createApplication);\n * initialize();\n * initialize();\n * // => `createApplication` is invoked once\n */\nfunction once(func) {\n return before(2, func);\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = once;\n", "const timespan = require('./lib/timespan');\nconst PS_SUPPORTED = require('./lib/psSupported');\nconst validateAsymmetricKey = require('./lib/validateAsymmetricKey');\nconst jws = require('jws');\nconst includes = require('lodash.includes');\nconst isBoolean = require('lodash.isboolean');\nconst isInteger = require('lodash.isinteger');\nconst isNumber = require('lodash.isnumber');\nconst isPlainObject = require('lodash.isplainobject');\nconst isString = require('lodash.isstring');\nconst once = require('lodash.once');\nconst { KeyObject, createSecretKey, createPrivateKey } = require('crypto')\n\nconst SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'];\nif (PS_SUPPORTED) {\n SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512');\n}\n\nconst sign_options_schema = {\n expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '\"expiresIn\" should be a number of seconds or string representing a timespan' },\n notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '\"notBefore\" should be a number of seconds or string representing a timespan' },\n audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '\"audience\" must be a string or array' },\n algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '\"algorithm\" must be a valid string enum value' },\n header: { isValid: isPlainObject, message: '\"header\" must be an object' },\n encoding: { isValid: isString, message: '\"encoding\" must be a string' },\n issuer: { isValid: isString, message: '\"issuer\" must be a string' },\n subject: { isValid: isString, message: '\"subject\" must be a string' },\n jwtid: { isValid: isString, message: '\"jwtid\" must be a string' },\n noTimestamp: { isValid: isBoolean, message: '\"noTimestamp\" must be a boolean' },\n keyid: { isValid: isString, message: '\"keyid\" must be a string' },\n mutatePayload: { isValid: isBoolean, message: '\"mutatePayload\" must be a boolean' },\n allowInsecureKeySizes: { isValid: isBoolean, message: '\"allowInsecureKeySizes\" must be a boolean'},\n allowInvalidAsymmetricKeyTypes: { isValid: isBoolean, message: '\"allowInvalidAsymmetricKeyTypes\" must be a boolean'}\n};\n\nconst registered_claims_schema = {\n iat: { isValid: isNumber, message: '\"iat\" should be a number of seconds' },\n exp: { isValid: isNumber, message: '\"exp\" should be a number of seconds' },\n nbf: { isValid: isNumber, message: '\"nbf\" should be a number of seconds' }\n};\n\nfunction validate(schema, allowUnknown, object, parameterName) {\n if (!isPlainObject(object)) {\n throw new Error('Expected \"' + parameterName + '\" to be a plain object.');\n }\n Object.keys(object)\n .forEach(function(key) {\n const validator = schema[key];\n if (!validator) {\n if (!allowUnknown) {\n throw new Error('\"' + key + '\" is not allowed in \"' + parameterName + '\"');\n }\n return;\n }\n if (!validator.isValid(object[key])) {\n throw new Error(validator.message);\n }\n });\n}\n\nfunction validateOptions(options) {\n return validate(sign_options_schema, false, options, 'options');\n}\n\nfunction validatePayload(payload) {\n return validate(registered_claims_schema, true, payload, 'payload');\n}\n\nconst options_to_payload = {\n 'audience': 'aud',\n 'issuer': 'iss',\n 'subject': 'sub',\n 'jwtid': 'jti'\n};\n\nconst options_for_objects = [\n 'expiresIn',\n 'notBefore',\n 'noTimestamp',\n 'audience',\n 'issuer',\n 'subject',\n 'jwtid',\n];\n\nmodule.exports = function (payload, secretOrPrivateKey, options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n } else {\n options = options || {};\n }\n\n const isObjectPayload = typeof payload === 'object' &&\n !Buffer.isBuffer(payload);\n\n const header = Object.assign({\n alg: options.algorithm || 'HS256',\n typ: isObjectPayload ? 'JWT' : undefined,\n kid: options.keyid\n }, options.header);\n\n function failure(err) {\n if (callback) {\n return callback(err);\n }\n throw err;\n }\n\n if (!secretOrPrivateKey && options.algorithm !== 'none') {\n return failure(new Error('secretOrPrivateKey must have a value'));\n }\n\n if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) {\n try {\n secretOrPrivateKey = createPrivateKey(secretOrPrivateKey)\n } catch (_) {\n try {\n secretOrPrivateKey = createSecretKey(typeof secretOrPrivateKey === 'string' ? Buffer.from(secretOrPrivateKey) : secretOrPrivateKey)\n } catch (_) {\n return failure(new Error('secretOrPrivateKey is not valid key material'));\n }\n }\n }\n\n if (header.alg.startsWith('HS') && secretOrPrivateKey.type !== 'secret') {\n return failure(new Error((`secretOrPrivateKey must be a symmetric key when using ${header.alg}`)))\n } else if (/^(?:RS|PS|ES)/.test(header.alg)) {\n if (secretOrPrivateKey.type !== 'private') {\n return failure(new Error((`secretOrPrivateKey must be an asymmetric key when using ${header.alg}`)))\n }\n if (!options.allowInsecureKeySizes &&\n !header.alg.startsWith('ES') &&\n secretOrPrivateKey.asymmetricKeyDetails !== undefined && //KeyObject.asymmetricKeyDetails is supported in Node 15+\n secretOrPrivateKey.asymmetricKeyDetails.modulusLength < 2048) {\n return failure(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`));\n }\n }\n\n if (typeof payload === 'undefined') {\n return failure(new Error('payload is required'));\n } else if (isObjectPayload) {\n try {\n validatePayload(payload);\n }\n catch (error) {\n return failure(error);\n }\n if (!options.mutatePayload) {\n payload = Object.assign({},payload);\n }\n } else {\n const invalid_options = options_for_objects.filter(function (opt) {\n return typeof options[opt] !== 'undefined';\n });\n\n if (invalid_options.length > 0) {\n return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload'));\n }\n }\n\n if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') {\n return failure(new Error('Bad \"options.expiresIn\" option the payload already has an \"exp\" property.'));\n }\n\n if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') {\n return failure(new Error('Bad \"options.notBefore\" option the payload already has an \"nbf\" property.'));\n }\n\n try {\n validateOptions(options);\n }\n catch (error) {\n return failure(error);\n }\n\n if (!options.allowInvalidAsymmetricKeyTypes) {\n try {\n validateAsymmetricKey(header.alg, secretOrPrivateKey);\n } catch (error) {\n return failure(error);\n }\n }\n\n const timestamp = payload.iat || Math.floor(Date.now() / 1000);\n\n if (options.noTimestamp) {\n delete payload.iat;\n } else if (isObjectPayload) {\n payload.iat = timestamp;\n }\n\n if (typeof options.notBefore !== 'undefined') {\n try {\n payload.nbf = timespan(options.notBefore, timestamp);\n }\n catch (err) {\n return failure(err);\n }\n if (typeof payload.nbf === 'undefined') {\n return failure(new Error('\"notBefore\" should be a number of seconds or string representing a timespan eg: \"1d\", \"20h\", 60'));\n }\n }\n\n if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') {\n try {\n payload.exp = timespan(options.expiresIn, timestamp);\n }\n catch (err) {\n return failure(err);\n }\n if (typeof payload.exp === 'undefined') {\n return failure(new Error('\"expiresIn\" should be a number of seconds or string representing a timespan eg: \"1d\", \"20h\", 60'));\n }\n }\n\n Object.keys(options_to_payload).forEach(function (key) {\n const claim = options_to_payload[key];\n if (typeof options[key] !== 'undefined') {\n if (typeof payload[claim] !== 'undefined') {\n return failure(new Error('Bad \"options.' + key + '\" option. The payload already has an \"' + claim + '\" property.'));\n }\n payload[claim] = options[key];\n }\n });\n\n const encoding = options.encoding || 'utf8';\n\n if (typeof callback === 'function') {\n callback = callback && once(callback);\n\n jws.createSign({\n header: header,\n privateKey: secretOrPrivateKey,\n payload: payload,\n encoding: encoding\n }).once('error', callback)\n .once('done', function (signature) {\n // TODO: Remove in favor of the modulus length check before signing once node 15+ is the minimum supported version\n if(!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) {\n return callback(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`))\n }\n callback(null, signature);\n });\n } else {\n let signature = jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});\n // TODO: Remove in favor of the modulus length check before signing once node 15+ is the minimum supported version\n if(!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) {\n throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`)\n }\n return signature\n }\n};\n", "module.exports = {\n decode: require('./decode'),\n verify: require('./verify'),\n sign: require('./sign'),\n JsonWebTokenError: require('./lib/JsonWebTokenError'),\n NotBeforeError: require('./lib/NotBeforeError'),\n TokenExpiredError: require('./lib/TokenExpiredError'),\n};\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport jwt from \"jsonwebtoken\";\nimport {\n TimeUtils,\n Constants,\n createClientAuthError,\n ClientAuthErrorCodes,\n} from \"@azure/msal-common\";\nimport { CryptoProvider } from \"../crypto/CryptoProvider.js\";\nimport { EncodingUtils } from \"../utils/EncodingUtils.js\";\nimport { JwtConstants } from \"../utils/Constants.js\";\n\n/**\n * Client assertion of type jwt-bearer used in confidential client flows\n * @public\n */\nexport class ClientAssertion {\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(\n thumbprint: string,\n privateKey: string,\n publicCertificate?: string\n ): ClientAssertion {\n const clientAssertion = new ClientAssertion();\n clientAssertion.privateKey = privateKey;\n clientAssertion.thumbprint = thumbprint;\n if (publicCertificate) {\n clientAssertion.publicCertificate =\n 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(\n cryptoProvider: CryptoProvider,\n issuer: string,\n jwtAudience: string\n ): string {\n // if assertion was created from certificate, check if jwt is expired and create new one.\n if (this.privateKey && this.thumbprint) {\n if (\n this.jwt &&\n !this.isExpired() &&\n issuer === this.issuer &&\n jwtAudience === this.jwtAudience\n ) {\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 createClientAuthError(ClientAuthErrorCodes.invalidAssertion);\n }\n\n /**\n * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3\n */\n private createJwt(\n cryptoProvider: CryptoProvider,\n issuer: string,\n jwtAudience: string\n ): string {\n this.issuer = issuer;\n this.jwtAudience = jwtAudience;\n const issuedAt = TimeUtils.nowSeconds();\n this.expirationTime = issuedAt + 600;\n\n const header: jwt.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<jwt.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 = 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 =\n /-----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 {\n AccessTokenEntity,\n AuthenticationResult,\n AuthenticationScheme,\n Authority,\n BaseClient,\n CacheOutcome,\n ClientAuthErrorCodes,\n ClientConfiguration,\n CommonClientCredentialRequest,\n Constants,\n CredentialFilter,\n CredentialType,\n GrantType,\n IAppTokenProvider,\n RequestParameterBuilder,\n RequestThumbprint,\n ResponseHandler,\n ScopeSet,\n ServerAuthorizationTokenResponse,\n StringUtils,\n TimeUtils,\n TokenCacheContext,\n UrlString,\n createClientAuthError,\n} from \"@azure/msal-common\";\n\n/**\n * OAuth2.0 client credential grant\n */\nexport class ClientCredentialClient extends BaseClient {\n private scopeSet: ScopeSet;\n private readonly appTokenProvider?: IAppTokenProvider;\n\n constructor(\n configuration: ClientConfiguration,\n appTokenProvider?: IAppTokenProvider\n ) {\n super(configuration);\n this.appTokenProvider = appTokenProvider;\n }\n\n /**\n * Public API to acquire a token with ClientCredential Flow for Confidential clients\n * @param request\n */\n public async acquireToken(\n request: CommonClientCredentialRequest\n ): Promise<AuthenticationResult | null> {\n this.scopeSet = new ScopeSet(request.scopes || []);\n\n if (request.skipCache) {\n return this.executeTokenRequest(request, this.authority);\n }\n\n const [cachedAuthenticationResult, lastCacheOutcome] =\n await this.getCachedAuthenticationResult(request);\n\n if (cachedAuthenticationResult) {\n // if the token is not expired but must be refreshed; get a new one in the background\n if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {\n this.logger.info(\n \"ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.\"\n );\n\n // refresh the access token in the background\n const refreshAccessToken = true;\n await this.executeTokenRequest(\n request,\n this.authority,\n refreshAccessToken\n );\n }\n\n // return the cached token\n return cachedAuthenticationResult;\n } else {\n return this.executeTokenRequest(request, this.authority);\n }\n }\n\n /**\n * looks up cache if the tokens are cached already\n */\n private async getCachedAuthenticationResult(\n request: CommonClientCredentialRequest\n ): Promise<[AuthenticationResult | null, CacheOutcome]> {\n let lastCacheOutcome: CacheOutcome = CacheOutcome.NOT_APPLICABLE;\n\n // read the user-supplied cache into memory, if applicable\n let cacheContext;\n if (this.config.serializableCache && this.config.persistencePlugin) {\n cacheContext = new TokenCacheContext(\n this.config.serializableCache,\n false\n );\n await this.config.persistencePlugin.beforeCacheAccess(cacheContext);\n }\n\n const cachedAccessToken = this.readAccessTokenFromCache();\n\n if (\n this.config.serializableCache &&\n this.config.persistencePlugin &&\n cacheContext\n ) {\n await this.config.persistencePlugin.afterCacheAccess(cacheContext);\n }\n\n // must refresh due to non-existent access_token\n if (!cachedAccessToken) {\n this.serverTelemetryManager?.setCacheOutcome(\n CacheOutcome.NO_CACHED_ACCESS_TOKEN\n );\n return [null, CacheOutcome.NO_CACHED_ACCESS_TOKEN];\n }\n\n // must refresh due to the expires_in value\n if (\n TimeUtils.isTokenExpired(\n cachedAccessToken.expiresOn,\n this.config.systemOptions.tokenRenewalOffsetSeconds\n )\n ) {\n this.serverTelemetryManager?.setCacheOutcome(\n CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED\n );\n return [null, CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED];\n }\n\n // must refresh (in the background) due to the refresh_in value\n if (\n cachedAccessToken.refreshOn &&\n TimeUtils.isTokenExpired(cachedAccessToken.refreshOn.toString(), 0)\n ) {\n lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;\n this.serverTelemetryManager?.setCacheOutcome(\n CacheOutcome.PROACTIVELY_REFRESHED\n );\n }\n\n return [\n await ResponseHandler.generateAuthenticationResult(\n this.cryptoUtils,\n this.authority,\n {\n account: null,\n idToken: null,\n accessToken: cachedAccessToken,\n refreshToken: null,\n appMetadata: null,\n },\n true,\n request\n ),\n lastCacheOutcome,\n ];\n }\n\n /**\n * Reads access token from the cache\n */\n private readAccessTokenFromCache(): AccessTokenEntity | null {\n const accessTokenFilter: CredentialFilter = {\n homeAccountId: Constants.EMPTY_STRING,\n environment:\n this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,\n credentialType: CredentialType.ACCESS_TOKEN,\n clientId: this.config.authOptions.clientId,\n realm: this.authority.tenant,\n target: ScopeSet.createSearchScopes(this.scopeSet.asArray()),\n };\n\n const accessTokens =\n this.cacheManager.getAccessTokensByFilter(accessTokenFilter);\n if (accessTokens.length < 1) {\n return null;\n } else if (accessTokens.length > 1) {\n throw createClientAuthError(\n ClientAuthErrorCodes.multipleMatchingTokens\n );\n }\n return accessTokens[0] as AccessTokenEntity;\n }\n\n /**\n * Makes a network call to request the token from the service\n * @param request\n * @param authority\n */\n private async executeTokenRequest(\n request: CommonClientCredentialRequest,\n authority: Authority,\n refreshAccessToken?: boolean\n ): Promise<AuthenticationResult | null> {\n let serverTokenResponse: ServerAuthorizationTokenResponse;\n let reqTimestamp: number;\n\n if (this.appTokenProvider) {\n this.logger.info(\"Using appTokenProvider extensibility.\");\n\n const appTokenPropviderParameters = {\n correlationId: request.correlationId,\n tenantId: this.config.authOptions.authority.tenant,\n scopes: request.scopes,\n claims: request.claims,\n };\n\n reqTimestamp = TimeUtils.nowSeconds();\n const appTokenProviderResult = await this.appTokenProvider(\n appTokenPropviderParameters\n );\n\n serverTokenResponse = {\n access_token: appTokenProviderResult.accessToken,\n expires_in: appTokenProviderResult.expiresInSeconds,\n refresh_in: appTokenProviderResult.refreshInSeconds,\n token_type: AuthenticationScheme.BEARER,\n };\n } else {\n const queryParametersString =\n this.createTokenQueryParameters(request);\n const endpoint = UrlString.appendQueryString(\n authority.tokenEndpoint,\n queryParametersString\n );\n\n const requestBody = this.createTokenRequestBody(request);\n const headers: Record<string, string> =\n this.createTokenRequestHeaders();\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: request.authority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid,\n };\n\n this.logger.info(\n \"Sending token request to endpoint: \" + authority.tokenEndpoint\n );\n\n reqTimestamp = TimeUtils.nowSeconds();\n const response = await this.executePostToTokenEndpoint(\n endpoint,\n requestBody,\n headers,\n thumbprint,\n request.correlationId\n );\n\n serverTokenResponse = response.body;\n serverTokenResponse.status = response.status;\n }\n\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin\n );\n\n responseHandler.validateTokenResponse(\n serverTokenResponse,\n refreshAccessToken\n );\n\n const tokenResponse = await responseHandler.handleServerTokenResponse(\n serverTokenResponse,\n this.authority,\n reqTimestamp,\n request\n );\n\n return tokenResponse;\n }\n\n /**\n * generate the request to the server in the acceptable format\n * @param request\n */\n private createTokenRequestBody(\n request: CommonClientCredentialRequest\n ): string {\n const parameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addClientId(this.config.authOptions.clientId);\n\n parameterBuilder.addScopes(request.scopes, false);\n\n parameterBuilder.addGrantType(GrantType.CLIENT_CREDENTIALS_GRANT);\n\n parameterBuilder.addLibraryInfo(this.config.libraryInfo);\n parameterBuilder.addApplicationTelemetry(\n this.config.telemetry.application\n );\n\n parameterBuilder.addThrottling();\n\n if (this.serverTelemetryManager) {\n parameterBuilder.addServerTelemetry(this.serverTelemetryManager);\n }\n\n const correlationId =\n request.correlationId ||\n this.config.cryptoInterface.createNewGuid();\n parameterBuilder.addCorrelationId(correlationId);\n\n if (this.config.clientCredentials.clientSecret) {\n parameterBuilder.addClientSecret(\n this.config.clientCredentials.clientSecret\n );\n }\n\n // Use clientAssertion from request, fallback to client assertion in base configuration\n const clientAssertion =\n request.clientAssertion ||\n this.config.clientCredentials.clientAssertion;\n\n if (clientAssertion) {\n parameterBuilder.addClientAssertion(clientAssertion.assertion);\n parameterBuilder.addClientAssertionType(\n clientAssertion.assertionType\n );\n }\n\n if (\n !StringUtils.isEmptyObj(request.claims) ||\n (this.config.authOptions.clientCapabilities &&\n this.config.authOptions.clientCapabilities.length > 0)\n ) {\n parameterBuilder.addClaims(\n request.claims,\n this.config.authOptions.clientCapabilities\n );\n }\n\n return parameterBuilder.createQueryString();\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AADServerParamKeys,\n AccessTokenEntity,\n AccountEntity,\n AccountInfo,\n AuthenticationResult,\n AuthenticationScheme,\n Authority,\n AuthToken,\n BaseClient,\n CacheOutcome,\n ClientAuthErrorCodes,\n ClientConfiguration,\n CommonOnBehalfOfRequest,\n Constants,\n createClientAuthError,\n CredentialFilter,\n CredentialType,\n GrantType,\n IdTokenEntity,\n RequestParameterBuilder,\n RequestThumbprint,\n ResponseHandler,\n ScopeSet,\n TimeUtils,\n TokenClaims,\n UrlString,\n} from \"@azure/msal-common\";\nimport { EncodingUtils } from \"../utils/EncodingUtils\";\n\n/**\n * On-Behalf-Of client\n */\nexport class OnBehalfOfClient extends BaseClient {\n private scopeSet: ScopeSet;\n private userAssertionHash: string;\n\n constructor(configuration: ClientConfiguration) {\n super(configuration);\n }\n\n /**\n * Public API to acquire tokens with on behalf of flow\n * @param request\n */\n public async acquireToken(\n request: CommonOnBehalfOfRequest\n ): Promise<AuthenticationResult | null> {\n this.scopeSet = new ScopeSet(request.scopes || []);\n\n // generate the user_assertion_hash for OBOAssertion\n this.userAssertionHash = await this.cryptoUtils.hashString(\n request.oboAssertion\n );\n\n if (request.skipCache) {\n return this.executeTokenRequest(\n request,\n this.authority,\n this.userAssertionHash\n );\n }\n\n try {\n return await this.getCachedAuthenticationResult(request);\n } catch (e) {\n // Any failure falls back to interactive request, once we implement distributed cache, we plan to handle `createRefreshRequiredError` to refresh using the RT\n return await this.executeTokenRequest(\n request,\n this.authority,\n this.userAssertionHash\n );\n }\n }\n\n /**\n * look up cache for tokens\n * Find idtoken in the cache\n * Find accessToken based on user assertion and account info in the cache\n * Please note we are not yet supported OBO tokens refreshed with long lived RT. User will have to send a new assertion if the current access token expires\n * This is to prevent security issues when the assertion changes over time, however, longlived RT helps retaining the session\n * @param request\n */\n private async getCachedAuthenticationResult(\n request: CommonOnBehalfOfRequest\n ): Promise<AuthenticationResult | null> {\n // look in the cache for the access_token which matches the incoming_assertion\n const cachedAccessToken = this.readAccessTokenFromCacheForOBO(\n this.config.authOptions.clientId,\n request\n );\n if (!cachedAccessToken) {\n // Must refresh due to non-existent access_token.\n this.serverTelemetryManager?.setCacheOutcome(\n CacheOutcome.NO_CACHED_ACCESS_TOKEN\n );\n this.logger.info(\n \"SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.\"\n );\n throw createClientAuthError(\n ClientAuthErrorCodes.tokenRefreshRequired\n );\n } else if (\n TimeUtils.isTokenExpired(\n cachedAccessToken.expiresOn,\n this.config.systemOptions.tokenRenewalOffsetSeconds\n )\n ) {\n // Access token expired, will need to renewed\n this.serverTelemetryManager?.setCacheOutcome(\n CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED\n );\n this.logger.info(\n `OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`\n );\n throw createClientAuthError(\n ClientAuthErrorCodes.tokenRefreshRequired\n );\n }\n\n // fetch the idToken from cache\n const cachedIdToken = this.readIdTokenFromCacheForOBO(\n cachedAccessToken.homeAccountId\n );\n let idTokenClaims: TokenClaims | undefined;\n let cachedAccount: AccountEntity | null = null;\n if (cachedIdToken) {\n idTokenClaims = AuthToken.extractTokenClaims(\n cachedIdToken.secret,\n EncodingUtils.base64Decode\n );\n const localAccountId = idTokenClaims.oid || idTokenClaims.sub;\n const accountInfo: AccountInfo = {\n homeAccountId: cachedIdToken.homeAccountId,\n environment: cachedIdToken.environment,\n tenantId: cachedIdToken.realm,\n username: Constants.EMPTY_STRING,\n localAccountId: localAccountId || Constants.EMPTY_STRING,\n };\n\n cachedAccount = this.cacheManager.readAccountFromCache(accountInfo);\n }\n\n // increment telemetry cache hit counter\n if (this.config.serverTelemetryManager) {\n this.config.serverTelemetryManager.incrementCacheHits();\n }\n\n return ResponseHandler.generateAuthenticationResult(\n this.cryptoUtils,\n this.authority,\n {\n account: cachedAccount,\n accessToken: cachedAccessToken,\n idToken: cachedIdToken,\n refreshToken: null,\n appMetadata: null,\n },\n true,\n request,\n idTokenClaims\n );\n }\n\n /**\n * read idtoken from cache, this is a specific implementation for OBO as the requirements differ from a generic lookup in the cacheManager\n * Certain use cases of OBO flow do not expect an idToken in the cache/or from the service\n * @param atHomeAccountId {string}\n */\n private readIdTokenFromCacheForOBO(\n atHomeAccountId: string\n ): IdTokenEntity | null {\n const idTokenFilter: CredentialFilter = {\n homeAccountId: atHomeAccountId,\n environment:\n this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,\n credentialType: CredentialType.ID_TOKEN,\n clientId: this.config.authOptions.clientId,\n realm: this.authority.tenant,\n };\n\n const idTokenMap: Map<string, IdTokenEntity> =\n this.cacheManager.getIdTokensByFilter(idTokenFilter);\n\n // When acquiring a token on behalf of an application, there might not be an id token in the cache\n if (Object.values(idTokenMap).length < 1) {\n return null;\n }\n return Object.values(idTokenMap)[0] as IdTokenEntity;\n }\n\n /**\n * Fetches the cached access token based on incoming assertion\n * @param clientId\n * @param request\n * @param userAssertionHash\n */\n private readAccessTokenFromCacheForOBO(\n clientId: string,\n request: CommonOnBehalfOfRequest\n ) {\n const authScheme =\n request.authenticationScheme || AuthenticationScheme.BEARER;\n /*\n * Distinguish between Bearer and PoP/SSH token cache types\n * Cast to lowercase to handle \"bearer\" from ADFS\n */\n const credentialType =\n authScheme &&\n authScheme.toLowerCase() !==\n AuthenticationScheme.BEARER.toLowerCase()\n ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME\n : CredentialType.ACCESS_TOKEN;\n\n const accessTokenFilter: CredentialFilter = {\n credentialType: credentialType,\n clientId,\n target: ScopeSet.createSearchScopes(this.scopeSet.asArray()),\n tokenType: authScheme,\n keyId: request.sshKid,\n requestedClaimsHash: request.requestedClaimsHash,\n userAssertionHash: this.userAssertionHash,\n };\n\n const accessTokens =\n this.cacheManager.getAccessTokensByFilter(accessTokenFilter);\n\n const numAccessTokens = accessTokens.length;\n if (numAccessTokens < 1) {\n return null;\n } else if (numAccessTokens > 1) {\n throw createClientAuthError(\n ClientAuthErrorCodes.multipleMatchingTokens\n );\n }\n\n return accessTokens[0] as AccessTokenEntity;\n }\n\n /**\n * Make a network call to the server requesting credentials\n * @param request\n * @param authority\n */\n private async executeTokenRequest(\n request: CommonOnBehalfOfRequest,\n authority: Authority,\n userAssertionHash: string\n ): Promise<AuthenticationResult | null> {\n const queryParametersString = this.createTokenQueryParameters(request);\n const endpoint = UrlString.appendQueryString(\n authority.tokenEndpoint,\n queryParametersString\n );\n const requestBody = this.createTokenRequestBody(request);\n const headers: Record<string, string> =\n this.createTokenRequestHeaders();\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: request.authority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid,\n };\n\n const reqTimestamp = TimeUtils.nowSeconds();\n const response = await this.executePostToTokenEndpoint(\n endpoint,\n requestBody,\n headers,\n thumbprint,\n request.correlationId\n );\n\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin\n );\n\n responseHandler.validateTokenResponse(response.body);\n const tokenResponse = await responseHandler.handleServerTokenResponse(\n response.body,\n this.authority,\n reqTimestamp,\n request,\n undefined,\n userAssertionHash\n );\n\n return tokenResponse;\n }\n\n /**\n * generate a server request in accepable format\n * @param request\n */\n private createTokenRequestBody(request: CommonOnBehalfOfRequest): string {\n const parameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addClientId(this.config.authOptions.clientId);\n\n parameterBuilder.addScopes(request.scopes);\n\n parameterBuilder.addGrantType(GrantType.JWT_BEARER);\n\n parameterBuilder.addClientInfo();\n\n parameterBuilder.addLibraryInfo(this.config.libraryInfo);\n parameterBuilder.addApplicationTelemetry(\n this.config.telemetry.application\n );\n parameterBuilder.addThrottling();\n\n if (this.serverTelemetryManager) {\n parameterBuilder.addServerTelemetry(this.serverTelemetryManager);\n }\n\n const correlationId =\n request.correlationId ||\n this.config.cryptoInterface.createNewGuid();\n parameterBuilder.addCorrelationId(correlationId);\n\n parameterBuilder.addRequestTokenUse(AADServerParamKeys.ON_BEHALF_OF);\n\n parameterBuilder.addOboAssertion(request.oboAssertion);\n\n if (this.config.clientCredentials.clientSecret) {\n parameterBuilder.addClientSecret(\n this.config.clientCredentials.clientSecret\n );\n }\n\n if (this.config.clientCredentials.clientAssertion) {\n const clientAssertion =\n this.config.clientCredentials.clientAssertion;\n parameterBuilder.addClientAssertion(clientAssertion.assertion);\n parameterBuilder.addClientAssertionType(\n clientAssertion.assertionType\n );\n }\n\n if (\n request.claims ||\n (this.config.authOptions.clientCapabilities &&\n this.config.authOptions.clientCapabilities.length > 0)\n ) {\n parameterBuilder.addClaims(\n request.claims,\n this.config.authOptions.clientCapabilities\n );\n }\n\n return parameterBuilder.createQueryString();\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n// AADAuthorityConstants\n\nimport { ClientApplication } from \"./ClientApplication.js\";\nimport { Configuration } from \"../config/Configuration.js\";\nimport { ClientAssertion } from \"./ClientAssertion.js\";\nimport {\n Constants as NodeConstants,\n ApiId,\n REGION_ENVIRONMENT_VARIABLE,\n} from \"../utils/Constants.js\";\nimport {\n CommonClientCredentialRequest,\n CommonOnBehalfOfRequest,\n AuthenticationResult,\n AzureRegionConfiguration,\n AuthError,\n Constants,\n IAppTokenProvider,\n OIDC_DEFAULT_SCOPES,\n UrlString,\n AADAuthorityConstants,\n createClientAuthError,\n ClientAuthErrorCodes,\n} from \"@azure/msal-common\";\nimport { IConfidentialClientApplication } from \"./IConfidentialClientApplication.js\";\nimport { OnBehalfOfRequest } from \"../request/OnBehalfOfRequest.js\";\nimport { ClientCredentialRequest } from \"../request/ClientCredentialRequest.js\";\nimport { ClientCredentialClient } from \"./ClientCredentialClient.js\";\nimport { OnBehalfOfClient } from \"./OnBehalfOfClient.js\";\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\n extends ClientApplication\n implements IConfidentialClientApplication\n{\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(\n request: ClientCredentialRequest\n ): Promise<AuthenticationResult | null> {\n this.logger.info(\n \"acquireTokenByClientCredential called\",\n request.correlationId\n );\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(\n (scope: string) => !OIDC_DEFAULT_SCOPES.includes(scope)\n ),\n };\n\n const validRequest: CommonClientCredentialRequest = {\n ...request,\n ...validBaseRequest,\n clientAssertion,\n };\n\n /*\n * valid request should not have \"common\" or \"organizations\" in lieu of the tenant_id in the authority in the auth configuration\n * example authority: \"https://login.microsoftonline.com/TenantId\",\n */\n const authority = new UrlString(validRequest.authority);\n const tenantId = authority.getUrlComponents().PathSegments[0];\n if (\n Object.values(AADAuthorityConstants).includes(\n tenantId as AADAuthorityConstants\n )\n ) {\n throw createClientAuthError(\n ClientAuthErrorCodes.missingTenantIdError\n );\n }\n\n const azureRegionConfiguration: AzureRegionConfiguration = {\n azureRegion: validRequest.azureRegion,\n environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE],\n };\n\n const serverTelemetryManager = this.initializeServerTelemetryManager(\n ApiId.acquireTokenByClientCredential,\n validRequest.correlationId,\n validRequest.skipCache\n );\n try {\n const clientCredentialConfig =\n await this.buildOauthClientConfiguration(\n validRequest.authority,\n validRequest.correlationId,\n serverTelemetryManager,\n azureRegionConfiguration,\n request.azureCloudOptions\n );\n const clientCredentialClient = new ClientCredentialClient(\n clientCredentialConfig,\n this.appTokenProvider\n );\n this.logger.verbose(\n \"Client credential client created\",\n validRequest.correlationId\n );\n return await 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(\n request: OnBehalfOfRequest\n ): Promise<AuthenticationResult | null> {\n this.logger.info(\n \"acquireTokenOnBehalfOf called\",\n request.correlationId\n );\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(\n \"On behalf of client created\",\n validRequest.correlationId\n );\n return await 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 = !!configuration.auth.clientSecret;\n const clientAssertionNotEmpty = !!configuration.auth.clientAssertion;\n const certificate = configuration.auth.clientCertificate || {\n thumbprint: Constants.EMPTY_STRING,\n privateKey: Constants.EMPTY_STRING,\n };\n const certificateNotEmpty =\n !!certificate.thumbprint || !!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 ) {\n throw createClientAuthError(\n ClientAuthErrorCodes.invalidClientCredential\n );\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(\n configuration.auth.clientAssertion\n );\n return;\n }\n\n if (!certificateNotEmpty) {\n throw createClientAuthError(\n ClientAuthErrorCodes.invalidClientCredential\n );\n } else {\n this.clientAssertion = ClientAssertion.fromCertificate(\n certificate.thumbprint,\n certificate.privateKey,\n configuration.auth.clientCertificate?.x5c\n );\n }\n }\n}\n", "/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n AccountEntity,\n ICachePlugin,\n TokenCacheContext,\n} from \"@azure/msal-common\";\nimport { TokenCache } from \"../TokenCache.js\";\nimport { IPartitionManager } from \"./IPartitionManager.js\";\nimport { ICacheClient } from \"./ICacheClient.js\";\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(\n cacheContext: TokenCacheContext\n ): 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(\n cacheContext: TokenCacheContext\n ): Promise<void> {\n if (cacheContext.cacheHasChanged) {\n const kvStore = (\n cacheContext.tokenCache as TokenCache\n ).getKVStore();\n const accountEntities = Object.values(kvStore).filter((value) =>\n AccountEntity.isAccountEntity(value as object)\n );\n\n if (accountEntities.length > 0) {\n const accountEntity = accountEntities[0] as AccountEntity;\n const partitionKey = await this.partitionManager.extractKey(\n accountEntity\n );\n\n await this.client.set(\n partitionKey,\n cacheContext.tokenCache.serialize()\n );\n }\n }\n }\n}\n", "/*! @azure/msal-node v2.6.2 2024-01-23 */\n'use strict';\nimport * as internals from './internals.mjs';\nexport { internals };\nexport { PublicClientApplication } from './client/PublicClientApplication.mjs';\nexport { ConfidentialClientApplication } from './client/ConfidentialClientApplication.mjs';\nexport { ClientApplication } from './client/ClientApplication.mjs';\nexport { ClientCredentialClient } from './client/ClientCredentialClient.mjs';\nexport { DeviceCodeClient } from './client/DeviceCodeClient.mjs';\nexport { OnBehalfOfClient } from './client/OnBehalfOfClient.mjs';\nexport { UsernamePasswordClient } from './client/UsernamePasswordClient.mjs';\nexport { buildAppConfiguration } from './config/Configuration.mjs';\nexport { ClientAssertion } from './client/ClientAssertion.mjs';\nexport { TokenCache } from './cache/TokenCache.mjs';\nexport { NodeStorage } from './cache/NodeStorage.mjs';\nexport { DistributedCachePlugin } from './cache/distributed/DistributedCachePlugin.mjs';\nexport { CryptoProvider } from './crypto/CryptoProvider.mjs';\nexport { AuthError, AuthErrorCodes, AuthErrorMessage, AzureCloudInstance, ClientAuthError, ClientAuthErrorCodes, ClientAuthErrorMessage, ClientConfigurationError, ClientConfigurationErrorCodes, ClientConfigurationErrorMessage, InteractionRequiredAuthError, InteractionRequiredAuthErrorCodes, InteractionRequiredAuthErrorMessage, LogLevel, Logger, PromptValue, ProtocolMode, ResponseMode, ServerError, TokenCacheContext } from '@azure/msal-common';\nexport { version } from './packageMetadata.mjs';\n//# sourceMappingURL=index.mjs.map\n", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.format(...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n", "/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n", "import {\n\tAgent,\n\tClientRequest,\n\tRequestOptions,\n\tAgentCallbackCallback,\n\tAgentCallbackPromise,\n\tAgentCallbackReturn\n} from './index';\n\ntype LegacyCallback = (\n\treq: ClientRequest,\n\topts: RequestOptions,\n\tfn: AgentCallbackCallback\n) => void;\n\nexport default function promisify(fn: LegacyCallback): AgentCallbackPromise {\n\treturn function(this: Agent, req: ClientRequest, opts: RequestOptions) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tfn.call(\n\t\t\t\tthis,\n\t\t\t\treq,\n\t\t\t\topts,\n\t\t\t\t(err: Error | null | undefined, rtn?: AgentCallbackReturn) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(rtn);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t});\n\t};\n}\n", "import net from 'net';\nimport http from 'http';\nimport https from 'https';\nimport { Duplex } from 'stream';\nimport { EventEmitter } from 'events';\nimport createDebug from 'debug';\nimport promisify from './promisify';\n\nconst debug = createDebug('agent-base');\n\nfunction isAgent(v: any): v is createAgent.AgentLike {\n\treturn Boolean(v) && typeof v.addRequest === 'function';\n}\n\nfunction isSecureEndpoint(): boolean {\n\tconst { stack } = new Error();\n\tif (typeof stack !== 'string') return false;\n\treturn stack.split('\\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);\n}\n\nfunction createAgent(opts?: createAgent.AgentOptions): createAgent.Agent;\nfunction createAgent(\n\tcallback: createAgent.AgentCallback,\n\topts?: createAgent.AgentOptions\n): createAgent.Agent;\nfunction createAgent(\n\tcallback?: createAgent.AgentCallback | createAgent.AgentOptions,\n\topts?: createAgent.AgentOptions\n) {\n\treturn new createAgent.Agent(callback, opts);\n}\n\nnamespace createAgent {\n\texport interface ClientRequest extends http.ClientRequest {\n\t\t_last?: boolean;\n\t\t_hadError?: boolean;\n\t\tmethod: string;\n\t}\n\n\texport interface AgentRequestOptions {\n\t\thost?: string;\n\t\tpath?: string;\n\t\t// `port` on `http.RequestOptions` can be a string or undefined,\n\t\t// but `net.TcpNetConnectOpts` expects only a number\n\t\tport: number;\n\t}\n\n\texport interface HttpRequestOptions\n\t\textends AgentRequestOptions,\n\t\t\tOmit<http.RequestOptions, keyof AgentRequestOptions> {\n\t\tsecureEndpoint: false;\n\t}\n\n\texport interface HttpsRequestOptions\n\t\textends AgentRequestOptions,\n\t\t\tOmit<https.RequestOptions, keyof AgentRequestOptions> {\n\t\tsecureEndpoint: true;\n\t}\n\n\texport type RequestOptions = HttpRequestOptions | HttpsRequestOptions;\n\n\texport type AgentLike = Pick<createAgent.Agent, 'addRequest'> | http.Agent;\n\n\texport type AgentCallbackReturn = Duplex | AgentLike;\n\n\texport type AgentCallbackCallback = (\n\t\terr?: Error | null,\n\t\tsocket?: createAgent.AgentCallbackReturn\n\t) => void;\n\n\texport type AgentCallbackPromise = (\n\t\treq: createAgent.ClientRequest,\n\t\topts: createAgent.RequestOptions\n\t) =>\n\t\t| createAgent.AgentCallbackReturn\n\t\t| Promise<createAgent.AgentCallbackReturn>;\n\n\texport type AgentCallback = typeof Agent.prototype.callback;\n\n\texport type AgentOptions = {\n\t\ttimeout?: number;\n\t};\n\n\t/**\n\t * Base `http.Agent` implementation.\n\t * No pooling/keep-alive is implemented by default.\n\t *\n\t * @param {Function} callback\n\t * @api public\n\t */\n\texport class Agent extends EventEmitter {\n\t\tpublic timeout: number | null;\n\t\tpublic maxFreeSockets: number;\n\t\tpublic maxTotalSockets: number;\n\t\tpublic maxSockets: number;\n\t\tpublic sockets: {\n\t\t\t[key: string]: net.Socket[];\n\t\t};\n\t\tpublic freeSockets: {\n\t\t\t[key: string]: net.Socket[];\n\t\t};\n\t\tpublic requests: {\n\t\t\t[key: string]: http.IncomingMessage[];\n\t\t};\n\t\tpublic options: https.AgentOptions;\n\t\tprivate promisifiedCallback?: createAgent.AgentCallbackPromise;\n\t\tprivate explicitDefaultPort?: number;\n\t\tprivate explicitProtocol?: string;\n\n\t\tconstructor(\n\t\t\tcallback?: createAgent.AgentCallback | createAgent.AgentOptions,\n\t\t\t_opts?: createAgent.AgentOptions\n\t\t) {\n\t\t\tsuper();\n\n\t\t\tlet opts = _opts;\n\t\t\tif (typeof callback === 'function') {\n\t\t\t\tthis.callback = callback;\n\t\t\t} else if (callback) {\n\t\t\t\topts = callback;\n\t\t\t}\n\n\t\t\t// Timeout for the socket to be returned from the callback\n\t\t\tthis.timeout = null;\n\t\t\tif (opts && typeof opts.timeout === 'number') {\n\t\t\t\tthis.timeout = opts.timeout;\n\t\t\t}\n\n\t\t\t// These aren't actually used by `agent-base`, but are required\n\t\t\t// for the TypeScript definition files in `@types/node` :/\n\t\t\tthis.maxFreeSockets = 1;\n\t\t\tthis.maxSockets = 1;\n\t\t\tthis.maxTotalSockets = Infinity;\n\t\t\tthis.sockets = {};\n\t\t\tthis.freeSockets = {};\n\t\t\tthis.requests = {};\n\t\t\tthis.options = {};\n\t\t}\n\n\t\tget defaultPort(): number {\n\t\t\tif (typeof this.explicitDefaultPort === 'number') {\n\t\t\t\treturn this.explicitDefaultPort;\n\t\t\t}\n\t\t\treturn isSecureEndpoint() ? 443 : 80;\n\t\t}\n\n\t\tset defaultPort(v: number) {\n\t\t\tthis.explicitDefaultPort = v;\n\t\t}\n\n\t\tget protocol(): string {\n\t\t\tif (typeof this.explicitProtocol === 'string') {\n\t\t\t\treturn this.explicitProtocol;\n\t\t\t}\n\t\t\treturn isSecureEndpoint() ? 'https:' : 'http:';\n\t\t}\n\n\t\tset protocol(v: string) {\n\t\t\tthis.explicitProtocol = v;\n\t\t}\n\n\t\tcallback(\n\t\t\treq: createAgent.ClientRequest,\n\t\t\topts: createAgent.RequestOptions,\n\t\t\tfn: createAgent.AgentCallbackCallback\n\t\t): void;\n\t\tcallback(\n\t\t\treq: createAgent.ClientRequest,\n\t\t\topts: createAgent.RequestOptions\n\t\t):\n\t\t\t| createAgent.AgentCallbackReturn\n\t\t\t| Promise<createAgent.AgentCallbackReturn>;\n\t\tcallback(\n\t\t\treq: createAgent.ClientRequest,\n\t\t\topts: createAgent.AgentOptions,\n\t\t\tfn?: createAgent.AgentCallbackCallback\n\t\t):\n\t\t\t| createAgent.AgentCallbackReturn\n\t\t\t| Promise<createAgent.AgentCallbackReturn>\n\t\t\t| void {\n\t\t\tthrow new Error(\n\t\t\t\t'\"agent-base\" has no default implementation, you must subclass and override `callback()`'\n\t\t\t);\n\t\t}\n\n\t\t/**\n\t\t * Called by node-core's \"_http_client.js\" module when creating\n\t\t * a new HTTP request with this Agent instance.\n\t\t *\n\t\t * @api public\n\t\t */\n\t\taddRequest(req: ClientRequest, _opts: RequestOptions): void {\n\t\t\tconst opts: RequestOptions = { ..._opts };\n\n\t\t\tif (typeof opts.secureEndpoint !== 'boolean') {\n\t\t\t\topts.secureEndpoint = isSecureEndpoint();\n\t\t\t}\n\n\t\t\tif (opts.host == null) {\n\t\t\t\topts.host = 'localhost';\n\t\t\t}\n\n\t\t\tif (opts.port == null) {\n\t\t\t\topts.port = opts.secureEndpoint ? 443 : 80;\n\t\t\t}\n\n\t\t\tif (opts.protocol == null) {\n\t\t\t\topts.protocol = opts.secureEndpoint ? 'https:' : 'http:';\n\t\t\t}\n\n\t\t\tif (opts.host && opts.path) {\n\t\t\t\t// If both a `host` and `path` are specified then it's most\n\t\t\t\t// likely the result of a `url.parse()` call... we need to\n\t\t\t\t// remove the `path` portion so that `net.connect()` doesn't\n\t\t\t\t// attempt to open that as a unix socket file.\n\t\t\t\tdelete opts.path;\n\t\t\t}\n\n\t\t\tdelete opts.agent;\n\t\t\tdelete opts.hostname;\n\t\t\tdelete opts._defaultAgent;\n\t\t\tdelete opts.defaultPort;\n\t\t\tdelete opts.createConnection;\n\n\t\t\t// Hint to use \"Connection: close\"\n\t\t\t// XXX: non-documented `http` module API :(\n\t\t\treq._last = true;\n\t\t\treq.shouldKeepAlive = false;\n\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutId: ReturnType<typeof setTimeout> | null = null;\n\t\t\tconst timeoutMs = opts.timeout || this.timeout;\n\n\t\t\tconst onerror = (err: NodeJS.ErrnoException) => {\n\t\t\t\tif (req._hadError) return;\n\t\t\t\treq.emit('error', err);\n\t\t\t\t// For Safety. Some additional errors might fire later on\n\t\t\t\t// and we need to make sure we don't double-fire the error event.\n\t\t\t\treq._hadError = true;\n\t\t\t};\n\n\t\t\tconst ontimeout = () => {\n\t\t\t\ttimeoutId = null;\n\t\t\t\ttimedOut = true;\n\t\t\t\tconst err: NodeJS.ErrnoException = new Error(\n\t\t\t\t\t`A \"socket\" was not created for HTTP request before ${timeoutMs}ms`\n\t\t\t\t);\n\t\t\t\terr.code = 'ETIMEOUT';\n\t\t\t\tonerror(err);\n\t\t\t};\n\n\t\t\tconst callbackError = (err: NodeJS.ErrnoException) => {\n\t\t\t\tif (timedOut) return;\n\t\t\t\tif (timeoutId !== null) {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\ttimeoutId = null;\n\t\t\t\t}\n\t\t\t\tonerror(err);\n\t\t\t};\n\n\t\t\tconst onsocket = (socket: AgentCallbackReturn) => {\n\t\t\t\tif (timedOut) return;\n\t\t\t\tif (timeoutId != null) {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\ttimeoutId = null;\n\t\t\t\t}\n\n\t\t\t\tif (isAgent(socket)) {\n\t\t\t\t\t// `socket` is actually an `http.Agent` instance, so\n\t\t\t\t\t// relinquish responsibility for this `req` to the Agent\n\t\t\t\t\t// from here on\n\t\t\t\t\tdebug(\n\t\t\t\t\t\t'Callback returned another Agent instance %o',\n\t\t\t\t\t\tsocket.constructor.name\n\t\t\t\t\t);\n\t\t\t\t\t(socket as createAgent.Agent).addRequest(req, opts);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (socket) {\n\t\t\t\t\tsocket.once('free', () => {\n\t\t\t\t\t\tthis.freeSocket(socket as net.Socket, opts);\n\t\t\t\t\t});\n\t\t\t\t\treq.onSocket(socket as net.Socket);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst err = new Error(\n\t\t\t\t\t`no Duplex stream was returned to agent-base for \\`${req.method} ${req.path}\\``\n\t\t\t\t);\n\t\t\t\tonerror(err);\n\t\t\t};\n\n\t\t\tif (typeof this.callback !== 'function') {\n\t\t\t\tonerror(new Error('`callback` is not defined'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!this.promisifiedCallback) {\n\t\t\t\tif (this.callback.length >= 3) {\n\t\t\t\t\tdebug('Converting legacy callback function to promise');\n\t\t\t\t\tthis.promisifiedCallback = promisify(this.callback);\n\t\t\t\t} else {\n\t\t\t\t\tthis.promisifiedCallback = this.callback;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (typeof timeoutMs === 'number' && timeoutMs > 0) {\n\t\t\t\ttimeoutId = setTimeout(ontimeout, timeoutMs);\n\t\t\t}\n\n\t\t\tif ('port' in opts && typeof opts.port !== 'number') {\n\t\t\t\topts.port = Number(opts.port);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tdebug(\n\t\t\t\t\t'Resolving socket for %o request: %o',\n\t\t\t\t\topts.protocol,\n\t\t\t\t\t`${req.method} ${req.path}`\n\t\t\t\t);\n\t\t\t\tPromise.resolve(this.promisifiedCallback(req, opts)).then(\n\t\t\t\t\tonsocket,\n\t\t\t\t\tcallbackError\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tPromise.reject(err).catch(callbackError);\n\t\t\t}\n\t\t}\n\n\t\tfreeSocket(socket: net.Socket, opts: AgentOptions) {\n\t\t\tdebug('Freeing socket %o %o', socket.constructor.name, opts);\n\t\t\tsocket.destroy();\n\t\t}\n\n\t\tdestroy() {\n\t\t\tdebug('Destroying agent %o', this.constructor.name);\n\t\t}\n\t}\n\n\t// So that `instanceof` works correctly\n\tcreateAgent.prototype = createAgent.Agent.prototype;\n}\n\nexport = createAgent;\n", null, null, null, null, "import {\n\tAgent,\n\tClientRequest,\n\tRequestOptions,\n\tAgentCallbackCallback,\n\tAgentCallbackPromise,\n\tAgentCallbackReturn\n} from './index';\n\ntype LegacyCallback = (\n\treq: ClientRequest,\n\topts: RequestOptions,\n\tfn: AgentCallbackCallback\n) => void;\n\nexport default function promisify(fn: LegacyCallback): AgentCallbackPromise {\n\treturn function(this: Agent, req: ClientRequest, opts: RequestOptions) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tfn.call(\n\t\t\t\tthis,\n\t\t\t\treq,\n\t\t\t\topts,\n\t\t\t\t(err: Error | null | undefined, rtn?: AgentCallbackReturn) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(rtn);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t});\n\t};\n}\n", "import net from 'net';\nimport http from 'http';\nimport https from 'https';\nimport { Duplex } from 'stream';\nimport { EventEmitter } from 'events';\nimport createDebug from 'debug';\nimport promisify from './promisify';\n\nconst debug = createDebug('agent-base');\n\nfunction isAgent(v: any): v is createAgent.AgentLike {\n\treturn Boolean(v) && typeof v.addRequest === 'function';\n}\n\nfunction isSecureEndpoint(): boolean {\n\tconst { stack } = new Error();\n\tif (typeof stack !== 'string') return false;\n\treturn stack.split('\\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);\n}\n\nfunction createAgent(opts?: createAgent.AgentOptions): createAgent.Agent;\nfunction createAgent(\n\tcallback: createAgent.AgentCallback,\n\topts?: createAgent.AgentOptions\n): createAgent.Agent;\nfunction createAgent(\n\tcallback?: createAgent.AgentCallback | createAgent.AgentOptions,\n\topts?: createAgent.AgentOptions\n) {\n\treturn new createAgent.Agent(callback, opts);\n}\n\nnamespace createAgent {\n\texport interface ClientRequest extends http.ClientRequest {\n\t\t_last?: boolean;\n\t\t_hadError?: boolean;\n\t\tmethod: string;\n\t}\n\n\texport interface AgentRequestOptions {\n\t\thost?: string;\n\t\tpath?: string;\n\t\t// `port` on `http.RequestOptions` can be a string or undefined,\n\t\t// but `net.TcpNetConnectOpts` expects only a number\n\t\tport: number;\n\t}\n\n\texport interface HttpRequestOptions\n\t\textends AgentRequestOptions,\n\t\t\tOmit<http.RequestOptions, keyof AgentRequestOptions> {\n\t\tsecureEndpoint: false;\n\t}\n\n\texport interface HttpsRequestOptions\n\t\textends AgentRequestOptions,\n\t\t\tOmit<https.RequestOptions, keyof AgentRequestOptions> {\n\t\tsecureEndpoint: true;\n\t}\n\n\texport type RequestOptions = HttpRequestOptions | HttpsRequestOptions;\n\n\texport type AgentLike = Pick<createAgent.Agent, 'addRequest'> | http.Agent;\n\n\texport type AgentCallbackReturn = Duplex | AgentLike;\n\n\texport type AgentCallbackCallback = (\n\t\terr?: Error | null,\n\t\tsocket?: createAgent.AgentCallbackReturn\n\t) => void;\n\n\texport type AgentCallbackPromise = (\n\t\treq: createAgent.ClientRequest,\n\t\topts: createAgent.RequestOptions\n\t) =>\n\t\t| createAgent.AgentCallbackReturn\n\t\t| Promise<createAgent.AgentCallbackReturn>;\n\n\texport type AgentCallback = typeof Agent.prototype.callback;\n\n\texport type AgentOptions = {\n\t\ttimeout?: number;\n\t};\n\n\t/**\n\t * Base `http.Agent` implementation.\n\t * No pooling/keep-alive is implemented by default.\n\t *\n\t * @param {Function} callback\n\t * @api public\n\t */\n\texport class Agent extends EventEmitter {\n\t\tpublic timeout: number | null;\n\t\tpublic maxFreeSockets: number;\n\t\tpublic maxTotalSockets: number;\n\t\tpublic maxSockets: number;\n\t\tpublic sockets: {\n\t\t\t[key: string]: net.Socket[];\n\t\t};\n\t\tpublic freeSockets: {\n\t\t\t[key: string]: net.Socket[];\n\t\t};\n\t\tpublic requests: {\n\t\t\t[key: string]: http.IncomingMessage[];\n\t\t};\n\t\tpublic options: https.AgentOptions;\n\t\tprivate promisifiedCallback?: createAgent.AgentCallbackPromise;\n\t\tprivate explicitDefaultPort?: number;\n\t\tprivate explicitProtocol?: string;\n\n\t\tconstructor(\n\t\t\tcallback?: createAgent.AgentCallback | createAgent.AgentOptions,\n\t\t\t_opts?: createAgent.AgentOptions\n\t\t) {\n\t\t\tsuper();\n\n\t\t\tlet opts = _opts;\n\t\t\tif (typeof callback === 'function') {\n\t\t\t\tthis.callback = callback;\n\t\t\t} else if (callback) {\n\t\t\t\topts = callback;\n\t\t\t}\n\n\t\t\t// Timeout for the socket to be returned from the callback\n\t\t\tthis.timeout = null;\n\t\t\tif (opts && typeof opts.timeout === 'number') {\n\t\t\t\tthis.timeout = opts.timeout;\n\t\t\t}\n\n\t\t\t// These aren't actually used by `agent-base`, but are required\n\t\t\t// for the TypeScript definition files in `@types/node` :/\n\t\t\tthis.maxFreeSockets = 1;\n\t\t\tthis.maxSockets = 1;\n\t\t\tthis.maxTotalSockets = Infinity;\n\t\t\tthis.sockets = {};\n\t\t\tthis.freeSockets = {};\n\t\t\tthis.requests = {};\n\t\t\tthis.options = {};\n\t\t}\n\n\t\tget defaultPort(): number {\n\t\t\tif (typeof this.explicitDefaultPort === 'number') {\n\t\t\t\treturn this.explicitDefaultPort;\n\t\t\t}\n\t\t\treturn isSecureEndpoint() ? 443 : 80;\n\t\t}\n\n\t\tset defaultPort(v: number) {\n\t\t\tthis.explicitDefaultPort = v;\n\t\t}\n\n\t\tget protocol(): string {\n\t\t\tif (typeof this.explicitProtocol === 'string') {\n\t\t\t\treturn this.explicitProtocol;\n\t\t\t}\n\t\t\treturn isSecureEndpoint() ? 'https:' : 'http:';\n\t\t}\n\n\t\tset protocol(v: string) {\n\t\t\tthis.explicitProtocol = v;\n\t\t}\n\n\t\tcallback(\n\t\t\treq: createAgent.ClientRequest,\n\t\t\topts: createAgent.RequestOptions,\n\t\t\tfn: createAgent.AgentCallbackCallback\n\t\t): void;\n\t\tcallback(\n\t\t\treq: createAgent.ClientRequest,\n\t\t\topts: createAgent.RequestOptions\n\t\t):\n\t\t\t| createAgent.AgentCallbackReturn\n\t\t\t| Promise<createAgent.AgentCallbackReturn>;\n\t\tcallback(\n\t\t\treq: createAgent.ClientRequest,\n\t\t\topts: createAgent.AgentOptions,\n\t\t\tfn?: createAgent.AgentCallbackCallback\n\t\t):\n\t\t\t| createAgent.AgentCallbackReturn\n\t\t\t| Promise<createAgent.AgentCallbackReturn>\n\t\t\t| void {\n\t\t\tthrow new Error(\n\t\t\t\t'\"agent-base\" has no default implementation, you must subclass and override `callback()`'\n\t\t\t);\n\t\t}\n\n\t\t/**\n\t\t * Called by node-core's \"_http_client.js\" module when creating\n\t\t * a new HTTP request with this Agent instance.\n\t\t *\n\t\t * @api public\n\t\t */\n\t\taddRequest(req: ClientRequest, _opts: RequestOptions): void {\n\t\t\tconst opts: RequestOptions = { ..._opts };\n\n\t\t\tif (typeof opts.secureEndpoint !== 'boolean') {\n\t\t\t\topts.secureEndpoint = isSecureEndpoint();\n\t\t\t}\n\n\t\t\tif (opts.host == null) {\n\t\t\t\topts.host = 'localhost';\n\t\t\t}\n\n\t\t\tif (opts.port == null) {\n\t\t\t\topts.port = opts.secureEndpoint ? 443 : 80;\n\t\t\t}\n\n\t\t\tif (opts.protocol == null) {\n\t\t\t\topts.protocol = opts.secureEndpoint ? 'https:' : 'http:';\n\t\t\t}\n\n\t\t\tif (opts.host && opts.path) {\n\t\t\t\t// If both a `host` and `path` are specified then it's most\n\t\t\t\t// likely the result of a `url.parse()` call... we need to\n\t\t\t\t// remove the `path` portion so that `net.connect()` doesn't\n\t\t\t\t// attempt to open that as a unix socket file.\n\t\t\t\tdelete opts.path;\n\t\t\t}\n\n\t\t\tdelete opts.agent;\n\t\t\tdelete opts.hostname;\n\t\t\tdelete opts._defaultAgent;\n\t\t\tdelete opts.defaultPort;\n\t\t\tdelete opts.createConnection;\n\n\t\t\t// Hint to use \"Connection: close\"\n\t\t\t// XXX: non-documented `http` module API :(\n\t\t\treq._last = true;\n\t\t\treq.shouldKeepAlive = false;\n\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutId: ReturnType<typeof setTimeout> | null = null;\n\t\t\tconst timeoutMs = opts.timeout || this.timeout;\n\n\t\t\tconst onerror = (err: NodeJS.ErrnoException) => {\n\t\t\t\tif (req._hadError) return;\n\t\t\t\treq.emit('error', err);\n\t\t\t\t// For Safety. Some additional errors might fire later on\n\t\t\t\t// and we need to make sure we don't double-fire the error event.\n\t\t\t\treq._hadError = true;\n\t\t\t};\n\n\t\t\tconst ontimeout = () => {\n\t\t\t\ttimeoutId = null;\n\t\t\t\ttimedOut = true;\n\t\t\t\tconst err: NodeJS.ErrnoException = new Error(\n\t\t\t\t\t`A \"socket\" was not created for HTTP request before ${timeoutMs}ms`\n\t\t\t\t);\n\t\t\t\terr.code = 'ETIMEOUT';\n\t\t\t\tonerror(err);\n\t\t\t};\n\n\t\t\tconst callbackError = (err: NodeJS.ErrnoException) => {\n\t\t\t\tif (timedOut) return;\n\t\t\t\tif (timeoutId !== null) {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\ttimeoutId = null;\n\t\t\t\t}\n\t\t\t\tonerror(err);\n\t\t\t};\n\n\t\t\tconst onsocket = (socket: AgentCallbackReturn) => {\n\t\t\t\tif (timedOut) return;\n\t\t\t\tif (timeoutId != null) {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\ttimeoutId = null;\n\t\t\t\t}\n\n\t\t\t\tif (isAgent(socket)) {\n\t\t\t\t\t// `socket` is actually an `http.Agent` instance, so\n\t\t\t\t\t// relinquish responsibility for this `req` to the Agent\n\t\t\t\t\t// from here on\n\t\t\t\t\tdebug(\n\t\t\t\t\t\t'Callback returned another Agent instance %o',\n\t\t\t\t\t\tsocket.constructor.name\n\t\t\t\t\t);\n\t\t\t\t\t(socket as createAgent.Agent).addRequest(req, opts);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (socket) {\n\t\t\t\t\tsocket.once('free', () => {\n\t\t\t\t\t\tthis.freeSocket(socket as net.Socket, opts);\n\t\t\t\t\t});\n\t\t\t\t\treq.onSocket(socket as net.Socket);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst err = new Error(\n\t\t\t\t\t`no Duplex stream was returned to agent-base for \\`${req.method} ${req.path}\\``\n\t\t\t\t);\n\t\t\t\tonerror(err);\n\t\t\t};\n\n\t\t\tif (typeof this.callback !== 'function') {\n\t\t\t\tonerror(new Error('`callback` is not defined'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!this.promisifiedCallback) {\n\t\t\t\tif (this.callback.length >= 3) {\n\t\t\t\t\tdebug('Converting legacy callback function to promise');\n\t\t\t\t\tthis.promisifiedCallback = promisify(this.callback);\n\t\t\t\t} else {\n\t\t\t\t\tthis.promisifiedCallback = this.callback;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (typeof timeoutMs === 'number' && timeoutMs > 0) {\n\t\t\t\ttimeoutId = setTimeout(ontimeout, timeoutMs);\n\t\t\t}\n\n\t\t\tif ('port' in opts && typeof opts.port !== 'number') {\n\t\t\t\topts.port = Number(opts.port);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tdebug(\n\t\t\t\t\t'Resolving socket for %o request: %o',\n\t\t\t\t\topts.protocol,\n\t\t\t\t\t`${req.method} ${req.path}`\n\t\t\t\t);\n\t\t\t\tPromise.resolve(this.promisifiedCallback(req, opts)).then(\n\t\t\t\t\tonsocket,\n\t\t\t\t\tcallbackError\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tPromise.reject(err).catch(callbackError);\n\t\t\t}\n\t\t}\n\n\t\tfreeSocket(socket: net.Socket, opts: AgentOptions) {\n\t\t\tdebug('Freeing socket %o %o', socket.constructor.name, opts);\n\t\t\tsocket.destroy();\n\t\t}\n\n\t\tdestroy() {\n\t\t\tdebug('Destroying agent %o', this.constructor.name);\n\t\t}\n\t}\n\n\t// So that `instanceof` works correctly\n\tcreateAgent.prototype = createAgent.Agent.prototype;\n}\n\nexport = createAgent;\n", null, null, "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TracingContext, TracingSpan } from \"./interfaces\";\n\n/** @internal */\nexport const knownContextKeys = {\n span: Symbol.for(\"@azure/core-tracing span\"),\n namespace: Symbol.for(\"@azure/core-tracing namespace\"),\n};\n\n/**\n * Creates a new {@link TracingContext} with the given options.\n * @param options - A set of known keys that may be set on the context.\n * @returns A new {@link TracingContext} with the given options.\n *\n * @internal\n */\nexport function createTracingContext(options: CreateTracingContextOptions = {}): TracingContext {\n let context: TracingContext = new TracingContextImpl(options.parentContext);\n if (options.span) {\n context = context.setValue(knownContextKeys.span, options.span);\n }\n if (options.namespace) {\n context = context.setValue(knownContextKeys.namespace, options.namespace);\n }\n return context;\n}\n\n/** @internal */\nexport class TracingContextImpl implements TracingContext {\n private _contextMap: Map<symbol, unknown>;\n constructor(initialContext?: TracingContext) {\n this._contextMap =\n initialContext instanceof TracingContextImpl\n ? new Map<symbol, unknown>(initialContext._contextMap)\n : new Map();\n }\n\n setValue(key: symbol, value: unknown): TracingContext {\n const newContext = new TracingContextImpl(this);\n newContext._contextMap.set(key, value);\n return newContext;\n }\n\n getValue(key: symbol): unknown {\n return this._contextMap.get(key);\n }\n\n deleteValue(key: symbol): TracingContext {\n const newContext = new TracingContextImpl(this);\n newContext._contextMap.delete(key);\n return newContext;\n }\n}\n\n/**\n * Represents a set of items that can be set when creating a new {@link TracingContext}.\n */\nexport interface CreateTracingContextOptions {\n /** The {@link parentContext} - the newly created context will contain all the values of the parent context unless overridden. */\n parentContext?: TracingContext;\n /** An initial span to set on the context. */\n span?: TracingSpan;\n /** The namespace to set on any child spans. */\n namespace?: string;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Instrumenter, InstrumenterSpanOptions, TracingContext, TracingSpan } from \"./interfaces\";\nimport { createTracingContext } from \"./tracingContext\";\n\nexport function createDefaultTracingSpan(): TracingSpan {\n return {\n end: () => {\n // noop\n },\n isRecording: () => false,\n recordException: () => {\n // noop\n },\n setAttribute: () => {\n // noop\n },\n setStatus: () => {\n // noop\n },\n };\n}\n\nexport function createDefaultInstrumenter(): Instrumenter {\n return {\n createRequestHeaders: (): Record<string, string> => {\n return {};\n },\n parseTraceparentHeader: (): TracingContext | undefined => {\n return undefined;\n },\n startSpan: (\n _name: string,\n spanOptions: InstrumenterSpanOptions\n ): { span: TracingSpan; tracingContext: TracingContext } => {\n return {\n span: createDefaultTracingSpan(),\n tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext }),\n };\n },\n withContext<\n CallbackArgs extends unknown[],\n Callback extends (...args: CallbackArgs) => ReturnType<Callback>\n >(\n _context: TracingContext,\n callback: Callback,\n ...callbackArgs: CallbackArgs\n ): ReturnType<Callback> {\n return callback(...callbackArgs);\n },\n };\n}\n\n/** @internal */\nlet instrumenterImplementation: Instrumenter | undefined;\n\n/**\n * Extends the Azure SDK with support for a given instrumenter implementation.\n *\n * @param instrumenter - The instrumenter implementation to use.\n */\nexport function useInstrumenter(instrumenter: Instrumenter): void {\n instrumenterImplementation = instrumenter;\n}\n\n/**\n * Gets the currently set instrumenter, a No-Op instrumenter by default.\n *\n * @returns The currently set instrumenter\n */\nexport function getInstrumenter(): Instrumenter {\n if (!instrumenterImplementation) {\n instrumenterImplementation = createDefaultInstrumenter();\n }\n return instrumenterImplementation;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n OperationTracingOptions,\n OptionsWithTracingContext,\n Resolved,\n TracingClient,\n TracingClientOptions,\n TracingContext,\n TracingSpan,\n TracingSpanOptions,\n} from \"./interfaces\";\nimport { getInstrumenter } from \"./instrumenter\";\nimport { knownContextKeys } from \"./tracingContext\";\n\n/**\n * Creates a new tracing client.\n *\n * @param options - Options used to configure the tracing client.\n * @returns - An instance of {@link TracingClient}.\n */\nexport function createTracingClient(options: TracingClientOptions): TracingClient {\n const { namespace, packageName, packageVersion } = options;\n\n function startSpan<Options extends { tracingOptions?: OperationTracingOptions }>(\n name: string,\n operationOptions?: Options,\n spanOptions?: TracingSpanOptions\n ): {\n span: TracingSpan;\n updatedOptions: OptionsWithTracingContext<Options>;\n } {\n const startSpanResult = getInstrumenter().startSpan(name, {\n ...spanOptions,\n packageName: packageName,\n packageVersion: packageVersion,\n tracingContext: operationOptions?.tracingOptions?.tracingContext,\n });\n let tracingContext = startSpanResult.tracingContext;\n const span = startSpanResult.span;\n if (!tracingContext.getValue(knownContextKeys.namespace)) {\n tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace);\n }\n span.setAttribute(\"az.namespace\", tracingContext.getValue(knownContextKeys.namespace));\n const updatedOptions: OptionsWithTracingContext<Options> = Object.assign({}, operationOptions, {\n tracingOptions: { ...operationOptions?.tracingOptions, tracingContext },\n });\n\n return {\n span,\n updatedOptions,\n };\n }\n\n async function withSpan<\n Options extends { tracingOptions?: OperationTracingOptions },\n Callback extends (\n updatedOptions: Options,\n span: Omit<TracingSpan, \"end\">\n ) => ReturnType<Callback>\n >(\n name: string,\n operationOptions: Options,\n callback: Callback,\n spanOptions?: TracingSpanOptions\n ): Promise<Resolved<ReturnType<Callback>>> {\n const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);\n try {\n const result = await withContext(updatedOptions.tracingOptions.tracingContext, () =>\n Promise.resolve(callback(updatedOptions, span))\n );\n span.setStatus({ status: \"success\" });\n return result as ReturnType<typeof withSpan>;\n } catch (err: any) {\n span.setStatus({ status: \"error\", error: err });\n throw err;\n } finally {\n span.end();\n }\n }\n\n function withContext<\n CallbackArgs extends unknown[],\n Callback extends (...args: CallbackArgs) => ReturnType<Callback>\n >(\n context: TracingContext,\n callback: Callback,\n ...callbackArgs: CallbackArgs\n ): ReturnType<Callback> {\n return getInstrumenter().withContext(context, callback, ...callbackArgs);\n }\n\n /**\n * Parses a traceparent header value into a span identifier.\n *\n * @param traceparentHeader - The traceparent header to parse.\n * @returns An implementation-specific identifier for the span.\n */\n function parseTraceparentHeader(traceparentHeader: string): TracingContext | undefined {\n return getInstrumenter().parseTraceparentHeader(traceparentHeader);\n }\n\n /**\n * Creates a set of request headers to propagate tracing information to a backend.\n *\n * @param tracingContext - The context containing the span to serialize.\n * @returns The set of headers to add to a request.\n */\n function createRequestHeaders(tracingContext?: TracingContext): Record<string, string> {\n return getInstrumenter().createRequestHeaders(tracingContext);\n }\n\n return {\n startSpan,\n withSpan,\n withContext,\n parseTraceparentHeader,\n createRequestHeaders,\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { HttpClient, PipelineRequest, PipelineResponse, SendRequest } from \"./interfaces\";\n\n/**\n * Policies are executed in phases.\n * The execution order is:\n * 1. Serialize Phase\n * 2. Policies not in a phase\n * 3. Deserialize Phase\n * 4. Retry Phase\n * 5. Sign Phase\n */\nexport type PipelinePhase = \"Deserialize\" | \"Serialize\" | \"Retry\" | \"Sign\";\n\nconst ValidPhaseNames = new Set<PipelinePhase>([\"Deserialize\", \"Serialize\", \"Retry\", \"Sign\"]);\n\n/**\n * Options when adding a policy to the pipeline.\n * Used to express dependencies on other policies.\n */\nexport interface AddPolicyOptions {\n /**\n * Policies that this policy must come before.\n */\n beforePolicies?: string[];\n /**\n * Policies that this policy must come after.\n */\n afterPolicies?: string[];\n /**\n * The phase that this policy must come after.\n */\n afterPhase?: PipelinePhase;\n /**\n * The phase this policy belongs to.\n */\n phase?: PipelinePhase;\n}\n\n/**\n * A pipeline policy manipulates a request as it travels through the pipeline.\n * It is conceptually a middleware that is allowed to modify the request before\n * it is made as well as the response when it is received.\n */\nexport interface PipelinePolicy {\n /**\n * The policy name. Must be a unique string in the pipeline.\n */\n name: string;\n /**\n * The main method to implement that manipulates a request/response.\n * @param request - The request being performed.\n * @param next - The next policy in the pipeline. Must be called to continue the pipeline.\n */\n sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse>;\n}\n\n/**\n * Represents a pipeline for making a HTTP request to a URL.\n * Pipelines can have multiple policies to manage manipulating each request\n * before and after it is made to the server.\n */\nexport interface Pipeline {\n /**\n * Add a new policy to the pipeline.\n * @param policy - A policy that manipulates a request.\n * @param options - A set of options for when the policy should run.\n */\n addPolicy(policy: PipelinePolicy, options?: AddPolicyOptions): void;\n /**\n * Remove a policy from the pipeline.\n * @param options - Options that let you specify which policies to remove.\n */\n removePolicy(options: { name?: string; phase?: PipelinePhase }): PipelinePolicy[];\n /**\n * Uses the pipeline to make a HTTP request.\n * @param httpClient - The HttpClient that actually performs the request.\n * @param request - The request to be made.\n */\n sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise<PipelineResponse>;\n /**\n * Returns the current set of policies in the pipeline in the order in which\n * they will be applied to the request. Later in the list is closer to when\n * the request is performed.\n */\n getOrderedPolicies(): PipelinePolicy[];\n /**\n * Duplicates this pipeline to allow for modifying an existing one without mutating it.\n */\n clone(): Pipeline;\n}\n\ninterface PipelineDescriptor {\n policy: PipelinePolicy;\n options: AddPolicyOptions;\n}\n\ninterface PolicyGraphNode {\n policy: PipelinePolicy;\n dependsOn: Set<PolicyGraphNode>;\n dependants: Set<PolicyGraphNode>;\n afterPhase?: Phase;\n}\n\ninterface Phase {\n name: PipelinePhase | \"None\";\n policies: Set<PolicyGraphNode>;\n hasRun: boolean;\n hasAfterPolicies: boolean;\n}\n\n/**\n * A private implementation of Pipeline.\n * Do not export this class from the package.\n * @internal\n */\nclass HttpPipeline implements Pipeline {\n private _policies: PipelineDescriptor[] = [];\n private _orderedPolicies?: PipelinePolicy[];\n\n private constructor(policies?: PipelineDescriptor[]) {\n this._policies = policies?.slice(0) ?? [];\n this._orderedPolicies = undefined;\n }\n\n public addPolicy(policy: PipelinePolicy, options: AddPolicyOptions = {}): void {\n if (options.phase && options.afterPhase) {\n throw new Error(\"Policies inside a phase cannot specify afterPhase.\");\n }\n if (options.phase && !ValidPhaseNames.has(options.phase)) {\n throw new Error(`Invalid phase name: ${options.phase}`);\n }\n if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {\n throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);\n }\n this._policies.push({\n policy,\n options,\n });\n this._orderedPolicies = undefined;\n }\n\n public removePolicy(options: { name?: string; phase?: string }): PipelinePolicy[] {\n const removedPolicies: PipelinePolicy[] = [];\n\n this._policies = this._policies.filter((policyDescriptor) => {\n if (\n (options.name && policyDescriptor.policy.name === options.name) ||\n (options.phase && policyDescriptor.options.phase === options.phase)\n ) {\n removedPolicies.push(policyDescriptor.policy);\n return false;\n } else {\n return true;\n }\n });\n this._orderedPolicies = undefined;\n\n return removedPolicies;\n }\n\n public sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise<PipelineResponse> {\n const policies = this.getOrderedPolicies();\n\n const pipeline = policies.reduceRight<SendRequest>(\n (next, policy) => {\n return (req: PipelineRequest) => {\n return policy.sendRequest(req, next);\n };\n },\n (req: PipelineRequest) => httpClient.sendRequest(req)\n );\n\n return pipeline(request);\n }\n\n public getOrderedPolicies(): PipelinePolicy[] {\n if (!this._orderedPolicies) {\n this._orderedPolicies = this.orderPolicies();\n }\n return this._orderedPolicies;\n }\n\n public clone(): Pipeline {\n return new HttpPipeline(this._policies);\n }\n\n public static create(): Pipeline {\n return new HttpPipeline();\n }\n\n private orderPolicies(): PipelinePolicy[] {\n /**\n * The goal of this method is to reliably order pipeline policies\n * based on their declared requirements when they were added.\n *\n * Order is first determined by phase:\n *\n * 1. Serialize Phase\n * 2. Policies not in a phase\n * 3. Deserialize Phase\n * 4. Retry Phase\n * 5. Sign Phase\n *\n * Within each phase, policies are executed in the order\n * they were added unless they were specified to execute\n * before/after other policies or after a particular phase.\n *\n * To determine the final order, we will walk the policy list\n * in phase order multiple times until all dependencies are\n * satisfied.\n *\n * `afterPolicies` are the set of policies that must be\n * executed before a given policy. This requirement is\n * considered satisfied when each of the listed policies\n * have been scheduled.\n *\n * `beforePolicies` are the set of policies that must be\n * executed after a given policy. Since this dependency\n * can be expressed by converting it into a equivalent\n * `afterPolicies` declarations, they are normalized\n * into that form for simplicity.\n *\n * An `afterPhase` dependency is considered satisfied when all\n * policies in that phase have scheduled.\n *\n */\n const result: PipelinePolicy[] = [];\n\n // Track all policies we know about.\n const policyMap: Map<string, PolicyGraphNode> = new Map<string, PolicyGraphNode>();\n\n function createPhase(name: PipelinePhase | \"None\"): Phase {\n return {\n name,\n policies: new Set<PolicyGraphNode>(),\n hasRun: false,\n hasAfterPolicies: false,\n };\n }\n\n // Track policies for each phase.\n const serializePhase = createPhase(\"Serialize\");\n const noPhase = createPhase(\"None\");\n const deserializePhase = createPhase(\"Deserialize\");\n const retryPhase = createPhase(\"Retry\");\n const signPhase = createPhase(\"Sign\");\n\n // a list of phases in order\n const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];\n\n // Small helper function to map phase name to each Phase\n function getPhase(phase: PipelinePhase | undefined): Phase {\n if (phase === \"Retry\") {\n return retryPhase;\n } else if (phase === \"Serialize\") {\n return serializePhase;\n } else if (phase === \"Deserialize\") {\n return deserializePhase;\n } else if (phase === \"Sign\") {\n return signPhase;\n } else {\n return noPhase;\n }\n }\n\n // First walk each policy and create a node to track metadata.\n for (const descriptor of this._policies) {\n const policy = descriptor.policy;\n const options = descriptor.options;\n const policyName = policy.name;\n if (policyMap.has(policyName)) {\n throw new Error(\"Duplicate policy names not allowed in pipeline\");\n }\n const node: PolicyGraphNode = {\n policy,\n dependsOn: new Set<PolicyGraphNode>(),\n dependants: new Set<PolicyGraphNode>(),\n };\n if (options.afterPhase) {\n node.afterPhase = getPhase(options.afterPhase);\n node.afterPhase.hasAfterPolicies = true;\n }\n policyMap.set(policyName, node);\n const phase = getPhase(options.phase);\n phase.policies.add(node);\n }\n\n // Now that each policy has a node, connect dependency references.\n for (const descriptor of this._policies) {\n const { policy, options } = descriptor;\n const policyName = policy.name;\n const node = policyMap.get(policyName);\n if (!node) {\n throw new Error(`Missing node for policy ${policyName}`);\n }\n\n if (options.afterPolicies) {\n for (const afterPolicyName of options.afterPolicies) {\n const afterNode = policyMap.get(afterPolicyName);\n if (afterNode) {\n // Linking in both directions helps later\n // when we want to notify dependants.\n node.dependsOn.add(afterNode);\n afterNode.dependants.add(node);\n }\n }\n }\n if (options.beforePolicies) {\n for (const beforePolicyName of options.beforePolicies) {\n const beforeNode = policyMap.get(beforePolicyName);\n if (beforeNode) {\n // To execute before another node, make it\n // depend on the current node.\n beforeNode.dependsOn.add(node);\n node.dependants.add(beforeNode);\n }\n }\n }\n }\n\n function walkPhase(phase: Phase): void {\n phase.hasRun = true;\n // Sets iterate in insertion order\n for (const node of phase.policies) {\n if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {\n // If this node is waiting on a phase to complete,\n // we need to skip it for now.\n // Even if the phase is empty, we should wait for it\n // to be walked to avoid re-ordering policies.\n continue;\n }\n if (node.dependsOn.size === 0) {\n // If there's nothing else we're waiting for, we can\n // add this policy to the result list.\n result.push(node.policy);\n // Notify anything that depends on this policy that\n // the policy has been scheduled.\n for (const dependant of node.dependants) {\n dependant.dependsOn.delete(node);\n }\n policyMap.delete(node.policy.name);\n phase.policies.delete(node);\n }\n }\n }\n\n function walkPhases(): void {\n for (const phase of orderedPhases) {\n walkPhase(phase);\n // if the phase isn't complete\n if (phase.policies.size > 0 && phase !== noPhase) {\n if (!noPhase.hasRun) {\n // Try running noPhase to see if that unblocks this phase next tick.\n // This can happen if a phase that happens before noPhase\n // is waiting on a noPhase policy to complete.\n walkPhase(noPhase);\n }\n // Don't proceed to the next phase until this phase finishes.\n return;\n }\n\n if (phase.hasAfterPolicies) {\n // Run any policies unblocked by this phase\n walkPhase(noPhase);\n }\n }\n }\n\n // Iterate until we've put every node in the result list.\n let iteration = 0;\n while (policyMap.size > 0) {\n iteration++;\n const initialResultLength = result.length;\n // Keep walking each phase in order until we can order every node.\n walkPhases();\n // The result list *should* get at least one larger each time\n // after the first full pass.\n // Otherwise, we're going to loop forever.\n if (result.length <= initialResultLength && iteration > 1) {\n throw new Error(\"Cannot satisfy policy dependencies due to requirements cycle.\");\n }\n }\n\n return result;\n }\n}\n\n/**\n * Creates a totally empty pipeline.\n * Useful for testing or creating a custom one.\n */\nexport function createEmptyPipeline(): Pipeline {\n return HttpPipeline.create();\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createClientLogger } from \"@azure/logger\";\nexport const logger = createClientLogger(\"core-rest-pipeline\");\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { UnknownObject, isObject } from \"@azure/core-util\";\n\n/**\n * @internal\n */\nexport interface SanitizerOptions {\n /**\n * Header names whose values will be logged when logging is enabled.\n * Defaults include a list of well-known safe headers. Any headers\n * specified in this field will be added to that list. Any other values will\n * be written to logs as \"REDACTED\".\n */\n additionalAllowedHeaderNames?: string[];\n\n /**\n * Query string names whose values will be logged when logging is enabled. By default no\n * query string values are logged.\n */\n additionalAllowedQueryParameters?: string[];\n}\n\nconst RedactedString = \"REDACTED\";\n\n// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts\nconst defaultAllowedHeaderNames = [\n \"x-ms-client-request-id\",\n \"x-ms-return-client-request-id\",\n \"x-ms-useragent\",\n \"x-ms-correlation-request-id\",\n \"x-ms-request-id\",\n \"client-request-id\",\n \"ms-cv\",\n \"return-client-request-id\",\n \"traceparent\",\n\n \"Access-Control-Allow-Credentials\",\n \"Access-Control-Allow-Headers\",\n \"Access-Control-Allow-Methods\",\n \"Access-Control-Allow-Origin\",\n \"Access-Control-Expose-Headers\",\n \"Access-Control-Max-Age\",\n \"Access-Control-Request-Headers\",\n \"Access-Control-Request-Method\",\n \"Origin\",\n\n \"Accept\",\n \"Accept-Encoding\",\n \"Cache-Control\",\n \"Connection\",\n \"Content-Length\",\n \"Content-Type\",\n \"Date\",\n \"ETag\",\n \"Expires\",\n \"If-Match\",\n \"If-Modified-Since\",\n \"If-None-Match\",\n \"If-Unmodified-Since\",\n \"Last-Modified\",\n \"Pragma\",\n \"Request-Id\",\n \"Retry-After\",\n \"Server\",\n \"Transfer-Encoding\",\n \"User-Agent\",\n \"WWW-Authenticate\",\n];\n\nconst defaultAllowedQueryParameters: string[] = [\"api-version\"];\n\n/**\n * @internal\n */\nexport class Sanitizer {\n private allowedHeaderNames: Set<string>;\n private allowedQueryParameters: Set<string>;\n\n constructor({\n additionalAllowedHeaderNames: allowedHeaderNames = [],\n additionalAllowedQueryParameters: allowedQueryParameters = [],\n }: SanitizerOptions = {}) {\n allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);\n allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);\n\n this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));\n this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));\n }\n\n public sanitize(obj: unknown): string {\n const seen = new Set<unknown>();\n return JSON.stringify(\n obj,\n (key: string, value: unknown) => {\n // Ensure Errors include their interesting non-enumerable members\n if (value instanceof Error) {\n return {\n ...value,\n name: value.name,\n message: value.message,\n };\n }\n\n if (key === \"headers\") {\n return this.sanitizeHeaders(value as UnknownObject);\n } else if (key === \"url\") {\n return this.sanitizeUrl(value as string);\n } else if (key === \"query\") {\n return this.sanitizeQuery(value as UnknownObject);\n } else if (key === \"body\") {\n // Don't log the request body\n return undefined;\n } else if (key === \"response\") {\n // Don't log response again\n return undefined;\n } else if (key === \"operationSpec\") {\n // When using sendOperationRequest, the request carries a massive\n // field with the autorest spec. No need to log it.\n return undefined;\n } else if (Array.isArray(value) || isObject(value)) {\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n }\n\n return value;\n },\n 2\n );\n }\n\n private sanitizeHeaders(obj: UnknownObject): UnknownObject {\n const sanitized: UnknownObject = {};\n for (const key of Object.keys(obj)) {\n if (this.allowedHeaderNames.has(key.toLowerCase())) {\n sanitized[key] = obj[key];\n } else {\n sanitized[key] = RedactedString;\n }\n }\n return sanitized;\n }\n\n private sanitizeQuery(value: UnknownObject): UnknownObject {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n\n const sanitized: UnknownObject = {};\n\n for (const k of Object.keys(value)) {\n if (this.allowedQueryParameters.has(k.toLowerCase())) {\n sanitized[k] = value[k];\n } else {\n sanitized[k] = RedactedString;\n }\n }\n\n return sanitized;\n }\n\n private sanitizeUrl(value: string): string {\n if (typeof value !== \"string\" || value === null) {\n return value;\n }\n\n const url = new URL(value);\n\n if (!url.search) {\n return value;\n }\n\n for (const [key] of url.searchParams) {\n if (!this.allowedQueryParameters.has(key.toLowerCase())) {\n url.searchParams.set(key, RedactedString);\n }\n }\n\n return url.toString();\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Debugger } from \"@azure/logger\";\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { logger as coreLogger } from \"../log\";\nimport { Sanitizer } from \"../util/sanitizer\";\n\n/**\n * The programmatic identifier of the logPolicy.\n */\nexport const logPolicyName = \"logPolicy\";\n\n/**\n * Options to configure the logPolicy.\n */\nexport interface LogPolicyOptions {\n /**\n * Header names whose values will be logged when logging is enabled.\n * Defaults include a list of well-known safe headers. Any headers\n * specified in this field will be added to that list. Any other values will\n * be written to logs as \"REDACTED\".\n */\n additionalAllowedHeaderNames?: string[];\n\n /**\n * Query string names whose values will be logged when logging is enabled. By default no\n * query string values are logged.\n */\n additionalAllowedQueryParameters?: string[];\n\n /**\n * The log function to use for writing pipeline logs.\n * Defaults to core-http's built-in logger.\n * Compatible with the `debug` library.\n */\n logger?: Debugger;\n}\n\n/**\n * A policy that logs all requests and responses.\n * @param options - Options to configure logPolicy.\n */\nexport function logPolicy(options: LogPolicyOptions = {}): PipelinePolicy {\n const logger = options.logger ?? coreLogger.info;\n const sanitizer = new Sanitizer({\n additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,\n additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,\n });\n return {\n name: logPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!logger.enabled) {\n return next(request);\n }\n\n logger(`Request: ${sanitizer.sanitize(request)}`);\n\n const response = await next(request);\n\n logger(`Response status code: ${response.status}`);\n logger(`Headers: ${sanitizer.sanitize(response.headers)}`);\n\n return response;\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the redirectPolicy.\n */\nexport const redirectPolicyName = \"redirectPolicy\";\n\n/**\n * Methods that are allowed to follow redirects 301 and 302\n */\nconst allowedRedirect = [\"GET\", \"HEAD\"];\n\n/**\n * Options for how redirect responses are handled.\n */\nexport interface RedirectPolicyOptions {\n /**\n * The maximum number of times the redirect URL will be tried before\n * failing. Defaults to 20.\n */\n maxRetries?: number;\n}\n\n/**\n * A policy to follow Location headers from the server in order\n * to support server-side redirection.\n * In the browser, this policy is not used.\n * @param options - Options to control policy behavior.\n */\nexport function redirectPolicy(options: RedirectPolicyOptions = {}): PipelinePolicy {\n const { maxRetries = 20 } = options;\n return {\n name: redirectPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n const response = await next(request);\n return handleRedirect(next, response, maxRetries);\n },\n };\n}\n\nasync function handleRedirect(\n next: SendRequest,\n response: PipelineResponse,\n maxRetries: number,\n currentRetries: number = 0\n): Promise<PipelineResponse> {\n const { request, status, headers } = response;\n const locationHeader = headers.get(\"location\");\n if (\n locationHeader &&\n (status === 300 ||\n (status === 301 && allowedRedirect.includes(request.method)) ||\n (status === 302 && allowedRedirect.includes(request.method)) ||\n (status === 303 && request.method === \"POST\") ||\n status === 307) &&\n currentRetries < maxRetries\n ) {\n const url = new URL(locationHeader, request.url);\n request.url = url.toString();\n\n // POST request with Status code 303 should be converted into a\n // redirected GET request if the redirect url is present in the location header\n if (status === 303) {\n request.method = \"GET\";\n request.headers.delete(\"Content-Length\");\n delete request.body;\n }\n\n request.headers.delete(\"Authorization\");\n\n const res = await next(request);\n return handleRedirect(next, res, maxRetries, currentRetries + 1);\n }\n\n return response;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as os from \"os\";\n\n/**\n * @internal\n */\nexport function getHeaderName(): string {\n return \"User-Agent\";\n}\n\n/**\n * @internal\n */\nexport function setPlatformSpecificData(map: Map<string, string>): void {\n map.set(\"Node\", process.version);\n map.set(\"OS\", `(${os.arch()}-${os.type()}-${os.release()})`);\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport const SDK_VERSION: string = \"1.12.3\";\n\nexport const DEFAULT_RETRY_POLICY_COUNT = 3;\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { getHeaderName, setPlatformSpecificData } from \"./userAgentPlatform\";\nimport { SDK_VERSION } from \"../constants\";\n\nfunction getUserAgentString(telemetryInfo: Map<string, string>): string {\n const parts: string[] = [];\n for (const [key, value] of telemetryInfo) {\n const token = value ? `${key}/${value}` : key;\n parts.push(token);\n }\n return parts.join(\" \");\n}\n\n/**\n * @internal\n */\nexport function getUserAgentHeaderName(): string {\n return getHeaderName();\n}\n\n/**\n * @internal\n */\nexport function getUserAgentValue(prefix?: string): string {\n const runtimeInfo = new Map<string, string>();\n runtimeInfo.set(\"core-rest-pipeline\", SDK_VERSION);\n setPlatformSpecificData(runtimeInfo);\n const defaultAgent = getUserAgentString(runtimeInfo);\n const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;\n return userAgentValue;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { getUserAgentHeaderName, getUserAgentValue } from \"../util/userAgent\";\n\nconst UserAgentHeaderName = getUserAgentHeaderName();\n\n/**\n * The programmatic identifier of the userAgentPolicy.\n */\nexport const userAgentPolicyName = \"userAgentPolicy\";\n\n/**\n * Options for adding user agent details to outgoing requests.\n */\nexport interface UserAgentPolicyOptions {\n /**\n * String prefix to add to the user agent for outgoing requests.\n * Defaults to an empty string.\n */\n userAgentPrefix?: string;\n}\n\n/**\n * A policy that sets the User-Agent header (or equivalent) to reflect\n * the library version.\n * @param options - Options to customize the user agent value.\n */\nexport function userAgentPolicy(options: UserAgentPolicyOptions = {}): PipelinePolicy {\n const userAgentValue = getUserAgentValue(options.userAgentPrefix);\n return {\n name: userAgentPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!request.headers.has(UserAgentHeaderName)) {\n request.headers.set(UserAgentHeaderName, userAgentValue);\n }\n return next(request);\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the decompressResponsePolicy.\n */\nexport const decompressResponsePolicyName = \"decompressResponsePolicy\";\n\n/**\n * A policy to enable response decompression according to Accept-Encoding header\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding\n */\nexport function decompressResponsePolicy(): PipelinePolicy {\n return {\n name: decompressResponsePolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n // HEAD requests have no body\n if (request.method !== \"HEAD\") {\n request.headers.set(\"Accept-Encoding\", \"gzip,deflate\");\n }\n return next(request);\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError, AbortSignalLike } from \"@azure/abort-controller\";\nimport { PipelineResponse } from \"../interfaces\";\n\nconst StandardAbortMessage = \"The operation was aborted.\";\n\n/**\n * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.\n * @param delayInMs - The number of milliseconds to be delayed.\n * @param value - The value to be resolved with after a timeout of t milliseconds.\n * @param options - The options for delay - currently abort options\n * - abortSignal - The abortSignal associated with containing operation.\n * - abortErrorMsg - The abort error message associated with containing operation.\n * @returns Resolved promise\n */\nexport function delay<T>(\n delayInMs: number,\n value?: T,\n options?: {\n abortSignal?: AbortSignalLike;\n abortErrorMsg?: string;\n }\n): Promise<T | void> {\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined = undefined;\n let onAborted: (() => void) | undefined = undefined;\n\n const rejectOnAbort = (): void => {\n return reject(\n new AbortError(options?.abortErrorMsg ? options?.abortErrorMsg : StandardAbortMessage)\n );\n };\n\n const removeListeners = (): void => {\n if (options?.abortSignal && onAborted) {\n options.abortSignal.removeEventListener(\"abort\", onAborted);\n }\n };\n\n onAborted = (): void => {\n if (timer) {\n clearTimeout(timer);\n }\n removeListeners();\n return rejectOnAbort();\n };\n\n if (options?.abortSignal && options.abortSignal.aborted) {\n return rejectOnAbort();\n }\n\n timer = setTimeout(() => {\n removeListeners();\n resolve(value);\n }, delayInMs);\n\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", onAborted);\n }\n });\n}\n\n/**\n * @internal\n * @returns the parsed value or undefined if the parsed value is invalid.\n */\nexport function parseHeaderValueAsNumber(\n response: PipelineResponse,\n headerName: string\n): number | undefined {\n const value = response.headers.get(headerName);\n if (!value) return;\n const valueAsNum = Number(value);\n if (Number.isNaN(valueAsNum)) return;\n return valueAsNum;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineResponse } from \"..\";\nimport { parseHeaderValueAsNumber } from \"../util/helpers\";\nimport { RetryStrategy } from \"./retryStrategy\";\n\n/**\n * The header that comes back from Azure services representing\n * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry).\n */\nconst RetryAfterHeader = \"Retry-After\";\n/**\n * The headers that come back from Azure services representing\n * the amount of time (minimum) to wait to retry.\n *\n * \"retry-after-ms\", \"x-ms-retry-after-ms\" : milliseconds\n * \"Retry-After\" : seconds or timestamp\n */\nconst AllRetryAfterHeaders: string[] = [\"retry-after-ms\", \"x-ms-retry-after-ms\", RetryAfterHeader];\n\n/**\n * A response is a throttling retry response if it has a throttling status code (429 or 503),\n * as long as one of the [ \"Retry-After\" or \"retry-after-ms\" or \"x-ms-retry-after-ms\" ] headers has a valid value.\n *\n * Returns the `retryAfterInMs` value if the response is a throttling retry response.\n * If not throttling retry response, returns `undefined`.\n *\n * @internal\n */\nfunction getRetryAfterInMs(response?: PipelineResponse): number | undefined {\n if (!(response && [429, 503].includes(response.status))) return undefined;\n try {\n // Headers: \"retry-after-ms\", \"x-ms-retry-after-ms\", \"Retry-After\"\n for (const header of AllRetryAfterHeaders) {\n const retryAfterValue = parseHeaderValueAsNumber(response, header);\n if (retryAfterValue === 0 || retryAfterValue) {\n // \"Retry-After\" header ==> seconds\n // \"retry-after-ms\", \"x-ms-retry-after-ms\" headers ==> milli-seconds\n const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;\n return retryAfterValue * multiplyingFactor; // in milli-seconds\n }\n }\n\n // RetryAfterHeader (\"Retry-After\") has a special case where it might be formatted as a date instead of a number of seconds\n const retryAfterHeader = response.headers.get(RetryAfterHeader);\n if (!retryAfterHeader) return;\n\n const date = Date.parse(retryAfterHeader);\n const diff = date - Date.now();\n // negative diff would mean a date in the past, so retry asap with 0 milliseconds\n return Number.isFinite(diff) ? Math.max(0, diff) : undefined;\n } catch (e: any) {\n return undefined;\n }\n}\n\n/**\n * A response is a retry response if it has a throttling status code (429 or 503),\n * as long as one of the [ \"Retry-After\" or \"retry-after-ms\" or \"x-ms-retry-after-ms\" ] headers has a valid value.\n */\nexport function isThrottlingRetryResponse(response?: PipelineResponse): boolean {\n return Number.isFinite(getRetryAfterInMs(response));\n}\n\nexport function throttlingRetryStrategy(): RetryStrategy {\n return {\n name: \"throttlingRetryStrategy\",\n retry({ response }) {\n const retryAfterInMs = getRetryAfterInMs(response);\n if (!Number.isFinite(retryAfterInMs)) {\n return { skipStrategy: true };\n }\n return {\n retryAfterInMs,\n };\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineResponse } from \"../interfaces\";\nimport { RestError } from \"../restError\";\nimport { getRandomIntegerInclusive } from \"@azure/core-util\";\nimport { RetryStrategy } from \"./retryStrategy\";\nimport { isThrottlingRetryResponse } from \"./throttlingRetryStrategy\";\n\n// intervals are in milliseconds\nconst DEFAULT_CLIENT_RETRY_INTERVAL = 1000;\nconst DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;\n\n/**\n * A retry strategy that retries with an exponentially increasing delay in these two cases:\n * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).\n * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505).\n */\nexport function exponentialRetryStrategy(\n options: {\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second.) The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n\n /**\n * If true it won't retry if it received a system error.\n */\n ignoreSystemErrors?: boolean;\n\n /**\n * If true it won't retry if it received a non-fatal HTTP status code.\n */\n ignoreHttpStatusCodes?: boolean;\n } = {}\n): RetryStrategy {\n const retryInterval = options.retryDelayInMs ?? DEFAULT_CLIENT_RETRY_INTERVAL;\n const maxRetryInterval = options.maxRetryDelayInMs ?? DEFAULT_CLIENT_MAX_RETRY_INTERVAL;\n\n let retryAfterInMs = retryInterval;\n\n return {\n name: \"exponentialRetryStrategy\",\n retry({ retryCount, response, responseError }) {\n const matchedSystemError = isSystemError(responseError);\n const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;\n\n const isExponential = isExponentialRetryResponse(response);\n const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;\n const unknownResponse = response && (isThrottlingRetryResponse(response) || !isExponential);\n\n if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {\n return { skipStrategy: true };\n }\n\n if (responseError && !matchedSystemError && !isExponential) {\n return { errorToThrow: responseError };\n }\n\n // Exponentially increase the delay each time\n const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount);\n // Don't let the delay exceed the maximum\n const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay);\n // Allow the final value to have some \"jitter\" (within 50% of the delay size) so\n // that retries across multiple clients don't occur simultaneously.\n retryAfterInMs =\n clampedExponentialDelay / 2 + getRandomIntegerInclusive(0, clampedExponentialDelay / 2);\n return { retryAfterInMs };\n },\n };\n}\n\n/**\n * A response is a retry response if it has status codes:\n * - 408, or\n * - Greater or equal than 500, except for 501 and 505.\n */\nexport function isExponentialRetryResponse(response?: PipelineResponse): boolean {\n return Boolean(\n response &&\n response.status !== undefined &&\n (response.status >= 500 || response.status === 408) &&\n response.status !== 501 &&\n response.status !== 505\n );\n}\n\n/**\n * Determines whether an error from a pipeline response was triggered in the network layer.\n */\nexport function isSystemError(err?: RestError): boolean {\n if (!err) {\n return false;\n }\n return (\n err.code === \"ETIMEDOUT\" ||\n err.code === \"ESOCKETTIMEDOUT\" ||\n err.code === \"ECONNREFUSED\" ||\n err.code === \"ECONNRESET\" ||\n err.code === \"ENOENT\" ||\n err.code === \"ENOTFOUND\"\n );\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { delay } from \"../util/helpers\";\nimport { createClientLogger } from \"@azure/logger\";\nimport { RetryStrategy } from \"../retryStrategies/retryStrategy\";\nimport { RestError } from \"../restError\";\nimport { AbortError } from \"@azure/abort-controller\";\nimport { AzureLogger } from \"@azure/logger\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\nconst retryPolicyLogger = createClientLogger(\"core-rest-pipeline retryPolicy\");\n\n/**\n * The programmatic identifier of the retryPolicy.\n */\nconst retryPolicyName = \"retryPolicy\";\n\n/**\n * Options to the {@link retryPolicy}\n */\nexport interface RetryPolicyOptions {\n /**\n * Maximum number of retries. If not specified, it will limit to 3 retries.\n */\n maxRetries?: number;\n /**\n * Logger. If it's not provided, a default logger is used.\n */\n logger?: AzureLogger;\n}\n\n/**\n * retryPolicy is a generic policy to enable retrying requests when certain conditions are met\n */\nexport function retryPolicy(\n strategies: RetryStrategy[],\n options: RetryPolicyOptions = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }\n): PipelinePolicy {\n const logger = options.logger || retryPolicyLogger;\n return {\n name: retryPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n let response: PipelineResponse | undefined;\n let responseError: RestError | undefined;\n let retryCount = -1;\n\n // eslint-disable-next-line no-constant-condition\n retryRequest: while (true) {\n retryCount += 1;\n response = undefined;\n responseError = undefined;\n\n try {\n logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);\n response = await next(request);\n logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);\n } catch (e: any) {\n logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);\n\n // RestErrors are valid targets for the retry strategies.\n // If none of the retry strategies can work with them, they will be thrown later in this policy.\n // If the received error is not a RestError, it is immediately thrown.\n responseError = e as RestError;\n if (!e || responseError.name !== \"RestError\") {\n throw e;\n }\n\n response = responseError.response;\n }\n\n if (request.abortSignal?.aborted) {\n logger.error(`Retry ${retryCount}: Request aborted.`);\n const abortError = new AbortError();\n throw abortError;\n }\n\n if (retryCount >= (options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT)) {\n logger.info(\n `Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`\n );\n if (responseError) {\n throw responseError;\n } else if (response) {\n return response;\n } else {\n throw new Error(\"Maximum retries reached with no response or error to throw\");\n }\n }\n\n logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);\n\n strategiesLoop: for (const strategy of strategies) {\n const strategyLogger = strategy.logger || retryPolicyLogger;\n strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);\n\n const modifiers = strategy.retry({\n retryCount,\n response,\n responseError,\n });\n\n if (modifiers.skipStrategy) {\n strategyLogger.info(`Retry ${retryCount}: Skipped.`);\n continue strategiesLoop;\n }\n\n const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;\n\n if (errorToThrow) {\n strategyLogger.error(\n `Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`,\n errorToThrow\n );\n throw errorToThrow;\n }\n\n if (retryAfterInMs || retryAfterInMs === 0) {\n strategyLogger.info(\n `Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`\n );\n await delay(retryAfterInMs, undefined, { abortSignal: request.abortSignal });\n continue retryRequest;\n }\n\n if (redirectTo) {\n strategyLogger.info(\n `Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`\n );\n request.url = redirectTo;\n continue retryRequest;\n }\n }\n\n if (responseError) {\n logger.info(\n `None of the retry strategies could work with the received error. Throwing it.`\n );\n throw responseError;\n }\n if (response) {\n logger.info(\n `None of the retry strategies could work with the received response. Returning it.`\n );\n return response;\n }\n\n // If all the retries skip and there's no response,\n // we're still in the retry loop, so a new request will be sent\n // until `maxRetries` is reached.\n }\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRetryOptions } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { exponentialRetryStrategy } from \"../retryStrategies/exponentialRetryStrategy\";\nimport { throttlingRetryStrategy } from \"../retryStrategies/throttlingRetryStrategy\";\nimport { retryPolicy } from \"./retryPolicy\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\n/**\n * Name of the {@link defaultRetryPolicy}\n */\nexport const defaultRetryPolicyName = \"defaultRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface DefaultRetryPolicyOptions extends PipelineRetryOptions {}\n\n/**\n * A policy that retries according to three strategies:\n * - When the server sends a 429 response with a Retry-After header.\n * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).\n * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.\n */\nexport function defaultRetryPolicy(options: DefaultRetryPolicyOptions = {}): PipelinePolicy {\n return {\n name: defaultRetryPolicyName,\n sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options)], {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }).sendRequest,\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { HttpHeaders, RawHttpHeaders, RawHttpHeadersInput } from \"./interfaces\";\n\ninterface HeaderEntry {\n name: string;\n value: string;\n}\n\nfunction normalizeName(name: string): string {\n return name.toLowerCase();\n}\n\nfunction* headerIterator(map: Map<string, HeaderEntry>): IterableIterator<[string, string]> {\n for (const entry of map.values()) {\n yield [entry.name, entry.value];\n }\n}\n\nclass HttpHeadersImpl implements HttpHeaders {\n private readonly _headersMap: Map<string, HeaderEntry>;\n\n constructor(rawHeaders?: RawHttpHeaders | RawHttpHeadersInput) {\n this._headersMap = new Map<string, HeaderEntry>();\n if (rawHeaders) {\n for (const headerName of Object.keys(rawHeaders)) {\n this.set(headerName, rawHeaders[headerName]);\n }\n }\n }\n\n /**\n * Set a header in this collection with the provided name and value. The name is\n * case-insensitive.\n * @param name - The name of the header to set. This value is case-insensitive.\n * @param value - The value of the header to set.\n */\n public set(name: string, value: string | number | boolean): void {\n this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });\n }\n\n /**\n * Get the header value for the provided header name, or undefined if no header exists in this\n * collection with the provided name.\n * @param name - The name of the header. This value is case-insensitive.\n */\n public get(name: string): string | undefined {\n return this._headersMap.get(normalizeName(name))?.value;\n }\n\n /**\n * Get whether or not this header collection contains a header entry for the provided header name.\n * @param name - The name of the header to set. This value is case-insensitive.\n */\n public has(name: string): boolean {\n return this._headersMap.has(normalizeName(name));\n }\n\n /**\n * Remove the header with the provided headerName.\n * @param name - The name of the header to remove.\n */\n public delete(name: string): void {\n this._headersMap.delete(normalizeName(name));\n }\n\n /**\n * Get the JSON object representation of this HTTP header collection.\n */\n public toJSON(options: { preserveCase?: boolean } = {}): RawHttpHeaders {\n const result: RawHttpHeaders = {};\n if (options.preserveCase) {\n for (const entry of this._headersMap.values()) {\n result[entry.name] = entry.value;\n }\n } else {\n for (const [normalizedName, entry] of this._headersMap) {\n result[normalizedName] = entry.value;\n }\n }\n\n return result;\n }\n\n /**\n * Get the string representation of this HTTP header collection.\n */\n public toString(): string {\n return JSON.stringify(this.toJSON({ preserveCase: true }));\n }\n\n /**\n * Iterate over tuples of header [name, value] pairs.\n */\n [Symbol.iterator](): Iterator<[string, string]> {\n return headerIterator(this._headersMap);\n }\n}\n\n/**\n * Creates an object that satisfies the `HttpHeaders` interface.\n * @param rawHeaders - A simple object representing initial headers\n */\nexport function createHttpHeaders(rawHeaders?: RawHttpHeadersInput): HttpHeaders {\n return new HttpHeadersImpl(rawHeaders);\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { stringToUint8Array } from \"@azure/core-util\";\nimport { createHttpHeaders } from \"../httpHeaders\";\nimport {\n BodyPart,\n FormDataMap,\n PipelineRequest,\n PipelineResponse,\n SendRequest,\n} from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the formDataPolicy.\n */\nexport const formDataPolicyName = \"formDataPolicy\";\n\n/**\n * A policy that encodes FormData on the request into the body.\n */\nexport function formDataPolicy(): PipelinePolicy {\n return {\n name: formDataPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (request.formData) {\n const contentType = request.headers.get(\"Content-Type\");\n if (contentType && contentType.indexOf(\"application/x-www-form-urlencoded\") !== -1) {\n request.body = wwwFormUrlEncode(request.formData);\n } else {\n await prepareFormData(request.formData, request);\n }\n\n request.formData = undefined;\n }\n return next(request);\n },\n };\n}\n\nfunction wwwFormUrlEncode(formData: FormDataMap): string {\n const urlSearchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(formData)) {\n if (Array.isArray(value)) {\n for (const subValue of value) {\n urlSearchParams.append(key, subValue.toString());\n }\n } else {\n urlSearchParams.append(key, value.toString());\n }\n }\n return urlSearchParams.toString();\n}\n\nasync function prepareFormData(formData: FormDataMap, request: PipelineRequest): Promise<void> {\n // validate content type (multipart/form-data)\n const contentType = request.headers.get(\"Content-Type\");\n if (contentType && !contentType.startsWith(\"multipart/form-data\")) {\n // content type is specified and is not multipart/form-data. Exit.\n return;\n }\n\n request.headers.set(\"Content-Type\", contentType ?? \"multipart/form-data\");\n\n // set body to MultipartRequestBody using content from FormDataMap\n const parts: BodyPart[] = [];\n\n for (const [fieldName, values] of Object.entries(formData)) {\n for (const value of Array.isArray(values) ? values : [values]) {\n if (typeof value === \"string\") {\n parts.push({\n headers: createHttpHeaders({\n \"Content-Disposition\": `form-data; name=\"${fieldName}\"`,\n }),\n body: stringToUint8Array(value, \"utf-8\"),\n });\n } else {\n // using || instead of ?? here since if value.name is empty we should create a file name\n const fileName = (value as File).name || \"blob\";\n const headers = createHttpHeaders();\n headers.set(\n \"Content-Disposition\",\n `form-data; name=\"${fieldName}\"; filename=\"${fileName}\"`\n );\n if (value.type) {\n headers.set(\"Content-Type\", value.type);\n }\n\n parts.push({\n headers,\n body: value,\n });\n }\n }\n\n request.multipartBody = { parts };\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as http from \"http\";\nimport * as https from \"https\";\nimport { HttpsProxyAgent, HttpsProxyAgentOptions } from \"https-proxy-agent\";\nimport { HttpProxyAgent, HttpProxyAgentOptions } from \"http-proxy-agent\";\nimport { PipelineRequest, PipelineResponse, ProxySettings, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { logger } from \"../log\";\n\nconst HTTPS_PROXY = \"HTTPS_PROXY\";\nconst HTTP_PROXY = \"HTTP_PROXY\";\nconst ALL_PROXY = \"ALL_PROXY\";\nconst NO_PROXY = \"NO_PROXY\";\n\n/**\n * The programmatic identifier of the proxyPolicy.\n */\nexport const proxyPolicyName = \"proxyPolicy\";\n\n/**\n * Stores the patterns specified in NO_PROXY environment variable.\n * @internal\n */\nexport const globalNoProxyList: string[] = [];\nlet noProxyListLoaded: boolean = false;\n\n/** A cache of whether a host should bypass the proxy. */\nconst globalBypassedMap: Map<string, boolean> = new Map();\n\nfunction getEnvironmentValue(name: string): string | undefined {\n if (process.env[name]) {\n return process.env[name];\n } else if (process.env[name.toLowerCase()]) {\n return process.env[name.toLowerCase()];\n }\n return undefined;\n}\n\nfunction loadEnvironmentProxyValue(): string | undefined {\n if (!process) {\n return undefined;\n }\n\n const httpsProxy = getEnvironmentValue(HTTPS_PROXY);\n const allProxy = getEnvironmentValue(ALL_PROXY);\n const httpProxy = getEnvironmentValue(HTTP_PROXY);\n\n return httpsProxy || allProxy || httpProxy;\n}\n\n/**\n * Check whether the host of a given `uri` matches any pattern in the no proxy list.\n * If there's a match, any request sent to the same host shouldn't have the proxy settings set.\n * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210\n */\nfunction isBypassed(\n uri: string,\n noProxyList: string[],\n bypassedMap?: Map<string, boolean>\n): boolean | undefined {\n if (noProxyList.length === 0) {\n return false;\n }\n const host = new URL(uri).hostname;\n if (bypassedMap?.has(host)) {\n return bypassedMap.get(host);\n }\n let isBypassedFlag = false;\n for (const pattern of noProxyList) {\n if (pattern[0] === \".\") {\n // This should match either domain it self or any subdomain or host\n // .foo.com will match foo.com it self or *.foo.com\n if (host.endsWith(pattern)) {\n isBypassedFlag = true;\n } else {\n if (host.length === pattern.length - 1 && host === pattern.slice(1)) {\n isBypassedFlag = true;\n }\n }\n } else {\n if (host === pattern) {\n isBypassedFlag = true;\n }\n }\n }\n bypassedMap?.set(host, isBypassedFlag);\n return isBypassedFlag;\n}\n\nexport function loadNoProxy(): string[] {\n const noProxy = getEnvironmentValue(NO_PROXY);\n noProxyListLoaded = true;\n if (noProxy) {\n return noProxy\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length);\n }\n\n return [];\n}\n\n/**\n * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.\n * If no argument is given, it attempts to parse a proxy URL from the environment\n * variables `HTTPS_PROXY` or `HTTP_PROXY`.\n * @param proxyUrl - The url of the proxy to use. May contain authentication information.\n */\nexport function getDefaultProxySettings(proxyUrl?: string): ProxySettings | undefined {\n if (!proxyUrl) {\n proxyUrl = loadEnvironmentProxyValue();\n if (!proxyUrl) {\n return undefined;\n }\n }\n\n const parsedUrl = new URL(proxyUrl);\n const schema = parsedUrl.protocol ? parsedUrl.protocol + \"//\" : \"\";\n return {\n host: schema + parsedUrl.hostname,\n port: Number.parseInt(parsedUrl.port || \"80\"),\n username: parsedUrl.username,\n password: parsedUrl.password,\n };\n}\n\n/**\n * @internal\n */\nexport function getProxyAgentOptions(\n proxySettings: ProxySettings,\n { headers, tlsSettings }: PipelineRequest\n): HttpProxyAgentOptions {\n let parsedProxyUrl: URL;\n try {\n parsedProxyUrl = new URL(proxySettings.host);\n } catch (_error) {\n throw new Error(\n `Expecting a valid host string in proxy settings, but found \"${proxySettings.host}\".`\n );\n }\n\n if (tlsSettings) {\n logger.warning(\n \"TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.\"\n );\n }\n\n const proxyAgentOptions: HttpsProxyAgentOptions = {\n hostname: parsedProxyUrl.hostname,\n port: proxySettings.port,\n protocol: parsedProxyUrl.protocol,\n headers: headers.toJSON(),\n };\n if (proxySettings.username && proxySettings.password) {\n proxyAgentOptions.auth = `${proxySettings.username}:${proxySettings.password}`;\n } else if (proxySettings.username) {\n proxyAgentOptions.auth = `${proxySettings.username}`;\n }\n return proxyAgentOptions;\n}\n\nfunction setProxyAgentOnRequest(request: PipelineRequest, cachedAgents: CachedAgents): void {\n // Custom Agent should take precedence so if one is present\n // we should skip to avoid overwriting it.\n if (request.agent) {\n return;\n }\n\n const url = new URL(request.url);\n\n const isInsecure = url.protocol !== \"https:\";\n\n const proxySettings = request.proxySettings;\n if (proxySettings) {\n if (isInsecure) {\n if (!cachedAgents.httpProxyAgent) {\n const proxyAgentOptions = getProxyAgentOptions(proxySettings, request);\n cachedAgents.httpProxyAgent = new HttpProxyAgent(proxyAgentOptions);\n }\n request.agent = cachedAgents.httpProxyAgent;\n } else {\n if (!cachedAgents.httpsProxyAgent) {\n const proxyAgentOptions = getProxyAgentOptions(proxySettings, request);\n cachedAgents.httpsProxyAgent = new HttpsProxyAgent(proxyAgentOptions);\n }\n request.agent = cachedAgents.httpsProxyAgent;\n }\n }\n}\n\ninterface CachedAgents {\n httpsProxyAgent?: https.Agent;\n httpProxyAgent?: http.Agent;\n}\n\n/**\n * A policy that allows one to apply proxy settings to all requests.\n * If not passed static settings, they will be retrieved from the HTTPS_PROXY\n * or HTTP_PROXY environment variables.\n * @param proxySettings - ProxySettings to use on each request.\n * @param options - additional settings, for example, custom NO_PROXY patterns\n */\nexport function proxyPolicy(\n proxySettings = getDefaultProxySettings(),\n options?: {\n /** a list of patterns to override those loaded from NO_PROXY environment variable. */\n customNoProxyList?: string[];\n }\n): PipelinePolicy {\n if (!noProxyListLoaded) {\n globalNoProxyList.push(...loadNoProxy());\n }\n\n const cachedAgents: CachedAgents = {};\n\n return {\n name: proxyPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (\n !request.proxySettings &&\n !isBypassed(\n request.url,\n options?.customNoProxyList ?? globalNoProxyList,\n options?.customNoProxyList ? undefined : globalBypassedMap\n )\n ) {\n request.proxySettings = proxySettings;\n }\n\n if (request.proxySettings) {\n setProxyAgentOnRequest(request, cachedAgents);\n }\n return next(request);\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the setClientRequestIdPolicy.\n */\nexport const setClientRequestIdPolicyName = \"setClientRequestIdPolicy\";\n\n/**\n * Each PipelineRequest gets a unique id upon creation.\n * This policy passes that unique id along via an HTTP header to enable better\n * telemetry and tracing.\n * @param requestIdHeaderName - The name of the header to pass the request ID to.\n */\nexport function setClientRequestIdPolicy(\n requestIdHeaderName = \"x-ms-client-request-id\"\n): PipelinePolicy {\n return {\n name: setClientRequestIdPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!request.headers.has(requestIdHeaderName)) {\n request.headers.set(requestIdHeaderName, request.requestId);\n }\n return next(request);\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelinePolicy } from \"../pipeline\";\nimport { TlsSettings } from \"../interfaces\";\n\n/**\n * Name of the TLS Policy\n */\nexport const tlsPolicyName = \"tlsPolicy\";\n\n/**\n * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.\n */\nexport function tlsPolicy(tlsSettings?: TlsSettings): PipelinePolicy {\n return {\n name: tlsPolicyName,\n sendRequest: async (req, next) => {\n // Users may define a request tlsSettings, honor those over the client level one\n if (!req.tlsSettings) {\n req.tlsSettings = tlsSettings;\n }\n return next(req);\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { inspect } from \"util\";\n\nexport const custom = inspect.custom;\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { isError } from \"@azure/core-util\";\nimport { PipelineRequest, PipelineResponse } from \"./interfaces\";\nimport { custom } from \"./util/inspect\";\nimport { Sanitizer } from \"./util/sanitizer\";\n\nconst errorSanitizer = new Sanitizer();\n\n/**\n * The options supported by RestError.\n */\nexport interface RestErrorOptions {\n /**\n * The code of the error itself (use statics on RestError if possible.)\n */\n code?: string;\n /**\n * The HTTP status code of the request (if applicable.)\n */\n statusCode?: number;\n /**\n * The request that was made.\n */\n request?: PipelineRequest;\n /**\n * The response received (if any.)\n */\n response?: PipelineResponse;\n}\n\n/**\n * A custom error type for failed pipeline requests.\n */\nexport class RestError extends Error {\n /**\n * Something went wrong when making the request.\n * This means the actual request failed for some reason,\n * such as a DNS issue or the connection being lost.\n */\n static readonly REQUEST_SEND_ERROR: string = \"REQUEST_SEND_ERROR\";\n /**\n * This means that parsing the response from the server failed.\n * It may have been malformed.\n */\n static readonly PARSE_ERROR: string = \"PARSE_ERROR\";\n\n /**\n * The code of the error itself (use statics on RestError if possible.)\n */\n public code?: string;\n /**\n * The HTTP status code of the request (if applicable.)\n */\n public statusCode?: number;\n /**\n * The request that was made.\n */\n public request?: PipelineRequest;\n /**\n * The response received (if any.)\n */\n public response?: PipelineResponse;\n /**\n * Bonus property set by the throw site.\n */\n public details?: unknown;\n\n constructor(message: string, options: RestErrorOptions = {}) {\n super(message);\n this.name = \"RestError\";\n this.code = options.code;\n this.statusCode = options.statusCode;\n this.request = options.request;\n this.response = options.response;\n\n Object.setPrototypeOf(this, RestError.prototype);\n }\n\n /**\n * Logging method for util.inspect in Node\n */\n [custom](): string {\n return `RestError: ${this.message} \\n ${errorSanitizer.sanitize(this)}`;\n }\n}\n\n/**\n * Typeguard for RestError\n * @param e - Something caught by a catch clause.\n */\nexport function isRestError(e: unknown): e is RestError {\n if (e instanceof RestError) {\n return true;\n }\n return isError(e) && e.name === \"RestError\";\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n TracingClient,\n TracingContext,\n TracingSpan,\n createTracingClient,\n} from \"@azure/core-tracing\";\nimport { SDK_VERSION } from \"../constants\";\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { getUserAgentValue } from \"../util/userAgent\";\nimport { logger } from \"../log\";\nimport { getErrorMessage, isError } from \"@azure/core-util\";\nimport { isRestError } from \"../restError\";\n\n/**\n * The programmatic identifier of the tracingPolicy.\n */\nexport const tracingPolicyName = \"tracingPolicy\";\n\n/**\n * Options to configure the tracing policy.\n */\nexport interface TracingPolicyOptions {\n /**\n * String prefix to add to the user agent logged as metadata\n * on the generated Span.\n * Defaults to an empty string.\n */\n userAgentPrefix?: string;\n}\n\n/**\n * A simple policy to create OpenTelemetry Spans for each request made by the pipeline\n * that has SpanOptions with a parent.\n * Requests made without a parent Span will not be recorded.\n * @param options - Options to configure the telemetry logged by the tracing policy.\n */\nexport function tracingPolicy(options: TracingPolicyOptions = {}): PipelinePolicy {\n const userAgent = getUserAgentValue(options.userAgentPrefix);\n const tracingClient = tryCreateTracingClient();\n\n return {\n name: tracingPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!tracingClient || !request.tracingOptions?.tracingContext) {\n return next(request);\n }\n\n const { span, tracingContext } = tryCreateSpan(tracingClient, request, userAgent) ?? {};\n\n if (!span || !tracingContext) {\n return next(request);\n }\n\n try {\n const response = await tracingClient.withContext(tracingContext, next, request);\n tryProcessResponse(span, response);\n return response;\n } catch (err: any) {\n tryProcessError(span, err);\n throw err;\n }\n },\n };\n}\n\nfunction tryCreateTracingClient(): TracingClient | undefined {\n try {\n return createTracingClient({\n namespace: \"\",\n packageName: \"@azure/core-rest-pipeline\",\n packageVersion: SDK_VERSION,\n });\n } catch (e: unknown) {\n logger.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`);\n return undefined;\n }\n}\n\nfunction tryCreateSpan(\n tracingClient: TracingClient,\n request: PipelineRequest,\n userAgent?: string\n): { span: TracingSpan; tracingContext: TracingContext } | undefined {\n try {\n // As per spec, we do not need to differentiate between HTTP and HTTPS in span name.\n const { span, updatedOptions } = tracingClient.startSpan(\n `HTTP ${request.method}`,\n { tracingOptions: request.tracingOptions },\n {\n spanKind: \"client\",\n spanAttributes: {\n \"http.method\": request.method,\n \"http.url\": request.url,\n requestId: request.requestId,\n },\n }\n );\n\n // If the span is not recording, don't do any more work.\n if (!span.isRecording()) {\n span.end();\n return undefined;\n }\n\n if (userAgent) {\n span.setAttribute(\"http.user_agent\", userAgent);\n }\n\n // set headers\n const headers = tracingClient.createRequestHeaders(\n updatedOptions.tracingOptions.tracingContext\n );\n for (const [key, value] of Object.entries(headers)) {\n request.headers.set(key, value);\n }\n return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };\n } catch (e: any) {\n logger.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`);\n return undefined;\n }\n}\n\nfunction tryProcessError(span: TracingSpan, error: unknown): void {\n try {\n span.setStatus({\n status: \"error\",\n error: isError(error) ? error : undefined,\n });\n if (isRestError(error) && error.statusCode) {\n span.setAttribute(\"http.status_code\", error.statusCode);\n }\n span.end();\n } catch (e: any) {\n logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);\n }\n}\n\nfunction tryProcessResponse(span: TracingSpan, response: PipelineResponse): void {\n try {\n span.setAttribute(\"http.status_code\", response.status);\n const serviceRequestId = response.headers.get(\"x-ms-request-id\");\n if (serviceRequestId) {\n span.setAttribute(\"serviceRequestId\", serviceRequestId);\n }\n span.setStatus({\n status: \"success\",\n });\n span.end();\n } catch (e: any) {\n logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport function isNodeReadableStream(x: unknown): x is NodeJS.ReadableStream {\n return Boolean(x && typeof (x as NodeJS.ReadableStream)[\"pipe\"] === \"function\");\n}\n\nexport function isWebReadableStream(x: unknown): x is ReadableStream {\n return Boolean(\n x &&\n typeof (x as ReadableStream).getReader === \"function\" &&\n typeof (x as ReadableStream).tee === \"function\"\n );\n}\n\nexport function isReadableStream(x: unknown): x is ReadableStream | NodeJS.ReadableStream {\n return isNodeReadableStream(x) || isWebReadableStream(x);\n}\n\nexport function isBlob(x: unknown): x is Blob {\n return typeof (x as Blob).stream === \"function\";\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Readable } from \"stream\";\nimport { ReadableStream as AsyncIterableReadableStream } from \"stream/web\";\nimport { isBlob, isNodeReadableStream, isWebReadableStream } from \"./typeGuards\";\n\nasync function* streamAsyncIterator(\n this: ReadableStream<Uint8Array>\n): AsyncIterableIterator<Uint8Array> {\n const reader = this.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nfunction makeAsyncIterable<T>(webStream: any): asserts webStream is AsyncIterableReadableStream<T> {\n if (!webStream[Symbol.asyncIterator]) {\n webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);\n }\n\n if (!webStream.values) {\n webStream.values = streamAsyncIterator.bind(webStream);\n }\n}\n\nfunction nodeStreamFromWebStream(webStream: ReadableStream<Uint8Array>): NodeJS.ReadableStream {\n makeAsyncIterable<Uint8Array>(webStream);\n return Readable.fromWeb(webStream);\n}\n\nexport function toWebStream(\n stream: ReadableStream<Uint8Array> | NodeJS.ReadableStream\n): ReadableStream<Uint8Array> {\n return isWebReadableStream(stream)\n ? stream\n : (Readable.toWeb(Readable.from(stream)) as ReadableStream<Uint8Array>);\n}\n\nexport function toStream(\n source: ReadableStream<Uint8Array> | NodeJS.ReadableStream | Uint8Array | Blob\n): NodeJS.ReadableStream | ReadableStream<Uint8Array> {\n if (source instanceof Uint8Array) {\n return Readable.from(Buffer.from(source));\n } else if (isBlob(source)) {\n return nodeStreamFromWebStream(source.stream());\n } else if (isNodeReadableStream(source)) {\n return source;\n } else {\n return nodeStreamFromWebStream(source);\n }\n}\n\nexport function concatenateStreams(\n sources: (ReadableStream<Uint8Array> | NodeJS.ReadableStream)[]\n): ReadableStream<Uint8Array> | NodeJS.ReadableStream {\n if (sources.some(isWebReadableStream)) {\n throw new Error(\"Was not expecting a Web stream here\");\n }\n\n return Readable.from(\n (async function* () {\n for (const stream of sources as NodeJS.ReadableStream[]) {\n for await (const chunk of stream) {\n yield chunk;\n }\n }\n })()\n );\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { randomUUID, stringToUint8Array } from \"@azure/core-util\";\nimport { BodyPart, HttpHeaders, PipelineRequest, RequestBodyType } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { toStream, concatenateStreams } from \"../util/stream\";\nimport { isBlob } from \"../util/typeGuards\";\n\nfunction generateBoundary(): string {\n return `----AzSDKFormBoundary${randomUUID()}`;\n}\n\nfunction encodeHeaders(headers: HttpHeaders): string {\n let result = \"\";\n for (const [key, value] of headers) {\n result += `${key}: ${value}\\r\\n`;\n }\n return result;\n}\n\nfunction getLength(\n source:\n | (() => ReadableStream<Uint8Array>)\n | (() => NodeJS.ReadableStream)\n | Uint8Array\n | Blob\n | ReadableStream\n | NodeJS.ReadableStream\n): number | undefined {\n if (source instanceof Uint8Array) {\n return source.byteLength;\n } else if (isBlob(source)) {\n // if was created using createFile then -1 means we have an unknown size\n return source.size === -1 ? undefined : source.size;\n } else {\n return undefined;\n }\n}\n\nfunction getTotalLength(\n sources: (\n | (() => ReadableStream<Uint8Array>)\n | (() => NodeJS.ReadableStream)\n | Uint8Array\n | Blob\n | ReadableStream\n | NodeJS.ReadableStream\n )[]\n): number | undefined {\n let total = 0;\n for (const source of sources) {\n const partLength = getLength(source);\n if (partLength === undefined) {\n return undefined;\n } else {\n total += partLength;\n }\n }\n return total;\n}\n\nfunction buildRequestBody(request: PipelineRequest, parts: BodyPart[], boundary: string): void {\n const sources = [\n stringToUint8Array(`--${boundary}`, \"utf-8\"),\n ...parts.flatMap((part) => [\n stringToUint8Array(\"\\r\\n\", \"utf-8\"),\n stringToUint8Array(encodeHeaders(part.headers), \"utf-8\"),\n stringToUint8Array(\"\\r\\n\", \"utf-8\"),\n part.body,\n stringToUint8Array(`\\r\\n--${boundary}`, \"utf-8\"),\n ]),\n stringToUint8Array(\"--\\r\\n\\r\\n\", \"utf-8\"),\n ];\n\n const contentLength = getTotalLength(sources);\n if (contentLength) {\n request.headers.set(\"Content-Length\", contentLength);\n }\n\n request.body = (() =>\n concatenateStreams(\n sources.map((source) => (typeof source === \"function\" ? source() : source)).map(toStream)\n )) as RequestBodyType;\n}\n\n/**\n * Name of multipart policy\n */\nexport const multipartPolicyName = \"multipartPolicy\";\n\nconst maxBoundaryLength = 70;\nconst validBoundaryCharacters = new Set(\n `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`\n);\n\nfunction assertValidBoundary(boundary: string): void {\n if (boundary.length > maxBoundaryLength) {\n throw new Error(`Multipart boundary \"${boundary}\" exceeds maximum length of 70 characters`);\n }\n\n if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {\n throw new Error(`Multipart boundary \"${boundary}\" contains invalid characters`);\n }\n}\n\n/**\n * Pipeline policy for multipart requests\n */\nexport function multipartPolicy(): PipelinePolicy {\n return {\n name: multipartPolicyName,\n sendRequest(request, next) {\n if (!request.multipartBody) {\n return next(request);\n }\n\n if (request.body) {\n throw new Error(\"multipartBody and regular body cannot be set at the same time\");\n }\n\n let boundary = request.multipartBody.boundary;\n\n const contentTypeHeader = request.headers.get(\"Content-Type\") ?? \"multipart/mixed\";\n const parsedHeader = contentTypeHeader.match(/^(multipart\\/[^ ;]+)(?:; *boundary=(.+))?$/);\n if (!parsedHeader) {\n throw new Error(\n `Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`\n );\n }\n\n const [, contentType, parsedBoundary] = parsedHeader;\n if (parsedBoundary && boundary && parsedBoundary !== boundary) {\n throw new Error(\n `Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`\n );\n }\n\n boundary ??= parsedBoundary;\n if (boundary) {\n assertValidBoundary(boundary);\n } else {\n boundary = generateBoundary();\n }\n request.headers.set(\"Content-Type\", `${contentType}; boundary=${boundary}`);\n buildRequestBody(request, request.multipartBody.parts, boundary);\n\n request.multipartBody = undefined;\n\n return next(request);\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { LogPolicyOptions, logPolicy } from \"./policies/logPolicy\";\nimport { Pipeline, createEmptyPipeline } from \"./pipeline\";\nimport { PipelineRetryOptions, TlsSettings } from \"./interfaces\";\nimport { RedirectPolicyOptions, redirectPolicy } from \"./policies/redirectPolicy\";\nimport { UserAgentPolicyOptions, userAgentPolicy } from \"./policies/userAgentPolicy\";\n\nimport { ProxySettings } from \".\";\nimport { decompressResponsePolicy } from \"./policies/decompressResponsePolicy\";\nimport { defaultRetryPolicy } from \"./policies/defaultRetryPolicy\";\nimport { formDataPolicy } from \"./policies/formDataPolicy\";\nimport { isNode } from \"@azure/core-util\";\nimport { proxyPolicy } from \"./policies/proxyPolicy\";\nimport { setClientRequestIdPolicy } from \"./policies/setClientRequestIdPolicy\";\nimport { tlsPolicy } from \"./policies/tlsPolicy\";\nimport { tracingPolicy } from \"./policies/tracingPolicy\";\nimport { multipartPolicy } from \"./policies/multipartPolicy\";\n\n/**\n * Defines options that are used to configure the HTTP pipeline for\n * an SDK client.\n */\nexport interface PipelineOptions {\n /**\n * Options that control how to retry failed requests.\n */\n retryOptions?: PipelineRetryOptions;\n\n /**\n * Options to configure a proxy for outgoing requests.\n */\n proxyOptions?: ProxySettings;\n\n /** Options for configuring TLS authentication */\n tlsOptions?: TlsSettings;\n\n /**\n * Options for how redirect responses are handled.\n */\n redirectOptions?: RedirectPolicyOptions;\n\n /**\n * Options for adding user agent details to outgoing requests.\n */\n userAgentOptions?: UserAgentPolicyOptions;\n\n /**\n * Options for setting common telemetry and tracing info to outgoing requests.\n */\n telemetryOptions?: TelemetryOptions;\n}\n\n/**\n * Defines options that are used to configure common telemetry and tracing info\n */\nexport interface TelemetryOptions {\n /**\n * The name of the header to pass the request ID to.\n */\n clientRequestIdHeaderName?: string;\n}\n\n/**\n * Defines options that are used to configure internal options of\n * the HTTP pipeline for an SDK client.\n */\nexport interface InternalPipelineOptions extends PipelineOptions {\n /**\n * Options to configure request/response logging.\n */\n loggingOptions?: LogPolicyOptions;\n}\n\n/**\n * Create a new pipeline with a default set of customizable policies.\n * @param options - Options to configure a custom pipeline.\n */\nexport function createPipelineFromOptions(options: InternalPipelineOptions): Pipeline {\n const pipeline = createEmptyPipeline();\n\n if (isNode) {\n if (options.tlsOptions) {\n pipeline.addPolicy(tlsPolicy(options.tlsOptions));\n }\n pipeline.addPolicy(proxyPolicy(options.proxyOptions));\n pipeline.addPolicy(decompressResponsePolicy());\n }\n\n pipeline.addPolicy(formDataPolicy());\n pipeline.addPolicy(userAgentPolicy(options.userAgentOptions));\n pipeline.addPolicy(setClientRequestIdPolicy(options.telemetryOptions?.clientRequestIdHeaderName));\n // The multipart policy is added after policies with no phase, so that\n // policies can be added between it and formDataPolicy to modify\n // properties (e.g., making the boundary constant in recorded tests).\n pipeline.addPolicy(multipartPolicy(), { afterPhase: \"Deserialize\" });\n pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: \"Retry\" });\n pipeline.addPolicy(tracingPolicy(options.userAgentOptions), { afterPhase: \"Retry\" });\n if (isNode) {\n // Both XHR and Fetch expect to handle redirects automatically,\n // so only include this policy when we're in Node.\n pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: \"Retry\" });\n }\n pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: \"Sign\" });\n\n return pipeline;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as http from \"http\";\nimport * as https from \"https\";\nimport * as zlib from \"zlib\";\nimport { Transform } from \"stream\";\nimport { AbortError } from \"@azure/abort-controller\";\nimport {\n HttpClient,\n HttpHeaders,\n PipelineRequest,\n PipelineResponse,\n RequestBodyType,\n TlsSettings,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { createHttpHeaders } from \"./httpHeaders\";\nimport { RestError } from \"./restError\";\nimport { IncomingMessage } from \"http\";\nimport { logger } from \"./log\";\n\nconst DEFAULT_TLS_SETTINGS = {};\n\nfunction isReadableStream(body: any): body is NodeJS.ReadableStream {\n return body && typeof body.pipe === \"function\";\n}\n\nfunction isStreamComplete(stream: NodeJS.ReadableStream): Promise<void> {\n return new Promise((resolve) => {\n stream.on(\"close\", resolve);\n stream.on(\"end\", resolve);\n stream.on(\"error\", resolve);\n });\n}\n\nfunction isArrayBuffer(body: any): body is ArrayBuffer | ArrayBufferView {\n return body && typeof body.byteLength === \"number\";\n}\n\nclass ReportTransform extends Transform {\n private loadedBytes = 0;\n private progressCallback: (progress: TransferProgressEvent) => void;\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n _transform(chunk: string | Buffer, _encoding: string, callback: Function): void {\n this.push(chunk);\n this.loadedBytes += chunk.length;\n try {\n this.progressCallback({ loadedBytes: this.loadedBytes });\n callback();\n } catch (e: any) {\n callback(e);\n }\n }\n\n constructor(progressCallback: (progress: TransferProgressEvent) => void) {\n super();\n this.progressCallback = progressCallback;\n }\n}\n\n/**\n * A HttpClient implementation that uses Node's \"https\" module to send HTTPS requests.\n * @internal\n */\nclass NodeHttpClient implements HttpClient {\n private cachedHttpAgent?: http.Agent;\n private cachedHttpsAgents: WeakMap<TlsSettings, https.Agent> = new WeakMap();\n\n /**\n * Makes a request over an underlying transport layer and returns the response.\n * @param request - The request to be made.\n */\n public async sendRequest(request: PipelineRequest): Promise<PipelineResponse> {\n const abortController = new AbortController();\n let abortListener: ((event: any) => void) | undefined;\n if (request.abortSignal) {\n if (request.abortSignal.aborted) {\n throw new AbortError(\"The operation was aborted.\");\n }\n\n abortListener = (event: Event) => {\n if (event.type === \"abort\") {\n abortController.abort();\n }\n };\n request.abortSignal.addEventListener(\"abort\", abortListener);\n }\n\n if (request.timeout > 0) {\n setTimeout(() => {\n abortController.abort();\n }, request.timeout);\n }\n\n const acceptEncoding = request.headers.get(\"Accept-Encoding\");\n const shouldDecompress =\n acceptEncoding?.includes(\"gzip\") || acceptEncoding?.includes(\"deflate\");\n\n let body = typeof request.body === \"function\" ? request.body() : request.body;\n if (body && !request.headers.has(\"Content-Length\")) {\n const bodyLength = getBodyLength(body);\n if (bodyLength !== null) {\n request.headers.set(\"Content-Length\", bodyLength);\n }\n }\n\n let responseStream: NodeJS.ReadableStream | undefined;\n try {\n if (body && request.onUploadProgress) {\n const onUploadProgress = request.onUploadProgress;\n const uploadReportStream = new ReportTransform(onUploadProgress);\n uploadReportStream.on(\"error\", (e) => {\n logger.error(\"Error in upload progress\", e);\n });\n if (isReadableStream(body)) {\n body.pipe(uploadReportStream);\n } else {\n uploadReportStream.end(body);\n }\n\n body = uploadReportStream;\n }\n\n const res = await this.makeRequest(request, abortController, body);\n\n const headers = getResponseHeaders(res);\n\n const status = res.statusCode ?? 0;\n const response: PipelineResponse = {\n status,\n headers,\n request,\n };\n\n // Responses to HEAD must not have a body.\n // If they do return a body, that body must be ignored.\n if (request.method === \"HEAD\") {\n // call resume() and not destroy() to avoid closing the socket\n // and losing keep alive\n res.resume();\n return response;\n }\n\n responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;\n\n const onDownloadProgress = request.onDownloadProgress;\n if (onDownloadProgress) {\n const downloadReportStream = new ReportTransform(onDownloadProgress);\n downloadReportStream.on(\"error\", (e) => {\n logger.error(\"Error in download progress\", e);\n });\n responseStream.pipe(downloadReportStream);\n responseStream = downloadReportStream;\n }\n\n if (\n // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code\n request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||\n request.streamResponseStatusCodes?.has(response.status)\n ) {\n response.readableStreamBody = responseStream;\n } else {\n response.bodyAsText = await streamToText(responseStream);\n }\n\n return response;\n } finally {\n // clean up event listener\n if (request.abortSignal && abortListener) {\n let uploadStreamDone = Promise.resolve();\n if (isReadableStream(body)) {\n uploadStreamDone = isStreamComplete(body as NodeJS.ReadableStream);\n }\n let downloadStreamDone = Promise.resolve();\n if (isReadableStream(responseStream)) {\n downloadStreamDone = isStreamComplete(responseStream);\n }\n\n Promise.all([uploadStreamDone, downloadStreamDone])\n .then(() => {\n // eslint-disable-next-line promise/always-return\n if (abortListener) {\n request.abortSignal?.removeEventListener(\"abort\", abortListener);\n }\n })\n .catch((e) => {\n logger.warning(\"Error when cleaning up abortListener on httpRequest\", e);\n });\n }\n }\n }\n\n private makeRequest(\n request: PipelineRequest,\n abortController: AbortController,\n body?: RequestBodyType\n ): Promise<http.IncomingMessage> {\n const url = new URL(request.url);\n\n const isInsecure = url.protocol !== \"https:\";\n\n if (isInsecure && !request.allowInsecureConnection) {\n throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);\n }\n\n const agent = (request.agent as http.Agent) ?? this.getOrCreateAgent(request, isInsecure);\n const options: http.RequestOptions = {\n agent,\n hostname: url.hostname,\n path: `${url.pathname}${url.search}`,\n port: url.port,\n method: request.method,\n headers: request.headers.toJSON({ preserveCase: true }),\n };\n\n return new Promise<http.IncomingMessage>((resolve, reject) => {\n const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve);\n\n req.once(\"error\", (err: Error & { code?: string }) => {\n reject(\n new RestError(err.message, { code: err.code ?? RestError.REQUEST_SEND_ERROR, request })\n );\n });\n\n abortController.signal.addEventListener(\"abort\", () => {\n const abortError = new AbortError(\"The operation was aborted.\");\n req.destroy(abortError);\n reject(abortError);\n });\n if (body && isReadableStream(body)) {\n body.pipe(req);\n } else if (body) {\n if (typeof body === \"string\" || Buffer.isBuffer(body)) {\n req.end(body);\n } else if (isArrayBuffer(body)) {\n req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));\n } else {\n logger.error(\"Unrecognized body type\", body);\n reject(new RestError(\"Unrecognized body type\"));\n }\n } else {\n // streams don't like \"undefined\" being passed as data\n req.end();\n }\n });\n }\n\n private getOrCreateAgent(request: PipelineRequest, isInsecure: boolean): http.Agent {\n const disableKeepAlive = request.disableKeepAlive;\n\n // Handle Insecure requests first\n if (isInsecure) {\n if (disableKeepAlive) {\n // keepAlive:false is the default so we don't need a custom Agent\n return http.globalAgent;\n }\n\n if (!this.cachedHttpAgent) {\n // If there is no cached agent create a new one and cache it.\n this.cachedHttpAgent = new http.Agent({ keepAlive: true });\n }\n return this.cachedHttpAgent;\n } else {\n if (disableKeepAlive && !request.tlsSettings) {\n // When there are no tlsSettings and keepAlive is false\n // we don't need a custom agent\n return https.globalAgent;\n }\n\n // We use the tlsSettings to index cached clients\n const tlsSettings = request.tlsSettings ?? DEFAULT_TLS_SETTINGS;\n\n // Get the cached agent or create a new one with the\n // provided values for keepAlive and tlsSettings\n let agent = this.cachedHttpsAgents.get(tlsSettings);\n\n if (agent && agent.options.keepAlive === !disableKeepAlive) {\n return agent;\n }\n\n logger.info(\"No cached TLS Agent exist, creating a new Agent\");\n agent = new https.Agent({\n // keepAlive is true if disableKeepAlive is false.\n keepAlive: !disableKeepAlive,\n // Since we are spreading, if no tslSettings were provided, nothing is added to the agent options.\n ...tlsSettings,\n });\n\n this.cachedHttpsAgents.set(tlsSettings, agent);\n return agent;\n }\n }\n}\n\nfunction getResponseHeaders(res: IncomingMessage): HttpHeaders {\n const headers = createHttpHeaders();\n for (const header of Object.keys(res.headers)) {\n const value = res.headers[header];\n if (Array.isArray(value)) {\n if (value.length > 0) {\n headers.set(header, value[0]);\n }\n } else if (value) {\n headers.set(header, value);\n }\n }\n return headers;\n}\n\nfunction getDecodedResponseStream(\n stream: IncomingMessage,\n headers: HttpHeaders\n): NodeJS.ReadableStream {\n const contentEncoding = headers.get(\"Content-Encoding\");\n if (contentEncoding === \"gzip\") {\n const unzip = zlib.createGunzip();\n stream.pipe(unzip);\n return unzip;\n } else if (contentEncoding === \"deflate\") {\n const inflate = zlib.createInflate();\n stream.pipe(inflate);\n return inflate;\n }\n\n return stream;\n}\n\nfunction streamToText(stream: NodeJS.ReadableStream): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const buffer: Buffer[] = [];\n\n stream.on(\"data\", (chunk) => {\n if (Buffer.isBuffer(chunk)) {\n buffer.push(chunk);\n } else {\n buffer.push(Buffer.from(chunk));\n }\n });\n stream.on(\"end\", () => {\n resolve(Buffer.concat(buffer).toString(\"utf8\"));\n });\n stream.on(\"error\", (e) => {\n if (e && e?.name === \"AbortError\") {\n reject(e);\n } else {\n reject(\n new RestError(`Error reading response as text: ${e.message}`, {\n code: RestError.PARSE_ERROR,\n })\n );\n }\n });\n });\n}\n\n/** @internal */\nexport function getBodyLength(body: RequestBodyType): number | null {\n if (!body) {\n return 0;\n } else if (Buffer.isBuffer(body)) {\n return body.length;\n } else if (isReadableStream(body)) {\n return null;\n } else if (isArrayBuffer(body)) {\n return body.byteLength;\n } else if (typeof body === \"string\") {\n return Buffer.from(body).length;\n } else {\n return null;\n }\n}\n\n/**\n * Create a new HttpClient instance for the NodeJS environment.\n * @internal\n */\nexport function createNodeHttpClient(): HttpClient {\n return new NodeHttpClient();\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { HttpClient } from \"./interfaces\";\nimport { createNodeHttpClient } from \"./nodeHttpClient\";\n\n/**\n * Create the correct HttpClient for the current environment.\n */\nexport function createDefaultHttpClient(): HttpClient {\n return createNodeHttpClient();\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n FormDataMap,\n HttpHeaders,\n HttpMethods,\n MultipartRequestBody,\n PipelineRequest,\n ProxySettings,\n RequestBodyType,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { createHttpHeaders } from \"./httpHeaders\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { randomUUID } from \"@azure/core-util\";\nimport { OperationTracingOptions } from \"@azure/core-tracing\";\n\n/**\n * Settings to initialize a request.\n * Almost equivalent to Partial<PipelineRequest>, but url is mandatory.\n */\nexport interface PipelineRequestOptions {\n /**\n * The URL to make the request to.\n */\n url: string;\n\n /**\n * The HTTP method to use when making the request.\n */\n method?: HttpMethods;\n\n /**\n * The HTTP headers to use when making the request.\n */\n headers?: HttpHeaders;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n * If the request is terminated, an `AbortError` is thrown.\n * Defaults to 0, which disables the timeout.\n */\n timeout?: number;\n\n /**\n * If credentials (cookies) should be sent along during an XHR.\n * Defaults to false.\n */\n withCredentials?: boolean;\n\n /**\n * A unique identifier for the request. Used for logging and tracing.\n */\n requestId?: string;\n\n /**\n * The HTTP body content (if any)\n */\n body?: RequestBodyType;\n\n /**\n * Body for a multipart request.\n */\n multipartBody?: MultipartRequestBody;\n\n /**\n * To simulate a browser form post\n */\n formData?: FormDataMap;\n\n /**\n * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.\n */\n streamResponseStatusCodes?: Set<number>;\n\n /**\n * BROWSER ONLY\n *\n * A browser only option to enable use of the Streams API. If this option is set and streaming is used\n * (see `streamResponseStatusCodes`), the response will have a property `browserStream` instead of\n * `blobBody` which will be undefined.\n *\n * Default value is false\n */\n enableBrowserStreams?: boolean;\n\n /**\n * Proxy configuration.\n */\n proxySettings?: ProxySettings;\n\n /**\n * If the connection should not be reused.\n */\n disableKeepAlive?: boolean;\n\n /**\n * Used to abort the request later.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * Options used to create a span when tracing is enabled.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Callback which fires upon download progress. */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Set to true if the request is sent over HTTP instead of HTTPS */\n allowInsecureConnection?: boolean;\n}\n\nclass PipelineRequestImpl implements PipelineRequest {\n public url: string;\n public method: HttpMethods;\n public headers: HttpHeaders;\n public timeout: number;\n public withCredentials: boolean;\n public body?: RequestBodyType;\n public multipartBody?: MultipartRequestBody;\n public formData?: FormDataMap;\n public streamResponseStatusCodes?: Set<number>;\n public enableBrowserStreams: boolean;\n\n public proxySettings?: ProxySettings;\n public disableKeepAlive: boolean;\n public abortSignal?: AbortSignalLike;\n public requestId: string;\n public tracingOptions?: OperationTracingOptions;\n public allowInsecureConnection?: boolean;\n public onUploadProgress?: (progress: TransferProgressEvent) => void;\n public onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n constructor(options: PipelineRequestOptions) {\n this.url = options.url;\n this.body = options.body;\n this.headers = options.headers ?? createHttpHeaders();\n this.method = options.method ?? \"GET\";\n this.timeout = options.timeout ?? 0;\n this.multipartBody = options.multipartBody;\n this.formData = options.formData;\n this.disableKeepAlive = options.disableKeepAlive ?? false;\n this.proxySettings = options.proxySettings;\n this.streamResponseStatusCodes = options.streamResponseStatusCodes;\n this.withCredentials = options.withCredentials ?? false;\n this.abortSignal = options.abortSignal;\n this.tracingOptions = options.tracingOptions;\n this.onUploadProgress = options.onUploadProgress;\n this.onDownloadProgress = options.onDownloadProgress;\n this.requestId = options.requestId || randomUUID();\n this.allowInsecureConnection = options.allowInsecureConnection ?? false;\n this.enableBrowserStreams = options.enableBrowserStreams ?? false;\n }\n}\n\n/**\n * Creates a new pipeline request with the given options.\n * This method is to allow for the easy setting of default values and not required.\n * @param options - The options to create the request with.\n */\nexport function createPipelineRequest(options: PipelineRequestOptions): PipelineRequest {\n return new PipelineRequestImpl(options);\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelinePolicy } from \"../pipeline\";\nimport { exponentialRetryStrategy } from \"../retryStrategies/exponentialRetryStrategy\";\nimport { retryPolicy } from \"./retryPolicy\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\n/**\n * The programmatic identifier of the exponentialRetryPolicy.\n */\nexport const exponentialRetryPolicyName = \"exponentialRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface ExponentialRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second.) The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * A policy that attempts to retry requests while introducing an exponentially increasing delay.\n * @param options - Options that configure retry logic.\n */\nexport function exponentialRetryPolicy(\n options: ExponentialRetryPolicyOptions = {}\n): PipelinePolicy {\n return retryPolicy(\n [\n exponentialRetryStrategy({\n ...options,\n ignoreSystemErrors: true,\n }),\n ],\n {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }\n );\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelinePolicy } from \"../pipeline\";\nimport { exponentialRetryStrategy } from \"../retryStrategies/exponentialRetryStrategy\";\nimport { retryPolicy } from \"./retryPolicy\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\n/**\n * Name of the {@link systemErrorRetryPolicy}\n */\nexport const systemErrorRetryPolicyName = \"systemErrorRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface SystemErrorRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second.) The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * A retry policy that specifically seeks to handle errors in the\n * underlying transport layer (e.g. DNS lookup failures) rather than\n * retryable error codes from the server itself.\n * @param options - Options that customize the policy.\n */\nexport function systemErrorRetryPolicy(\n options: SystemErrorRetryPolicyOptions = {}\n): PipelinePolicy {\n return {\n name: systemErrorRetryPolicyName,\n sendRequest: retryPolicy(\n [\n exponentialRetryStrategy({\n ...options,\n ignoreHttpStatusCodes: true,\n }),\n ],\n {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }\n ).sendRequest,\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelinePolicy } from \"../pipeline\";\nimport { throttlingRetryStrategy } from \"../retryStrategies/throttlingRetryStrategy\";\nimport { retryPolicy } from \"./retryPolicy\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\n/**\n * Name of the {@link throttlingRetryPolicy}\n */\nexport const throttlingRetryPolicyName = \"throttlingRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface ThrottlingRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n}\n\n/**\n * A policy that retries when the server sends a 429 response with a Retry-After header.\n *\n * To learn more, please refer to\n * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,\n * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and\n * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors\n *\n * @param options - Options that configure retry logic.\n */\nexport function throttlingRetryPolicy(options: ThrottlingRetryPolicyOptions = {}): PipelinePolicy {\n return {\n name: throttlingRetryPolicyName,\n sendRequest: retryPolicy([throttlingRetryStrategy()], {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }).sendRequest,\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { delay } from \"./helpers\";\n\n/**\n * A function that gets a promise of an access token and allows providing\n * options.\n *\n * @param options - the options to pass to the underlying token provider\n */\nexport type AccessTokenGetter = (\n scopes: string | string[],\n options: GetTokenOptions\n) => Promise<AccessToken>;\n\nexport interface TokenCyclerOptions {\n /**\n * The window of time before token expiration during which the token will be\n * considered unusable due to risk of the token expiring before sending the\n * request.\n *\n * This will only become meaningful if the refresh fails for over\n * (refreshWindow - forcedRefreshWindow) milliseconds.\n */\n forcedRefreshWindowInMs: number;\n /**\n * Interval in milliseconds to retry failed token refreshes.\n */\n retryIntervalInMs: number;\n /**\n * The window of time before token expiration during which\n * we will attempt to refresh the token.\n */\n refreshWindowInMs: number;\n}\n\n// Default options for the cycler if none are provided\nexport const DEFAULT_CYCLER_OPTIONS: TokenCyclerOptions = {\n forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires\n retryIntervalInMs: 3000, // Allow refresh attempts every 3s\n refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry\n};\n\n/**\n * Converts an an unreliable access token getter (which may resolve with null)\n * into an AccessTokenGetter by retrying the unreliable getter in a regular\n * interval.\n *\n * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.\n * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.\n * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.\n * @returns - A promise that, if it resolves, will resolve with an access token.\n */\nasync function beginRefresh(\n getAccessToken: () => Promise<AccessToken | null>,\n retryIntervalInMs: number,\n refreshTimeout: number\n): Promise<AccessToken> {\n // This wrapper handles exceptions gracefully as long as we haven't exceeded\n // the timeout.\n async function tryGetAccessToken(): Promise<AccessToken | null> {\n if (Date.now() < refreshTimeout) {\n try {\n return await getAccessToken();\n } catch {\n return null;\n }\n } else {\n const finalToken = await getAccessToken();\n\n // Timeout is up, so throw if it's still null\n if (finalToken === null) {\n throw new Error(\"Failed to refresh access token.\");\n }\n\n return finalToken;\n }\n }\n\n let token: AccessToken | null = await tryGetAccessToken();\n\n while (token === null) {\n await delay(retryIntervalInMs);\n\n token = await tryGetAccessToken();\n }\n\n return token;\n}\n\n/**\n * Creates a token cycler from a credential, scopes, and optional settings.\n *\n * A token cycler represents a way to reliably retrieve a valid access token\n * from a TokenCredential. It will handle initializing the token, refreshing it\n * when it nears expiration, and synchronizes refresh attempts to avoid\n * concurrency hazards.\n *\n * @param credential - the underlying TokenCredential that provides the access\n * token\n * @param tokenCyclerOptions - optionally override default settings for the cycler\n *\n * @returns - a function that reliably produces a valid access token\n */\nexport function createTokenCycler(\n credential: TokenCredential,\n tokenCyclerOptions?: Partial<TokenCyclerOptions>\n): AccessTokenGetter {\n let refreshWorker: Promise<AccessToken> | null = null;\n let token: AccessToken | null = null;\n let tenantId: string | undefined;\n\n const options = {\n ...DEFAULT_CYCLER_OPTIONS,\n ...tokenCyclerOptions,\n };\n\n /**\n * This little holder defines several predicates that we use to construct\n * the rules of refreshing the token.\n */\n const cycler = {\n /**\n * Produces true if a refresh job is currently in progress.\n */\n get isRefreshing(): boolean {\n return refreshWorker !== null;\n },\n /**\n * Produces true if the cycler SHOULD refresh (we are within the refresh\n * window and not already refreshing)\n */\n get shouldRefresh(): boolean {\n return (\n !cycler.isRefreshing &&\n (token?.expiresOnTimestamp ?? 0) - options.refreshWindowInMs < Date.now()\n );\n },\n /**\n * Produces true if the cycler MUST refresh (null or nearly-expired\n * token).\n */\n get mustRefresh(): boolean {\n return (\n token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()\n );\n },\n };\n\n /**\n * Starts a refresh job or returns the existing job if one is already\n * running.\n */\n function refresh(\n scopes: string | string[],\n getTokenOptions: GetTokenOptions\n ): Promise<AccessToken> {\n if (!cycler.isRefreshing) {\n // We bind `scopes` here to avoid passing it around a lot\n const tryGetAccessToken = (): Promise<AccessToken | null> =>\n credential.getToken(scopes, getTokenOptions);\n\n // Take advantage of promise chaining to insert an assignment to `token`\n // before the refresh can be considered done.\n refreshWorker = beginRefresh(\n tryGetAccessToken,\n options.retryIntervalInMs,\n // If we don't have a token, then we should timeout immediately\n token?.expiresOnTimestamp ?? Date.now()\n )\n .then((_token) => {\n refreshWorker = null;\n token = _token;\n tenantId = getTokenOptions.tenantId;\n return token;\n })\n .catch((reason) => {\n // We also should reset the refresher if we enter a failed state. All\n // existing awaiters will throw, but subsequent requests will start a\n // new retry chain.\n refreshWorker = null;\n token = null;\n tenantId = undefined;\n throw reason;\n });\n }\n\n return refreshWorker as Promise<AccessToken>;\n }\n\n return async (scopes: string | string[], tokenOptions: GetTokenOptions): Promise<AccessToken> => {\n //\n // Simple rules:\n // - If we MUST refresh, then return the refresh task, blocking\n // the pipeline until a token is available.\n // - If we SHOULD refresh, then run refresh but don't return it\n // (we can still use the cached token).\n // - Return the token, since it's fine if we didn't return in\n // step 1.\n //\n\n // If the tenantId passed in token options is different to the one we have\n // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to\n // refresh the token with the new tenantId or token.\n const mustRefresh =\n tenantId !== tokenOptions.tenantId || Boolean(tokenOptions.claims) || cycler.mustRefresh;\n\n if (mustRefresh) return refresh(scopes, tokenOptions);\n\n if (cycler.shouldRefresh) {\n refresh(scopes, tokenOptions);\n }\n\n return token as AccessToken;\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AzureLogger } from \"@azure/logger\";\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { createTokenCycler } from \"../util/tokenCycler\";\nimport { logger as coreLogger } from \"../log\";\n\n/**\n * The programmatic identifier of the bearerTokenAuthenticationPolicy.\n */\nexport const bearerTokenAuthenticationPolicyName = \"bearerTokenAuthenticationPolicy\";\n\n/**\n * Options sent to the authorizeRequest callback\n */\nexport interface AuthorizeRequestOptions {\n /**\n * The scopes for which the bearer token applies.\n */\n scopes: string[];\n /**\n * Function that retrieves either a cached access token or a new access token.\n */\n getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise<AccessToken | null>;\n /**\n * Request that the policy is trying to fulfill.\n */\n request: PipelineRequest;\n /**\n * A logger, if one was sent through the HTTP pipeline.\n */\n logger?: AzureLogger;\n}\n\n/**\n * Options sent to the authorizeRequestOnChallenge callback\n */\nexport interface AuthorizeRequestOnChallengeOptions {\n /**\n * The scopes for which the bearer token applies.\n */\n scopes: string[];\n /**\n * Function that retrieves either a cached access token or a new access token.\n */\n getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise<AccessToken | null>;\n /**\n * Request that the policy is trying to fulfill.\n */\n request: PipelineRequest;\n /**\n * Response containing the challenge.\n */\n response: PipelineResponse;\n /**\n * A logger, if one was sent through the HTTP pipeline.\n */\n logger?: AzureLogger;\n}\n\n/**\n * Options to override the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.\n */\nexport interface ChallengeCallbacks {\n /**\n * Allows for the authorization of the main request of this policy before it's sent.\n */\n authorizeRequest?(options: AuthorizeRequestOptions): Promise<void>;\n /**\n * Allows to handle authentication challenges and to re-authorize the request.\n * The response containing the challenge is `options.response`.\n * If this method returns true, the underlying request will be sent once again.\n * The request may be modified before being sent.\n */\n authorizeRequestOnChallenge?(options: AuthorizeRequestOnChallengeOptions): Promise<boolean>;\n}\n\n/**\n * Options to configure the bearerTokenAuthenticationPolicy\n */\nexport interface BearerTokenAuthenticationPolicyOptions {\n /**\n * The TokenCredential implementation that can supply the bearer token.\n */\n credential?: TokenCredential;\n /**\n * The scopes for which the bearer token applies.\n */\n scopes: string | string[];\n /**\n * Allows for the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.\n * If provided, it must contain at least the `authorizeRequestOnChallenge` method.\n * If provided, after a request is sent, if it has a challenge, it can be processed to re-send the original request with the relevant challenge information.\n */\n challengeCallbacks?: ChallengeCallbacks;\n /**\n * A logger can be sent for debugging purposes.\n */\n logger?: AzureLogger;\n}\n\n/**\n * Default authorize request handler\n */\nasync function defaultAuthorizeRequest(options: AuthorizeRequestOptions): Promise<void> {\n const { scopes, getAccessToken, request } = options;\n const getTokenOptions: GetTokenOptions = {\n abortSignal: request.abortSignal,\n tracingOptions: request.tracingOptions,\n };\n const accessToken = await getAccessToken(scopes, getTokenOptions);\n\n if (accessToken) {\n options.request.headers.set(\"Authorization\", `Bearer ${accessToken.token}`);\n }\n}\n\n/**\n * We will retrieve the challenge only if the response status code was 401,\n * and if the response contained the header \"WWW-Authenticate\" with a non-empty value.\n */\nfunction getChallenge(response: PipelineResponse): string | undefined {\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (response.status === 401 && challenge) {\n return challenge;\n }\n return;\n}\n\n/**\n * A policy that can request a token from a TokenCredential implementation and\n * then apply it to the Authorization header of a request as a Bearer token.\n */\nexport function bearerTokenAuthenticationPolicy(\n options: BearerTokenAuthenticationPolicyOptions\n): PipelinePolicy {\n const { credential, scopes, challengeCallbacks } = options;\n const logger = options.logger || coreLogger;\n const callbacks = {\n authorizeRequest: challengeCallbacks?.authorizeRequest ?? defaultAuthorizeRequest,\n authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge,\n // keep all other properties\n ...challengeCallbacks,\n };\n\n // This function encapsulates the entire process of reliably retrieving the token\n // The options are left out of the public API until there's demand to configure this.\n // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`\n // in order to pass through the `options` object.\n const getAccessToken = credential\n ? createTokenCycler(credential /* , options */)\n : () => Promise.resolve(null);\n\n return {\n name: bearerTokenAuthenticationPolicyName,\n /**\n * If there's no challenge parameter:\n * - It will try to retrieve the token using the cache, or the credential's getToken.\n * - Then it will try the next policy with or without the retrieved token.\n *\n * It uses the challenge parameters to:\n * - Skip a first attempt to get the token from the credential if there's no cached token,\n * since it expects the token to be retrievable only after the challenge.\n * - Prepare the outgoing request if the `prepareRequest` method has been provided.\n * - Send an initial request to receive the challenge if it fails.\n * - Process a challenge if the response contains it.\n * - Retrieve a token with the challenge information, then re-send the request.\n */\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!request.url.toLowerCase().startsWith(\"https://\")) {\n throw new Error(\n \"Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.\"\n );\n }\n\n await callbacks.authorizeRequest({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n request,\n getAccessToken,\n logger,\n });\n\n let response: PipelineResponse;\n let error: Error | undefined;\n try {\n response = await next(request);\n } catch (err: any) {\n error = err;\n response = err.response;\n }\n\n if (\n callbacks.authorizeRequestOnChallenge &&\n response?.status === 401 &&\n getChallenge(response)\n ) {\n // processes challenge\n const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n request,\n response,\n getAccessToken,\n logger,\n });\n\n if (shouldSendRequest) {\n return next(request);\n }\n }\n\n if (error) {\n throw error;\n } else {\n return response;\n }\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the ndJsonPolicy.\n */\nexport const ndJsonPolicyName = \"ndJsonPolicy\";\n\n/**\n * ndJsonPolicy is a policy used to control keep alive settings for every request.\n */\nexport function ndJsonPolicy(): PipelinePolicy {\n return {\n name: ndJsonPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n // There currently isn't a good way to bypass the serializer\n if (typeof request.body === \"string\" && request.body.startsWith(\"[\")) {\n const body = JSON.parse(request.body);\n if (Array.isArray(body)) {\n request.body = body.map((item) => JSON.stringify(item) + \"\\n\").join(\"\");\n }\n }\n return next(request);\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AzureLogger } from \"@azure/logger\";\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { AccessTokenGetter, createTokenCycler } from \"../util/tokenCycler\";\nimport { logger as coreLogger } from \"../log\";\nimport { AuthorizeRequestOptions } from \"./bearerTokenAuthenticationPolicy\";\n\n/**\n * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.\n */\nexport const auxiliaryAuthenticationHeaderPolicyName = \"auxiliaryAuthenticationHeaderPolicy\";\nconst AUTHORIZATION_AUXILIARY_HEADER = \"x-ms-authorization-auxiliary\";\n\n/**\n * Options to configure the auxiliaryAuthenticationHeaderPolicy\n */\nexport interface AuxiliaryAuthenticationHeaderPolicyOptions {\n /**\n * TokenCredential list used to get token from auxiliary tenants and\n * one credential for each tenant the client may need to access\n */\n credentials?: TokenCredential[];\n /**\n * Scopes depend on the cloud your application runs in\n */\n scopes: string | string[];\n /**\n * A logger can be sent for debugging purposes.\n */\n logger?: AzureLogger;\n}\n\nasync function sendAuthorizeRequest(options: AuthorizeRequestOptions): Promise<string> {\n const { scopes, getAccessToken, request } = options;\n const getTokenOptions: GetTokenOptions = {\n abortSignal: request.abortSignal,\n tracingOptions: request.tracingOptions,\n };\n\n return (await getAccessToken(scopes, getTokenOptions))?.token ?? \"\";\n}\n\n/**\n * A policy for external tokens to `x-ms-authorization-auxiliary` header.\n * This header will be used when creating a cross-tenant application we may need to handle authentication requests\n * for resources that are in different tenants.\n * You could see [ARM docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works\n */\nexport function auxiliaryAuthenticationHeaderPolicy(\n options: AuxiliaryAuthenticationHeaderPolicyOptions\n): PipelinePolicy {\n const { credentials, scopes } = options;\n const logger = options.logger || coreLogger;\n const tokenCyclerMap = new WeakMap<TokenCredential, AccessTokenGetter>();\n\n return {\n name: auxiliaryAuthenticationHeaderPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!request.url.toLowerCase().startsWith(\"https://\")) {\n throw new Error(\n \"Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.\"\n );\n }\n if (!credentials || credentials.length === 0) {\n logger.info(\n `${auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`\n );\n return next(request);\n }\n\n const tokenPromises: Promise<string>[] = [];\n for (const credential of credentials) {\n let getAccessToken = tokenCyclerMap.get(credential);\n if (!getAccessToken) {\n getAccessToken = createTokenCycler(credential);\n tokenCyclerMap.set(credential, getAccessToken);\n }\n tokenPromises.push(\n sendAuthorizeRequest({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n request,\n getAccessToken,\n logger,\n })\n );\n }\n const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));\n if (auxiliaryTokens.length === 0) {\n logger.warning(\n `None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`\n );\n return next(request);\n }\n request.headers.set(\n AUTHORIZATION_AUXILIARY_HEADER,\n auxiliaryTokens.map((token) => `Bearer ${token}`).join(\", \")\n );\n\n return next(request);\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { toWebStream } from \"./stream\";\n\n/**\n * Options passed into createFile specifying metadata about the file.\n */\nexport interface CreateFileOptions {\n /**\n * The MIME type of the file.\n */\n type?: string;\n\n /**\n * Last modified time of the file as a UNIX timestamp.\n * This will default to the current date.\n */\n lastModified?: number;\n\n /**\n * relative path of this file when uploading a directory.\n */\n webkitRelativePath?: string;\n}\n\n/**\n * Extra options for createFile when a stream is being passed in.\n */\nexport interface CreateFileFromStreamOptions extends CreateFileOptions {\n /**\n * Size of the file represented by the stream in bytes.\n *\n * This will be used by the pipeline when calculating the Content-Length header\n * for the overall request.\n */\n size?: number;\n}\n\nconst unimplementedMethods = {\n arrayBuffer: () => {\n throw new Error(\"Not implemented\");\n },\n slice: () => {\n throw new Error(\"Not implemented\");\n },\n text: () => {\n throw new Error(\"Not implemented\");\n },\n};\n\n/**\n * Create an object that implements the File interface. This object is intended to be\n * passed into RequestBodyType.formData, and is not guaranteed to work as expected in\n * other situations.\n *\n * Use this function to:\n * - Create a File object for use in RequestBodyType.formData in environments where the\n * global File object is unavailable.\n * - Create a File-like object from a readable stream without reading the stream into memory.\n *\n * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is\n * passed in a request's form data map, the stream will not be read into memory\n * and instead will be streamed when the request is made. In the event of a retry, the\n * stream needs to be read again, so this callback SHOULD return a fresh stream if possible.\n * @param name - the name of the file.\n * @param options - optional metadata about the file, e.g. file name, file size, MIME type.\n */\nexport function createFileFromStream(\n stream: () => ReadableStream<Uint8Array> | NodeJS.ReadableStream,\n name: string,\n options: CreateFileFromStreamOptions = {}\n): File {\n return {\n ...unimplementedMethods,\n type: options.type ?? \"\",\n lastModified: options.lastModified ?? new Date().getTime(),\n webkitRelativePath: options.webkitRelativePath ?? \"\",\n size: options.size ?? -1,\n name,\n stream: () => toWebStream(stream()),\n };\n}\n\n/**\n * Create an object that implements the File interface. This object is intended to be\n * passed into RequestBodyType.formData, and is not guaranteed to work as expected in\n * other situations.\n *\n * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.\n *\n * @param content - the content of the file as a Uint8Array in memory.\n * @param name - the name of the file.\n * @param options - optional metadata about the file, e.g. file name, file size, MIME type.\n */\nexport function createFile(\n content: Uint8Array,\n name: string,\n options: CreateFileOptions = {}\n): File {\n return {\n ...unimplementedMethods,\n type: options.type ?? \"\",\n lastModified: options.lastModified ?? new Date().getTime(),\n webkitRelativePath: options.webkitRelativePath ?? \"\",\n size: content.byteLength,\n name,\n arrayBuffer: async () => content.buffer,\n stream: () => new Blob([content]).stream(),\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Encodes a string in base64 format.\n * @param value - the string to encode\n * @internal\n */\nexport function encodeString(value: string): string {\n return Buffer.from(value).toString(\"base64\");\n}\n\n/**\n * Encodes a byte array in base64 format.\n * @param value - the Uint8Aray to encode\n * @internal\n */\nexport function encodeByteArray(value: Uint8Array): string {\n // Buffer.from accepts <ArrayBuffer> | <SharedArrayBuffer>-- the TypeScript definition is off here\n // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length\n const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer as ArrayBuffer);\n return bufferValue.toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string into a byte array.\n * @param value - the base64 string to decode\n * @internal\n */\nexport function decodeString(value: string): Uint8Array {\n return Buffer.from(value, \"base64\");\n}\n\n/**\n * Decodes a base64 string into a string.\n * @param value - the base64 string to decode\n * @internal\n */\nexport function decodeStringToString(value: string): string {\n return Buffer.from(value, \"base64\").toString();\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n HttpClient,\n HttpMethods,\n PipelineOptions,\n PipelinePolicy,\n PipelineRequest,\n PipelineResponse,\n TransferProgressEvent,\n} from \"@azure/core-rest-pipeline\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { OperationTracingOptions } from \"@azure/core-tracing\";\n\n/**\n * Default key used to access the XML attributes.\n */\nexport const XML_ATTRKEY = \"$\";\n/**\n * Default key used to access the XML value content.\n */\nexport const XML_CHARKEY = \"_\";\n/**\n * Options to govern behavior of xml parser and builder.\n */\nexport interface XmlOptions {\n /**\n * indicates the name of the root element in the resulting XML when building XML.\n */\n rootName?: string;\n /**\n * indicates whether the root element is to be included or not in the output when parsing XML.\n */\n includeRoot?: boolean;\n /**\n * key used to access the XML value content when parsing XML.\n */\n xmlCharKey?: string;\n}\n/**\n * Options to configure serialization/de-serialization behavior.\n */\nexport interface SerializerOptions {\n /**\n * Options to configure xml parser/builder behavior.\n */\n xml: XmlOptions;\n /**\n * Normally additional properties are included in the result object, even if there is no mapper for them.\n * This flag disables this behavior when true. It is used when parsing headers to avoid polluting the result object.\n */\n ignoreUnknownProperties?: boolean;\n}\n\nexport type RequiredSerializerOptions = {\n [K in keyof SerializerOptions]: Required<SerializerOptions[K]>;\n};\n\n/**\n * A type alias for future proofing.\n */\nexport type OperationRequest = PipelineRequest;\n\n/**\n * Metadata that is used to properly parse a response.\n */\nexport interface OperationRequestInfo {\n /**\n * Used to parse the response.\n */\n operationSpec?: OperationSpec;\n\n /**\n * Used to encode the request.\n */\n operationArguments?: OperationArguments;\n\n /**\n * A function that returns the proper OperationResponseMap for the given OperationSpec and\n * PipelineResponse combination. If this is undefined, then a simple status code lookup will\n * be used.\n */\n operationResponseGetter?: (\n operationSpec: OperationSpec,\n response: PipelineResponse\n ) => undefined | OperationResponseMap;\n\n /**\n * Whether or not the PipelineResponse should be deserialized. Defaults to true.\n */\n shouldDeserialize?: boolean | ((response: PipelineResponse) => boolean);\n}\n\n/**\n * The base options type for all operations.\n */\nexport interface OperationOptions {\n /**\n * The signal which can be used to abort requests.\n */\n abortSignal?: AbortSignalLike;\n /**\n * Options used when creating and sending HTTP requests for this operation.\n */\n requestOptions?: OperationRequestOptions;\n /**\n * Options used when tracing is enabled.\n */\n tracingOptions?: OperationTracingOptions;\n /**\n * Options to override serialization/de-serialization behavior.\n */\n serializerOptions?: SerializerOptions;\n\n /**\n * A function to be called each time a response is received from the server\n * while performing the requested operation.\n * May be called multiple times.\n */\n onResponse?: RawResponseCallback;\n}\n\n/**\n * Options used when creating and sending HTTP requests for this operation.\n */\nexport interface OperationRequestOptions {\n /**\n * User defined custom request headers that\n * will be applied before the request is sent.\n */\n customHeaders?: { [key: string]: string };\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n */\n timeout?: number;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Callback which fires upon download progress.\n */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Whether or not the HttpOperationResponse should be deserialized. If this is undefined, then the\n * HttpOperationResponse should be deserialized.\n */\n shouldDeserialize?: boolean | ((response: PipelineResponse) => boolean);\n\n /**\n * Set to true if the request is sent over HTTP instead of HTTPS\n */\n allowInsecureConnection?: boolean;\n}\n\n/**\n * A collection of properties that apply to a single invocation of an operation.\n */\nexport interface OperationArguments {\n /**\n * The parameters that were passed to the operation method.\n */\n [parameterName: string]: unknown;\n\n /**\n * The optional arguments that are provided to an operation.\n */\n options?: OperationOptions;\n}\n\n/**\n * The format that will be used to join an array of values together for a query parameter value.\n */\nexport type QueryCollectionFormat = \"CSV\" | \"SSV\" | \"TSV\" | \"Pipes\" | \"Multi\";\n\n/**\n * Encodes how to reach a particular property on an object.\n */\nexport type ParameterPath = string | string[] | { [propertyName: string]: ParameterPath };\n\n/**\n * A common interface that all Operation parameter's extend.\n */\nexport interface OperationParameter {\n /**\n * The path to this parameter's value in OperationArguments or the object that contains paths for\n * each property's value in OperationArguments.\n */\n parameterPath: ParameterPath;\n\n /**\n * The mapper that defines how to validate and serialize this parameter's value.\n */\n mapper: Mapper;\n}\n\n/**\n * A parameter for an operation that will be substituted into the operation's request URL.\n */\nexport interface OperationURLParameter extends OperationParameter {\n /**\n * Whether or not to skip encoding the URL parameter's value before adding it to the URL.\n */\n skipEncoding?: boolean;\n}\n\n/**\n * A parameter for an operation that will be added as a query parameter to the operation's HTTP\n * request.\n */\nexport interface OperationQueryParameter extends OperationParameter {\n /**\n * Whether or not to skip encoding the query parameter's value before adding it to the URL.\n */\n skipEncoding?: boolean;\n\n /**\n * If this query parameter's value is a collection, what type of format should the value be\n * converted to.\n */\n collectionFormat?: QueryCollectionFormat;\n}\n\n/**\n * An OperationResponse that can be returned from an operation request for a single status code.\n */\nexport interface OperationResponseMap {\n /**\n * The mapper that will be used to deserialize the response headers.\n */\n headersMapper?: Mapper;\n\n /**\n * The mapper that will be used to deserialize the response body.\n */\n bodyMapper?: Mapper;\n\n /**\n * Indicates if this is an error response\n */\n isError?: boolean;\n}\n\n/**\n * A specification that defines an operation.\n */\nexport interface OperationSpec {\n /**\n * The serializer to use in this operation.\n */\n readonly serializer: Serializer;\n\n /**\n * The HTTP method that should be used by requests for this operation.\n */\n readonly httpMethod: HttpMethods;\n\n /**\n * The URL that was provided in the service's specification. This will still have all of the URL\n * template variables in it. If this is not provided when the OperationSpec is created, then it\n * will be populated by a \"baseUri\" property on the ServiceClient.\n */\n readonly baseUrl?: string;\n\n /**\n * The fixed path for this operation's URL. This will still have all of the URL template variables\n * in it.\n */\n readonly path?: string;\n\n /**\n * The content type of the request body. This value will be used as the \"Content-Type\" header if\n * it is provided.\n */\n readonly contentType?: string;\n\n /**\n * The media type of the request body.\n * This value can be used to aide in serialization if it is provided.\n */\n readonly mediaType?:\n | \"json\"\n | \"xml\"\n | \"form\"\n | \"binary\"\n | \"multipart\"\n | \"text\"\n | \"unknown\"\n | string;\n /**\n * The parameter that will be used to construct the HTTP request's body.\n */\n readonly requestBody?: OperationParameter;\n\n /**\n * Whether or not this operation uses XML request and response bodies.\n */\n readonly isXML?: boolean;\n\n /**\n * The parameters to the operation method that will be substituted into the constructed URL.\n */\n readonly urlParameters?: ReadonlyArray<OperationURLParameter>;\n\n /**\n * The parameters to the operation method that will be added to the constructed URL's query.\n */\n readonly queryParameters?: ReadonlyArray<OperationQueryParameter>;\n\n /**\n * The parameters to the operation method that will be converted to headers on the operation's\n * HTTP request.\n */\n readonly headerParameters?: ReadonlyArray<OperationParameter>;\n\n /**\n * The parameters to the operation method that will be used to create a formdata body for the\n * operation's HTTP request.\n */\n readonly formDataParameters?: ReadonlyArray<OperationParameter>;\n\n /**\n * The different types of responses that this operation can return based on what status code is\n * returned.\n */\n readonly responses: { [responseCode: string]: OperationResponseMap };\n}\n\n/**\n * Wrapper object for http request and response. Deserialized object is stored in\n * the `parsedBody` property when the response body is received in JSON or XML.\n */\nexport interface FullOperationResponse extends PipelineResponse {\n /**\n * The parsed HTTP response headers.\n */\n parsedHeaders?: { [key: string]: unknown };\n\n /**\n * The response body as parsed JSON or XML.\n */\n parsedBody?: any;\n\n /**\n * The request that generated the response.\n */\n request: OperationRequest;\n}\n\n/**\n * A function to be called each time a response is received from the server\n * while performing the requested operation.\n * May be called multiple times.\n */\nexport type RawResponseCallback = (\n rawResponse: FullOperationResponse,\n flatResponse: unknown,\n error?: unknown\n) => void;\n\n/**\n * Used to map raw response objects to final shapes.\n * Helps packing and unpacking Dates and other encoded types that are not intrinsic to JSON.\n * Also allows pulling values from headers, as well as inserting default values and constants.\n */\nexport interface Serializer {\n /**\n * The provided model mapper.\n */\n readonly modelMappers: { [key: string]: any };\n /**\n * Whether the contents are XML or not.\n */\n readonly isXML: boolean;\n\n /**\n * Validates constraints, if any. This function will throw if the provided value does not respect those constraints.\n * @param mapper - The definition of data models.\n * @param value - The value.\n * @param objectName - Name of the object. Used in the error messages.\n * @deprecated Removing the constraints validation on client side.\n */\n validateConstraints(mapper: Mapper, value: any, objectName: string): void;\n\n /**\n * Serialize the given object based on its metadata defined in the mapper.\n *\n * @param mapper - The mapper which defines the metadata of the serializable object.\n * @param object - A valid Javascript object to be serialized.\n * @param objectName - Name of the serialized object.\n * @param options - additional options to deserialization.\n * @returns A valid serialized Javascript object.\n */\n serialize(mapper: Mapper, object: any, objectName?: string, options?: SerializerOptions): any;\n\n /**\n * Deserialize the given object based on its metadata defined in the mapper.\n *\n * @param mapper - The mapper which defines the metadata of the serializable object.\n * @param responseBody - A valid Javascript entity to be deserialized.\n * @param objectName - Name of the deserialized object.\n * @param options - Controls behavior of XML parser and builder.\n * @returns A valid deserialized Javascript object.\n */\n deserialize(\n mapper: Mapper,\n responseBody: any,\n objectName: string,\n options?: SerializerOptions\n ): any;\n}\n\n/**\n * Description of various value constraints such as integer ranges and string regex.\n */\nexport interface MapperConstraints {\n /**\n * The value should be less than or equal to the `InclusiveMaximum` value.\n */\n InclusiveMaximum?: number;\n /**\n * The value should be less than the `ExclusiveMaximum` value.\n */\n ExclusiveMaximum?: number;\n /**\n * The value should be greater than or equal to the `InclusiveMinimum` value.\n */\n InclusiveMinimum?: number;\n /**\n * The value should be greater than the `InclusiveMinimum` value.\n */\n ExclusiveMinimum?: number;\n /**\n * The length should be smaller than the `MaxLength`.\n */\n MaxLength?: number;\n /**\n * The length should be bigger than the `MinLength`.\n */\n MinLength?: number;\n /**\n * The value must match the pattern.\n */\n Pattern?: RegExp;\n /**\n * The value must contain fewer items than the MaxItems value.\n */\n MaxItems?: number;\n /**\n * The value must contain more items than the `MinItems` value.\n */\n MinItems?: number;\n /**\n * The value must contain only unique items.\n */\n UniqueItems?: true;\n /**\n * The value should be exactly divisible by the `MultipleOf` value.\n */\n MultipleOf?: number;\n}\n\n/**\n * Type of the mapper. Includes known mappers.\n */\nexport type MapperType =\n | SimpleMapperType\n | CompositeMapperType\n | SequenceMapperType\n | DictionaryMapperType\n | EnumMapperType;\n\n/**\n * The type of a simple mapper.\n */\nexport interface SimpleMapperType {\n /**\n * Name of the type of the property.\n */\n name:\n | \"Base64Url\"\n | \"Boolean\"\n | \"ByteArray\"\n | \"Date\"\n | \"DateTime\"\n | \"DateTimeRfc1123\"\n | \"Object\"\n | \"Stream\"\n | \"String\"\n | \"TimeSpan\"\n | \"UnixTime\"\n | \"Uuid\"\n | \"Number\"\n | \"any\";\n}\n\n/**\n * Helps build a mapper that describes how to map a set of properties of an object based on other mappers.\n *\n * Only one of the following properties should be present: `className`, `modelProperties` and `additionalProperties`.\n */\nexport interface CompositeMapperType {\n /**\n * Name of the composite mapper type.\n */\n name: \"Composite\";\n\n /**\n * Use `className` to reference another type definition.\n */\n className?: string;\n\n /**\n * Use `modelProperties` when the reference to the other type has been resolved.\n */\n modelProperties?: { [propertyName: string]: Mapper };\n\n /**\n * Used when a model has `additionalProperties: true`. Allows the generic processing of unnamed model properties on the response object.\n */\n additionalProperties?: Mapper;\n\n /**\n * The name of the top-most parent scheme, the one that has no parents.\n */\n uberParent?: string;\n\n /**\n * A polymorphic discriminator.\n */\n polymorphicDiscriminator?: PolymorphicDiscriminator;\n}\n\n/**\n * Helps build a mapper that describes how to parse a sequence of mapped values.\n */\nexport interface SequenceMapperType {\n /**\n * Name of the sequence type mapper.\n */\n name: \"Sequence\";\n /**\n * The mapper to use to map each one of the properties of the sequence.\n */\n element: Mapper;\n}\n\n/**\n * Helps build a mapper that describes how to parse a dictionary of mapped values.\n */\nexport interface DictionaryMapperType {\n /**\n * Name of the sequence type mapper.\n */\n name: \"Dictionary\";\n /**\n * The mapper to use to map the value of each property in the dictionary.\n */\n value: Mapper;\n}\n\n/**\n * Helps build a mapper that describes how to parse an enum value.\n */\nexport interface EnumMapperType {\n /**\n * Name of the enum type mapper.\n */\n name: \"Enum\";\n /**\n * Values allowed by this mapper.\n */\n allowedValues: any[];\n}\n\n/**\n * The base definition of a mapper. Can be used for XML and plain JavaScript objects.\n */\nexport interface BaseMapper {\n /**\n * Name for the xml element\n */\n xmlName?: string;\n /**\n * Xml element namespace\n */\n xmlNamespace?: string;\n /**\n * Xml element namespace prefix\n */\n xmlNamespacePrefix?: string;\n /**\n * Determines if the current property should be serialized as an attribute of the parent xml element\n */\n xmlIsAttribute?: boolean;\n /**\n * Determines if the current property should be serialized as the inner content of the xml element\n */\n xmlIsMsText?: boolean;\n /**\n * Name for the xml elements when serializing an array\n */\n xmlElementName?: string;\n /**\n * Whether or not the current property should have a wrapping XML element\n */\n xmlIsWrapped?: boolean;\n /**\n * Whether or not the current property is readonly\n */\n readOnly?: boolean;\n /**\n * Whether or not the current property is a constant\n */\n isConstant?: boolean;\n /**\n * Whether or not the current property is required\n */\n required?: boolean;\n /**\n * Whether or not the current property allows mull as a value\n */\n nullable?: boolean;\n /**\n * The name to use when serializing\n */\n serializedName?: string;\n /**\n * Type of the mapper\n */\n type: MapperType;\n /**\n * Default value when one is not explicitly provided\n */\n defaultValue?: any;\n /**\n * Constraints to test the current value against\n */\n constraints?: MapperConstraints;\n}\n\n/**\n * Mappers are definitions of the data models used in the library.\n * These data models are part of the Operation or Client definitions in the responses or parameters.\n */\nexport type Mapper = BaseMapper | CompositeMapper | SequenceMapper | DictionaryMapper | EnumMapper;\n\n/**\n * Used to disambiguate discriminated type unions.\n * For example, if response can have many shapes but also includes a 'kind' field (or similar),\n * that field can be used to determine how to deserialize the response to the correct type.\n */\nexport interface PolymorphicDiscriminator {\n /**\n * Name of the discriminant property in the original JSON payload, e.g. `@odata.kind`.\n */\n serializedName: string;\n /**\n * Name to use on the resulting object instead of the original property name.\n * Useful since the JSON property could be difficult to work with.\n * For example: For a field received as `@odata.kind`, the final object could instead include a property simply named `kind`.\n */\n clientName: string;\n /**\n * It may contain any other property.\n */\n [key: string]: string;\n}\n\n/**\n * A mapper composed of other mappers.\n */\nexport interface CompositeMapper extends BaseMapper {\n /**\n * The type descriptor of the `CompositeMapper`.\n */\n type: CompositeMapperType;\n}\n\n/**\n * A mapper describing arrays.\n */\nexport interface SequenceMapper extends BaseMapper {\n /**\n * The type descriptor of the `SequenceMapper`.\n */\n type: SequenceMapperType;\n}\n\n/**\n * A mapper describing plain JavaScript objects used as key/value pairs.\n */\nexport interface DictionaryMapper extends BaseMapper {\n /**\n * The type descriptor of the `DictionaryMapper`.\n */\n type: DictionaryMapperType;\n /**\n * Optionally, a prefix to add to the header collection.\n */\n headerCollectionPrefix?: string;\n}\n\n/**\n * A mapper describing an enum value.\n */\nexport interface EnumMapper extends BaseMapper {\n /**\n * The type descriptor of the `EnumMapper`.\n */\n type: EnumMapperType;\n}\n\nexport interface UrlParameterValue {\n value: string;\n skipUrlEncoding: boolean;\n}\n\n/**\n * Configuration for creating a new Tracing Span\n */\nexport interface SpanConfig {\n /**\n * Package name prefix\n */\n packagePrefix: string;\n /**\n * Service namespace\n */\n namespace: string;\n}\n\n/**\n * Used to configure additional policies added to the pipeline at construction.\n */\nexport interface AdditionalPolicyConfig {\n /**\n * A policy to be added.\n */\n policy: PipelinePolicy;\n /**\n * Determines if this policy be applied before or after retry logic.\n * Only use `perRetry` if you need to modify the request again\n * each time the operation is retried due to retryable service\n * issues.\n */\n position: \"perCall\" | \"perRetry\";\n}\n\n/**\n * The common set of options that high level clients are expected to expose.\n */\nexport interface CommonClientOptions extends PipelineOptions {\n /**\n * The HttpClient that will be used to send HTTP requests.\n */\n httpClient?: HttpClient;\n /**\n * Set to true if the request is sent over HTTP instead of HTTPS\n */\n allowInsecureConnection?: boolean;\n /**\n * Additional policies to include in the HTTP pipeline.\n */\n additionalPolicies?: AdditionalPolicyConfig[];\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CompositeMapper, FullOperationResponse, OperationResponseMap } from \"./interfaces\";\n\n/**\n * The union of all possible types for a primitive response body.\n * @internal\n */\nexport type BodyPrimitive = number | string | boolean | Date | Uint8Array | undefined | null;\n\n/**\n * A type guard for a primitive response body.\n * @param value - Value to test\n *\n * @internal\n */\nexport function isPrimitiveBody(value: unknown, mapperTypeName?: string): value is BodyPrimitive {\n return (\n mapperTypeName !== \"Composite\" &&\n mapperTypeName !== \"Dictionary\" &&\n (typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n mapperTypeName?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i) !==\n null ||\n value === undefined ||\n value === null)\n );\n}\n\nconst validateISODuration =\n /^(-|\\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;\n\n/**\n * Returns true if the given string is in ISO 8601 format.\n * @param value - The value to be validated for ISO 8601 duration format.\n * @internal\n */\nexport function isDuration(value: string): boolean {\n return validateISODuration.test(value);\n}\n\nconst validUuidRegex =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;\n\n/**\n * Returns true if the provided uuid is valid.\n *\n * @param uuid - The uuid that needs to be validated.\n *\n * @internal\n */\nexport function isValidUuid(uuid: string): boolean {\n return validUuidRegex.test(uuid);\n}\n\n/**\n * Representation of parsed response headers and body coupled with information\n * about how to map them:\n * - whether the response body should be wrapped (typically if its type is primitive).\n * - whether the response is nullable so it can be null if the combination of\n * the headers and the body is empty.\n */\ninterface ResponseObjectWithMetadata {\n /** whether the mapper allows nullable body */\n hasNullableType: boolean;\n /** whether the response's body should be wrapped */\n shouldWrapBody: boolean;\n /** parsed headers of the response */\n headers:\n | {\n [key: string]: unknown;\n }\n | undefined;\n /** parsed body of the response */\n body: any;\n}\n\n/**\n * Maps the response as follows:\n * - wraps the response body if needed (typically if its type is primitive).\n * - returns null if the combination of the headers and the body is empty.\n * - otherwise, returns the combination of the headers and the body.\n *\n * @param responseObject - a representation of the parsed response\n * @returns the response that will be returned to the user which can be null and/or wrapped\n *\n * @internal\n */\nfunction handleNullableResponseAndWrappableBody(\n responseObject: ResponseObjectWithMetadata\n): unknown | null {\n const combinedHeadersAndBody = {\n ...responseObject.headers,\n ...responseObject.body,\n };\n if (\n responseObject.hasNullableType &&\n Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0\n ) {\n return responseObject.shouldWrapBody ? { body: null } : null;\n } else {\n return responseObject.shouldWrapBody\n ? {\n ...responseObject.headers,\n body: responseObject.body,\n }\n : combinedHeadersAndBody;\n }\n}\n\n/**\n * Take a `FullOperationResponse` and turn it into a flat\n * response object to hand back to the consumer.\n * @param fullResponse - The processed response from the operation request\n * @param responseSpec - The response map from the OperationSpec\n *\n * @internal\n */\nexport function flattenResponse(\n fullResponse: FullOperationResponse,\n responseSpec: OperationResponseMap | undefined\n): unknown {\n const parsedHeaders = fullResponse.parsedHeaders;\n\n // head methods never have a body, but we return a boolean set to body property\n // to indicate presence/absence of the resource\n if (fullResponse.request.method === \"HEAD\") {\n return {\n ...parsedHeaders,\n body: fullResponse.parsedBody,\n };\n }\n const bodyMapper = responseSpec && responseSpec.bodyMapper;\n const isNullable = Boolean(bodyMapper?.nullable);\n const expectedBodyTypeName = bodyMapper?.type.name;\n\n /** If the body is asked for, we look at the expected body type to handle it */\n if (expectedBodyTypeName === \"Stream\") {\n return {\n ...parsedHeaders,\n blobBody: fullResponse.blobBody,\n readableStreamBody: fullResponse.readableStreamBody,\n };\n }\n\n const modelProperties =\n (expectedBodyTypeName === \"Composite\" &&\n (bodyMapper as CompositeMapper).type.modelProperties) ||\n {};\n const isPageableResponse = Object.keys(modelProperties).some(\n (k) => modelProperties[k].serializedName === \"\"\n );\n if (expectedBodyTypeName === \"Sequence\" || isPageableResponse) {\n const arrayResponse: { [key: string]: unknown } =\n fullResponse.parsedBody ?? ([] as unknown as { [key: string]: unknown });\n\n for (const key of Object.keys(modelProperties)) {\n if (modelProperties[key].serializedName) {\n arrayResponse[key] = fullResponse.parsedBody?.[key];\n }\n }\n\n if (parsedHeaders) {\n for (const key of Object.keys(parsedHeaders)) {\n arrayResponse[key] = parsedHeaders[key];\n }\n }\n return isNullable &&\n !fullResponse.parsedBody &&\n !parsedHeaders &&\n Object.getOwnPropertyNames(modelProperties).length === 0\n ? null\n : arrayResponse;\n }\n\n return handleNullableResponseAndWrappableBody({\n body: fullResponse.parsedBody,\n headers: parsedHeaders,\n hasNullableType: isNullable,\n shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),\n });\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as base64 from \"./base64\";\nimport {\n BaseMapper,\n CompositeMapper,\n DictionaryMapper,\n EnumMapper,\n Mapper,\n MapperConstraints,\n PolymorphicDiscriminator,\n RequiredSerializerOptions,\n SequenceMapper,\n Serializer,\n SerializerOptions,\n XML_ATTRKEY,\n XML_CHARKEY,\n} from \"./interfaces\";\nimport { isDuration, isValidUuid } from \"./utils\";\n\nclass SerializerImpl implements Serializer {\n constructor(\n public readonly modelMappers: { [key: string]: any } = {},\n public readonly isXML: boolean = false\n ) {}\n\n /**\n * @deprecated Removing the constraints validation on client side.\n */\n validateConstraints(mapper: Mapper, value: any, objectName: string): void {\n const failValidation = (\n constraintName: keyof MapperConstraints,\n constraintValue: any\n ): never => {\n throw new Error(\n `\"${objectName}\" with value \"${value}\" should satisfy the constraint \"${constraintName}\": ${constraintValue}.`\n );\n };\n if (mapper.constraints && value !== undefined && value !== null) {\n const {\n ExclusiveMaximum,\n ExclusiveMinimum,\n InclusiveMaximum,\n InclusiveMinimum,\n MaxItems,\n MaxLength,\n MinItems,\n MinLength,\n MultipleOf,\n Pattern,\n UniqueItems,\n } = mapper.constraints;\n if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {\n failValidation(\"ExclusiveMaximum\", ExclusiveMaximum);\n }\n if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {\n failValidation(\"ExclusiveMinimum\", ExclusiveMinimum);\n }\n if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {\n failValidation(\"InclusiveMaximum\", InclusiveMaximum);\n }\n if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {\n failValidation(\"InclusiveMinimum\", InclusiveMinimum);\n }\n if (MaxItems !== undefined && value.length > MaxItems) {\n failValidation(\"MaxItems\", MaxItems);\n }\n if (MaxLength !== undefined && value.length > MaxLength) {\n failValidation(\"MaxLength\", MaxLength);\n }\n if (MinItems !== undefined && value.length < MinItems) {\n failValidation(\"MinItems\", MinItems);\n }\n if (MinLength !== undefined && value.length < MinLength) {\n failValidation(\"MinLength\", MinLength);\n }\n if (MultipleOf !== undefined && value % MultipleOf !== 0) {\n failValidation(\"MultipleOf\", MultipleOf);\n }\n if (Pattern) {\n const pattern: RegExp = typeof Pattern === \"string\" ? new RegExp(Pattern) : Pattern;\n if (typeof value !== \"string\" || value.match(pattern) === null) {\n failValidation(\"Pattern\", Pattern);\n }\n }\n if (\n UniqueItems &&\n value.some((item: any, i: number, ar: Array<any>) => ar.indexOf(item) !== i)\n ) {\n failValidation(\"UniqueItems\", UniqueItems);\n }\n }\n }\n\n /**\n * Serialize the given object based on its metadata defined in the mapper\n *\n * @param mapper - The mapper which defines the metadata of the serializable object\n *\n * @param object - A valid Javascript object to be serialized\n *\n * @param objectName - Name of the serialized object\n *\n * @param options - additional options to serialization\n *\n * @returns A valid serialized Javascript object\n */\n serialize(\n mapper: Mapper,\n object: any,\n objectName?: string,\n options: SerializerOptions = { xml: {} }\n ): any {\n const updatedOptions: RequiredSerializerOptions = {\n xml: {\n rootName: options.xml.rootName ?? \"\",\n includeRoot: options.xml.includeRoot ?? false,\n xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY,\n },\n };\n let payload: any = {};\n const mapperType = mapper.type.name as string;\n if (!objectName) {\n objectName = mapper.serializedName!;\n }\n if (mapperType.match(/^Sequence$/i) !== null) {\n payload = [];\n }\n\n if (mapper.isConstant) {\n object = mapper.defaultValue;\n }\n\n // This table of allowed values should help explain\n // the mapper.required and mapper.nullable properties.\n // X means \"neither undefined or null are allowed\".\n // || required\n // || true | false\n // nullable || ==========================\n // true || null | undefined/null\n // false || X | undefined\n // undefined || X | undefined/null\n\n const { required, nullable } = mapper;\n\n if (required && nullable && object === undefined) {\n throw new Error(`${objectName} cannot be undefined.`);\n }\n if (required && !nullable && (object === undefined || object === null)) {\n throw new Error(`${objectName} cannot be null or undefined.`);\n }\n if (!required && nullable === false && object === null) {\n throw new Error(`${objectName} cannot be null.`);\n }\n\n if (object === undefined || object === null) {\n payload = object;\n } else {\n if (mapperType.match(/^any$/i) !== null) {\n payload = object;\n } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {\n payload = serializeBasicTypes(mapperType, objectName, object);\n } else if (mapperType.match(/^Enum$/i) !== null) {\n const enumMapper = mapper as EnumMapper;\n payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);\n } else if (\n mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null\n ) {\n payload = serializeDateTypes(mapperType, object, objectName);\n } else if (mapperType.match(/^ByteArray$/i) !== null) {\n payload = serializeByteArrayType(objectName, object);\n } else if (mapperType.match(/^Base64Url$/i) !== null) {\n payload = serializeBase64UrlType(objectName, object);\n } else if (mapperType.match(/^Sequence$/i) !== null) {\n payload = serializeSequenceType(\n this,\n mapper as SequenceMapper,\n object,\n objectName,\n Boolean(this.isXML),\n updatedOptions\n );\n } else if (mapperType.match(/^Dictionary$/i) !== null) {\n payload = serializeDictionaryType(\n this,\n mapper as DictionaryMapper,\n object,\n objectName,\n Boolean(this.isXML),\n updatedOptions\n );\n } else if (mapperType.match(/^Composite$/i) !== null) {\n payload = serializeCompositeType(\n this,\n mapper as CompositeMapper,\n object,\n objectName,\n Boolean(this.isXML),\n updatedOptions\n );\n }\n }\n return payload;\n }\n\n /**\n * Deserialize the given object based on its metadata defined in the mapper\n *\n * @param mapper - The mapper which defines the metadata of the serializable object\n *\n * @param responseBody - A valid Javascript entity to be deserialized\n *\n * @param objectName - Name of the deserialized object\n *\n * @param options - Controls behavior of XML parser and builder.\n *\n * @returns A valid deserialized Javascript object\n */\n deserialize(\n mapper: Mapper,\n responseBody: any,\n objectName: string,\n options: SerializerOptions = { xml: {} }\n ): any {\n const updatedOptions: RequiredSerializerOptions = {\n xml: {\n rootName: options.xml.rootName ?? \"\",\n includeRoot: options.xml.includeRoot ?? false,\n xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY,\n },\n ignoreUnknownProperties: options.ignoreUnknownProperties ?? false,\n };\n if (responseBody === undefined || responseBody === null) {\n if (this.isXML && mapper.type.name === \"Sequence\" && !mapper.xmlIsWrapped) {\n // Edge case for empty XML non-wrapped lists. xml2js can't distinguish\n // between the list being empty versus being missing,\n // so let's do the more user-friendly thing and return an empty list.\n responseBody = [];\n }\n // specifically check for undefined as default value can be a falsey value `0, \"\", false, null`\n if (mapper.defaultValue !== undefined) {\n responseBody = mapper.defaultValue;\n }\n return responseBody;\n }\n\n let payload: any;\n const mapperType = mapper.type.name;\n if (!objectName) {\n objectName = mapper.serializedName!;\n }\n\n if (mapperType.match(/^Composite$/i) !== null) {\n payload = deserializeCompositeType(\n this,\n mapper as CompositeMapper,\n responseBody,\n objectName,\n updatedOptions\n );\n } else {\n if (this.isXML) {\n const xmlCharKey = updatedOptions.xml.xmlCharKey;\n /**\n * If the mapper specifies this as a non-composite type value but the responseBody contains\n * both header (\"$\" i.e., XML_ATTRKEY) and body (\"#\" i.e., XML_CHARKEY) properties,\n * then just reduce the responseBody value to the body (\"#\" i.e., XML_CHARKEY) property.\n */\n if (responseBody[XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {\n responseBody = responseBody[xmlCharKey];\n }\n }\n\n if (mapperType.match(/^Number$/i) !== null) {\n payload = parseFloat(responseBody);\n if (isNaN(payload)) {\n payload = responseBody;\n }\n } else if (mapperType.match(/^Boolean$/i) !== null) {\n if (responseBody === \"true\") {\n payload = true;\n } else if (responseBody === \"false\") {\n payload = false;\n } else {\n payload = responseBody;\n }\n } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {\n payload = responseBody;\n } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {\n payload = new Date(responseBody);\n } else if (mapperType.match(/^UnixTime$/i) !== null) {\n payload = unixTimeToDate(responseBody);\n } else if (mapperType.match(/^ByteArray$/i) !== null) {\n payload = base64.decodeString(responseBody);\n } else if (mapperType.match(/^Base64Url$/i) !== null) {\n payload = base64UrlToByteArray(responseBody);\n } else if (mapperType.match(/^Sequence$/i) !== null) {\n payload = deserializeSequenceType(\n this,\n mapper as SequenceMapper,\n responseBody,\n objectName,\n updatedOptions\n );\n } else if (mapperType.match(/^Dictionary$/i) !== null) {\n payload = deserializeDictionaryType(\n this,\n mapper as DictionaryMapper,\n responseBody,\n objectName,\n updatedOptions\n );\n }\n }\n\n if (mapper.isConstant) {\n payload = mapper.defaultValue;\n }\n\n return payload;\n }\n}\n\n/**\n * Method that creates and returns a Serializer.\n * @param modelMappers - Known models to map\n * @param isXML - If XML should be supported\n */\nexport function createSerializer(\n modelMappers: { [key: string]: any } = {},\n isXML: boolean = false\n): Serializer {\n return new SerializerImpl(modelMappers, isXML);\n}\n\nfunction trimEnd(str: string, ch: string): string {\n let len = str.length;\n while (len - 1 >= 0 && str[len - 1] === ch) {\n --len;\n }\n return str.substr(0, len);\n}\n\nfunction bufferToBase64Url(buffer: Uint8Array): string | undefined {\n if (!buffer) {\n return undefined;\n }\n if (!(buffer instanceof Uint8Array)) {\n throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);\n }\n // Uint8Array to Base64.\n const str = base64.encodeByteArray(buffer);\n // Base64 to Base64Url.\n return trimEnd(str, \"=\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\nfunction base64UrlToByteArray(str: string): Uint8Array | undefined {\n if (!str) {\n return undefined;\n }\n if (str && typeof str.valueOf() !== \"string\") {\n throw new Error(\"Please provide an input of type string for converting to Uint8Array\");\n }\n // Base64Url to Base64.\n str = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Base64 to Uint8Array.\n return base64.decodeString(str);\n}\n\nfunction splitSerializeName(prop: string | undefined): string[] {\n const classes: string[] = [];\n let partialclass = \"\";\n if (prop) {\n const subwords = prop.split(\".\");\n\n for (const item of subwords) {\n if (item.charAt(item.length - 1) === \"\\\\\") {\n partialclass += item.substr(0, item.length - 1) + \".\";\n } else {\n partialclass += item;\n classes.push(partialclass);\n partialclass = \"\";\n }\n }\n }\n\n return classes;\n}\n\nfunction dateToUnixTime(d: string | Date): number | undefined {\n if (!d) {\n return undefined;\n }\n\n if (typeof d.valueOf() === \"string\") {\n d = new Date(d as string);\n }\n return Math.floor((d as Date).getTime() / 1000);\n}\n\nfunction unixTimeToDate(n: number): Date | undefined {\n if (!n) {\n return undefined;\n }\n return new Date(n * 1000);\n}\n\nfunction serializeBasicTypes(typeName: string, objectName: string, value: any): any {\n if (value !== null && value !== undefined) {\n if (typeName.match(/^Number$/i) !== null) {\n if (typeof value !== \"number\") {\n throw new Error(`${objectName} with value ${value} must be of type number.`);\n }\n } else if (typeName.match(/^String$/i) !== null) {\n if (typeof value.valueOf() !== \"string\") {\n throw new Error(`${objectName} with value \"${value}\" must be of type string.`);\n }\n } else if (typeName.match(/^Uuid$/i) !== null) {\n if (!(typeof value.valueOf() === \"string\" && isValidUuid(value))) {\n throw new Error(\n `${objectName} with value \"${value}\" must be of type string and a valid uuid.`\n );\n }\n } else if (typeName.match(/^Boolean$/i) !== null) {\n if (typeof value !== \"boolean\") {\n throw new Error(`${objectName} with value ${value} must be of type boolean.`);\n }\n } else if (typeName.match(/^Stream$/i) !== null) {\n const objectType = typeof value;\n if (\n objectType !== \"string\" &&\n typeof value.pipe !== \"function\" &&\n !(value instanceof ArrayBuffer) &&\n !ArrayBuffer.isView(value) &&\n // File objects count as a type of Blob, so we want to use instanceof explicitly\n !((typeof Blob === \"function\" || typeof Blob === \"object\") && value instanceof Blob) &&\n objectType !== \"function\"\n ) {\n throw new Error(\n `${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, NodeJS.ReadableStream, or () => NodeJS.ReadableStream.`\n );\n }\n }\n }\n return value;\n}\n\nfunction serializeEnumType(objectName: string, allowedValues: Array<any>, value: any): any {\n if (!allowedValues) {\n throw new Error(\n `Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`\n );\n }\n const isPresent = allowedValues.some((item) => {\n if (typeof item.valueOf() === \"string\") {\n return item.toLowerCase() === value.toLowerCase();\n }\n return item === value;\n });\n if (!isPresent) {\n throw new Error(\n `${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(\n allowedValues\n )}.`\n );\n }\n return value;\n}\n\nfunction serializeByteArrayType(objectName: string, value: any): any {\n if (value !== undefined && value !== null) {\n if (!(value instanceof Uint8Array)) {\n throw new Error(`${objectName} must be of type Uint8Array.`);\n }\n value = base64.encodeByteArray(value);\n }\n return value;\n}\n\nfunction serializeBase64UrlType(objectName: string, value: any): any {\n if (value !== undefined && value !== null) {\n if (!(value instanceof Uint8Array)) {\n throw new Error(`${objectName} must be of type Uint8Array.`);\n }\n value = bufferToBase64Url(value);\n }\n return value;\n}\n\nfunction serializeDateTypes(typeName: string, value: any, objectName: string): any {\n if (value !== undefined && value !== null) {\n if (typeName.match(/^Date$/i) !== null) {\n if (\n !(\n value instanceof Date ||\n (typeof value.valueOf() === \"string\" && !isNaN(Date.parse(value)))\n )\n ) {\n throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);\n }\n value =\n value instanceof Date\n ? value.toISOString().substring(0, 10)\n : new Date(value).toISOString().substring(0, 10);\n } else if (typeName.match(/^DateTime$/i) !== null) {\n if (\n !(\n value instanceof Date ||\n (typeof value.valueOf() === \"string\" && !isNaN(Date.parse(value)))\n )\n ) {\n throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);\n }\n value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();\n } else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {\n if (\n !(\n value instanceof Date ||\n (typeof value.valueOf() === \"string\" && !isNaN(Date.parse(value)))\n )\n ) {\n throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);\n }\n value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();\n } else if (typeName.match(/^UnixTime$/i) !== null) {\n if (\n !(\n value instanceof Date ||\n (typeof value.valueOf() === \"string\" && !isNaN(Date.parse(value)))\n )\n ) {\n throw new Error(\n `${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +\n `for it to be serialized in UnixTime/Epoch format.`\n );\n }\n value = dateToUnixTime(value);\n } else if (typeName.match(/^TimeSpan$/i) !== null) {\n if (!isDuration(value)) {\n throw new Error(\n `${objectName} must be a string in ISO 8601 format. Instead was \"${value}\".`\n );\n }\n }\n }\n return value;\n}\n\nfunction serializeSequenceType(\n serializer: Serializer,\n mapper: SequenceMapper,\n object: any,\n objectName: string,\n isXml: boolean,\n options: RequiredSerializerOptions\n): any {\n if (!Array.isArray(object)) {\n throw new Error(`${objectName} must be of type Array.`);\n }\n let elementType = mapper.type.element;\n if (!elementType || typeof elementType !== \"object\") {\n throw new Error(\n `element\" metadata for an Array must be defined in the ` +\n `mapper and it must of type \"object\" in ${objectName}.`\n );\n }\n // Quirk: Composite mappers referenced by `element` might\n // not have *all* properties declared (like uberParent),\n // so let's try to look up the full definition by name.\n if (elementType.type.name === \"Composite\" && elementType.type.className) {\n elementType = serializer.modelMappers[elementType.type.className] ?? elementType;\n }\n const tempArray = [];\n for (let i = 0; i < object.length; i++) {\n const serializedValue = serializer.serialize(elementType, object[i], objectName, options);\n if (isXml && elementType.xmlNamespace) {\n const xmlnsKey = elementType.xmlNamespacePrefix\n ? `xmlns:${elementType.xmlNamespacePrefix}`\n : \"xmlns\";\n if (elementType.type.name === \"Composite\") {\n tempArray[i] = { ...serializedValue };\n tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };\n } else {\n tempArray[i] = {};\n tempArray[i][options.xml.xmlCharKey] = serializedValue;\n tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };\n }\n } else {\n tempArray[i] = serializedValue;\n }\n }\n return tempArray;\n}\n\nfunction serializeDictionaryType(\n serializer: Serializer,\n mapper: DictionaryMapper,\n object: any,\n objectName: string,\n isXml: boolean,\n options: RequiredSerializerOptions\n): any {\n if (typeof object !== \"object\") {\n throw new Error(`${objectName} must be of type object.`);\n }\n const valueType = mapper.type.value;\n if (!valueType || typeof valueType !== \"object\") {\n throw new Error(\n `\"value\" metadata for a Dictionary must be defined in the ` +\n `mapper and it must of type \"object\" in ${objectName}.`\n );\n }\n const tempDictionary: { [key: string]: any } = {};\n for (const key of Object.keys(object)) {\n const serializedValue = serializer.serialize(valueType, object[key], objectName, options);\n // If the element needs an XML namespace we need to add it within the $ property\n tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);\n }\n\n // Add the namespace to the root element if needed\n if (isXml && mapper.xmlNamespace) {\n const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : \"xmlns\";\n const result = tempDictionary;\n result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };\n return result;\n }\n\n return tempDictionary;\n}\n\n/**\n * Resolves the additionalProperties property from a referenced mapper\n * @param serializer - the serializer containing the entire set of mappers\n * @param mapper - the composite mapper to resolve\n * @param objectName - name of the object being serialized\n */\nfunction resolveAdditionalProperties(\n serializer: Serializer,\n mapper: CompositeMapper,\n objectName: string\n): SequenceMapper | BaseMapper | CompositeMapper | DictionaryMapper | EnumMapper | undefined {\n const additionalProperties = mapper.type.additionalProperties;\n\n if (!additionalProperties && mapper.type.className) {\n const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);\n return modelMapper?.type.additionalProperties;\n }\n\n return additionalProperties;\n}\n\n/**\n * Finds the mapper referenced by className\n * @param serializer - the serializer containing the entire set of mappers\n * @param mapper - the composite mapper to resolve\n * @param objectName - name of the object being serialized\n */\nfunction resolveReferencedMapper(\n serializer: Serializer,\n mapper: CompositeMapper,\n objectName: string\n): CompositeMapper | undefined {\n const className = mapper.type.className;\n if (!className) {\n throw new Error(\n `Class name for model \"${objectName}\" is not provided in the mapper \"${JSON.stringify(\n mapper,\n undefined,\n 2\n )}\".`\n );\n }\n\n return serializer.modelMappers[className];\n}\n\n/**\n * Resolves a composite mapper's modelProperties.\n * @param serializer - the serializer containing the entire set of mappers\n * @param mapper - the composite mapper to resolve\n */\nfunction resolveModelProperties(\n serializer: Serializer,\n mapper: CompositeMapper,\n objectName: string\n): { [propertyName: string]: Mapper } {\n let modelProps = mapper.type.modelProperties;\n if (!modelProps) {\n const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);\n if (!modelMapper) {\n throw new Error(`mapper() cannot be null or undefined for model \"${mapper.type.className}\".`);\n }\n modelProps = modelMapper?.type.modelProperties;\n if (!modelProps) {\n throw new Error(\n `modelProperties cannot be null or undefined in the ` +\n `mapper \"${JSON.stringify(modelMapper)}\" of type \"${\n mapper.type.className\n }\" for object \"${objectName}\".`\n );\n }\n }\n\n return modelProps;\n}\n\nfunction serializeCompositeType(\n serializer: Serializer,\n mapper: CompositeMapper,\n object: any,\n objectName: string,\n isXml: boolean,\n options: RequiredSerializerOptions\n): any {\n if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {\n mapper = getPolymorphicMapper(serializer, mapper, object, \"clientName\");\n }\n\n if (object !== undefined && object !== null) {\n const payload: any = {};\n const modelProps = resolveModelProperties(serializer, mapper, objectName);\n for (const key of Object.keys(modelProps)) {\n const propertyMapper = modelProps[key];\n if (propertyMapper.readOnly) {\n continue;\n }\n\n let propName: string | undefined;\n let parentObject: any = payload;\n if (serializer.isXML) {\n if (propertyMapper.xmlIsWrapped) {\n propName = propertyMapper.xmlName;\n } else {\n propName = propertyMapper.xmlElementName || propertyMapper.xmlName;\n }\n } else {\n const paths = splitSerializeName(propertyMapper.serializedName!);\n propName = paths.pop();\n\n for (const pathName of paths) {\n const childObject = parentObject[pathName];\n if (\n (childObject === undefined || childObject === null) &&\n ((object[key] !== undefined && object[key] !== null) ||\n propertyMapper.defaultValue !== undefined)\n ) {\n parentObject[pathName] = {};\n }\n parentObject = parentObject[pathName];\n }\n }\n\n if (parentObject !== undefined && parentObject !== null) {\n if (isXml && mapper.xmlNamespace) {\n const xmlnsKey = mapper.xmlNamespacePrefix\n ? `xmlns:${mapper.xmlNamespacePrefix}`\n : \"xmlns\";\n parentObject[XML_ATTRKEY] = {\n ...parentObject[XML_ATTRKEY],\n [xmlnsKey]: mapper.xmlNamespace,\n };\n }\n const propertyObjectName =\n propertyMapper.serializedName !== \"\"\n ? objectName + \".\" + propertyMapper.serializedName\n : objectName;\n\n let toSerialize = object[key];\n const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);\n if (\n polymorphicDiscriminator &&\n polymorphicDiscriminator.clientName === key &&\n (toSerialize === undefined || toSerialize === null)\n ) {\n toSerialize = mapper.serializedName;\n }\n\n const serializedValue = serializer.serialize(\n propertyMapper,\n toSerialize,\n propertyObjectName,\n options\n );\n if (serializedValue !== undefined && propName !== undefined && propName !== null) {\n const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);\n if (isXml && propertyMapper.xmlIsAttribute) {\n // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.\n // This keeps things simple while preventing name collision\n // with names in user documents.\n parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {};\n parentObject[XML_ATTRKEY][propName] = serializedValue;\n } else if (isXml && propertyMapper.xmlIsWrapped) {\n parentObject[propName] = { [propertyMapper.xmlElementName!]: value };\n } else {\n parentObject[propName] = value;\n }\n }\n }\n }\n\n const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);\n if (additionalPropertiesMapper) {\n const propNames = Object.keys(modelProps);\n for (const clientPropName in object) {\n const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);\n if (isAdditionalProperty) {\n payload[clientPropName] = serializer.serialize(\n additionalPropertiesMapper,\n object[clientPropName],\n objectName + '[\"' + clientPropName + '\"]',\n options\n );\n }\n }\n }\n\n return payload;\n }\n return object;\n}\n\nfunction getXmlObjectValue(\n propertyMapper: Mapper,\n serializedValue: any,\n isXml: boolean,\n options: RequiredSerializerOptions\n): any {\n if (!isXml || !propertyMapper.xmlNamespace) {\n return serializedValue;\n }\n\n const xmlnsKey = propertyMapper.xmlNamespacePrefix\n ? `xmlns:${propertyMapper.xmlNamespacePrefix}`\n : \"xmlns\";\n const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };\n\n if ([\"Composite\"].includes(propertyMapper.type.name)) {\n if (serializedValue[XML_ATTRKEY]) {\n return serializedValue;\n } else {\n const result: any = { ...serializedValue };\n result[XML_ATTRKEY] = xmlNamespace;\n return result;\n }\n }\n const result: any = {};\n result[options.xml.xmlCharKey] = serializedValue;\n result[XML_ATTRKEY] = xmlNamespace;\n return result;\n}\n\nfunction isSpecialXmlProperty(propertyName: string, options: RequiredSerializerOptions): boolean {\n return [XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);\n}\n\nfunction deserializeCompositeType(\n serializer: Serializer,\n mapper: CompositeMapper,\n responseBody: any,\n objectName: string,\n options: RequiredSerializerOptions\n): any {\n const xmlCharKey = options.xml.xmlCharKey ?? XML_CHARKEY;\n if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {\n mapper = getPolymorphicMapper(serializer, mapper, responseBody, \"serializedName\");\n }\n\n const modelProps = resolveModelProperties(serializer, mapper, objectName);\n let instance: { [key: string]: any } = {};\n const handledPropertyNames: string[] = [];\n\n for (const key of Object.keys(modelProps)) {\n const propertyMapper = modelProps[key];\n const paths = splitSerializeName(modelProps[key].serializedName!);\n handledPropertyNames.push(paths[0]);\n const { serializedName, xmlName, xmlElementName } = propertyMapper;\n let propertyObjectName = objectName;\n if (serializedName !== \"\" && serializedName !== undefined) {\n propertyObjectName = objectName + \".\" + serializedName;\n }\n\n const headerCollectionPrefix = (propertyMapper as DictionaryMapper).headerCollectionPrefix;\n if (headerCollectionPrefix) {\n const dictionary: any = {};\n for (const headerKey of Object.keys(responseBody)) {\n if (headerKey.startsWith(headerCollectionPrefix)) {\n dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(\n (propertyMapper as DictionaryMapper).type.value,\n responseBody[headerKey],\n propertyObjectName,\n options\n );\n }\n\n handledPropertyNames.push(headerKey);\n }\n instance[key] = dictionary;\n } else if (serializer.isXML) {\n if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) {\n instance[key] = serializer.deserialize(\n propertyMapper,\n responseBody[XML_ATTRKEY][xmlName!],\n propertyObjectName,\n options\n );\n } else if (propertyMapper.xmlIsMsText) {\n if (responseBody[xmlCharKey] !== undefined) {\n instance[key] = responseBody[xmlCharKey];\n } else if (typeof responseBody === \"string\") {\n // The special case where xml parser parses \"<Name>content</Name>\" into JSON of\n // `{ name: \"content\"}` instead of `{ name: { \"_\": \"content\" }}`\n instance[key] = responseBody;\n }\n } else {\n const propertyName = xmlElementName || xmlName || serializedName;\n if (propertyMapper.xmlIsWrapped) {\n /* a list of <xmlElementName> wrapped by <xmlName>\n For the xml example below\n <Cors>\n <CorsRule>...</CorsRule>\n <CorsRule>...</CorsRule>\n </Cors>\n the responseBody has\n {\n Cors: {\n CorsRule: [{...}, {...}]\n }\n }\n xmlName is \"Cors\" and xmlElementName is\"CorsRule\".\n */\n const wrapped = responseBody[xmlName!];\n const elementList = wrapped?.[xmlElementName!] ?? [];\n instance[key] = serializer.deserialize(\n propertyMapper,\n elementList,\n propertyObjectName,\n options\n );\n handledPropertyNames.push(xmlName!);\n } else {\n const property = responseBody[propertyName!];\n instance[key] = serializer.deserialize(\n propertyMapper,\n property,\n propertyObjectName,\n options\n );\n handledPropertyNames.push(propertyName!);\n }\n }\n } else {\n // deserialize the property if it is present in the provided responseBody instance\n let propertyInstance;\n let res = responseBody;\n // traversing the object step by step.\n let steps = 0;\n for (const item of paths) {\n if (!res) break;\n steps++;\n res = res[item];\n }\n // only accept null when reaching the last position of object otherwise it would be undefined\n if (res === null && steps < paths.length) {\n res = undefined;\n }\n propertyInstance = res;\n const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;\n // checking that the model property name (key)(ex: \"fishtype\") and the\n // clientName of the polymorphicDiscriminator {metadata} (ex: \"fishtype\")\n // instead of the serializedName of the polymorphicDiscriminator (ex: \"fish.type\")\n // is a better approach. The generator is not consistent with escaping '\\.' in the\n // serializedName of the property (ex: \"fish\\.type\") that is marked as polymorphic discriminator\n // and the serializedName of the metadata polymorphicDiscriminator (ex: \"fish.type\"). However,\n // the clientName transformation of the polymorphicDiscriminator (ex: \"fishtype\") and\n // the transformation of model property name (ex: \"fishtype\") is done consistently.\n // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.\n if (\n polymorphicDiscriminator &&\n key === polymorphicDiscriminator.clientName &&\n (propertyInstance === undefined || propertyInstance === null)\n ) {\n propertyInstance = mapper.serializedName;\n }\n\n let serializedValue;\n // paging\n if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === \"\") {\n propertyInstance = responseBody[key];\n const arrayInstance = serializer.deserialize(\n propertyMapper,\n propertyInstance,\n propertyObjectName,\n options\n );\n // Copy over any properties that have already been added into the instance, where they do\n // not exist on the newly de-serialized array\n for (const [k, v] of Object.entries(instance)) {\n if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {\n arrayInstance[k] = v;\n }\n }\n instance = arrayInstance;\n } else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {\n serializedValue = serializer.deserialize(\n propertyMapper,\n propertyInstance,\n propertyObjectName,\n options\n );\n instance[key] = serializedValue;\n }\n }\n }\n\n const additionalPropertiesMapper = mapper.type.additionalProperties;\n if (additionalPropertiesMapper) {\n const isAdditionalProperty = (responsePropName: string): boolean => {\n for (const clientPropName in modelProps) {\n const paths = splitSerializeName(modelProps[clientPropName].serializedName);\n if (paths[0] === responsePropName) {\n return false;\n }\n }\n return true;\n };\n\n for (const responsePropName in responseBody) {\n if (isAdditionalProperty(responsePropName)) {\n instance[responsePropName] = serializer.deserialize(\n additionalPropertiesMapper,\n responseBody[responsePropName],\n objectName + '[\"' + responsePropName + '\"]',\n options\n );\n }\n }\n } else if (responseBody && !options.ignoreUnknownProperties) {\n for (const key of Object.keys(responseBody)) {\n if (\n instance[key] === undefined &&\n !handledPropertyNames.includes(key) &&\n !isSpecialXmlProperty(key, options)\n ) {\n instance[key] = responseBody[key];\n }\n }\n }\n\n return instance;\n}\n\nfunction deserializeDictionaryType(\n serializer: Serializer,\n mapper: DictionaryMapper,\n responseBody: any,\n objectName: string,\n options: RequiredSerializerOptions\n): any {\n /* jshint validthis: true */\n const value = mapper.type.value;\n if (!value || typeof value !== \"object\") {\n throw new Error(\n `\"value\" metadata for a Dictionary must be defined in the ` +\n `mapper and it must of type \"object\" in ${objectName}`\n );\n }\n if (responseBody) {\n const tempDictionary: { [key: string]: any } = {};\n for (const key of Object.keys(responseBody)) {\n tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);\n }\n return tempDictionary;\n }\n return responseBody;\n}\n\nfunction deserializeSequenceType(\n serializer: Serializer,\n mapper: SequenceMapper,\n responseBody: any,\n objectName: string,\n options: RequiredSerializerOptions\n): any {\n let element = mapper.type.element;\n if (!element || typeof element !== \"object\") {\n throw new Error(\n `element\" metadata for an Array must be defined in the ` +\n `mapper and it must of type \"object\" in ${objectName}`\n );\n }\n if (responseBody) {\n if (!Array.isArray(responseBody)) {\n // xml2js will interpret a single element array as just the element, so force it to be an array\n responseBody = [responseBody];\n }\n\n // Quirk: Composite mappers referenced by `element` might\n // not have *all* properties declared (like uberParent),\n // so let's try to look up the full definition by name.\n if (element.type.name === \"Composite\" && element.type.className) {\n element = serializer.modelMappers[element.type.className] ?? element;\n }\n\n const tempArray = [];\n for (let i = 0; i < responseBody.length; i++) {\n tempArray[i] = serializer.deserialize(\n element,\n responseBody[i],\n `${objectName}[${i}]`,\n options\n );\n }\n return tempArray;\n }\n return responseBody;\n}\n\nfunction getIndexDiscriminator(\n discriminators: Record<string, CompositeMapper>,\n discriminatorValue: string,\n typeName: string\n): CompositeMapper | undefined {\n const typeNamesToCheck = [typeName];\n while (typeNamesToCheck.length) {\n const currentName = typeNamesToCheck.shift();\n const indexDiscriminator =\n discriminatorValue === currentName\n ? discriminatorValue\n : currentName + \".\" + discriminatorValue;\n if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {\n return discriminators[indexDiscriminator];\n } else {\n for (const [name, mapper] of Object.entries(discriminators)) {\n if (\n name.startsWith(currentName + \".\") &&\n mapper.type.uberParent === currentName &&\n mapper.type.className\n ) {\n typeNamesToCheck.push(mapper.type.className);\n }\n }\n }\n }\n\n return undefined;\n}\n\nfunction getPolymorphicMapper(\n serializer: Serializer,\n mapper: CompositeMapper,\n object: any,\n polymorphicPropertyName: \"clientName\" | \"serializedName\"\n): CompositeMapper {\n const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);\n\n if (polymorphicDiscriminator) {\n let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];\n if (discriminatorName) {\n // The serializedName might have \\\\, which we just want to ignore\n if (polymorphicPropertyName === \"serializedName\") {\n discriminatorName = discriminatorName.replace(/\\\\/gi, \"\");\n }\n const discriminatorValue = object[discriminatorName];\n const typeName = mapper.type.uberParent ?? mapper.type.className;\n\n if (typeof discriminatorValue === \"string\" && typeName) {\n const polymorphicMapper = getIndexDiscriminator(\n serializer.modelMappers.discriminators,\n discriminatorValue,\n typeName\n );\n if (polymorphicMapper) {\n mapper = polymorphicMapper;\n }\n }\n }\n }\n return mapper;\n}\n\nfunction getPolymorphicDiscriminatorRecursively(\n serializer: Serializer,\n mapper: CompositeMapper\n): PolymorphicDiscriminator | undefined {\n return (\n mapper.type.polymorphicDiscriminator ||\n getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||\n getPolymorphicDiscriminatorSafely(serializer, mapper.type.className)\n );\n}\n\nfunction getPolymorphicDiscriminatorSafely(\n serializer: Serializer,\n typeName?: string\n): PolymorphicDiscriminator | undefined {\n return (\n typeName &&\n serializer.modelMappers[typeName] &&\n serializer.modelMappers[typeName].type.polymorphicDiscriminator\n );\n}\n\n/**\n * Known types of Mappers\n */\nexport const MapperTypeNames = {\n Base64Url: \"Base64Url\",\n Boolean: \"Boolean\",\n ByteArray: \"ByteArray\",\n Composite: \"Composite\",\n Date: \"Date\",\n DateTime: \"DateTime\",\n DateTimeRfc1123: \"DateTimeRfc1123\",\n Dictionary: \"Dictionary\",\n Enum: \"Enum\",\n Number: \"Number\",\n Object: \"Object\",\n Sequence: \"Sequence\",\n String: \"String\",\n Stream: \"Stream\",\n TimeSpan: \"TimeSpan\",\n UnixTime: \"UnixTime\",\n} as const;\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n CompositeMapper,\n Mapper,\n OperationArguments,\n OperationParameter,\n OperationRequest,\n OperationRequestInfo,\n ParameterPath,\n} from \"./interfaces\";\n\n/**\n * @internal\n * Retrieves the value to use for a given operation argument\n * @param operationArguments - The arguments passed from the generated client\n * @param parameter - The parameter description\n * @param fallbackObject - If something isn't found in the arguments bag, look here.\n * Generally used to look at the service client properties.\n */\nexport function getOperationArgumentValueFromParameter(\n operationArguments: OperationArguments,\n parameter: OperationParameter,\n fallbackObject?: { [parameterName: string]: any }\n): any {\n let parameterPath = parameter.parameterPath;\n const parameterMapper = parameter.mapper;\n let value: any;\n if (typeof parameterPath === \"string\") {\n parameterPath = [parameterPath];\n }\n if (Array.isArray(parameterPath)) {\n if (parameterPath.length > 0) {\n if (parameterMapper.isConstant) {\n value = parameterMapper.defaultValue;\n } else {\n let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);\n\n if (!propertySearchResult.propertyFound && fallbackObject) {\n propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);\n }\n\n let useDefaultValue = false;\n if (!propertySearchResult.propertyFound) {\n useDefaultValue =\n parameterMapper.required ||\n (parameterPath[0] === \"options\" && parameterPath.length === 2);\n }\n value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;\n }\n }\n } else {\n if (parameterMapper.required) {\n value = {};\n }\n\n for (const propertyName in parameterPath) {\n const propertyMapper: Mapper = (parameterMapper as CompositeMapper).type.modelProperties![\n propertyName\n ];\n const propertyPath: ParameterPath = parameterPath[propertyName];\n const propertyValue: any = getOperationArgumentValueFromParameter(\n operationArguments,\n {\n parameterPath: propertyPath,\n mapper: propertyMapper,\n },\n fallbackObject\n );\n if (propertyValue !== undefined) {\n if (!value) {\n value = {};\n }\n value[propertyName] = propertyValue;\n }\n }\n }\n return value;\n}\n\ninterface PropertySearchResult {\n propertyValue?: any;\n propertyFound: boolean;\n}\n\nfunction getPropertyFromParameterPath(\n parent: { [parameterName: string]: any },\n parameterPath: string[]\n): PropertySearchResult {\n const result: PropertySearchResult = { propertyFound: false };\n let i = 0;\n for (; i < parameterPath.length; ++i) {\n const parameterPathPart: string = parameterPath[i];\n // Make sure to check inherited properties too, so don't use hasOwnProperty().\n if (parent && parameterPathPart in parent) {\n parent = parent[parameterPathPart];\n } else {\n break;\n }\n }\n if (i === parameterPath.length) {\n result.propertyValue = parent;\n result.propertyFound = true;\n }\n return result;\n}\n\nconst operationRequestMap = new WeakMap<OperationRequest, OperationRequestInfo>();\nconst originalRequestSymbol = Symbol.for(\"@azure/core-client original request\");\n\nfunction hasOriginalRequest(\n request: OperationRequest\n): request is OperationRequest & { [originalRequestSymbol]: OperationRequest } {\n return originalRequestSymbol in request;\n}\n\nexport function getOperationRequestInfo(request: OperationRequest): OperationRequestInfo {\n if (hasOriginalRequest(request)) {\n return getOperationRequestInfo(request[originalRequestSymbol]);\n }\n let info = operationRequestMap.get(request);\n\n if (!info) {\n info = {};\n operationRequestMap.set(request, info);\n }\n return info;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n FullOperationResponse,\n OperationRequest,\n OperationResponseMap,\n OperationSpec,\n RequiredSerializerOptions,\n SerializerOptions,\n XML_CHARKEY,\n XmlOptions,\n} from \"./interfaces\";\nimport {\n PipelinePolicy,\n PipelineRequest,\n PipelineResponse,\n RestError,\n SendRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { MapperTypeNames } from \"./serializer\";\nimport { getOperationRequestInfo } from \"./operationHelpers\";\n\nconst defaultJsonContentTypes = [\"application/json\", \"text/json\"];\nconst defaultXmlContentTypes = [\"application/xml\", \"application/atom+xml\"];\n\n/**\n * The programmatic identifier of the deserializationPolicy.\n */\nexport const deserializationPolicyName = \"deserializationPolicy\";\n\n/**\n * Options to configure API response deserialization.\n */\nexport interface DeserializationPolicyOptions {\n /**\n * Configures the expected content types for the deserialization of\n * JSON and XML response bodies.\n */\n expectedContentTypes?: DeserializationContentTypes;\n\n /**\n * A function that is able to parse XML. Required for XML support.\n */\n parseXML?: (str: string, opts?: XmlOptions) => Promise<any>;\n\n /**\n * Configures behavior of xml parser and builder.\n */\n serializerOptions?: SerializerOptions;\n}\n\n/**\n * The content-types that will indicate that an operation response should be deserialized in a\n * particular way.\n */\nexport interface DeserializationContentTypes {\n /**\n * The content-types that indicate that an operation response should be deserialized as JSON.\n * Defaults to [ \"application/json\", \"text/json\" ].\n */\n json?: string[];\n\n /**\n * The content-types that indicate that an operation response should be deserialized as XML.\n * Defaults to [ \"application/xml\", \"application/atom+xml\" ].\n */\n xml?: string[];\n}\n\n/**\n * This policy handles parsing out responses according to OperationSpecs on the request.\n */\nexport function deserializationPolicy(options: DeserializationPolicyOptions = {}): PipelinePolicy {\n const jsonContentTypes = options.expectedContentTypes?.json ?? defaultJsonContentTypes;\n const xmlContentTypes = options.expectedContentTypes?.xml ?? defaultXmlContentTypes;\n const parseXML = options.parseXML;\n const serializerOptions = options.serializerOptions;\n const updatedOptions: RequiredSerializerOptions = {\n xml: {\n rootName: serializerOptions?.xml.rootName ?? \"\",\n includeRoot: serializerOptions?.xml.includeRoot ?? false,\n xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY,\n },\n };\n\n return {\n name: deserializationPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n const response = await next(request);\n return deserializeResponseBody(\n jsonContentTypes,\n xmlContentTypes,\n response,\n updatedOptions,\n parseXML\n );\n },\n };\n}\n\nfunction getOperationResponseMap(\n parsedResponse: PipelineResponse\n): undefined | OperationResponseMap {\n let result: OperationResponseMap | undefined;\n const request: OperationRequest = parsedResponse.request;\n const operationInfo = getOperationRequestInfo(request);\n const operationSpec = operationInfo?.operationSpec;\n if (operationSpec) {\n if (!operationInfo?.operationResponseGetter) {\n result = operationSpec.responses[parsedResponse.status];\n } else {\n result = operationInfo?.operationResponseGetter(operationSpec, parsedResponse);\n }\n }\n return result;\n}\n\nfunction shouldDeserializeResponse(parsedResponse: PipelineResponse): boolean {\n const request: OperationRequest = parsedResponse.request;\n const operationInfo = getOperationRequestInfo(request);\n const shouldDeserialize = operationInfo?.shouldDeserialize;\n let result: boolean;\n if (shouldDeserialize === undefined) {\n result = true;\n } else if (typeof shouldDeserialize === \"boolean\") {\n result = shouldDeserialize;\n } else {\n result = shouldDeserialize(parsedResponse);\n }\n return result;\n}\n\nasync function deserializeResponseBody(\n jsonContentTypes: string[],\n xmlContentTypes: string[],\n response: PipelineResponse,\n options: RequiredSerializerOptions,\n parseXML?: (str: string, opts?: XmlOptions) => Promise<any>\n): Promise<PipelineResponse> {\n const parsedResponse = await parse(\n jsonContentTypes,\n xmlContentTypes,\n response,\n options,\n parseXML\n );\n if (!shouldDeserializeResponse(parsedResponse)) {\n return parsedResponse;\n }\n\n const operationInfo = getOperationRequestInfo(parsedResponse.request);\n const operationSpec = operationInfo?.operationSpec;\n if (!operationSpec || !operationSpec.responses) {\n return parsedResponse;\n }\n\n const responseSpec = getOperationResponseMap(parsedResponse);\n const { error, shouldReturnResponse } = handleErrorResponse(\n parsedResponse,\n operationSpec,\n responseSpec,\n options\n );\n if (error) {\n throw error;\n } else if (shouldReturnResponse) {\n return parsedResponse;\n }\n\n // An operation response spec does exist for current status code, so\n // use it to deserialize the response.\n if (responseSpec) {\n if (responseSpec.bodyMapper) {\n let valueToDeserialize: any = parsedResponse.parsedBody;\n if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperTypeNames.Sequence) {\n valueToDeserialize =\n typeof valueToDeserialize === \"object\"\n ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName!]\n : [];\n }\n try {\n parsedResponse.parsedBody = operationSpec.serializer.deserialize(\n responseSpec.bodyMapper,\n valueToDeserialize,\n \"operationRes.parsedBody\",\n options\n );\n } catch (deserializeError: any) {\n const restError = new RestError(\n `Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`,\n {\n statusCode: parsedResponse.status,\n request: parsedResponse.request,\n response: parsedResponse,\n }\n );\n throw restError;\n }\n } else if (operationSpec.httpMethod === \"HEAD\") {\n // head methods never have a body, but we return a boolean to indicate presence/absence of the resource\n parsedResponse.parsedBody = response.status >= 200 && response.status < 300;\n }\n\n if (responseSpec.headersMapper) {\n parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(\n responseSpec.headersMapper,\n parsedResponse.headers.toJSON(),\n \"operationRes.parsedHeaders\",\n { xml: {}, ignoreUnknownProperties: true }\n );\n }\n }\n\n return parsedResponse;\n}\n\nfunction isOperationSpecEmpty(operationSpec: OperationSpec): boolean {\n const expectedStatusCodes = Object.keys(operationSpec.responses);\n return (\n expectedStatusCodes.length === 0 ||\n (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === \"default\")\n );\n}\n\nfunction handleErrorResponse(\n parsedResponse: FullOperationResponse,\n operationSpec: OperationSpec,\n responseSpec: OperationResponseMap | undefined,\n options: RequiredSerializerOptions\n): { error: RestError | null; shouldReturnResponse: boolean } {\n const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;\n const isExpectedStatusCode: boolean = isOperationSpecEmpty(operationSpec)\n ? isSuccessByStatus\n : !!responseSpec;\n\n if (isExpectedStatusCode) {\n if (responseSpec) {\n if (!responseSpec.isError) {\n return { error: null, shouldReturnResponse: false };\n }\n } else {\n return { error: null, shouldReturnResponse: false };\n }\n }\n\n const errorResponseSpec = responseSpec ?? operationSpec.responses.default;\n\n const initialErrorMessage = parsedResponse.request.streamResponseStatusCodes?.has(\n parsedResponse.status\n )\n ? `Unexpected status code: ${parsedResponse.status}`\n : (parsedResponse.bodyAsText as string);\n\n const error = new RestError(initialErrorMessage, {\n statusCode: parsedResponse.status,\n request: parsedResponse.request,\n response: parsedResponse,\n });\n\n // If the item failed but there's no error spec or default spec to deserialize the error,\n // we should fail so we just throw the parsed response\n if (!errorResponseSpec) {\n throw error;\n }\n\n const defaultBodyMapper = errorResponseSpec.bodyMapper;\n const defaultHeadersMapper = errorResponseSpec.headersMapper;\n\n try {\n // If error response has a body, try to deserialize it using default body mapper.\n // Then try to extract error code & message from it\n if (parsedResponse.parsedBody) {\n const parsedBody = parsedResponse.parsedBody;\n let deserializedError;\n\n if (defaultBodyMapper) {\n let valueToDeserialize: any = parsedBody;\n if (operationSpec.isXML && defaultBodyMapper.type.name === MapperTypeNames.Sequence) {\n valueToDeserialize = [];\n const elementName = defaultBodyMapper.xmlElementName;\n if (typeof parsedBody === \"object\" && elementName) {\n valueToDeserialize = parsedBody[elementName];\n }\n }\n deserializedError = operationSpec.serializer.deserialize(\n defaultBodyMapper,\n valueToDeserialize,\n \"error.response.parsedBody\",\n options\n );\n }\n\n const internalError: any = parsedBody.error || deserializedError || parsedBody;\n error.code = internalError.code;\n if (internalError.message) {\n error.message = internalError.message;\n }\n\n if (defaultBodyMapper) {\n (error.response! as FullOperationResponse).parsedBody = deserializedError;\n }\n }\n\n // If error response has headers, try to deserialize it using default header mapper\n if (parsedResponse.headers && defaultHeadersMapper) {\n (error.response! as FullOperationResponse).parsedHeaders =\n operationSpec.serializer.deserialize(\n defaultHeadersMapper,\n parsedResponse.headers.toJSON(),\n \"operationRes.parsedHeaders\"\n );\n }\n } catch (defaultError: any) {\n error.message = `Error \"${defaultError.message}\" occurred in deserializing the responseBody - \"${parsedResponse.bodyAsText}\" for the default response.`;\n }\n\n return { error, shouldReturnResponse: false };\n}\n\nasync function parse(\n jsonContentTypes: string[],\n xmlContentTypes: string[],\n operationResponse: FullOperationResponse,\n opts: RequiredSerializerOptions,\n parseXML?: (str: string, opts?: XmlOptions) => Promise<any>\n): Promise<FullOperationResponse> {\n if (\n !operationResponse.request.streamResponseStatusCodes?.has(operationResponse.status) &&\n operationResponse.bodyAsText\n ) {\n const text = operationResponse.bodyAsText;\n const contentType: string = operationResponse.headers.get(\"Content-Type\") || \"\";\n const contentComponents: string[] = !contentType\n ? []\n : contentType.split(\";\").map((component) => component.toLowerCase());\n\n try {\n if (\n contentComponents.length === 0 ||\n contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)\n ) {\n operationResponse.parsedBody = JSON.parse(text);\n return operationResponse;\n } else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {\n if (!parseXML) {\n throw new Error(\"Parsing XML not supported.\");\n }\n const body = await parseXML(text, opts.xml);\n operationResponse.parsedBody = body;\n return operationResponse;\n }\n } catch (err: any) {\n const msg = `Error \"${err}\" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;\n const errCode = err.code || RestError.PARSE_ERROR;\n const e = new RestError(msg, {\n code: errCode,\n statusCode: operationResponse.status,\n request: operationResponse.request,\n response: operationResponse,\n });\n throw e;\n }\n }\n\n return operationResponse;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { OperationParameter, OperationSpec } from \"./interfaces\";\nimport { MapperTypeNames } from \"./serializer\";\n\n/**\n * Gets the list of status codes for streaming responses.\n * @internal\n */\nexport function getStreamingResponseStatusCodes(operationSpec: OperationSpec): Set<number> {\n const result = new Set<number>();\n for (const statusCode in operationSpec.responses) {\n const operationResponse = operationSpec.responses[statusCode];\n if (\n operationResponse.bodyMapper &&\n operationResponse.bodyMapper.type.name === MapperTypeNames.Stream\n ) {\n result.add(Number(statusCode));\n }\n }\n return result;\n}\n\n/**\n * Get the path to this parameter's value as a dotted string (a.b.c).\n * @param parameter - The parameter to get the path string for.\n * @returns The path to this parameter's value as a dotted string.\n * @internal\n */\nexport function getPathStringFromParameter(parameter: OperationParameter): string {\n const { parameterPath, mapper } = parameter;\n let result: string;\n if (typeof parameterPath === \"string\") {\n result = parameterPath;\n } else if (Array.isArray(parameterPath)) {\n result = parameterPath.join(\".\");\n } else {\n result = mapper.serializedName!;\n }\n return result;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n DictionaryMapper,\n OperationArguments,\n OperationRequest,\n OperationSpec,\n RequiredSerializerOptions,\n SerializerOptions,\n XML_ATTRKEY,\n XML_CHARKEY,\n XmlOptions,\n} from \"./interfaces\";\nimport { PipelinePolicy, PipelineResponse, SendRequest } from \"@azure/core-rest-pipeline\";\nimport {\n getOperationArgumentValueFromParameter,\n getOperationRequestInfo,\n} from \"./operationHelpers\";\nimport { MapperTypeNames } from \"./serializer\";\nimport { getPathStringFromParameter } from \"./interfaceHelpers\";\n\n/**\n * The programmatic identifier of the serializationPolicy.\n */\nexport const serializationPolicyName = \"serializationPolicy\";\n\n/**\n * Options to configure API request serialization.\n */\nexport interface SerializationPolicyOptions {\n /**\n * A function that is able to write XML. Required for XML support.\n */\n stringifyXML?: (obj: any, opts?: XmlOptions) => string;\n\n /**\n * Configures behavior of xml parser and builder.\n */\n serializerOptions?: SerializerOptions;\n}\n\n/**\n * This policy handles assembling the request body and headers using\n * an OperationSpec and OperationArguments on the request.\n */\nexport function serializationPolicy(options: SerializationPolicyOptions = {}): PipelinePolicy {\n const stringifyXML = options.stringifyXML;\n\n return {\n name: serializationPolicyName,\n async sendRequest(request: OperationRequest, next: SendRequest): Promise<PipelineResponse> {\n const operationInfo = getOperationRequestInfo(request);\n const operationSpec = operationInfo?.operationSpec;\n const operationArguments = operationInfo?.operationArguments;\n if (operationSpec && operationArguments) {\n serializeHeaders(request, operationArguments, operationSpec);\n serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);\n }\n return next(request);\n },\n };\n}\n\n/**\n * @internal\n */\nexport function serializeHeaders(\n request: OperationRequest,\n operationArguments: OperationArguments,\n operationSpec: OperationSpec\n): void {\n if (operationSpec.headerParameters) {\n for (const headerParameter of operationSpec.headerParameters) {\n let headerValue = getOperationArgumentValueFromParameter(operationArguments, headerParameter);\n if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {\n headerValue = operationSpec.serializer.serialize(\n headerParameter.mapper,\n headerValue,\n getPathStringFromParameter(headerParameter)\n );\n const headerCollectionPrefix = (headerParameter.mapper as DictionaryMapper)\n .headerCollectionPrefix;\n if (headerCollectionPrefix) {\n for (const key of Object.keys(headerValue)) {\n request.headers.set(headerCollectionPrefix + key, headerValue[key]);\n }\n } else {\n request.headers.set(\n headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter),\n headerValue\n );\n }\n }\n }\n }\n const customHeaders = operationArguments.options?.requestOptions?.customHeaders;\n if (customHeaders) {\n for (const customHeaderName of Object.keys(customHeaders)) {\n request.headers.set(customHeaderName, customHeaders[customHeaderName]);\n }\n }\n}\n\n/**\n * @internal\n */\nexport function serializeRequestBody(\n request: OperationRequest,\n operationArguments: OperationArguments,\n operationSpec: OperationSpec,\n stringifyXML: (obj: any, opts?: XmlOptions) => string = function () {\n throw new Error(\"XML serialization unsupported!\");\n }\n): void {\n const serializerOptions = operationArguments.options?.serializerOptions;\n const updatedOptions: RequiredSerializerOptions = {\n xml: {\n rootName: serializerOptions?.xml.rootName ?? \"\",\n includeRoot: serializerOptions?.xml.includeRoot ?? false,\n xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY,\n },\n };\n\n const xmlCharKey = updatedOptions.xml.xmlCharKey;\n if (operationSpec.requestBody && operationSpec.requestBody.mapper) {\n request.body = getOperationArgumentValueFromParameter(\n operationArguments,\n operationSpec.requestBody\n );\n\n const bodyMapper = operationSpec.requestBody.mapper;\n const {\n required,\n serializedName,\n xmlName,\n xmlElementName,\n xmlNamespace,\n xmlNamespacePrefix,\n nullable,\n } = bodyMapper;\n const typeName = bodyMapper.type.name;\n\n try {\n if (\n (request.body !== undefined && request.body !== null) ||\n (nullable && request.body === null) ||\n required\n ) {\n const requestBodyParameterPathString: string = getPathStringFromParameter(\n operationSpec.requestBody\n );\n request.body = operationSpec.serializer.serialize(\n bodyMapper,\n request.body,\n requestBodyParameterPathString,\n updatedOptions\n );\n\n const isStream = typeName === MapperTypeNames.Stream;\n\n if (operationSpec.isXML) {\n const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : \"xmlns\";\n const value = getXmlValueWithNamespace(\n xmlNamespace,\n xmlnsKey,\n typeName,\n request.body,\n updatedOptions\n );\n\n if (typeName === MapperTypeNames.Sequence) {\n request.body = stringifyXML(\n prepareXMLRootList(\n value,\n xmlElementName || xmlName || serializedName!,\n xmlnsKey,\n xmlNamespace\n ),\n { rootName: xmlName || serializedName, xmlCharKey }\n );\n } else if (!isStream) {\n request.body = stringifyXML(value, {\n rootName: xmlName || serializedName,\n xmlCharKey,\n });\n }\n } else if (\n typeName === MapperTypeNames.String &&\n (operationSpec.contentType?.match(\"text/plain\") || operationSpec.mediaType === \"text\")\n ) {\n // the String serializer has validated that request body is a string\n // so just send the string.\n return;\n } else if (!isStream) {\n request.body = JSON.stringify(request.body);\n }\n }\n } catch (error: any) {\n throw new Error(\n `Error \"${error.message}\" occurred in serializing the payload - ${JSON.stringify(\n serializedName,\n undefined,\n \" \"\n )}.`\n );\n }\n } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {\n request.formData = {};\n for (const formDataParameter of operationSpec.formDataParameters) {\n const formDataParameterValue = getOperationArgumentValueFromParameter(\n operationArguments,\n formDataParameter\n );\n if (formDataParameterValue !== undefined && formDataParameterValue !== null) {\n const formDataParameterPropertyName: string =\n formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);\n request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(\n formDataParameter.mapper,\n formDataParameterValue,\n getPathStringFromParameter(formDataParameter),\n updatedOptions\n );\n }\n }\n }\n}\n\n/**\n * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself\n */\nfunction getXmlValueWithNamespace(\n xmlNamespace: string | undefined,\n xmlnsKey: string,\n typeName: string,\n serializedValue: any,\n options: RequiredSerializerOptions\n): any {\n // Composite and Sequence schemas already got their root namespace set during serialization\n // We just need to add xmlns to the other schema types\n if (xmlNamespace && ![\"Composite\", \"Sequence\", \"Dictionary\"].includes(typeName)) {\n const result: any = {};\n result[options.xml.xmlCharKey] = serializedValue;\n result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };\n return result;\n }\n\n return serializedValue;\n}\n\nfunction prepareXMLRootList(\n obj: any,\n elementName: string,\n xmlNamespaceKey?: string,\n xmlNamespace?: string\n): { [key: string]: any[] } {\n if (!Array.isArray(obj)) {\n obj = [obj];\n }\n if (!xmlNamespaceKey || !xmlNamespace) {\n return { [elementName]: obj };\n }\n\n const result = { [elementName]: obj };\n result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };\n return result;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { DeserializationPolicyOptions, deserializationPolicy } from \"./deserializationPolicy\";\nimport {\n InternalPipelineOptions,\n Pipeline,\n bearerTokenAuthenticationPolicy,\n createPipelineFromOptions,\n} from \"@azure/core-rest-pipeline\";\nimport { SerializationPolicyOptions, serializationPolicy } from \"./serializationPolicy\";\nimport { TokenCredential } from \"@azure/core-auth\";\n\n/**\n * Options for creating a Pipeline to use with ServiceClient.\n * Mostly for customizing the auth policy (if using token auth) or\n * the deserialization options when using XML.\n */\nexport interface InternalClientPipelineOptions extends InternalPipelineOptions {\n /**\n * Options to customize bearerTokenAuthenticationPolicy.\n */\n credentialOptions?: { credentialScopes: string | string[]; credential: TokenCredential };\n /**\n * Options to customize deserializationPolicy.\n */\n deserializationOptions?: DeserializationPolicyOptions;\n /**\n * Options to customize serializationPolicy.\n */\n serializationOptions?: SerializationPolicyOptions;\n}\n\n/**\n * Creates a new Pipeline for use with a Service Client.\n * Adds in deserializationPolicy by default.\n * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.\n * @param options - Options to customize the created pipeline.\n */\nexport function createClientPipeline(options: InternalClientPipelineOptions = {}): Pipeline {\n const pipeline = createPipelineFromOptions(options ?? {});\n if (options.credentialOptions) {\n pipeline.addPolicy(\n bearerTokenAuthenticationPolicy({\n credential: options.credentialOptions.credential,\n scopes: options.credentialOptions.credentialScopes,\n })\n );\n }\n\n pipeline.addPolicy(serializationPolicy(options.serializationOptions), { phase: \"Serialize\" });\n pipeline.addPolicy(deserializationPolicy(options.deserializationOptions), {\n phase: \"Deserialize\",\n });\n\n return pipeline;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { HttpClient, createDefaultHttpClient } from \"@azure/core-rest-pipeline\";\n\nlet cachedHttpClient: HttpClient | undefined;\n\nexport function getCachedDefaultHttpClient(): HttpClient {\n if (!cachedHttpClient) {\n cachedHttpClient = createDefaultHttpClient();\n }\n\n return cachedHttpClient;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { OperationArguments, OperationSpec, QueryCollectionFormat } from \"./interfaces\";\nimport { getOperationArgumentValueFromParameter } from \"./operationHelpers\";\nimport { getPathStringFromParameter } from \"./interfaceHelpers\";\n\nconst CollectionFormatToDelimiterMap: { [key in QueryCollectionFormat]: string } = {\n CSV: \",\",\n SSV: \" \",\n Multi: \"Multi\",\n TSV: \"\\t\",\n Pipes: \"|\",\n};\n\nexport function getRequestUrl(\n baseUri: string,\n operationSpec: OperationSpec,\n operationArguments: OperationArguments,\n fallbackObject: { [parameterName: string]: any }\n): string {\n const urlReplacements = calculateUrlReplacements(\n operationSpec,\n operationArguments,\n fallbackObject\n );\n\n let isAbsolutePath = false;\n\n let requestUrl = replaceAll(baseUri, urlReplacements);\n if (operationSpec.path) {\n let path = replaceAll(operationSpec.path, urlReplacements);\n // QUIRK: sometimes we get a path component like /{nextLink}\n // which may be a fully formed URL with a leading /. In that case, we should\n // remove the leading /\n if (operationSpec.path === \"/{nextLink}\" && path.startsWith(\"/\")) {\n path = path.substring(1);\n }\n // QUIRK: sometimes we get a path component like {nextLink}\n // which may be a fully formed URL. In that case, we should\n // ignore the baseUri.\n if (isAbsoluteUrl(path)) {\n requestUrl = path;\n isAbsolutePath = true;\n } else {\n requestUrl = appendPath(requestUrl, path);\n }\n }\n\n const { queryParams, sequenceParams } = calculateQueryParameters(\n operationSpec,\n operationArguments,\n fallbackObject\n );\n /**\n * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`\n * is an absolute path. This ensures that existing query parameter values in `requestUrl`\n * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it\n * is still being built so there is nothing to overwrite.\n */\n requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);\n\n return requestUrl;\n}\n\nfunction replaceAll(input: string, replacements: Map<string, string>): string {\n let result = input;\n for (const [searchValue, replaceValue] of replacements) {\n result = result.split(searchValue).join(replaceValue);\n }\n return result;\n}\n\nfunction calculateUrlReplacements(\n operationSpec: OperationSpec,\n operationArguments: OperationArguments,\n fallbackObject: { [parameterName: string]: any }\n): Map<string, string> {\n const result = new Map<string, string>();\n if (operationSpec.urlParameters?.length) {\n for (const urlParameter of operationSpec.urlParameters) {\n let urlParameterValue: string = getOperationArgumentValueFromParameter(\n operationArguments,\n urlParameter,\n fallbackObject\n );\n const parameterPathString = getPathStringFromParameter(urlParameter);\n urlParameterValue = operationSpec.serializer.serialize(\n urlParameter.mapper,\n urlParameterValue,\n parameterPathString\n );\n if (!urlParameter.skipEncoding) {\n urlParameterValue = encodeURIComponent(urlParameterValue);\n }\n result.set(\n `{${urlParameter.mapper.serializedName || parameterPathString}}`,\n urlParameterValue\n );\n }\n }\n return result;\n}\n\nfunction isAbsoluteUrl(url: string): boolean {\n return url.includes(\"://\");\n}\n\nfunction appendPath(url: string, pathToAppend?: string): string {\n if (!pathToAppend) {\n return url;\n }\n\n const parsedUrl = new URL(url);\n let newPath = parsedUrl.pathname;\n\n if (!newPath.endsWith(\"/\")) {\n newPath = `${newPath}/`;\n }\n\n if (pathToAppend.startsWith(\"/\")) {\n pathToAppend = pathToAppend.substring(1);\n }\n\n const searchStart = pathToAppend.indexOf(\"?\");\n if (searchStart !== -1) {\n const path = pathToAppend.substring(0, searchStart);\n const search = pathToAppend.substring(searchStart + 1);\n newPath = newPath + path;\n if (search) {\n parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;\n }\n } else {\n newPath = newPath + pathToAppend;\n }\n\n parsedUrl.pathname = newPath;\n\n return parsedUrl.toString();\n}\n\nfunction calculateQueryParameters(\n operationSpec: OperationSpec,\n operationArguments: OperationArguments,\n fallbackObject: { [parameterName: string]: any }\n): {\n queryParams: Map<string, string | string[]>;\n sequenceParams: Set<string>;\n} {\n const result = new Map<string, string | string[]>();\n const sequenceParams: Set<string> = new Set<string>();\n\n if (operationSpec.queryParameters?.length) {\n for (const queryParameter of operationSpec.queryParameters) {\n if (queryParameter.mapper.type.name === \"Sequence\" && queryParameter.mapper.serializedName) {\n sequenceParams.add(queryParameter.mapper.serializedName);\n }\n let queryParameterValue: string | string[] = getOperationArgumentValueFromParameter(\n operationArguments,\n queryParameter,\n fallbackObject\n );\n if (\n (queryParameterValue !== undefined && queryParameterValue !== null) ||\n queryParameter.mapper.required\n ) {\n queryParameterValue = operationSpec.serializer.serialize(\n queryParameter.mapper,\n queryParameterValue,\n getPathStringFromParameter(queryParameter)\n );\n\n const delimiter = queryParameter.collectionFormat\n ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]\n : \"\";\n if (Array.isArray(queryParameterValue)) {\n // replace null and undefined\n queryParameterValue = queryParameterValue.map((item) => {\n if (item === null || item === undefined) {\n return \"\";\n }\n\n return item;\n });\n }\n if (queryParameter.collectionFormat === \"Multi\" && queryParameterValue.length === 0) {\n continue;\n } else if (\n Array.isArray(queryParameterValue) &&\n (queryParameter.collectionFormat === \"SSV\" || queryParameter.collectionFormat === \"TSV\")\n ) {\n queryParameterValue = queryParameterValue.join(delimiter);\n }\n if (!queryParameter.skipEncoding) {\n if (Array.isArray(queryParameterValue)) {\n queryParameterValue = queryParameterValue.map((item: string) => {\n return encodeURIComponent(item);\n });\n } else {\n queryParameterValue = encodeURIComponent(queryParameterValue);\n }\n }\n\n // Join pipes and CSV *after* encoding, or the server will be upset.\n if (\n Array.isArray(queryParameterValue) &&\n (queryParameter.collectionFormat === \"CSV\" || queryParameter.collectionFormat === \"Pipes\")\n ) {\n queryParameterValue = queryParameterValue.join(delimiter);\n }\n\n result.set(\n queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter),\n queryParameterValue\n );\n }\n }\n }\n return {\n queryParams: result,\n sequenceParams,\n };\n}\n\nfunction simpleParseQueryParams(queryString: string): Map<string, string | string[] | undefined> {\n const result: Map<string, string | string[] | undefined> = new Map<\n string,\n string | string[] | undefined\n >();\n if (!queryString || queryString[0] !== \"?\") {\n return result;\n }\n\n // remove the leading ?\n queryString = queryString.slice(1);\n const pairs = queryString.split(\"&\");\n\n for (const pair of pairs) {\n const [name, value] = pair.split(\"=\", 2);\n const existingValue = result.get(name);\n if (existingValue) {\n if (Array.isArray(existingValue)) {\n existingValue.push(value);\n } else {\n result.set(name, [existingValue, value]);\n }\n } else {\n result.set(name, value);\n }\n }\n\n return result;\n}\n\n/** @internal */\nexport function appendQueryParams(\n url: string,\n queryParams: Map<string, string | string[]>,\n sequenceParams: Set<string>,\n noOverwrite: boolean = false\n): string {\n if (queryParams.size === 0) {\n return url;\n }\n\n const parsedUrl = new URL(url);\n\n // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which\n // can change their meaning to the server, such as in the case of a SAS signature.\n // To avoid accidentally un-encoding a query param, we parse the key/values ourselves\n const combinedParams = simpleParseQueryParams(parsedUrl.search);\n\n for (const [name, value] of queryParams) {\n const existingValue = combinedParams.get(name);\n if (Array.isArray(existingValue)) {\n if (Array.isArray(value)) {\n existingValue.push(...value);\n const valueSet = new Set(existingValue);\n combinedParams.set(name, Array.from(valueSet));\n } else {\n existingValue.push(value);\n }\n } else if (existingValue) {\n if (Array.isArray(value)) {\n value.unshift(existingValue);\n } else if (sequenceParams.has(name)) {\n combinedParams.set(name, [existingValue, value]);\n }\n if (!noOverwrite) {\n combinedParams.set(name, value);\n }\n } else {\n combinedParams.set(name, value);\n }\n }\n\n const searchPieces: string[] = [];\n for (const [name, value] of combinedParams) {\n if (typeof value === \"string\") {\n searchPieces.push(`${name}=${value}`);\n } else if (Array.isArray(value)) {\n // QUIRK: If we get an array of values, include multiple key/value pairs\n for (const subValue of value) {\n searchPieces.push(`${name}=${subValue}`);\n }\n } else {\n searchPieces.push(`${name}=${value}`);\n }\n }\n\n // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.\n parsedUrl.search = searchPieces.length ? `?${searchPieces.join(\"&\")}` : \"\";\n return parsedUrl.toString();\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createClientLogger } from \"@azure/logger\";\nexport const logger = createClientLogger(\"core-client\");\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n CommonClientOptions,\n OperationArguments,\n OperationRequest,\n OperationSpec,\n} from \"./interfaces\";\nimport {\n HttpClient,\n Pipeline,\n PipelineRequest,\n PipelineResponse,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { TokenCredential } from \"@azure/core-auth\";\nimport { createClientPipeline } from \"./pipeline\";\nimport { flattenResponse } from \"./utils\";\nimport { getCachedDefaultHttpClient } from \"./httpClientCache\";\nimport { getOperationRequestInfo } from \"./operationHelpers\";\nimport { getRequestUrl } from \"./urlHelpers\";\nimport { getStreamingResponseStatusCodes } from \"./interfaceHelpers\";\nimport { logger } from \"./log\";\n\n/**\n * Options to be provided while creating the client.\n */\nexport interface ServiceClientOptions extends CommonClientOptions {\n /**\n * If specified, this is the base URI that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n * @deprecated This property is deprecated and will be removed soon, please use endpoint instead\n */\n baseUri?: string;\n /**\n * If specified, this is the endpoint that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n * to encourage customer to use endpoint, we mark the baseUri as deprecated.\n */\n endpoint?: string;\n /**\n * If specified, will be used to build the BearerTokenAuthenticationPolicy.\n */\n credentialScopes?: string | string[];\n /**\n * The default request content type for the service.\n * Used if no requestContentType is present on an OperationSpec.\n */\n requestContentType?: string;\n /**\n * Credential used to authenticate the request.\n */\n credential?: TokenCredential;\n /**\n * A customized pipeline to use, otherwise a default one will be created.\n */\n pipeline?: Pipeline;\n}\n\n/**\n * Initializes a new instance of the ServiceClient.\n */\nexport class ServiceClient {\n /**\n * If specified, this is the base URI that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n */\n private readonly _endpoint?: string;\n\n /**\n * The default request content type for the service.\n * Used if no requestContentType is present on an OperationSpec.\n */\n private readonly _requestContentType?: string;\n\n /**\n * Set to true if the request is sent over HTTP instead of HTTPS\n */\n private readonly _allowInsecureConnection?: boolean;\n\n /**\n * The HTTP client that will be used to send requests.\n */\n private readonly _httpClient: HttpClient;\n\n /**\n * The pipeline used by this client to make requests\n */\n public readonly pipeline: Pipeline;\n\n /**\n * The ServiceClient constructor\n * @param credential - The credentials used for authentication with the service.\n * @param options - The service client options that govern the behavior of the client.\n */\n constructor(options: ServiceClientOptions = {}) {\n this._requestContentType = options.requestContentType;\n this._endpoint = options.endpoint ?? options.baseUri;\n if (options.baseUri) {\n logger.warning(\n \"The baseUri option for SDK Clients has been deprecated, please use endpoint instead.\"\n );\n }\n this._allowInsecureConnection = options.allowInsecureConnection;\n this._httpClient = options.httpClient || getCachedDefaultHttpClient();\n\n this.pipeline = options.pipeline || createDefaultPipeline(options);\n if (options.additionalPolicies?.length) {\n for (const { policy, position } of options.additionalPolicies) {\n // Sign happens after Retry and is commonly needed to occur\n // before policies that intercept post-retry.\n const afterPhase = position === \"perRetry\" ? \"Sign\" : undefined;\n this.pipeline.addPolicy(policy, {\n afterPhase,\n });\n }\n }\n }\n\n /**\n * Send the provided httpRequest.\n */\n async sendRequest(request: PipelineRequest): Promise<PipelineResponse> {\n return this.pipeline.sendRequest(this._httpClient, request);\n }\n\n /**\n * Send an HTTP request that is populated using the provided OperationSpec.\n * @typeParam T - The typed result of the request, based on the OperationSpec.\n * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.\n * @param operationSpec - The OperationSpec to use to populate the httpRequest.\n */\n async sendOperationRequest<T>(\n operationArguments: OperationArguments,\n operationSpec: OperationSpec\n ): Promise<T> {\n const endpoint: string | undefined = operationSpec.baseUrl || this._endpoint;\n if (!endpoint) {\n throw new Error(\n \"If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.\"\n );\n }\n\n // Templatized URLs sometimes reference properties on the ServiceClient child class,\n // so we have to pass `this` below in order to search these properties if they're\n // not part of OperationArguments\n const url = getRequestUrl(endpoint, operationSpec, operationArguments, this);\n\n const request: OperationRequest = createPipelineRequest({\n url,\n });\n request.method = operationSpec.httpMethod;\n const operationInfo = getOperationRequestInfo(request);\n operationInfo.operationSpec = operationSpec;\n operationInfo.operationArguments = operationArguments;\n\n const contentType = operationSpec.contentType || this._requestContentType;\n if (contentType && operationSpec.requestBody) {\n request.headers.set(\"Content-Type\", contentType);\n }\n\n const options = operationArguments.options;\n if (options) {\n const requestOptions = options.requestOptions;\n\n if (requestOptions) {\n if (requestOptions.timeout) {\n request.timeout = requestOptions.timeout;\n }\n\n if (requestOptions.onUploadProgress) {\n request.onUploadProgress = requestOptions.onUploadProgress;\n }\n\n if (requestOptions.onDownloadProgress) {\n request.onDownloadProgress = requestOptions.onDownloadProgress;\n }\n\n if (requestOptions.shouldDeserialize !== undefined) {\n operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;\n }\n\n if (requestOptions.allowInsecureConnection) {\n request.allowInsecureConnection = true;\n }\n }\n\n if (options.abortSignal) {\n request.abortSignal = options.abortSignal;\n }\n\n if (options.tracingOptions) {\n request.tracingOptions = options.tracingOptions;\n }\n }\n\n if (this._allowInsecureConnection) {\n request.allowInsecureConnection = true;\n }\n\n if (request.streamResponseStatusCodes === undefined) {\n request.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec);\n }\n\n try {\n const rawResponse = await this.sendRequest(request);\n const flatResponse = flattenResponse(\n rawResponse,\n operationSpec.responses[rawResponse.status]\n ) as T;\n if (options?.onResponse) {\n options.onResponse(rawResponse, flatResponse);\n }\n return flatResponse;\n } catch (error: any) {\n if (typeof error === \"object\" && error?.response) {\n const rawResponse = error.response;\n const flatResponse = flattenResponse(\n rawResponse,\n operationSpec.responses[error.statusCode] || operationSpec.responses[\"default\"]\n );\n error.details = flatResponse;\n if (options?.onResponse) {\n options.onResponse(rawResponse, flatResponse, error);\n }\n }\n throw error;\n }\n }\n}\n\nfunction createDefaultPipeline(options: ServiceClientOptions): Pipeline {\n const credentialScopes = getCredentialScopes(options);\n const credentialOptions =\n options.credential && credentialScopes\n ? { credentialScopes, credential: options.credential }\n : undefined;\n\n return createClientPipeline({\n ...options,\n credentialOptions,\n });\n}\n\nfunction getCredentialScopes(options: ServiceClientOptions): string | string[] | undefined {\n if (options.credentialScopes) {\n return options.credentialScopes;\n }\n\n if (options.endpoint) {\n return `${options.endpoint}/.default`;\n }\n\n if (options.baseUri) {\n return `${options.baseUri}/.default`;\n }\n\n if (options.credential && !options.credentialScopes) {\n throw new Error(\n `When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`\n );\n }\n\n return undefined;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AuthorizeRequestOnChallengeOptions } from \"@azure/core-rest-pipeline\";\nimport { logger as coreClientLogger } from \"./log\";\nimport { decodeStringToString } from \"./base64\";\n\n/**\n * Converts: `Bearer a=\"b\", c=\"d\", Bearer d=\"e\", f=\"g\"`.\n * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.\n *\n * @internal\n */\nexport function parseCAEChallenge(challenges: string): any[] {\n const bearerChallenges = `, ${challenges.trim()}`.split(\", Bearer \").filter((x) => x);\n return bearerChallenges.map((challenge) => {\n const challengeParts = `${challenge.trim()}, `.split('\", ').filter((x) => x);\n const keyValuePairs = challengeParts.map((keyValue) =>\n (([key, value]) => ({ [key]: value }))(keyValue.trim().split('=\"'))\n );\n // Key-value pairs to plain object:\n return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {});\n });\n}\n\n/**\n * CAE Challenge structure\n */\nexport interface CAEChallenge {\n scope: string;\n claims: string;\n}\n\n/**\n * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:\n * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).\n *\n * Call the `bearerTokenAuthenticationPolicy` with the following options:\n *\n * ```ts\n * import { bearerTokenAuthenticationPolicy } from \"@azure/core-rest-pipeline\";\n * import { authorizeRequestOnClaimChallenge } from \"@azure/core-client\";\n *\n * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({\n * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge\n * });\n * ```\n *\n * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.\n * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.\n *\n * Example challenge with claims:\n *\n * ```\n * Bearer authorization_uri=\"https://login.windows-ppe.net/\", error=\"invalid_token\",\n * error_description=\"User session has been revoked\",\n * claims=\"eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0=\"\n * ```\n */\nexport async function authorizeRequestOnClaimChallenge(\n onChallengeOptions: AuthorizeRequestOnChallengeOptions\n): Promise<boolean> {\n const { scopes, response } = onChallengeOptions;\n const logger = onChallengeOptions.logger || coreClientLogger;\n\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (!challenge) {\n logger.info(\n `The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`\n );\n return false;\n }\n const challenges: CAEChallenge[] = parseCAEChallenge(challenge) || [];\n\n const parsedChallenge = challenges.find((x) => x.claims);\n if (!parsedChallenge) {\n logger.info(\n `The WWW-Authenticate header was missing the necessary \"claims\" to perform the Continuous Access Evaluation authentication flow.`\n );\n return false;\n }\n\n const accessToken = await onChallengeOptions.getAccessToken(\n parsedChallenge.scope ? [parsedChallenge.scope] : scopes,\n {\n claims: decodeStringToString(parsedChallenge.claims),\n }\n );\n\n if (!accessToken) {\n return false;\n }\n\n onChallengeOptions.request.headers.set(\"Authorization\", `Bearer ${accessToken.token}`);\n return true;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AuthorizeRequestOnChallengeOptions,\n PipelineRequest,\n PipelineResponse,\n} from \"@azure/core-rest-pipeline\";\n\nimport { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * A set of constants used internally when processing requests.\n */\nconst Constants = {\n DefaultScope: \"/.default\",\n /**\n * Defines constants for use with HTTP headers.\n */\n HeaderConstants: {\n /**\n * The Authorization header.\n */\n AUTHORIZATION: \"authorization\",\n },\n};\n\n/**\n * Defines a callback to handle auth challenge for Storage APIs.\n * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge\n * Handling has specific features for storage that departs to the general AAD challenge docs.\n **/\nexport const authorizeRequestOnTenantChallenge: (\n challengeOptions: AuthorizeRequestOnChallengeOptions\n) => Promise<boolean> = async (challengeOptions) => {\n const requestOptions = requestToOptions(challengeOptions.request);\n const challenge = getChallenge(challengeOptions.response);\n if (challenge) {\n const challengeInfo: Challenge = parseChallenge(challenge);\n const challengeScopes = buildScopes(challengeOptions, challengeInfo);\n const tenantId = extractTenantId(challengeInfo);\n const accessToken = await challengeOptions.getAccessToken(challengeScopes, {\n ...requestOptions,\n tenantId,\n });\n\n if (!accessToken) {\n return false;\n }\n\n challengeOptions.request.headers.set(\n Constants.HeaderConstants.AUTHORIZATION,\n `Bearer ${accessToken.token}`\n );\n return true;\n }\n return false;\n};\n\n/**\n * Extracts the tenant id from the challenge information\n * The tenant id is contained in the authorization_uri as the first\n * path part.\n */\nfunction extractTenantId(challengeInfo: Challenge): string {\n const parsedAuthUri = new URL(challengeInfo.authorization_uri);\n const pathSegments = parsedAuthUri.pathname.split(\"/\");\n const tenantId = pathSegments[1];\n\n return tenantId;\n}\n\n/**\n * Builds the authentication scopes based on the information that comes in the\n * challenge information. Scopes url is present in the resource_id, if it is empty\n * we keep using the original scopes.\n */\nfunction buildScopes(\n challengeOptions: AuthorizeRequestOnChallengeOptions,\n challengeInfo: Challenge\n): string[] {\n if (!challengeInfo.resource_uri) {\n return challengeOptions.scopes;\n }\n\n const challengeScopes = new URL(challengeInfo.resource_uri);\n challengeScopes.pathname = Constants.DefaultScope;\n return [challengeScopes.toString()];\n}\n\n/**\n * We will retrieve the challenge only if the response status code was 401,\n * and if the response contained the header \"WWW-Authenticate\" with a non-empty value.\n */\nfunction getChallenge(response: PipelineResponse): string | undefined {\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (response.status === 401 && challenge) {\n return challenge;\n }\n return;\n}\n\n/**\n * Challenge structure\n */\ninterface Challenge {\n authorization_uri: string;\n resource_uri?: string;\n}\n\n/**\n * Converts: `Bearer a=\"b\" c=\"d\"`.\n * Into: `[ { a: 'b', c: 'd' }]`.\n *\n * @internal\n */\nfunction parseChallenge(challenge: string): Challenge {\n const bearerChallenge = challenge.slice(\"Bearer \".length);\n const challengeParts = `${bearerChallenge.trim()} `.split(\" \").filter((x) => x);\n const keyValuePairs = challengeParts.map((keyValue) =>\n (([key, value]) => ({ [key]: value }))(keyValue.trim().split(\"=\"))\n );\n // Key-value pairs to plain object:\n return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {} as Challenge);\n}\n\n/**\n * Extracts the options form a Pipeline Request for later re-use\n */\nfunction requestToOptions(request: PipelineRequest): GetTokenOptions {\n return {\n abortSignal: request.abortSignal,\n requestOptions: {\n timeout: request.timeout,\n },\n tracingOptions: request.tracingOptions,\n };\n}\n", "'use strict';\nconst fs = require('fs');\n\nlet isDocker;\n\nfunction hasDockerEnv() {\n\ttry {\n\t\tfs.statSync('/.dockerenv');\n\t\treturn true;\n\t} catch (_) {\n\t\treturn false;\n\t}\n}\n\nfunction hasDockerCGroup() {\n\ttry {\n\t\treturn fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');\n\t} catch (_) {\n\t\treturn false;\n\t}\n}\n\nmodule.exports = () => {\n\tif (isDocker === undefined) {\n\t\tisDocker = hasDockerEnv() || hasDockerCGroup();\n\t}\n\n\treturn isDocker;\n};\n", "'use strict';\nconst os = require('os');\nconst fs = require('fs');\nconst isDocker = require('is-docker');\n\nconst isWsl = () => {\n\tif (process.platform !== 'linux') {\n\t\treturn false;\n\t}\n\n\tif (os.release().toLowerCase().includes('microsoft')) {\n\t\tif (isDocker()) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\ttry {\n\t\treturn fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?\n\t\t\t!isDocker() : false;\n\t} catch (_) {\n\t\treturn false;\n\t}\n};\n\nif (process.env.__IS_WSL_TEST__) {\n\tmodule.exports = isWsl;\n} else {\n\tmodule.exports = isWsl();\n}\n", "'use strict';\nmodule.exports = (object, propertyName, fn) => {\n\tconst define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});\n\n\tObject.defineProperty(object, propertyName, {\n\t\tconfigurable: true,\n\t\tenumerable: true,\n\t\tget() {\n\t\t\tconst result = fn();\n\t\t\tdefine(result);\n\t\t\treturn result;\n\t\t},\n\t\tset(value) {\n\t\t\tdefine(value);\n\t\t}\n\t});\n\n\treturn object;\n};\n", "const path = require('path');\nconst childProcess = require('child_process');\nconst {promises: fs, constants: fsConstants} = require('fs');\nconst isWsl = require('is-wsl');\nconst isDocker = require('is-docker');\nconst defineLazyProperty = require('define-lazy-prop');\n\n// Path to included `xdg-open`.\nconst localXdgOpenPath = path.join(__dirname, 'xdg-open');\n\nconst {platform, arch} = process;\n\n// Podman detection\nconst hasContainerEnv = () => {\n\ttry {\n\t\tfs.statSync('/run/.containerenv');\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nlet cachedResult;\nfunction isInsideContainer() {\n\tif (cachedResult === undefined) {\n\t\tcachedResult = hasContainerEnv() || isDocker();\n\t}\n\n\treturn cachedResult;\n}\n\n/**\nGet the mount point for fixed drives in WSL.\n\n@inner\n@returns {string} The mount point.\n*/\nconst getWslDrivesMountPoint = (() => {\n\t// Default value for \"root\" param\n\t// according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config\n\tconst defaultMountPoint = '/mnt/';\n\n\tlet mountPoint;\n\n\treturn async function () {\n\t\tif (mountPoint) {\n\t\t\t// Return memoized mount point value\n\t\t\treturn mountPoint;\n\t\t}\n\n\t\tconst configFilePath = '/etc/wsl.conf';\n\n\t\tlet isConfigFileExists = false;\n\t\ttry {\n\t\t\tawait fs.access(configFilePath, fsConstants.F_OK);\n\t\t\tisConfigFileExists = true;\n\t\t} catch {}\n\n\t\tif (!isConfigFileExists) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tconst configContent = await fs.readFile(configFilePath, {encoding: 'utf8'});\n\t\tconst configMountPoint = /(?<!#.*)root\\s*=\\s*(?<mountPoint>.*)/g.exec(configContent);\n\n\t\tif (!configMountPoint) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tmountPoint = configMountPoint.groups.mountPoint.trim();\n\t\tmountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;\n\n\t\treturn mountPoint;\n\t};\n})();\n\nconst pTryEach = async (array, mapper) => {\n\tlet latestError;\n\n\tfor (const item of array) {\n\t\ttry {\n\t\t\treturn await mapper(item); // eslint-disable-line no-await-in-loop\n\t\t} catch (error) {\n\t\t\tlatestError = error;\n\t\t}\n\t}\n\n\tthrow latestError;\n};\n\nconst baseOpen = async options => {\n\toptions = {\n\t\twait: false,\n\t\tbackground: false,\n\t\tnewInstance: false,\n\t\tallowNonzeroExitCode: false,\n\t\t...options\n\t};\n\n\tif (Array.isArray(options.app)) {\n\t\treturn pTryEach(options.app, singleApp => baseOpen({\n\t\t\t...options,\n\t\t\tapp: singleApp\n\t\t}));\n\t}\n\n\tlet {name: app, arguments: appArguments = []} = options.app || {};\n\tappArguments = [...appArguments];\n\n\tif (Array.isArray(app)) {\n\t\treturn pTryEach(app, appName => baseOpen({\n\t\t\t...options,\n\t\t\tapp: {\n\t\t\t\tname: appName,\n\t\t\t\targuments: appArguments\n\t\t\t}\n\t\t}));\n\t}\n\n\tlet command;\n\tconst cliArguments = [];\n\tconst childProcessOptions = {};\n\n\tif (platform === 'darwin') {\n\t\tcommand = 'open';\n\n\t\tif (options.wait) {\n\t\t\tcliArguments.push('--wait-apps');\n\t\t}\n\n\t\tif (options.background) {\n\t\t\tcliArguments.push('--background');\n\t\t}\n\n\t\tif (options.newInstance) {\n\t\t\tcliArguments.push('--new');\n\t\t}\n\n\t\tif (app) {\n\t\t\tcliArguments.push('-a', app);\n\t\t}\n\t} else if (platform === 'win32' || (isWsl && !isInsideContainer() && !app)) {\n\t\tconst mountPoint = await getWslDrivesMountPoint();\n\n\t\tcommand = isWsl ?\n\t\t\t`${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :\n\t\t\t`${process.env.SYSTEMROOT}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell`;\n\n\t\tcliArguments.push(\n\t\t\t'-NoProfile',\n\t\t\t'-NonInteractive',\n\t\t\t'\u2013ExecutionPolicy',\n\t\t\t'Bypass',\n\t\t\t'-EncodedCommand'\n\t\t);\n\n\t\tif (!isWsl) {\n\t\t\tchildProcessOptions.windowsVerbatimArguments = true;\n\t\t}\n\n\t\tconst encodedArguments = ['Start'];\n\n\t\tif (options.wait) {\n\t\t\tencodedArguments.push('-Wait');\n\t\t}\n\n\t\tif (app) {\n\t\t\t// Double quote with double quotes to ensure the inner quotes are passed through.\n\t\t\t// Inner quotes are delimited for PowerShell interpretation with backticks.\n\t\t\tencodedArguments.push(`\"\\`\"${app}\\`\"\"`, '-ArgumentList');\n\t\t\tif (options.target) {\n\t\t\t\tappArguments.unshift(options.target);\n\t\t\t}\n\t\t} else if (options.target) {\n\t\t\tencodedArguments.push(`\"${options.target}\"`);\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tappArguments = appArguments.map(arg => `\"\\`\"${arg}\\`\"\"`);\n\t\t\tencodedArguments.push(appArguments.join(','));\n\t\t}\n\n\t\t// Using Base64-encoded command, accepted by PowerShell, to allow special characters.\n\t\toptions.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');\n\t} else {\n\t\tif (app) {\n\t\t\tcommand = app;\n\t\t} else {\n\t\t\t// When bundled by Webpack, there's no actual package file path and no local `xdg-open`.\n\t\t\tconst isBundled = !__dirname || __dirname === '/';\n\n\t\t\t// Check if local `xdg-open` exists and is executable.\n\t\t\tlet exeLocalXdgOpen = false;\n\t\t\ttry {\n\t\t\t\tawait fs.access(localXdgOpenPath, fsConstants.X_OK);\n\t\t\t\texeLocalXdgOpen = true;\n\t\t\t} catch {}\n\n\t\t\tconst useSystemXdgOpen = process.versions.electron ||\n\t\t\t\tplatform === 'android' || isBundled || !exeLocalXdgOpen;\n\t\t\tcommand = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tcliArguments.push(...appArguments);\n\t\t}\n\n\t\tif (!options.wait) {\n\t\t\t// `xdg-open` will block the process unless stdio is ignored\n\t\t\t// and it's detached from the parent even if it's unref'd.\n\t\t\tchildProcessOptions.stdio = 'ignore';\n\t\t\tchildProcessOptions.detached = true;\n\t\t}\n\t}\n\n\tif (options.target) {\n\t\tcliArguments.push(options.target);\n\t}\n\n\tif (platform === 'darwin' && appArguments.length > 0) {\n\t\tcliArguments.push('--args', ...appArguments);\n\t}\n\n\tconst subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);\n\n\tif (options.wait) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tsubprocess.once('error', reject);\n\n\t\t\tsubprocess.once('close', exitCode => {\n\t\t\t\tif (!options.allowNonzeroExitCode && exitCode > 0) {\n\t\t\t\t\treject(new Error(`Exited with code ${exitCode}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresolve(subprocess);\n\t\t\t});\n\t\t});\n\t}\n\n\tsubprocess.unref();\n\n\treturn subprocess;\n};\n\nconst open = (target, options) => {\n\tif (typeof target !== 'string') {\n\t\tthrow new TypeError('Expected a `target`');\n\t}\n\n\treturn baseOpen({\n\t\t...options,\n\t\ttarget\n\t});\n};\n\nconst openApp = (name, options) => {\n\tif (typeof name !== 'string') {\n\t\tthrow new TypeError('Expected a `name`');\n\t}\n\n\tconst {arguments: appArguments = []} = options || {};\n\tif (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {\n\t\tthrow new TypeError('Expected `appArguments` as Array type');\n\t}\n\n\treturn baseOpen({\n\t\t...options,\n\t\tapp: {\n\t\t\tname,\n\t\t\targuments: appArguments\n\t\t}\n\t});\n};\n\nfunction detectArchBinary(binary) {\n\tif (typeof binary === 'string' || Array.isArray(binary)) {\n\t\treturn binary;\n\t}\n\n\tconst {[arch]: archBinary} = binary;\n\n\tif (!archBinary) {\n\t\tthrow new Error(`${arch} is not supported`);\n\t}\n\n\treturn archBinary;\n}\n\nfunction detectPlatformBinary({[platform]: platformBinary}, {wsl}) {\n\tif (wsl && isWsl) {\n\t\treturn detectArchBinary(wsl);\n\t}\n\n\tif (!platformBinary) {\n\t\tthrow new Error(`${platform} is not supported`);\n\t}\n\n\treturn detectArchBinary(platformBinary);\n}\n\nconst apps = {};\n\ndefineLazyProperty(apps, 'chrome', () => detectPlatformBinary({\n\tdarwin: 'google chrome',\n\twin32: 'chrome',\n\tlinux: ['google-chrome', 'google-chrome-stable', 'chromium']\n}, {\n\twsl: {\n\t\tia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',\n\t\tx64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']\n\t}\n}));\n\ndefineLazyProperty(apps, 'firefox', () => detectPlatformBinary({\n\tdarwin: 'firefox',\n\twin32: 'C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe',\n\tlinux: 'firefox'\n}, {\n\twsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'\n}));\n\ndefineLazyProperty(apps, 'edge', () => detectPlatformBinary({\n\tdarwin: 'microsoft edge',\n\twin32: 'msedge',\n\tlinux: ['microsoft-edge', 'microsoft-edge-dev']\n}, {\n\twsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'\n}));\n\nopen.apps = apps;\nopen.openApp = openApp;\n\nmodule.exports = open;\n", "'use strict'\n\nconst https = require('https')\n\nmodule.exports = (server, grace) => {\n grace = typeof grace === 'undefined' ? Infinity : grace\n const reqsPerSocket = new Map()\n let stopped = false\n let gracefully = true\n\n if (server instanceof https.Server) {\n server.on('secureConnection', onConnection)\n } else {\n server.on('connection', onConnection)\n }\n\n server.on('request', onRequest)\n server.stop = stop\n server._pendingSockets = reqsPerSocket\n return server\n\n function onConnection (socket) {\n reqsPerSocket.set(socket, 0)\n socket.once('close', () => reqsPerSocket.delete(socket))\n }\n\n function onRequest (req, res) {\n reqsPerSocket.set(req.socket, reqsPerSocket.get(req.socket) + 1)\n res.once('finish', () => {\n const pending = reqsPerSocket.get(req.socket) - 1\n reqsPerSocket.set(req.socket, pending)\n if (stopped && pending === 0) {\n req.socket.end()\n }\n })\n }\n\n function stop (callback) {\n // allow request handlers to update state before we act on that state\n setImmediate(() => {\n stopped = true\n if (grace < Infinity) {\n setTimeout(destroyAll, grace).unref()\n }\n server.close(e => {\n if (callback) {\n callback(e, gracefully)\n }\n })\n reqsPerSocket.forEach(endIfIdle)\n })\n }\n\n function endIfIdle (requests, socket) {\n if (requests === 0) socket.end()\n }\n\n function destroyAll () {\n gracefully = false\n reqsPerSocket.forEach((reqs, socket) => socket.end())\n setImmediate(() => {\n reqsPerSocket.forEach((reqs, socket) => socket.destroy())\n })\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { GetTokenOptions } from \"@azure/core-auth\";\n\n/**\n * See the official documentation for more details:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n /**\n * The string identifier for the error.\n */\n error: string;\n\n /**\n * The error's description.\n */\n errorDescription: string;\n\n /**\n * An array of codes pertaining to the error(s) that occurred.\n */\n errorCodes?: number[];\n\n /**\n * The timestamp at which the error occurred.\n */\n timestamp?: string;\n\n /**\n * The trace identifier for this error occurrence.\n */\n traceId?: string;\n\n /**\n * The correlation ID to be used for tracking the source of the error.\n */\n correlationId?: string;\n}\n\n/**\n * Used for internal deserialization of OAuth responses. Public model is ErrorResponse\n * @internal\n */\nexport interface OAuthErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is OAuthErrorResponse {\n return (\n errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\"\n );\n}\n\n/**\n * The Error.name value of an CredentialUnavailable\n */\nexport const CredentialUnavailableErrorName = \"CredentialUnavailableError\";\n\n/**\n * This signifies that the credential that was tried in a chained credential\n * was not available to be used as the credential. Rather than treating this as\n * an error that should halt the chain, it's caught and the chain continues\n */\nexport class CredentialUnavailableError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = CredentialUnavailableErrorName;\n }\n}\n\n/**\n * The Error.name value of an AuthenticationError\n */\nexport const AuthenticationErrorName = \"AuthenticationError\";\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n /**\n * The HTTP status code returned from the authentication request.\n */\n public readonly statusCode: number;\n\n /**\n * The error response details.\n */\n public readonly errorResponse: ErrorResponse;\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(statusCode: number, errorBody: object | string | undefined | null) {\n let errorResponse: ErrorResponse = {\n error: \"unknown\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody);\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n const oauthErrorResponse: OAuthErrorResponse = JSON.parse(errorBody);\n errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse);\n } catch (e: any) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"authority_not_found\",\n errorDescription: \"The specified authority URL was not found.\",\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: `An unknown error has occurred. Response body:\\n\\n${errorBody}`,\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n errorDescription: \"An unknown error occurred and no additional details are available.\",\n };\n }\n\n super(\n `${errorResponse.error} Status code: ${statusCode}\\nMore details:\\n${errorResponse.errorDescription}`\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = AuthenticationErrorName;\n }\n}\n\n/**\n * The Error.name value of an AggregateAuthenticationError\n */\nexport const AggregateAuthenticationErrorName = \"AggregateAuthenticationError\";\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n /**\n * The array of error objects that were thrown while trying to authenticate\n * with the credentials in a {@link ChainedTokenCredential}.\n */\n public errors: any[];\n\n constructor(errors: any[], errorMessage?: string) {\n const errorDetail = errors.join(\"\\n\");\n super(`${errorMessage}\\n${errorDetail}`);\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = AggregateAuthenticationErrorName;\n }\n}\n\nfunction convertOAuthErrorResponseToErrorResponse(errorBody: OAuthErrorResponse): ErrorResponse {\n return {\n error: errorBody.error,\n errorDescription: errorBody.error_description,\n correlationId: errorBody.correlation_id,\n errorCodes: errorBody.error_codes,\n timestamp: errorBody.timestamp,\n traceId: errorBody.trace_id,\n };\n}\n\n/**\n * Optional parameters to the {@link AuthenticationRequiredError}\n */\nexport interface AuthenticationRequiredErrorOptions {\n /**\n * The list of scopes for which the token will have access.\n */\n scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n getTokenOptions?: GetTokenOptions;\n /**\n * The message of the error.\n */\n message?: string;\n}\n\n/**\n * Error used to enforce authentication after trying to retrieve a token silently.\n */\nexport class AuthenticationRequiredError extends Error {\n /**\n * The list of scopes for which the token will have access.\n */\n public scopes: string[];\n /**\n * The options passed to the getToken request.\n */\n public getTokenOptions?: GetTokenOptions;\n\n constructor(\n /**\n * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters.\n */\n options: AuthenticationRequiredErrorOptions\n ) {\n super(options.message);\n this.scopes = options.scopes;\n this.getTokenOptions = options.getTokenOptions;\n this.name = \"AuthenticationRequiredError\";\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzureLogger, createClientLogger } from \"@azure/logger\";\n\n/**\n * The AzureLogger used for all clients within the identity package\n */\nexport const logger = createClientLogger(\"identity\");\n\ninterface EnvironmentAccumulator {\n missing: string[];\n assigned: string[];\n}\n\n/**\n * Separates a list of environment variable names into a plain object with two arrays: an array of missing environment variables and another array with assigned environment variables.\n * @param supportedEnvVars - List of environment variable names\n */\nexport function processEnvVars(supportedEnvVars: string[]): EnvironmentAccumulator {\n return supportedEnvVars.reduce(\n (acc: EnvironmentAccumulator, envVariable: string) => {\n if (process.env[envVariable]) {\n acc.assigned.push(envVariable);\n } else {\n acc.missing.push(envVariable);\n }\n return acc;\n },\n { missing: [], assigned: [] }\n );\n}\n\n/**\n * Based on a given list of environment variable names,\n * logs the environment variables currently assigned during the usage of a credential that goes by the given name.\n * @param credentialName - Name of the credential in use\n * @param supportedEnvVars - List of environment variables supported by that credential\n */\nexport function logEnvVars(credentialName: string, supportedEnvVars: string[]): void {\n const { assigned } = processEnvVars(supportedEnvVars);\n logger.info(\n `${credentialName} => Found the following environment variables: ${assigned.join(\", \")}`\n );\n}\n\n/**\n * Formatting the success event on the credentials\n */\nexport function formatSuccess(scope: string | string[]): string {\n return `SUCCESS. Scopes: ${Array.isArray(scope) ? scope.join(\", \") : scope}.`;\n}\n\n/**\n * Formatting the success event on the credentials\n */\nexport function formatError(scope: string | string[] | undefined, error: Error | string): string {\n let message = \"ERROR.\";\n if (scope?.length) {\n message += ` Scopes: ${Array.isArray(scope) ? scope.join(\", \") : scope}.`;\n }\n return `${message} Error message: ${typeof error === \"string\" ? error : error.message}.`;\n}\n\n/**\n * A CredentialLoggerInstance is a logger properly formatted to work in a credential's constructor, and its methods.\n */\nexport interface CredentialLoggerInstance {\n title: string;\n fullTitle: string;\n info(message: string): void;\n warning(message: string): void;\n verbose(message: string): void;\n /**\n * The logging functions for warning and error are intentionally left out, since we want the identity logging to be at the info level.\n * Otherwise, they would look like:\n *\n * warning(message: string): void;\n * error(err: Error): void;\n */\n}\n\n/**\n * Generates a CredentialLoggerInstance.\n *\n * It logs with the format:\n *\n * `[title] => [message]`\n *\n */\nexport function credentialLoggerInstance(\n title: string,\n parent?: CredentialLoggerInstance,\n log: AzureLogger = logger\n): CredentialLoggerInstance {\n const fullTitle = parent ? `${parent.fullTitle} ${title}` : title;\n\n function info(message: string): void {\n log.info(`${fullTitle} =>`, message);\n }\n\n function warning(message: string): void {\n log.warning(`${fullTitle} =>`, message);\n }\n\n function verbose(message: string): void {\n log.verbose(`${fullTitle} =>`, message);\n }\n return {\n title,\n fullTitle,\n info,\n warning,\n verbose,\n };\n}\n\n/**\n * A CredentialLogger is a logger declared at the credential's constructor, and used at any point in the credential.\n * It has all the properties of a CredentialLoggerInstance, plus other logger instances, one per method.\n */\nexport interface CredentialLogger extends CredentialLoggerInstance {\n parent: AzureLogger;\n getToken: CredentialLoggerInstance;\n}\n\n/**\n * Generates a CredentialLogger, which is a logger declared at the credential's constructor, and used at any point in the credential.\n * It has all the properties of a CredentialLoggerInstance, plus other logger instances, one per method.\n *\n * It logs with the format:\n *\n * `[title] => [message]`\n * `[title] => getToken() => [message]`\n *\n */\nexport function credentialLogger(title: string, log: AzureLogger = logger): CredentialLogger {\n const credLogger = credentialLoggerInstance(title, undefined, log);\n return {\n ...credLogger,\n parent: log,\n getToken: credentialLoggerInstance(\"=> getToken()\", credLogger, log),\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Current version of the `@azure/identity` package.\n */\n\nexport const SDK_VERSION = `3.4.2`;\n\n/**\n * The default client ID for authentication\n * @internal\n */\n// TODO: temporary - this is the Azure CLI clientID - we'll replace it when\n// Developer Sign On application is available\n// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9\nexport const DeveloperSignOnClientId = \"04b07795-8ddb-461a-bbee-02f9e1bf7b46\";\n\n/**\n * The default tenant for authentication\n * @internal\n */\nexport const DefaultTenantId = \"common\";\n\n/**\n * A list of known Azure authority hosts\n */\nexport enum AzureAuthorityHosts {\n /**\n * China-based Azure Authority Host\n */\n AzureChina = \"https://login.chinacloudapi.cn\",\n /**\n * Germany-based Azure Authority Host\n */\n AzureGermany = \"https://login.microsoftonline.de\",\n /**\n * US Government Azure Authority Host\n */\n AzureGovernment = \"https://login.microsoftonline.us\",\n /**\n * Public Cloud Azure Authority Host\n */\n AzurePublicCloud = \"https://login.microsoftonline.com\",\n}\n\n/**\n * The default authority host.\n */\nexport const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud;\n\n/**\n * Allow acquiring tokens for any tenant for multi-tentant auth.\n */\nexport const ALL_TENANTS: string[] = [\"*\"];\n\nexport const CACHE_CAE_SUFFIX = \".cae\";\nexport const CACHE_NON_CAE_SUFFIX = \".nocae\";\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalCommon from \"@azure/msal-node\";\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { AuthenticationRecord, MsalAccountInfo, MsalResult, MsalToken } from \"./types\";\nimport { AuthenticationRequiredError, CredentialUnavailableError } from \"../errors\";\nimport { CredentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { DefaultAuthorityHost, DefaultTenantId } from \"../constants\";\nimport { AbortError } from \"@azure/abort-controller\";\nimport { MsalFlowOptions } from \"./flows\";\nimport { isNode, randomUUID } from \"@azure/core-util\";\nimport { AzureLogLevel } from \"@azure/logger\";\n\nexport interface ILoggerCallback {\n (level: msalCommon.LogLevel, message: string, containsPii: boolean): void;\n}\n\n/**\n * Latest AuthenticationRecord version\n * @internal\n */\nconst LatestAuthenticationRecordVersion = \"1.0\";\n\n/**\n * Ensures the validity of the MSAL token\n * @internal\n */\nexport function ensureValidMsalToken(\n scopes: string | string[],\n logger: CredentialLogger,\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions\n): void {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n}\n\n/**\n * Generates a valid authority by combining a host with a tenantId.\n * @internal\n */\nexport function getAuthority(tenantId: string, host?: string): string {\n if (!host) {\n host = DefaultAuthorityHost;\n }\n if (new RegExp(`${tenantId}/?$`).test(host)) {\n return host;\n }\n if (host.endsWith(\"/\")) {\n return host + tenantId;\n } else {\n return `${host}/${tenantId}`;\n }\n}\n\n/**\n * Generates the known authorities.\n * If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one.\n * For that reason, we have to force MSAL to disable validating the authority\n * by sending it within the known authorities in the MSAL configuration.\n * @internal\n */\nexport function getKnownAuthorities(\n tenantId: string,\n authorityHost: string,\n disableInstanceDiscovery?: boolean\n): string[] {\n if ((tenantId === \"adfs\" && authorityHost) || disableInstanceDiscovery) {\n return [authorityHost];\n }\n return [];\n}\n\n/**\n * Generates a logger that can be passed to the MSAL clients.\n * @param logger - The logger of the credential.\n * @internal\n */\nexport const defaultLoggerCallback: (\n logger: CredentialLogger,\n platform?: \"Node\" | \"Browser\"\n) => ILoggerCallback =\n (logger: CredentialLogger, platform: \"Node\" | \"Browser\" = isNode ? \"Node\" : \"Browser\") =>\n (level, message, containsPii): void => {\n if (containsPii) {\n return;\n }\n switch (level) {\n case msalCommon.LogLevel.Error:\n logger.info(`MSAL ${platform} V2 error: ${message}`);\n return;\n case msalCommon.LogLevel.Info:\n logger.info(`MSAL ${platform} V2 info message: ${message}`);\n return;\n case msalCommon.LogLevel.Verbose:\n logger.info(`MSAL ${platform} V2 verbose message: ${message}`);\n return;\n case msalCommon.LogLevel.Warning:\n logger.info(`MSAL ${platform} V2 warning: ${message}`);\n return;\n }\n };\n\n/**\n * @internal\n */\nexport function getMSALLogLevel(logLevel: AzureLogLevel | undefined): msalCommon.LogLevel {\n switch (logLevel) {\n case \"error\":\n return msalCommon.LogLevel.Error;\n case \"info\":\n return msalCommon.LogLevel.Info;\n case \"verbose\":\n return msalCommon.LogLevel.Verbose;\n case \"warning\":\n return msalCommon.LogLevel.Warning;\n default:\n // default msal logging level should be Info\n return msalCommon.LogLevel.Info;\n }\n}\n\n/**\n * The common utility functions for the MSAL clients.\n * Defined as a class so that the classes extending this one can have access to its methods and protected properties.\n *\n * It keeps track of a logger and an in-memory copy of the AuthenticationRecord.\n *\n * @internal\n */\nexport class MsalBaseUtilities {\n protected logger: CredentialLogger;\n protected account: AuthenticationRecord | undefined;\n\n constructor(options: MsalFlowOptions) {\n this.logger = options.logger;\n this.account = options.authenticationRecord;\n }\n\n /**\n * Generates a UUID\n */\n generateUuid(): string {\n return randomUUID();\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n protected handleResult(\n scopes: string | string[],\n clientId: string,\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions\n ): AccessToken {\n if (result?.account) {\n this.account = msalToPublic(clientId, result.account);\n }\n ensureValidMsalToken(scopes, this.logger, result, getTokenOptions);\n this.logger.getToken.info(formatSuccess(scopes));\n return {\n token: result!.accessToken!,\n expiresOnTimestamp: result!.expiresOn!.getTime(),\n };\n }\n\n /**\n * Handles MSAL errors.\n */\n protected handleError(scopes: string[], error: Error, getTokenOptions?: GetTokenOptions): Error {\n if (\n error.name === \"AuthError\" ||\n error.name === \"ClientAuthError\" ||\n error.name === \"BrowserAuthError\"\n ) {\n const msalError = error as msalCommon.AuthError;\n switch (msalError.errorCode) {\n case \"endpoints_resolution_error\":\n this.logger.info(formatError(scopes, error.message));\n return new CredentialUnavailableError(error.message);\n case \"device_code_polling_cancelled\":\n return new AbortError(\"The authentication has been aborted by the caller.\");\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n this.logger.info(\n formatError(scopes, `Authentication returned errorCode ${msalError.errorCode}`)\n );\n break;\n default:\n this.logger.info(formatError(scopes, `Failed to acquire token: ${error.message}`));\n break;\n }\n }\n if (\n error.name === \"ClientConfigurationError\" ||\n error.name === \"BrowserConfigurationAuthError\" ||\n error.name === \"AbortError\"\n ) {\n return error;\n }\n return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message });\n }\n}\n\n// transformations.ts\n\nexport function publicToMsal(account: AuthenticationRecord): msalCommon.AccountInfo {\n const [environment] = account.authority.match(/([a-z]*\\.[a-z]*\\.[a-z]*)/) || [\"\"];\n return {\n ...account,\n localAccountId: account.homeAccountId,\n environment,\n };\n}\n\nexport function msalToPublic(clientId: string, account: MsalAccountInfo): AuthenticationRecord {\n const record = {\n authority: getAuthority(account.tenantId, account.environment),\n homeAccountId: account.homeAccountId,\n tenantId: account.tenantId || DefaultTenantId,\n username: account.username,\n clientId,\n version: LatestAuthenticationRecordVersion,\n };\n return record;\n}\n\n/**\n * Serializes an `AuthenticationRecord` into a string.\n *\n * The output of a serialized authentication record will contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`.\n */\nexport function serializeAuthenticationRecord(record: AuthenticationRecord): string {\n return JSON.stringify(record);\n}\n\n/**\n * Deserializes a previously serialized authentication record from a string into an object.\n *\n * The input string must contain the following properties:\n *\n * - \"authority\"\n * - \"homeAccountId\"\n * - \"clientId\"\n * - \"tenantId\"\n * - \"username\"\n * - \"version\"\n *\n * If the version we receive is unsupported, an error will be thrown.\n *\n * At the moment, the only available version is: \"1.0\", which is always set when the authentication record is serialized.\n *\n * @param serializedRecord - Authentication record previously serialized into string.\n * @returns AuthenticationRecord.\n */\nexport function deserializeAuthenticationRecord(serializedRecord: string): AuthenticationRecord {\n const parsed: AuthenticationRecord & { version?: string } = JSON.parse(serializedRecord);\n\n if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) {\n throw Error(\"Unsupported AuthenticationRecord version\");\n }\n\n return parsed;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { CredentialLogger } from \"./logging\";\n\nfunction createConfigurationErrorMessage(tenantId: string): string {\n return `The current credential is not configured to acquire tokens for tenant ${tenantId}. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add \"*\" to AdditionallyAllowedTenants to allow acquiring tokens for any tenant.`;\n}\n\n/**\n * Of getToken contains a tenantId, this functions allows picking this tenantId as the appropriate for authentication,\n * unless multitenant authentication has been disabled through the AZURE_IDENTITY_DISABLE_MULTITENANTAUTH (on Node.js),\n * or unless the original tenant Id is `adfs`.\n * @internal\n */\nexport function processMultiTenantRequest(\n tenantId?: string,\n getTokenOptions?: GetTokenOptions,\n additionallyAllowedTenantIds: string[] = [],\n logger?: CredentialLogger\n): string | undefined {\n let resolvedTenantId: string | undefined;\n if (process.env.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH) {\n resolvedTenantId = tenantId;\n } else if (tenantId === \"adfs\") {\n resolvedTenantId = tenantId;\n } else {\n resolvedTenantId = getTokenOptions?.tenantId ?? tenantId;\n }\n if (\n tenantId &&\n resolvedTenantId !== tenantId &&\n !additionallyAllowedTenantIds.includes(\"*\") &&\n !additionallyAllowedTenantIds.some((t) => t.localeCompare(resolvedTenantId!) === 0)\n ) {\n const message = createConfigurationErrorMessage(tenantId);\n logger?.info(message);\n throw new CredentialUnavailableError(message);\n }\n\n return resolvedTenantId;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ALL_TENANTS, DeveloperSignOnClientId } from \"../constants\";\nimport { CredentialLogger, formatError } from \"./logging\";\nexport { processMultiTenantRequest } from \"./processMultiTenantRequest\";\n\n/**\n * @internal\n */\nexport function checkTenantId(logger: CredentialLogger, tenantId: string): void {\n if (!tenantId.match(/^[0-9a-zA-Z-.]+$/)) {\n const error = new Error(\n \"Invalid tenant id provided. You can locate your tenant id by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names.\"\n );\n logger.info(formatError(\"\", error));\n throw error;\n }\n}\n\n/**\n * @internal\n */\nexport function resolveTenantId(\n logger: CredentialLogger,\n tenantId?: string,\n clientId?: string\n): string {\n if (tenantId) {\n checkTenantId(logger, tenantId);\n return tenantId;\n }\n if (!clientId) {\n clientId = DeveloperSignOnClientId;\n }\n if (clientId !== DeveloperSignOnClientId) {\n return \"common\";\n }\n return \"organizations\";\n}\n\n/**\n * @internal\n */\nexport function resolveAdditionallyAllowedTenantIds(\n additionallyAllowedTenants?: string[]\n): string[] {\n if (!additionallyAllowedTenants || additionallyAllowedTenants.length === 0) {\n return [];\n }\n\n if (additionallyAllowedTenants.includes(\"*\")) {\n return ALL_TENANTS;\n }\n\n return additionallyAllowedTenants;\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport function getIdentityTokenEndpointSuffix(tenantId: string): string {\n if (tenantId === \"adfs\") {\n return \"oauth2/token\";\n } else {\n return \"oauth2/v2.0/token\";\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { SDK_VERSION } from \"../constants\";\nimport { createTracingClient } from \"@azure/core-tracing\";\n\n/**\n * Creates a span using the global tracer.\n * @internal\n */\nexport const tracingClient = createTracingClient({\n namespace: \"Microsoft.AAD\",\n packageName: \"@azure/identity\",\n packageVersion: SDK_VERSION,\n});\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport const DefaultScopeSuffix = \"/.default\";\nexport const imdsHost = \"http://169.254.169.254\";\nexport const imdsEndpointPath = \"/metadata/identity/oauth2/token\";\nexport const imdsApiVersion = \"2018-02-01\";\nexport const azureArcAPIVersion = \"2019-11-01\";\nexport const azureFabricVersion = \"2019-07-01-preview\";\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { DefaultScopeSuffix } from \"./constants\";\n\n/**\n * Most MSIs send requests to the IMDS endpoint, or a similar endpoint.\n * These are GET requests that require sending a `resource` parameter on the query.\n * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received.\n * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case.\n *\n * For that reason, when we encounter multiple scopes, we return undefined.\n * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors).\n */\nexport function mapScopesToResource(scopes: string | string[]): string | undefined {\n let scope = \"\";\n if (Array.isArray(scopes)) {\n if (scopes.length !== 1) {\n return;\n }\n\n scope = scopes[0];\n } else if (typeof scopes === \"string\") {\n scope = scopes;\n }\n\n if (!scope.endsWith(DefaultScopeSuffix)) {\n return scope;\n }\n\n return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix));\n}\n\n/**\n * Internal type roughly matching the raw responses of the authentication endpoints.\n *\n * @internal\n */\nexport interface TokenResponseParsedBody {\n access_token?: string;\n refresh_token?: string;\n expires_in: number;\n expires_on?: number | string;\n refresh_in?: number;\n}\n\n/**\n * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch.\n * @param body - A parsed response body from the authentication endpoint.\n */\nexport function parseExpirationTimestamp(body: TokenResponseParsedBody): number {\n if (typeof body.expires_on === \"number\") {\n return body.expires_on * 1000;\n }\n\n if (typeof body.expires_on === \"string\") {\n const asNumber = +body.expires_on;\n if (!isNaN(asNumber)) {\n return asNumber * 1000;\n }\n\n const asDate = Date.parse(body.expires_on);\n if (!isNaN(asDate)) {\n return asDate;\n }\n }\n\n if (typeof body.expires_in === \"number\") {\n return Date.now() + body.expires_in * 1000;\n }\n\n throw new Error(\n `Failed to parse token expiration from body. expires_in=\"${body.expires_in}\", expires_on=\"${body.expires_on}\"`\n );\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport type { INetworkModule, NetworkRequestOptions, NetworkResponse } from \"@azure/msal-node\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { ServiceClient } from \"@azure/core-client\";\nimport { isNode } from \"@azure/core-util\";\nimport {\n PipelineRequest,\n PipelineResponse,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { AbortController, AbortSignalLike } from \"@azure/abort-controller\";\nimport { AuthenticationError, AuthenticationErrorName } from \"../errors\";\nimport { getIdentityTokenEndpointSuffix } from \"../util/identityTokenEndpoint\";\nimport { DefaultAuthorityHost, SDK_VERSION } from \"../constants\";\nimport { tracingClient } from \"../util/tracing\";\nimport { logger } from \"../util/logging\";\nimport { TokenCredentialOptions } from \"../tokenCredentialOptions\";\nimport {\n TokenResponseParsedBody,\n parseExpirationTimestamp,\n} from \"../credentials/managedIdentityCredential/utils\";\n\nconst noCorrelationId = \"noCorrelationId\";\n\n/**\n * An internal type used to communicate details of a token request's\n * response that should not be sent back as part of the access token.\n */\nexport interface TokenResponse {\n /**\n * The AccessToken to be returned from getToken.\n */\n accessToken: AccessToken;\n /**\n * The refresh token if the 'offline_access' scope was used.\n */\n refreshToken?: string;\n}\n\n/**\n * @internal\n */\nexport function getIdentityClientAuthorityHost(options?: TokenCredentialOptions): string {\n // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable.\n let authorityHost = options?.authorityHost;\n\n // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js.\n if (isNode) {\n authorityHost = authorityHost ?? process.env.AZURE_AUTHORITY_HOST;\n }\n\n // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com\n return authorityHost ?? DefaultAuthorityHost;\n}\n\n/**\n * The network module used by the Identity credentials.\n *\n * It allows for credentials to abort any pending request independently of the MSAL flow,\n * by calling to the `abortRequests()` method.\n *\n */\nexport class IdentityClient extends ServiceClient implements INetworkModule {\n public authorityHost: string;\n private allowLoggingAccountIdentifiers?: boolean;\n private abortControllers: Map<string, AbortController[] | undefined>;\n // used for WorkloadIdentity\n private tokenCredentialOptions: TokenCredentialOptions;\n\n constructor(options?: TokenCredentialOptions) {\n const packageDetails = `azsdk-js-identity/${SDK_VERSION}`;\n const userAgentPrefix = options?.userAgentOptions?.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const baseUri = getIdentityClientAuthorityHost(options);\n if (!baseUri.startsWith(\"https:\")) {\n throw new Error(\"The authorityHost address must use the 'https' protocol.\");\n }\n\n super({\n requestContentType: \"application/json; charset=utf-8\",\n retryOptions: {\n maxRetries: 3,\n },\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n baseUri,\n });\n\n this.authorityHost = baseUri;\n this.abortControllers = new Map();\n this.allowLoggingAccountIdentifiers = options?.loggingOptions?.allowLoggingAccountIdentifiers;\n // used for WorkloadIdentity\n this.tokenCredentialOptions = { ...options };\n }\n\n async sendTokenRequest(request: PipelineRequest): Promise<TokenResponse | null> {\n logger.info(`IdentityClient: sending token request to [${request.url}]`);\n const response = await this.sendRequest(request);\n\n if (response.bodyAsText && (response.status === 200 || response.status === 201)) {\n const parsedBody: TokenResponseParsedBody = JSON.parse(response.bodyAsText);\n\n if (!parsedBody.access_token) {\n return null;\n }\n\n this.logIdentifiers(response);\n\n const token = {\n accessToken: {\n token: parsedBody.access_token,\n expiresOnTimestamp: parseExpirationTimestamp(parsedBody),\n },\n refreshToken: parsedBody.refresh_token,\n };\n\n logger.info(\n `IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`\n );\n return token;\n } else {\n const error = new AuthenticationError(response.status, response.bodyAsText);\n logger.warning(\n `IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`\n );\n throw error;\n }\n }\n\n async refreshAccessToken(\n tenantId: string,\n clientId: string,\n scopes: string,\n refreshToken: string | undefined,\n clientSecret: string | undefined,\n options: GetTokenOptions = {}\n ): Promise<TokenResponse | null> {\n if (refreshToken === undefined) {\n return null;\n }\n logger.info(\n `IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`\n );\n\n const refreshParams = {\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scopes,\n };\n\n if (clientSecret !== undefined) {\n (refreshParams as any).client_secret = clientSecret;\n }\n\n const query = new URLSearchParams(refreshParams);\n\n return tracingClient.withSpan(\n \"IdentityClient.refreshAccessToken\",\n options,\n async (updatedOptions) => {\n try {\n const urlSuffix = getIdentityTokenEndpointSuffix(tenantId);\n const request = createPipelineRequest({\n url: `${this.authorityHost}/${tenantId}/${urlSuffix}`,\n method: \"POST\",\n body: query.toString(),\n abortSignal: options.abortSignal,\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n tracingOptions: updatedOptions.tracingOptions,\n });\n\n const response = await this.sendTokenRequest(request);\n logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`);\n return response;\n } catch (err: any) {\n if (\n err.name === AuthenticationErrorName &&\n err.errorResponse.error === \"interaction_required\"\n ) {\n // It's likely that the refresh token has expired, so\n // return null so that the credential implementation will\n // initiate the authentication flow again.\n logger.info(`IdentityClient: interaction required for client ID: ${clientId}`);\n return null;\n } else {\n logger.warning(\n `IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`\n );\n throw err;\n }\n }\n }\n );\n }\n\n // Here is a custom layer that allows us to abort requests that go through MSAL,\n // since MSAL doesn't allow us to pass options all the way through.\n\n generateAbortSignal(correlationId: string): AbortSignalLike {\n const controller = new AbortController();\n const controllers = this.abortControllers.get(correlationId) || [];\n controllers.push(controller);\n this.abortControllers.set(correlationId, controllers);\n const existingOnAbort = controller.signal.onabort;\n controller.signal.onabort = (...params) => {\n this.abortControllers.set(correlationId, undefined);\n if (existingOnAbort) {\n existingOnAbort(...params);\n }\n };\n return controller.signal;\n }\n\n abortRequests(correlationId?: string): void {\n const key = correlationId || noCorrelationId;\n const controllers = [\n ...(this.abortControllers.get(key) || []),\n // MSAL passes no correlation ID to the get requests...\n ...(this.abortControllers.get(noCorrelationId) || []),\n ];\n if (!controllers.length) {\n return;\n }\n for (const controller of controllers) {\n controller.abort();\n }\n this.abortControllers.set(key, undefined);\n }\n\n getCorrelationId(options?: NetworkRequestOptions): string {\n const parameter = options?.body\n ?.split(\"&\")\n .map((part) => part.split(\"=\"))\n .find(([key]) => key === \"client-request-id\");\n return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId;\n }\n\n // The MSAL network module methods follow\n\n async sendGetRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"GET\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n abortSignal: this.generateAbortSignal(noCorrelationId),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n async sendPostRequestAsync<T>(\n url: string,\n options?: NetworkRequestOptions\n ): Promise<NetworkResponse<T>> {\n const request = createPipelineRequest({\n url,\n method: \"POST\",\n body: options?.body,\n headers: createHttpHeaders(options?.headers),\n // MSAL doesn't send the correlation ID on the get requests.\n abortSignal: this.generateAbortSignal(this.getCorrelationId(options)),\n });\n\n const response = await this.sendRequest(request);\n\n this.logIdentifiers(response);\n\n return {\n body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined,\n headers: response.headers.toJSON(),\n status: response.status,\n };\n }\n\n /**\n *\n * @internal\n */\n getTokenCredentialOptions(): TokenCredentialOptions {\n return this.tokenCredentialOptions;\n }\n /**\n * If allowLoggingAccountIdentifiers was set on the constructor options\n * we try to log the account identifiers by parsing the received access token.\n *\n * The account identifiers we try to log are:\n * - `appid`: The application or Client Identifier.\n * - `upn`: User Principal Name.\n * - It might not be available in some authentication scenarios.\n * - If it's not available, we put a placeholder: \"No User Principal Name available\".\n * - `tid`: Tenant Identifier.\n * - `oid`: Object Identifier of the authenticated user.\n */\n private logIdentifiers(response: PipelineResponse): void {\n if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) {\n return;\n }\n const unavailableUpn = \"No User Principal Name available\";\n try {\n const parsed = (response as any).parsedBody || JSON.parse(response.bodyAsText);\n const accessToken = parsed.access_token;\n if (!accessToken) {\n // Without an access token allowLoggingAccountIdentifiers isn't useful.\n return;\n }\n const base64Metadata = accessToken.split(\".\")[1];\n const { appid, upn, tid, oid } = JSON.parse(\n Buffer.from(base64Metadata, \"base64\").toString(\"utf8\")\n );\n\n logger.info(\n `[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${\n upn || unavailableUpn\n }. Object ID (user): ${oid}`\n );\n } catch (e: any) {\n logger.warning(\n \"allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:\",\n e.message\n );\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Helps specify a regional authority, or \"AutoDiscoverRegion\" to auto-detect the region.\n */\nexport enum RegionalAuthority {\n /** Instructs MSAL to attempt to discover the region */\n AutoDiscoverRegion = \"AutoDiscoverRegion\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westus' region. */\n USWest = \"westus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westus2' region. */\n USWest2 = \"westus2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'centralus' region. */\n USCentral = \"centralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'eastus' region. */\n USEast = \"eastus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'eastus2' region. */\n USEast2 = \"eastus2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'northcentralus' region. */\n USNorthCentral = \"northcentralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southcentralus' region. */\n USSouthCentral = \"southcentralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westcentralus' region. */\n USWestCentral = \"westcentralus\",\n /** Uses the {@link RegionalAuthority} for the Azure 'canadacentral' region. */\n CanadaCentral = \"canadacentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'canadaeast' region. */\n CanadaEast = \"canadaeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'brazilsouth' region. */\n BrazilSouth = \"brazilsouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'northeurope' region. */\n EuropeNorth = \"northeurope\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westeurope' region. */\n EuropeWest = \"westeurope\",\n /** Uses the {@link RegionalAuthority} for the Azure 'uksouth' region. */\n UKSouth = \"uksouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'ukwest' region. */\n UKWest = \"ukwest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'francecentral' region. */\n FranceCentral = \"francecentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'francesouth' region. */\n FranceSouth = \"francesouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandnorth' region. */\n SwitzerlandNorth = \"switzerlandnorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandwest' region. */\n SwitzerlandWest = \"switzerlandwest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanynorth' region. */\n GermanyNorth = \"germanynorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanywestcentral' region. */\n GermanyWestCentral = \"germanywestcentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'norwaywest' region. */\n NorwayWest = \"norwaywest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'norwayeast' region. */\n NorwayEast = \"norwayeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'eastasia' region. */\n AsiaEast = \"eastasia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southeastasia' region. */\n AsiaSouthEast = \"southeastasia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'japaneast' region. */\n JapanEast = \"japaneast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'japanwest' region. */\n JapanWest = \"japanwest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiaeast' region. */\n AustraliaEast = \"australiaeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiasoutheast' region. */\n AustraliaSouthEast = \"australiasoutheast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral' region. */\n AustraliaCentral = \"australiacentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral2' region. */\n AustraliaCentral2 = \"australiacentral2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'centralindia' region. */\n IndiaCentral = \"centralindia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southindia' region. */\n IndiaSouth = \"southindia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'westindia' region. */\n IndiaWest = \"westindia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'koreasouth' region. */\n KoreaSouth = \"koreasouth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'koreacentral' region. */\n KoreaCentral = \"koreacentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'uaecentral' region. */\n UAECentral = \"uaecentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'uaenorth' region. */\n UAENorth = \"uaenorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southafricanorth' region. */\n SouthAfricaNorth = \"southafricanorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'southafricawest' region. */\n SouthAfricaWest = \"southafricawest\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth' region. */\n ChinaNorth = \"chinanorth\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast' region. */\n ChinaEast = \"chinaeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth2' region. */\n ChinaNorth2 = \"chinanorth2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast2' region. */\n ChinaEast2 = \"chinaeast2\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanycentral' region. */\n GermanyCentral = \"germanycentral\",\n /** Uses the {@link RegionalAuthority} for the Azure 'germanynortheast' region. */\n GermanyNorthEast = \"germanynortheast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgovvirginia' region. */\n GovernmentUSVirginia = \"usgovvirginia\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgoviowa' region. */\n GovernmentUSIowa = \"usgoviowa\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgovarizona' region. */\n GovernmentUSArizona = \"usgovarizona\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usgovtexas' region. */\n GovernmentUSTexas = \"usgovtexas\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usdodeast' region. */\n GovernmentUSDodEast = \"usdodeast\",\n /** Uses the {@link RegionalAuthority} for the Azure 'usdodcentral' region. */\n GovernmentUSDodCentral = \"usdodcentral\",\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { getLogLevel } from \"@azure/logger\";\nimport {\n MsalBaseUtilities,\n defaultLoggerCallback,\n getAuthority,\n getKnownAuthorities,\n msalToPublic,\n publicToMsal,\n getMSALLogLevel,\n} from \"../utils\";\nimport { MsalFlow, MsalFlowOptions } from \"../flows\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n resolveTenantId,\n} from \"../../util/tenantIdUtils\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AppType, AuthenticationRecord } from \"../types\";\nimport { AuthenticationRequiredError } from \"../../errors\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX, DeveloperSignOnClientId } from \"../../constants\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { LogPolicyOptions } from \"@azure/core-rest-pipeline\";\nimport { MultiTenantTokenCredentialOptions } from \"../../credentials/multiTenantTokenCredentialOptions\";\nimport { RegionalAuthority } from \"../../regionalAuthority\";\nimport { TokenCachePersistenceOptions } from \"./tokenCachePersistenceOptions\";\n\n/**\n * Union of the constructor parameters that all MSAL flow types for Node.\n * @internal\n */\nexport interface MsalNodeOptions extends MsalFlowOptions {\n tokenCachePersistenceOptions?: TokenCachePersistenceOptions;\n tokenCredentialOptions: MultiTenantTokenCredentialOptions;\n /**\n * Specifies a regional authority. Please refer to the {@link RegionalAuthority} type for the accepted values.\n * If {@link RegionalAuthority.AutoDiscoverRegion} is specified, we will try to discover the regional authority endpoint.\n * If the property is not specified, uses a non-regional authority endpoint.\n */\n regionalAuthority?: string;\n /**\n * Allows users to configure settings for logging policy options, allow logging account information and personally identifiable information for customer support.\n */\n loggingOptions?: LogPolicyOptions & {\n /**\n * Allows logging account information once the authentication flow succeeds.\n */\n allowLoggingAccountIdentifiers?: boolean;\n /**\n * Allows logging personally identifiable information for customer support.\n */\n enableUnsafeSupportLogging?: boolean;\n };\n}\n\n/**\n * The current persistence provider, undefined by default.\n * @internal\n */\nlet persistenceProvider:\n | ((options?: TokenCachePersistenceOptions) => Promise<msalNode.ICachePlugin>)\n | undefined = undefined;\n\n/**\n * An object that allows setting the persistence provider.\n * @internal\n */\nexport const msalNodeFlowCacheControl = {\n setPersistence(pluginProvider: Exclude<typeof persistenceProvider, undefined>): void {\n persistenceProvider = pluginProvider;\n },\n};\n\n/**\n * MSAL partial base client for Node.js.\n *\n * It completes the input configuration with some default values.\n * It also provides with utility protected methods that can be used from any of the clients,\n * which includes handlers for successful responses and errors.\n *\n * @internal\n */\nexport abstract class MsalNode extends MsalBaseUtilities implements MsalFlow {\n // protected publicApp: msalNode.PublicClientApplication | undefined;\n // protected publicAppCae: msalNode.PublicClientApplication | undefined;\n // protected confidentialApp: msalNode.ConfidentialClientApplication | undefined;\n // protected confidentialAppCae: msalNode.ConfidentialClientApplication | undefined;\n private app: {\n public?: msalNode.PublicClientApplication;\n confidential?: msalNode.ConfidentialClientApplication;\n } = {};\n private caeApp: {\n public?: msalNode.PublicClientApplication;\n confidential?: msalNode.ConfidentialClientApplication;\n } = {};\n protected msalConfig: msalNode.Configuration;\n protected clientId: string;\n protected tenantId: string;\n protected additionallyAllowedTenantIds: string[];\n protected authorityHost?: string;\n protected identityClient?: IdentityClient;\n protected requiresConfidential: boolean = false;\n protected azureRegion?: string;\n protected createCachePlugin: (() => Promise<msalNode.ICachePlugin>) | undefined;\n protected createCachePluginCae: (() => Promise<msalNode.ICachePlugin>) | undefined;\n\n /**\n * MSAL currently caches the tokens depending on the claims used to retrieve them.\n * In cases like CAE, in which we use claims to update the tokens, trying to retrieve the token without the claims will yield the original token.\n * To ensure we always get the latest token, we have to keep track of the claims.\n */\n private cachedClaims: string | undefined;\n\n protected getAssertion: (() => Promise<string>) | undefined;\n constructor(options: MsalNodeOptions) {\n super(options);\n this.msalConfig = this.defaultNodeMsalConfig(options);\n this.tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.tokenCredentialOptions?.additionallyAllowedTenants\n );\n this.clientId = this.msalConfig.auth.clientId;\n if (options?.getAssertion) {\n this.getAssertion = options.getAssertion;\n }\n\n // If persistence has been configured\n if (persistenceProvider !== undefined && options.tokenCachePersistenceOptions?.enabled) {\n const nonCaeOptions = {\n name: `${options.tokenCachePersistenceOptions.name}.${CACHE_NON_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n };\n const caeOptions = {\n name: `${options.tokenCachePersistenceOptions.name}.${CACHE_CAE_SUFFIX}`,\n ...options.tokenCachePersistenceOptions,\n };\n this.createCachePlugin = () => persistenceProvider!(nonCaeOptions);\n this.createCachePluginCae = () => persistenceProvider!(caeOptions);\n } else if (options.tokenCachePersistenceOptions?.enabled) {\n throw new Error(\n [\n \"Persistent token caching was requested, but no persistence provider was configured.\",\n \"You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.\",\n ].join(\" \")\n );\n }\n\n this.azureRegion = options.regionalAuthority ?? process.env.AZURE_REGIONAL_AUTHORITY_NAME;\n if (this.azureRegion === RegionalAuthority.AutoDiscoverRegion) {\n this.azureRegion = \"AUTO_DISCOVER\";\n }\n }\n\n /**\n * Generates a MSAL configuration that generally works for Node.js\n */\n protected defaultNodeMsalConfig(options: MsalNodeOptions): msalNode.Configuration {\n const clientId = options.clientId || DeveloperSignOnClientId;\n const tenantId = resolveTenantId(options.logger, options.tenantId, options.clientId);\n\n this.authorityHost = options.authorityHost || process.env.AZURE_AUTHORITY_HOST;\n const authority = getAuthority(tenantId, this.authorityHost);\n\n this.identityClient = new IdentityClient({\n ...options.tokenCredentialOptions,\n authorityHost: authority,\n loggingOptions: options.loggingOptions,\n });\n\n const clientCapabilities: string[] = [];\n\n return {\n auth: {\n clientId,\n authority,\n knownAuthorities: getKnownAuthorities(\n tenantId,\n authority,\n options.disableInstanceDiscovery\n ),\n clientCapabilities,\n },\n // Cache is defined in this.prepare();\n system: {\n networkClient: this.identityClient,\n loggerOptions: {\n loggerCallback: defaultLoggerCallback(options.logger),\n logLevel: getMSALLogLevel(getLogLevel()),\n piiLoggingEnabled: options.loggingOptions?.enableUnsafeSupportLogging,\n },\n },\n };\n }\n protected getApp(\n appType: \"publicFirst\" | \"confidentialFirst\",\n enableCae?: boolean\n ): msalNode.ConfidentialClientApplication | msalNode.PublicClientApplication;\n protected getApp(appType: \"public\", enableCae?: boolean): msalNode.PublicClientApplication;\n\n protected getApp(\n appType: \"confidential\",\n enableCae?: boolean\n ): msalNode.ConfidentialClientApplication;\n\n protected getApp(\n appType: AppType,\n enableCae?: boolean\n ): msalNode.ConfidentialClientApplication | msalNode.PublicClientApplication {\n const app = enableCae ? this.caeApp : this.app;\n if (appType === \"publicFirst\") {\n return (app.public || app.confidential)!;\n } else if (appType === \"confidentialFirst\") {\n return (app.confidential || app.public)!;\n } else if (appType === \"confidential\") {\n return app.confidential!;\n } else {\n return app.public!;\n }\n }\n\n /**\n * Prepares the MSAL applications.\n */\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n // This will abort any pending request in the IdentityClient,\n // based on the received or generated correlationId\n this.identityClient!.abortRequests(options.correlationId);\n });\n }\n\n const app = options?.enableCae ? this.caeApp : this.app;\n if (options?.enableCae) {\n this.msalConfig.auth.clientCapabilities = [\"cp1\"];\n }\n if (app.public || app.confidential) {\n return;\n }\n if (options?.enableCae && this.createCachePluginCae !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePluginCae(),\n };\n }\n if (this.createCachePlugin !== undefined) {\n this.msalConfig.cache = {\n cachePlugin: await this.createCachePlugin(),\n };\n }\n\n if (options?.enableCae) {\n this.caeApp.public = new msalNode.PublicClientApplication(this.msalConfig);\n } else {\n this.app.public = new msalNode.PublicClientApplication(this.msalConfig);\n }\n\n if (this.getAssertion) {\n this.msalConfig.auth.clientAssertion = await this.getAssertion();\n }\n // The confidential client requires either a secret, assertion or certificate.\n if (\n this.msalConfig.auth.clientSecret ||\n this.msalConfig.auth.clientAssertion ||\n this.msalConfig.auth.clientCertificate\n ) {\n if (options?.enableCae) {\n this.caeApp.confidential = new msalNode.ConfidentialClientApplication(this.msalConfig);\n } else {\n this.app.confidential = new msalNode.ConfidentialClientApplication(this.msalConfig);\n }\n } else {\n if (this.requiresConfidential) {\n throw new Error(\n \"Unable to generate the MSAL confidential client. Missing either the client's secret, certificate or assertion.\"\n );\n }\n }\n }\n\n /**\n * Allows the cancellation of a MSAL request.\n */\n protected withCancellation(\n promise: Promise<msalNode.AuthenticationResult | null>,\n abortSignal?: AbortSignalLike,\n onCancel?: () => void\n ): Promise<msalNode.AuthenticationResult | null> {\n return new Promise((resolve, reject) => {\n promise\n .then((msalToken) => {\n return resolve(msalToken!);\n })\n .catch(reject);\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n onCancel?.();\n });\n }\n });\n }\n\n /**\n * Returns the existing account, attempts to load the account from MSAL.\n */\n async getActiveAccount(enableCae = false): Promise<AuthenticationRecord | undefined> {\n if (this.account) {\n return this.account;\n }\n const cache = this.getApp(\"confidentialFirst\", enableCae).getTokenCache();\n const accountsByTenant = await cache?.getAllAccounts();\n\n if (!accountsByTenant) {\n return;\n }\n\n if (accountsByTenant.length === 1) {\n this.account = msalToPublic(this.clientId, accountsByTenant[0]);\n } else {\n this.logger\n .info(`More than one account was found authenticated for this Client ID and Tenant ID.\nHowever, no \"authenticationRecord\" has been provided for this credential,\ntherefore we're unable to pick between these accounts.\nA new login attempt will be requested, to ensure the correct account is picked.\nTo work with multiple accounts for the same Client ID and Tenant ID, please provide an \"authenticationRecord\" when initializing a credential to prevent this from happening.`);\n return;\n }\n\n return this.account;\n }\n\n /**\n * Attempts to retrieve a token from cache.\n */\n async getTokenSilent(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n await this.getActiveAccount(options?.enableCae);\n if (!this.account) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Silent authentication failed. We couldn't retrieve an active account from the cache.\",\n });\n }\n\n const silentRequest: msalNode.SilentFlowRequest = {\n // To be able to re-use the account, the Token Cache must also have been provided.\n account: publicToMsal(this.account),\n correlationId: options?.correlationId,\n scopes,\n authority: options?.authority,\n claims: options?.claims,\n };\n\n try {\n this.logger.info(\"Attempting to acquire token silently\");\n /**\n * The following code to retrieve all accounts is done as a workaround in an attempt to force the\n * refresh of the token cache with the token and the account passed in through the\n * `authenticationRecord` parameter. See issue - https://github.com/Azure/azure-sdk-for-js/issues/24349#issuecomment-1496715651\n * This workaround serves as a workaround for silent authentication not happening when authenticationRecord is passed.\n */\n await this.getApp(\"publicFirst\", options?.enableCae)?.getTokenCache().getAllAccounts();\n const response =\n (await this.getApp(\"confidential\", options?.enableCae)?.acquireTokenSilent(\n silentRequest\n )) ?? (await this.getApp(\"public\", options?.enableCae).acquireTokenSilent(silentRequest));\n return this.handleResult(scopes, this.clientId, response || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n\n /**\n * Attempts to retrieve an authenticated token from MSAL.\n */\n protected abstract doGetToken(scopes: string[], options?: GetTokenOptions): Promise<AccessToken>;\n\n /**\n * Wrapper around each MSAL flow get token operation: doGetToken.\n * If disableAutomaticAuthentication is sent through the constructor, it will prevent MSAL from requesting the user input.\n */\n public async getToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId =\n processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds) ||\n this.tenantId;\n\n options.authority = getAuthority(tenantId, this.authorityHost);\n\n options.correlationId = options?.correlationId || this.generateUuid();\n await this.init(options);\n\n try {\n // MSAL now caches tokens based on their claims,\n // so now one has to keep track fo claims in order to retrieve the newer tokens from acquireTokenSilent\n // This update happened on PR: https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/4533\n const optionsClaims = (options as any).claims;\n if (optionsClaims) {\n this.cachedClaims = optionsClaims;\n }\n if (this.cachedClaims && !optionsClaims) {\n (options as any).claims = this.cachedClaims;\n }\n // We don't return the promise since we want to catch errors right here.\n return await this.getTokenSilent(scopes, options);\n } catch (err: any) {\n if (err.name !== \"AuthenticationRequiredError\") {\n throw err;\n }\n if (options?.disableAutomaticAuthentication) {\n throw new AuthenticationRequiredError({\n scopes,\n getTokenOptions: options,\n message:\n \"Automatic authentication has been disabled. You may call the authentication() method.\",\n });\n }\n this.logger.info(`Silent authentication failed, falling back to interactive method.`);\n return this.doGetToken(scopes, options);\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { AzureAuthorityHosts } from \"../constants\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport { VisualStudioCodeCredentialOptions } from \"./visualStudioCodeCredentialOptions\";\nimport { VSCodeCredentialFinder } from \"./visualStudioCodeCredentialPlugin\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\n\nconst CommonTenantId = \"common\";\nconst AzureAccountClientId = \"aebc6443-996d-45c2-90f0-388ff96faa56\"; // VSC: 'aebc6443-996d-45c2-90f0-388ff96faa56'\nconst logger = credentialLogger(\"VisualStudioCodeCredential\");\n\nlet findCredentials: VSCodeCredentialFinder | undefined = undefined;\n\nexport const vsCodeCredentialControl = {\n setVsCodeCredentialFinder(finder: VSCodeCredentialFinder): void {\n findCredentials = finder;\n },\n};\n\n// Map of unsupported Tenant IDs and the errors we will be throwing.\nconst unsupportedTenantIds: Record<string, string> = {\n adfs: \"The VisualStudioCodeCredential does not support authentication with ADFS tenants.\",\n};\n\nfunction checkUnsupportedTenant(tenantId: string): void {\n // If the Tenant ID isn't supported, we throw.\n const unsupportedTenantError = unsupportedTenantIds[tenantId];\n if (unsupportedTenantError) {\n throw new CredentialUnavailableError(unsupportedTenantError);\n }\n}\n\ntype VSCodeCloudNames = \"AzureCloud\" | \"AzureChina\" | \"AzureGermanCloud\" | \"AzureUSGovernment\";\n\nconst mapVSCodeAuthorityHosts: Record<VSCodeCloudNames, string> = {\n AzureCloud: AzureAuthorityHosts.AzurePublicCloud,\n AzureChina: AzureAuthorityHosts.AzureChina,\n AzureGermanCloud: AzureAuthorityHosts.AzureGermany,\n AzureUSGovernment: AzureAuthorityHosts.AzureGovernment,\n};\n\n/**\n * Attempts to load a specific property from the VSCode configurations of the current OS.\n * If it fails at any point, returns undefined.\n */\nexport function getPropertyFromVSCode(property: string): string | undefined {\n const settingsPath = [\"User\", \"settings.json\"];\n // Eventually we can add more folders for more versions of VSCode.\n const vsCodeFolder = \"Code\";\n const homedir = os.homedir();\n\n function loadProperty(...pathSegments: string[]): string | undefined {\n const fullPath = path.join(...pathSegments, vsCodeFolder, ...settingsPath);\n const settings = JSON.parse(fs.readFileSync(fullPath, { encoding: \"utf8\" }));\n return settings[property];\n }\n\n try {\n let appData: string;\n switch (process.platform) {\n case \"win32\":\n appData = process.env.APPDATA!;\n return appData ? loadProperty(appData) : undefined;\n case \"darwin\":\n return loadProperty(homedir, \"Library\", \"Application Support\");\n case \"linux\":\n return loadProperty(homedir, \".config\");\n default:\n return;\n }\n } catch (e: any) {\n logger.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`);\n return;\n }\n}\n\n/**\n * Connects to Azure using the credential provided by the VSCode extension 'Azure Account'.\n * Once the user has logged in via the extension, this credential can share the same refresh token\n * that is cached by the extension.\n *\n * It's a [known issue](https://github.com/Azure/azure-sdk-for-js/issues/20500) that this credential doesn't\n * work with [Azure Account extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account)\n * versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider\n * authenticating with {@link AzureCliCredential}.\n */\nexport class VisualStudioCodeCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private cloudName: VSCodeCloudNames;\n\n /**\n * Creates an instance of VisualStudioCodeCredential to use for automatically authenticating via VSCode.\n *\n * **Note**: `VisualStudioCodeCredential` is provided by a plugin package:\n * `@azure/identity-vscode`. If this package is not installed and registered\n * using the plugin API (`useIdentityPlugin`), then authentication using\n * `VisualStudioCodeCredential` will not be available.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: VisualStudioCodeCredentialOptions) {\n // We want to make sure we use the one assigned by the user on the VSCode settings.\n // Or just `AzureCloud` by default.\n this.cloudName = (getPropertyFromVSCode(\"azure.cloud\") || \"AzureCloud\") as VSCodeCloudNames;\n\n // Picking an authority host based on the cloud name.\n const authorityHost = mapVSCodeAuthorityHosts[this.cloudName];\n\n this.identityClient = new IdentityClient({\n authorityHost,\n ...options,\n });\n\n if (options && options.tenantId) {\n checkTenantId(logger, options.tenantId);\n this.tenantId = options.tenantId;\n } else {\n this.tenantId = CommonTenantId;\n }\n\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n\n checkUnsupportedTenant(this.tenantId);\n }\n\n /**\n * Runs preparations for any further getToken request.\n */\n private async prepare(): Promise<void> {\n // Attempts to load the tenant from the VSCode configuration file.\n const settingsTenant = getPropertyFromVSCode(\"azure.tenant\");\n if (settingsTenant) {\n this.tenantId = settingsTenant;\n }\n checkUnsupportedTenant(this.tenantId);\n }\n\n /**\n * The promise of the single preparation that will be executed at the first getToken request for an instance of this class.\n */\n private preparePromise: Promise<void> | undefined;\n\n /**\n * Runs preparations for any further getToken, but only once.\n */\n private prepareOnce(): Promise<void> | undefined {\n if (!this.preparePromise) {\n this.preparePromise = this.prepare();\n }\n return this.preparePromise;\n }\n\n /**\n * Returns the token found by searching VSCode's authentication cache or\n * returns null if no token could be found.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * `TokenCredential` implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken> {\n await this.prepareOnce();\n\n const tenantId =\n processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds,\n logger\n ) || this.tenantId;\n\n if (findCredentials === undefined) {\n throw new CredentialUnavailableError(\n [\n \"No implementation of `VisualStudioCodeCredential` is available.\",\n \"You must install the identity-vscode plugin package (`npm install --save-dev @azure/identity-vscode`)\",\n \"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling\",\n \"`useIdentityPlugin(vsCodePlugin)` before creating a `VisualStudioCodeCredential`.\",\n \"To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\",\n ].join(\" \")\n );\n }\n\n let scopeString = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n\n // Check to make sure the scope we get back is a valid scope\n if (!scopeString.match(/^[0-9a-zA-Z-.:/]+$/)) {\n const error = new Error(\"Invalid scope was specified by the user or calling client\");\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n if (scopeString.indexOf(\"offline_access\") < 0) {\n scopeString += \" offline_access\";\n }\n\n // findCredentials returns an array similar to:\n // [\n // {\n // account: \"\",\n // password: \"\",\n // },\n // /* ... */\n // ]\n const credentials = await findCredentials();\n\n // If we can't find the credential based on the name, we'll pick the first one available.\n const { password: refreshToken } =\n credentials.find(({ account }) => account === this.cloudName) ?? credentials[0] ?? {};\n\n if (refreshToken) {\n const tokenResponse = await this.identityClient.refreshAccessToken(\n tenantId,\n AzureAccountClientId,\n scopeString,\n refreshToken,\n undefined\n );\n\n if (tokenResponse) {\n logger.getToken.info(formatSuccess(scopes));\n return tokenResponse.accessToken;\n } else {\n const error = new CredentialUnavailableError(\n \"Could not retrieve the token associated with Visual Studio Code. Have you connected using the 'Azure Account' extension recently? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n } else {\n const error = new CredentialUnavailableError(\n \"Could not retrieve the token associated with Visual Studio Code. Did you connect using the 'Azure Account' extension? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzurePluginContext, IdentityPlugin } from \"./provider\";\nimport { msalNodeFlowCacheControl } from \"../msal/nodeFlows/msalNodeCommon\";\nimport { vsCodeCredentialControl } from \"../credentials/visualStudioCodeCredential\";\n\n/**\n * The context passed to an Identity plugin. This contains objects that\n * plugins can use to set backend implementations.\n * @internal\n */\nconst pluginContext: AzurePluginContext = {\n cachePluginControl: msalNodeFlowCacheControl,\n vsCodeCredentialControl: vsCodeCredentialControl,\n};\n\n/**\n * Extend Azure Identity with additional functionality. Pass a plugin from\n * a plugin package, such as:\n *\n * - `@azure/identity-cache-persistence`: provides persistent token caching\n * - `@azure/identity-vscode`: provides the dependencies of\n * `VisualStudioCodeCredential` and enables it\n *\n * Example:\n *\n * ```javascript\n * import { cachePersistencePlugin } from \"@azure/identity-cache-persistence\";\n *\n * import { useIdentityPlugin, DefaultAzureCredential } from \"@azure/identity\";\n * useIdentityPlugin(cachePersistencePlugin);\n *\n * // The plugin has the capability to extend `DefaultAzureCredential` and to\n * // add middleware to the underlying credentials, such as persistence.\n * const credential = new DefaultAzureCredential({\n * tokenCachePersistenceOptions: {\n * enabled: true\n * }\n * });\n * ```\n *\n * @param plugin - the plugin to register\n */\nexport function useIdentityPlugin(plugin: IdentityPlugin): void {\n plugin(pluginContext);\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n PipelineRequestOptions,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\n\nconst msiName = \"ManagedIdentityCredential - AppServiceMSI 2017\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": \"2017-09-01\",\n };\n\n if (clientId) {\n queryParameters.clientid = clientId;\n }\n\n const query = new URLSearchParams(queryParameters);\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.MSI_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: MSI_ENDPOINT`);\n }\n if (!process.env.MSI_SECRET) {\n throw new Error(`${msiName}: Missing environment variable: MSI_SECRET`);\n }\n\n return {\n url: `${process.env.MSI_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n secret: process.env.MSI_SECRET,\n }),\n };\n}\n\n/**\n * Defines how to determine whether the Azure App Service MSI is available, and also how to retrieve a token from the Azure App Service MSI.\n */\nexport const appServiceMsi2017: MSI = {\n name: \"appServiceMsi2017\",\n async isAvailable({ scopes }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n const env = process.env;\n const result = Boolean(env.MSI_ENDPOINT && env.MSI_SECRET);\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: MSI_ENDPOINT and MSI_SECRET.`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (resourceId) {\n logger.warning(\n `${msiName}: managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`\n );\n }\n\n logger.info(\n `${msiName}: Using the endpoint and the secret coming form the environment variables: MSI_ENDPOINT=${process.env.MSI_ENDPOINT} and MSI_SECRET=[REDACTED].`\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId),\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n PipelineRequestOptions,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\n\nconst msiName = \"ManagedIdentityCredential - CloudShellMSI\";\nexport const logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const body: Record<string, string> = {\n resource,\n };\n\n if (clientId) {\n body.client_id = clientId;\n }\n if (resourceId) {\n body.msi_res_id = resourceId;\n }\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.MSI_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: MSI_ENDPOINT`);\n }\n const params = new URLSearchParams(body);\n return {\n url: process.env.MSI_ENDPOINT,\n method: \"POST\",\n body: params.toString(),\n headers: createHttpHeaders({\n Accept: \"application/json\",\n Metadata: \"true\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }),\n };\n}\n\n/**\n * Defines how to determine whether the Azure Cloud Shell MSI is available, and also how to retrieve a token from the Azure Cloud Shell MSI.\n * Since Azure Managed Identities aren't available in the Azure Cloud Shell, we log a warning for users that try to access cloud shell using user assigned identity.\n */\nexport const cloudShellMsi: MSI = {\n name: \"cloudShellMsi\",\n async isAvailable({ scopes }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n\n const result = Boolean(process.env.MSI_ENDPOINT);\n if (!result) {\n logger.info(`${msiName}: Unavailable. The environment variable MSI_ENDPOINT is needed.`);\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (clientId) {\n logger.warning(\n `${msiName}: user-assigned identities not supported. The argument clientId might be ignored by the service.`\n );\n }\n\n if (resourceId) {\n logger.warning(\n `${msiName}: user defined managed Identity by resource Id not supported. The argument resourceId might be ignored by the service.`\n );\n }\n\n logger.info(\n `${msiName}: Using the endpoint coming form the environment variable MSI_ENDPOINT = ${process.env.MSI_ENDPOINT}.`\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { delay, isError } from \"@azure/core-util\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport {\n PipelineRequestOptions,\n PipelineResponse,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { AuthenticationError } from \"../../errors\";\nimport { tracingClient } from \"../../util/tracing\";\nimport { imdsApiVersion, imdsEndpointPath, imdsHost } from \"./constants\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\n\nconst msiName = \"ManagedIdentityCredential - IMDS\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string,\n options?: {\n skipQuery?: boolean;\n skipMetadataHeader?: boolean;\n }\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const { skipQuery, skipMetadataHeader } = options || {};\n let query = \"\";\n\n // Pod Identity will try to process this request even if the Metadata header is missing.\n // We can exclude the request query to ensure no IMDS endpoint tries to process the ping request.\n if (!skipQuery) {\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": imdsApiVersion,\n };\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n const params = new URLSearchParams(queryParameters);\n query = `?${params.toString()}`;\n }\n\n const url = new URL(imdsEndpointPath, process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST ?? imdsHost);\n\n const rawHeaders: Record<string, string> = {\n Accept: \"application/json\",\n Metadata: \"true\",\n };\n\n // Remove the Metadata header to invoke a request error from some IMDS endpoints.\n if (skipMetadataHeader) {\n delete rawHeaders.Metadata;\n }\n\n return {\n // In this case, the `?` should be added in the \"query\" variable `skipQuery` is not set.\n url: `${url}${query}`,\n method: \"GET\",\n headers: createHttpHeaders(rawHeaders),\n };\n}\n\n// 800ms -> 1600ms -> 3200ms\nexport const imdsMsiRetryConfig = {\n maxRetries: 3,\n startDelayInMs: 800,\n intervalIncrement: 2,\n};\n\n/**\n * Defines how to determine whether the Azure IMDS MSI is available, and also how to retrieve a token from the Azure IMDS MSI.\n */\nexport const imdsMsi: MSI = {\n name: \"imdsMsi\",\n async isAvailable({\n scopes,\n identityClient,\n clientId,\n resourceId,\n getTokenOptions = {},\n }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n\n // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n return true;\n }\n\n if (!identityClient) {\n throw new Error(\"Missing IdentityClient\");\n }\n\n const requestOptions = prepareRequestOptions(resource, clientId, resourceId, {\n skipMetadataHeader: true,\n skipQuery: true,\n });\n\n return tracingClient.withSpan(\n \"ManagedIdentityCredential-pingImdsEndpoint\",\n getTokenOptions,\n async (options) => {\n requestOptions.tracingOptions = options.tracingOptions;\n\n // Create a request with a timeout since we expect that\n // not having a \"Metadata\" header should cause an error to be\n // returned quickly from the endpoint, proving its availability.\n const request = createPipelineRequest(requestOptions);\n\n // Default to 1000 if the default of 0 is used.\n // Negative values can still be used to disable the timeout.\n request.timeout = options.requestOptions?.timeout || 1000;\n\n // This MSI uses the imdsEndpoint to get the token, which only uses http://\n request.allowInsecureConnection = true;\n let response: PipelineResponse;\n try {\n logger.info(`${msiName}: Pinging the Azure IMDS endpoint`);\n response = await identityClient.sendRequest(request);\n } catch (err: unknown) {\n // If the request failed, or Node.js was unable to establish a connection,\n // or the host was down, we'll assume the IMDS endpoint isn't available.\n if (isError(err)) {\n logger.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`);\n }\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\"\n // rather than just timing out, as expected.\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n return false;\n }\n if (response.status === 403) {\n if (\n response.bodyAsText?.includes(\n \"A socket operation was attempted to an unreachable network\"\n )\n ) {\n logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`);\n logger.info(`${msiName}: ${response.bodyAsText}`);\n return false;\n }\n }\n // If we received any response, the endpoint is available\n logger.info(`${msiName}: The Azure IMDS endpoint is available`);\n return true;\n }\n );\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) {\n logger.info(\n `${msiName}: Using the Azure IMDS endpoint coming from the environment variable AZURE_POD_IDENTITY_AUTHORITY_HOST=${process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST}.`\n );\n } else {\n logger.info(`${msiName}: Using the default Azure IMDS endpoint ${imdsHost}.`);\n }\n\n let nextDelayInMs = imdsMsiRetryConfig.startDelayInMs;\n for (let retries = 0; retries < imdsMsiRetryConfig.maxRetries; retries++) {\n try {\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n\n return (tokenResponse && tokenResponse.accessToken) || null;\n } catch (error: any) {\n if (error.statusCode === 404) {\n await delay(nextDelayInMs);\n nextDelayInMs *= imdsMsiRetryConfig.intervalIncrement;\n continue;\n }\n throw error;\n }\n }\n\n throw new AuthenticationError(\n 404,\n `${msiName}: Failed to retrieve IMDS token after ${imdsMsiRetryConfig.maxRetries} retries.`\n );\n },\n};\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n PipelineRequestOptions,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { readFile } from \"fs\";\nimport { AuthenticationError } from \"../../errors\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { mapScopesToResource } from \"./utils\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { azureArcAPIVersion } from \"./constants\";\n\nconst msiName = \"ManagedIdentityCredential - Azure Arc MSI\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": azureArcAPIVersion,\n };\n\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.IDENTITY_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: IDENTITY_ENDPOINT`);\n }\n\n const query = new URLSearchParams(queryParameters);\n\n return createPipelineRequest({\n // Should be similar to: http://localhost:40342/metadata/identity/oauth2/token\n url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n Metadata: \"true\",\n }),\n });\n}\n\n/**\n * Retrieves the file contents at the given path using promises.\n * Useful since `fs`'s readFileSync locks the thread, and to avoid extra dependencies.\n */\nfunction readFileAsync(path: string, options: { encoding: BufferEncoding }): Promise<string> {\n return new Promise((resolve, reject) =>\n readFile(path, options, (err, data) => {\n if (err) {\n reject(err);\n }\n resolve(data);\n })\n );\n}\n\n/**\n * Does a request to the authentication provider that results in a file path.\n */\nasync function filePathRequest(\n identityClient: IdentityClient,\n requestPrepareOptions: PipelineRequestOptions\n): Promise<string | undefined> {\n const response = await identityClient.sendRequest(createPipelineRequest(requestPrepareOptions));\n\n if (response.status !== 401) {\n let message = \"\";\n if (response.bodyAsText) {\n message = ` Response: ${response.bodyAsText}`;\n }\n throw new AuthenticationError(\n response.status,\n `${msiName}: To authenticate with Azure Arc MSI, status code 401 is expected on the first request. ${message}`\n );\n }\n\n const authHeader = response.headers.get(\"www-authenticate\") || \"\";\n try {\n return authHeader.split(\"=\").slice(1)[0];\n } catch (e: any) {\n throw Error(`Invalid www-authenticate header format: ${authHeader}`);\n }\n}\n\n/**\n * Defines how to determine whether the Azure Arc MSI is available, and also how to retrieve a token from the Azure Arc MSI.\n */\nexport const arcMsi: MSI = {\n name: \"arc\",\n async isAvailable({ scopes }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n const result = Boolean(process.env.IMDS_ENDPOINT && process.env.IDENTITY_ENDPOINT);\n if (!result) {\n logger.info(\n `${msiName}: The environment variables needed are: IMDS_ENDPOINT and IDENTITY_ENDPOINT`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n if (clientId) {\n logger.warning(\n `${msiName}: user-assigned identities not supported. The argument clientId might be ignored by the service.`\n );\n }\n if (resourceId) {\n logger.warning(\n `${msiName}: user defined managed Identity by resource Id is not supported. Argument resourceId will be ignored.`\n );\n }\n\n logger.info(`${msiName}: Authenticating.`);\n\n const requestOptions = {\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n allowInsecureConnection: true,\n };\n\n const filePath = await filePathRequest(identityClient, requestOptions);\n\n if (!filePath) {\n throw new Error(`${msiName}: Failed to find the token file.`);\n }\n\n const key = await readFileAsync(filePath, { encoding: \"utf-8\" });\n requestOptions.headers?.set(\"Authorization\", `Basic ${key}`);\n\n const request = createPipelineRequest({\n ...requestOptions,\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { isError } from \"@azure/core-util\";\n\n/**\n * Options that can be passed to configure MSAL to handle client assertions.\n * @internal\n */\nexport interface MsalClientAssertionOptions extends MsalNodeOptions {\n /**\n * A function that retrieves the assertion for the credential to use.\n */\n getAssertion: () => Promise<string>;\n}\n\n/**\n * MSAL client assertion client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.\n * @internal\n */\nexport class MsalClientAssertion extends MsalNode {\n getAssertion: () => Promise<string>;\n constructor(options: MsalClientAssertionOptions) {\n super(options);\n this.requiresConfidential = true;\n this.getAssertion = options.getAssertion;\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const assertion = await this.getAssertion();\n const result = await this.getApp(\n \"confidential\",\n options.enableCae\n ).acquireTokenByClientCredential({\n scopes,\n correlationId: options.correlationId,\n azureRegion: this.azureRegion,\n authority: options.authority,\n claims: options.claims,\n clientAssertion: assertion,\n });\n // The Client Credential flow does not return an account,\n // so each time getToken gets called, we will have to acquire a new token through the service.\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: unknown) {\n let err2 = err;\n if (err === null || err === undefined) {\n err2 = new Error(JSON.stringify(err));\n } else {\n err2 = isError(err) ? err : new Error(String(err));\n }\n throw this.handleError(scopes, err2 as Error, options);\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { ClientAssertionCredentialOptions } from \"./clientAssertionCredentialOptions\";\nimport { MsalClientAssertion } from \"../msal/nodeFlows/msalClientAssertion\";\nimport { MsalFlow } from \"../msal/flows\";\nimport { credentialLogger } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"ClientAssertionCredential\");\n\n/**\n * Authenticates a service principal with a JWT assertion.\n */\nexport class ClientAssertionCredential implements TokenCredential {\n private msalFlow: MsalFlow;\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private clientId: string;\n private options: ClientAssertionCredentialOptions;\n\n /**\n * Creates an instance of the ClientAssertionCredential with the details\n * needed to authenticate against Azure Active Directory with a client\n * assertion provided by the developer through the `getAssertion` function parameter.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param getAssertion - A function that retrieves the assertion for the credential to use.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n getAssertion: () => Promise<string>,\n options: ClientAssertionCredentialOptions = {}\n ) {\n if (!tenantId || !clientId || !getAssertion) {\n throw new Error(\n \"ClientAssertionCredential: tenantId, clientId, and clientAssertion are required parameters.\"\n );\n }\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n this.clientId = clientId;\n this.options = options;\n this.msalFlow = new MsalClientAssertion({\n ...options,\n logger,\n clientId: this.clientId,\n tenantId: this.tenantId,\n tokenCredentialOptions: this.options,\n getAssertion,\n });\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger\n );\n\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n return this.msalFlow.getToken(arrayScopes, newOptions);\n }\n );\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { ClientAssertionCredential } from \"./clientAssertionCredential\";\nimport { WorkloadIdentityCredentialOptions } from \"./workloadIdentityCredentialOptions\";\nimport { readFile } from \"fs/promises\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger, processEnvVars } from \"../util/logging\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\n\nconst credentialName = \"WorkloadIdentityCredential\";\n/**\n * Contains the list of all supported environment variable names so that an\n * appropriate error message can be generated when no credentials can be\n * configured.\n *\n * @internal\n */\nexport const SupportedWorkloadEnvironmentVariables = [\n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_FEDERATED_TOKEN_FILE\",\n];\nconst logger = credentialLogger(credentialName);\n/**\n * Workload Identity authentication is a feature in Azure that allows applications running on virtual machines (VMs)\n * to access other Azure resources without the need for a service principal or managed identity. With Workload Identity\n * authentication, applications authenticate themselves using their own identity, rather than using a shared service\n * principal or managed identity. Under the hood, Workload Identity authentication uses the concept of Service Account\n * Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using Workload\n * Identity authentication, you can avoid the need to manage and rotate service principals or managed identities for\n * each application on each VM. Additionally, because SACs are created automatically and managed by Azure, you don't\n * need to worry about storing and securing sensitive credentials themselves.\n * The WorkloadIdentityCredential supports Azure workload identity authentication on Azure Kubernetes and acquires\n * a token using the SACs available in the Azure Kubernetes environment.\n * Refer to <a href=\"https://learn.microsoft.com/azure/aks/workload-identity-overview\">Azure Active Directory\n * Workload Identity</a> for more information.\n */\nexport class WorkloadIdentityCredential implements TokenCredential {\n private client: ClientAssertionCredential | undefined;\n private azureFederatedTokenFileContent: string | undefined = undefined;\n private cacheDate: number | undefined = undefined;\n private federatedTokenFilePath: string | undefined;\n\n /**\n * WorkloadIdentityCredential supports Azure workload identity on Kubernetes.\n *\n * @param options - The identity client options to use for authentication.\n */\n constructor(options?: WorkloadIdentityCredentialOptions) {\n // Logging environment variables for error details\n const assignedEnv = processEnvVars(SupportedWorkloadEnvironmentVariables).assigned.join(\", \");\n logger.info(`Found the following environment variables: ${assignedEnv}`);\n\n const workloadIdentityCredentialOptions = options ?? {};\n const tenantId = workloadIdentityCredentialOptions.tenantId || process.env.AZURE_TENANT_ID;\n const clientId = workloadIdentityCredentialOptions.clientId || process.env.AZURE_CLIENT_ID;\n this.federatedTokenFilePath =\n workloadIdentityCredentialOptions.tokenFilePath || process.env.AZURE_FEDERATED_TOKEN_FILE;\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n if (clientId && tenantId && this.federatedTokenFilePath) {\n logger.info(\n `Invoking ClientAssertionCredential with tenant ID: ${tenantId}, clientId: ${workloadIdentityCredentialOptions.clientId} and federated token path: [REDACTED]`\n );\n this.client = new ClientAssertionCredential(\n tenantId,\n clientId,\n this.readFileContents.bind(this),\n options\n );\n }\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n if (!this.client) {\n const errorMessage = `${credentialName}: is unavailable. tenantId, clientId, and federatedTokenFilePath are required parameters. \n In DefaultAzureCredential and ManagedIdentityCredential, these can be provided as environment variables - \n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_FEDERATED_TOKEN_FILE\". See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot `;\n logger.info(errorMessage);\n throw new CredentialUnavailableError(errorMessage);\n }\n logger.info(\"Invoking getToken() of Client Assertion Credential\");\n return this.client.getToken(scopes, options);\n }\n\n private async readFileContents(): Promise<string> {\n // Cached assertions expire after 5 minutes\n if (this.cacheDate !== undefined && Date.now() - this.cacheDate >= 1000 * 60 * 5) {\n this.azureFederatedTokenFileContent = undefined;\n }\n if (!this.federatedTokenFilePath) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. Invalid file path provided ${this.federatedTokenFilePath}.`\n );\n }\n if (!this.azureFederatedTokenFileContent) {\n const file = await readFile(this.federatedTokenFilePath, \"utf8\");\n const value = file.trim();\n if (!value) {\n throw new CredentialUnavailableError(\n `${credentialName}: is unavailable. No content on the file ${this.federatedTokenFilePath}.`\n );\n } else {\n this.azureFederatedTokenFileContent = value;\n this.cacheDate = Date.now();\n }\n }\n return this.azureFederatedTokenFileContent;\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions } from \"@azure/core-auth\";\nimport { MSI, MSIConfiguration } from \"./models\";\nimport { WorkloadIdentityCredential } from \"../workloadIdentityCredential\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { WorkloadIdentityCredentialOptions } from \"../workloadIdentityCredentialOptions\";\n\nconst msiName = \"ManagedIdentityCredential - Token Exchange\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI.\n */\nexport function tokenExchangeMsi(): MSI {\n return {\n name: \"tokenExchangeMsi\",\n async isAvailable({ clientId }): Promise<boolean> {\n const env = process.env;\n const result = Boolean(\n (clientId || env.AZURE_CLIENT_ID) &&\n env.AZURE_TENANT_ID &&\n process.env.AZURE_FEDERATED_TOKEN_FILE\n );\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<AccessToken | null> {\n const { scopes, clientId } = configuration;\n const identityClientTokenCredentialOptions = {};\n const workloadIdentityCredential = new WorkloadIdentityCredential({\n clientId,\n tenantId: process.env.AZURE_TENANT_ID,\n tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE,\n ...identityClientTokenCredentialOptions,\n disableInstanceDiscovery: true,\n } as WorkloadIdentityCredentialOptions);\n const token = await workloadIdentityCredential.getToken(scopes, getTokenOptions);\n return token;\n },\n };\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport https from \"https\";\nimport {\n PipelineRequestOptions,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\nimport { azureFabricVersion } from \"./constants\";\n\n// This MSI can be easily tested by deploying a container to Azure Service Fabric with the Dockerfile:\n//\n// FROM node:12\n// RUN wget https://host.any/path/bash.sh\n// CMD [\"bash\", \"bash.sh\"]\n//\n// Where the bash script contains:\n//\n// curl --insecure $IDENTITY_ENDPOINT'?api-version=2019-07-01-preview&resource=https://vault.azure.net/' -H \"Secret: $IDENTITY_HEADER\"\n//\n\nconst msiName = \"ManagedIdentityCredential - Fabric MSI\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": azureFabricVersion,\n };\n\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n if (resourceId) {\n queryParameters.msi_res_id = resourceId;\n }\n const query = new URLSearchParams(queryParameters);\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.IDENTITY_ENDPOINT) {\n throw new Error(\"Missing environment variable: IDENTITY_ENDPOINT\");\n }\n if (!process.env.IDENTITY_HEADER) {\n throw new Error(\"Missing environment variable: IDENTITY_HEADER\");\n }\n\n return {\n url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n secret: process.env.IDENTITY_HEADER,\n }),\n };\n}\n\n/**\n * Defines how to determine whether the Azure Service Fabric MSI is available, and also how to retrieve a token from the Azure Service Fabric MSI.\n */\nexport const fabricMsi: MSI = {\n name: \"fabricMsi\",\n async isAvailable({ scopes }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n const env = process.env;\n const result = Boolean(\n env.IDENTITY_ENDPOINT && env.IDENTITY_HEADER && env.IDENTITY_SERVER_THUMBPRINT\n );\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT, IDENTITY_HEADER and IDENTITY_SERVER_THUMBPRINT`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<MSIToken | null> {\n const { scopes, identityClient, clientId, resourceId } = configuration;\n\n if (resourceId) {\n logger.warning(\n `${msiName}: user defined managed Identity by resource Id is not supported. Argument resourceId might be ignored by the service.`\n );\n }\n\n logger.info(\n [\n `${msiName}:`,\n \"Using the endpoint and the secret coming from the environment variables:\",\n `IDENTITY_ENDPOINT=${process.env.IDENTITY_ENDPOINT},`,\n \"IDENTITY_HEADER=[REDACTED] and\",\n \"IDENTITY_SERVER_THUMBPRINT=[REDACTED].\",\n ].join(\" \")\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n // The service fabric MSI endpoint will be HTTPS (however, the certificate will be self-signed).\n // allowInsecureConnection: true\n });\n\n request.agent = new https.Agent({\n // This is necessary because Service Fabric provides a self-signed certificate.\n // The alternative path is to verify the certificate using the IDENTITY_SERVER_THUMBPRINT env variable.\n rejectUnauthorized: false,\n });\n\n const tokenResponse = await identityClient.sendTokenRequest(request);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n PipelineRequestOptions,\n createHttpHeaders,\n createPipelineRequest,\n} from \"@azure/core-rest-pipeline\";\nimport { GetTokenOptions } from \"@azure/core-auth\";\nimport { credentialLogger } from \"../../util/logging\";\nimport { MSI, MSIConfiguration, MSIToken } from \"./models\";\nimport { mapScopesToResource } from \"./utils\";\n\nconst msiName = \"ManagedIdentityCredential - AppServiceMSI 2019\";\nconst logger = credentialLogger(msiName);\n\n/**\n * Generates the options used on the request for an access token.\n */\nfunction prepareRequestOptions(\n scopes: string | string[],\n clientId?: string,\n resourceId?: string\n): PipelineRequestOptions {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n throw new Error(`${msiName}: Multiple scopes are not supported.`);\n }\n\n const queryParameters: Record<string, string> = {\n resource,\n \"api-version\": \"2019-08-01\",\n };\n\n if (clientId) {\n queryParameters.client_id = clientId;\n }\n\n if (resourceId) {\n queryParameters.mi_res_id = resourceId;\n }\n const query = new URLSearchParams(queryParameters);\n\n // This error should not bubble up, since we verify that this environment variable is defined in the isAvailable() method defined below.\n if (!process.env.IDENTITY_ENDPOINT) {\n throw new Error(`${msiName}: Missing environment variable: IDENTITY_ENDPOINT`);\n }\n if (!process.env.IDENTITY_HEADER) {\n throw new Error(`${msiName}: Missing environment variable: IDENTITY_HEADER`);\n }\n\n return {\n url: `${process.env.IDENTITY_ENDPOINT}?${query.toString()}`,\n method: \"GET\",\n headers: createHttpHeaders({\n Accept: \"application/json\",\n \"X-IDENTITY-HEADER\": process.env.IDENTITY_HEADER,\n }),\n };\n}\n\n/**\n * Defines how to determine whether the Azure App Service MSI is available, and also how to retrieve a token from the Azure App Service MSI.\n */\nexport const appServiceMsi2019: MSI = {\n name: \"appServiceMsi2019\",\n async isAvailable({ scopes }): Promise<boolean> {\n const resource = mapScopesToResource(scopes);\n if (!resource) {\n logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`);\n return false;\n }\n const env = process.env;\n const result = Boolean(env.IDENTITY_ENDPOINT && env.IDENTITY_HEADER);\n if (!result) {\n logger.info(\n `${msiName}: Unavailable. The environment variables needed are: IDENTITY_ENDPOINT and IDENTITY_HEADER.`\n );\n }\n return result;\n },\n async getToken(\n configuration: MSIConfiguration,\n getTokenOptions: GetTokenOptions = {}\n ): Promise<MSIToken | null> {\n const { identityClient, scopes, clientId, resourceId } = configuration;\n\n logger.info(\n `${msiName}: Using the endpoint and the secret coming form the environment variables: IDENTITY_ENDPOINT=${process.env.IDENTITY_ENDPOINT} and IDENTITY_HEADER=[REDACTED].`\n );\n\n const request = createPipelineRequest({\n abortSignal: getTokenOptions.abortSignal,\n ...prepareRequestOptions(scopes, clientId, resourceId),\n // Generally, MSI endpoints use the HTTP protocol, without transport layer security (TLS).\n allowInsecureConnection: true,\n });\n const tokenResponse = await identityClient.sendTokenRequest(request);\n return (tokenResponse && tokenResponse.accessToken) || null;\n },\n};\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\n\nimport { IdentityClient } from \"../../client/identityClient\";\nimport { TokenCredentialOptions } from \"../../tokenCredentialOptions\";\nimport {\n AuthenticationError,\n AuthenticationRequiredError,\n CredentialUnavailableError,\n} from \"../../errors\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { appServiceMsi2017 } from \"./appServiceMsi2017\";\nimport { tracingClient } from \"../../util/tracing\";\nimport { cloudShellMsi } from \"./cloudShellMsi\";\nimport { imdsMsi } from \"./imdsMsi\";\nimport { MSI, MSIToken } from \"./models\";\nimport { arcMsi } from \"./arcMsi\";\nimport { tokenExchangeMsi } from \"./tokenExchangeMsi\";\nimport { fabricMsi } from \"./fabricMsi\";\nimport { appServiceMsi2019 } from \"./appServiceMsi2019\";\nimport { AppTokenProviderParameters, ConfidentialClientApplication } from \"@azure/msal-node\";\nimport { DeveloperSignOnClientId } from \"../../constants\";\nimport { MsalResult, MsalToken } from \"../../msal/types\";\nimport { getMSALLogLevel } from \"../../msal/utils\";\nimport { getLogLevel } from \"@azure/logger\";\n\nconst logger = credentialLogger(\"ManagedIdentityCredential\");\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `clientId` and not `resourceId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialClientIdOptions extends TokenCredentialOptions {\n /**\n * The client ID of the user - assigned identity, or app registration(when working with AKS pod - identity).\n */\n clientId?: string;\n}\n\n/**\n * Options to send on the {@link ManagedIdentityCredential} constructor.\n * This variation supports `resourceId` and not `clientId`, since only one of both is supported.\n */\nexport interface ManagedIdentityCredentialResourceIdOptions extends TokenCredentialOptions {\n /**\n * Allows specifying a custom resource Id.\n * In scenarios such as when user assigned identities are created using an ARM template,\n * where the resource Id of the identity is known but the client Id can't be known ahead of time,\n * this parameter allows programs to use these user assigned identities\n * without having to first determine the client Id of the created identity.\n */\n resourceId: string;\n}\n\n/**\n * Attempts authentication using a managed identity available at the deployment environment.\n * This authentication type works in Azure VMs, App Service instances, Azure Functions applications,\n * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell.\n *\n * More information about configuring managed identities can be found here:\n * https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview\n */\nexport class ManagedIdentityCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private clientId: string | undefined;\n private resourceId: string | undefined;\n private isEndpointUnavailable: boolean | null = null;\n private isAvailableIdentityClient: IdentityClient;\n private confidentialApp: ConfidentialClientApplication;\n private isAppTokenProviderInitialized: boolean = false;\n\n /**\n * Creates an instance of ManagedIdentityCredential with the client ID of a\n * user-assigned identity, or app registration (when working with AKS pod-identity).\n *\n * @param clientId - The client ID of the user-assigned identity, or app registration (when working with AKS pod-identity).\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(clientId: string, options?: TokenCredentialOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with clientId\n *\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialClientIdOptions);\n /**\n * Creates an instance of ManagedIdentityCredential with Resource Id\n *\n * @param options - Options for configuring the resource which makes the access token request.\n */\n constructor(options?: ManagedIdentityCredentialResourceIdOptions);\n /**\n * @internal\n * @hidden\n */\n constructor(\n clientIdOrOptions?:\n | string\n | ManagedIdentityCredentialClientIdOptions\n | ManagedIdentityCredentialResourceIdOptions,\n options?: TokenCredentialOptions\n ) {\n let _options: TokenCredentialOptions | undefined;\n if (typeof clientIdOrOptions === \"string\") {\n this.clientId = clientIdOrOptions;\n _options = options;\n } else {\n this.clientId = (clientIdOrOptions as ManagedIdentityCredentialClientIdOptions)?.clientId;\n _options = clientIdOrOptions;\n }\n this.resourceId = (_options as ManagedIdentityCredentialResourceIdOptions)?.resourceId;\n // For JavaScript users.\n if (this.clientId && this.resourceId) {\n throw new Error(\n `${ManagedIdentityCredential.name} - Client Id and Resource Id can't be provided at the same time.`\n );\n }\n this.identityClient = new IdentityClient(_options);\n this.isAvailableIdentityClient = new IdentityClient({\n ..._options,\n retryOptions: {\n maxRetries: 0,\n },\n });\n\n /** authority host validation and metadata discovery to be skipped in managed identity\n * since this wasn't done previously before adding token cache support\n */\n this.confidentialApp = new ConfidentialClientApplication({\n auth: {\n authority: \"https://login.microsoftonline.com/managed_identity\",\n clientId: this.clientId ?? DeveloperSignOnClientId,\n clientSecret: \"dummy-secret\",\n cloudDiscoveryMetadata:\n '{\"tenant_discovery_endpoint\":\"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration\",\"api-version\":\"1.1\",\"metadata\":[{\"preferred_network\":\"login.microsoftonline.com\",\"preferred_cache\":\"login.windows.net\",\"aliases\":[\"login.microsoftonline.com\",\"login.windows.net\",\"login.microsoft.com\",\"sts.windows.net\"]},{\"preferred_network\":\"login.partner.microsoftonline.cn\",\"preferred_cache\":\"login.partner.microsoftonline.cn\",\"aliases\":[\"login.partner.microsoftonline.cn\",\"login.chinacloudapi.cn\"]},{\"preferred_network\":\"login.microsoftonline.de\",\"preferred_cache\":\"login.microsoftonline.de\",\"aliases\":[\"login.microsoftonline.de\"]},{\"preferred_network\":\"login.microsoftonline.us\",\"preferred_cache\":\"login.microsoftonline.us\",\"aliases\":[\"login.microsoftonline.us\",\"login.usgovcloudapi.net\"]},{\"preferred_network\":\"login-us.microsoftonline.com\",\"preferred_cache\":\"login-us.microsoftonline.com\",\"aliases\":[\"login-us.microsoftonline.com\"]}]}',\n authorityMetadata:\n '{\"token_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_post\",\"private_key_jwt\",\"client_secret_basic\"],\"jwks_uri\":\"https://login.microsoftonline.com/common/discovery/v2.0/keys\",\"response_modes_supported\":[\"query\",\"fragment\",\"form_post\"],\"subject_types_supported\":[\"pairwise\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"response_types_supported\":[\"code\",\"id_token\",\"code id_token\",\"id_token token\"],\"scopes_supported\":[\"openid\",\"profile\",\"email\",\"offline_access\"],\"issuer\":\"https://login.microsoftonline.com/{tenantid}/v2.0\",\"request_uri_parameter_supported\":false,\"userinfo_endpoint\":\"https://graph.microsoft.com/oidc/userinfo\",\"authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/authorize\",\"device_authorization_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/devicecode\",\"http_logout_supported\":true,\"frontchannel_logout_supported\":true,\"end_session_endpoint\":\"https://login.microsoftonline.com/common/oauth2/v2.0/logout\",\"claims_supported\":[\"sub\",\"iss\",\"cloud_instance_name\",\"cloud_instance_host_name\",\"cloud_graph_host_name\",\"msgraph_host\",\"aud\",\"exp\",\"iat\",\"auth_time\",\"acr\",\"nonce\",\"preferred_username\",\"name\",\"tid\",\"ver\",\"at_hash\",\"c_hash\",\"email\"],\"kerberos_endpoint\":\"https://login.microsoftonline.com/common/kerberos\",\"tenant_region_scope\":null,\"cloud_instance_name\":\"microsoftonline.com\",\"cloud_graph_host_name\":\"graph.windows.net\",\"msgraph_host\":\"graph.microsoft.com\",\"rbac_url\":\"https://pas.windows.net\"}',\n clientCapabilities: [],\n },\n system: {\n loggerOptions: {\n logLevel: getMSALLogLevel(getLogLevel()),\n },\n },\n });\n }\n\n private cachedMSI: MSI | undefined;\n\n private async cachedAvailableMSI(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions\n ): Promise<MSI> {\n if (this.cachedMSI) {\n return this.cachedMSI;\n }\n\n const MSIs = [\n arcMsi,\n fabricMsi,\n appServiceMsi2019,\n appServiceMsi2017,\n cloudShellMsi,\n tokenExchangeMsi(),\n imdsMsi,\n ];\n\n for (const msi of MSIs) {\n if (\n await msi.isAvailable({\n scopes,\n identityClient: this.isAvailableIdentityClient,\n clientId: this.clientId,\n resourceId: this.resourceId,\n getTokenOptions,\n })\n ) {\n this.cachedMSI = msi;\n return msi;\n }\n }\n\n throw new CredentialUnavailableError(\n `${ManagedIdentityCredential.name} - No MSI credential available`\n );\n }\n\n private async authenticateManagedIdentity(\n scopes: string | string[],\n getTokenOptions?: GetTokenOptions\n ): Promise<MSIToken | null> {\n const { span, updatedOptions } = tracingClient.startSpan(\n `${ManagedIdentityCredential.name}.authenticateManagedIdentity`,\n getTokenOptions\n );\n\n try {\n // Determining the available MSI, and avoiding checking for other MSIs while the program is running.\n const availableMSI = await this.cachedAvailableMSI(scopes, updatedOptions);\n return availableMSI.getToken(\n {\n identityClient: this.identityClient,\n scopes,\n clientId: this.clientId,\n resourceId: this.resourceId,\n },\n updatedOptions\n );\n } catch (err: any) {\n span.setStatus({\n status: \"error\",\n error: err,\n });\n throw err;\n } finally {\n span.end();\n }\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken> {\n let result: AccessToken | null = null;\n const { span, updatedOptions } = tracingClient.startSpan(\n `${ManagedIdentityCredential.name}.getToken`,\n options\n );\n try {\n // isEndpointAvailable can be true, false, or null,\n // If it's null, it means we don't yet know whether\n // the endpoint is available and need to check for it.\n if (this.isEndpointUnavailable !== true) {\n const availableMSI = await this.cachedAvailableMSI(scopes, updatedOptions);\n if (availableMSI.name === \"tokenExchangeMsi\") {\n result = await this.authenticateManagedIdentity(scopes, updatedOptions);\n } else {\n const appTokenParameters: AppTokenProviderParameters = {\n correlationId: this.identityClient.getCorrelationId(),\n tenantId: options?.tenantId || \"managed_identity\",\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n claims: options?.claims,\n };\n\n // Added a check to see if SetAppTokenProvider was already defined.\n this.initializeSetAppTokenProvider();\n const authenticationResult = await this.confidentialApp.acquireTokenByClientCredential({\n ...appTokenParameters,\n });\n result = this.handleResult(scopes, authenticationResult || undefined);\n }\n if (result === null) {\n // If authenticateManagedIdentity returns null,\n // it means no MSI endpoints are available.\n // If so, we avoid trying to reach to them in future requests.\n this.isEndpointUnavailable = true;\n\n // It also means that the endpoint answered with either 200 or 201 (see the sendTokenRequest method),\n // yet we had no access token. For this reason, we'll throw once with a specific message:\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint was reached, yet no tokens were received.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // Since `authenticateManagedIdentity` didn't throw, and the result was not null,\n // We will assume that this endpoint is reachable from this point forward,\n // and avoid pinging again to it.\n this.isEndpointUnavailable = false;\n } else {\n // We've previously determined that the endpoint was unavailable,\n // either because it was unreachable or permanently unable to authenticate.\n const error = new CredentialUnavailableError(\n \"The managed identity endpoint is not currently available\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err: any) {\n // CredentialUnavailable errors are expected to reach here.\n // We intend them to bubble up, so that DefaultAzureCredential can catch them.\n if (err.name === \"AuthenticationRequiredError\") {\n throw err;\n }\n\n // Expected errors to reach this point:\n // - Errors coming from a method unexpectedly breaking.\n // - When identityClient.sendTokenRequest throws, in which case\n // if the status code was 400, it means that the endpoint is working,\n // but no identity is available.\n\n span.setStatus({\n status: \"error\",\n error: err,\n });\n\n // If either the network is unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"ENETUNREACH\") {\n const error = new CredentialUnavailableError(\n `${ManagedIdentityCredential.name}: Unavailable. Network unreachable. Message: ${err.message}`\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n // If either the host was unreachable,\n // we can safely assume the credential is unavailable.\n if (err.code === \"EHOSTUNREACH\") {\n const error = new CredentialUnavailableError(\n `${ManagedIdentityCredential.name}: Unavailable. No managed identity endpoint found. Message: ${err.message}`\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n // If err.statusCode has a value of 400, it comes from sendTokenRequest,\n // and it means that the endpoint is working, but that no identity is available.\n if (err.statusCode === 400) {\n throw new CredentialUnavailableError(\n `${ManagedIdentityCredential.name}: The managed identity endpoint is indicating there's no available identity. Message: ${err.message}`\n );\n }\n\n // This is a special case for Docker Desktop which responds with a 403 with a message that contains \"A socket operation was attempted to an unreachable network\"\n // rather than just timing out, as expected.\n if (err.statusCode === 403 || err.code === 403) {\n if (err.message.includes(\"A socket operation was attempted to an unreachable network\")) {\n const error = new CredentialUnavailableError(\n `${ManagedIdentityCredential.name}: Unavailable. Network unreachable. Message: ${err.message}`\n );\n\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n }\n\n // If the error has no status code, we can assume there was no available identity.\n // This will throw silently during any ChainedTokenCredential.\n if (err.statusCode === undefined) {\n throw new CredentialUnavailableError(\n `${ManagedIdentityCredential.name}: Authentication failed. Message ${err.message}`\n );\n }\n\n // Any other error should break the chain.\n throw new AuthenticationError(err.statusCode, {\n error: `${ManagedIdentityCredential.name} authentication failed.`,\n error_description: err.message,\n });\n } finally {\n // Finally is always called, both if we return and if we throw in the above try/catch.\n span.end();\n }\n }\n\n /**\n * Handles the MSAL authentication result.\n * If the result has an account, we update the local account reference.\n * If the token received is invalid, an error will be thrown depending on what's missing.\n */\n private handleResult(\n scopes: string | string[],\n result?: MsalResult,\n getTokenOptions?: GetTokenOptions\n ): AccessToken {\n this.ensureValidMsalToken(scopes, result, getTokenOptions);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: result!.accessToken!,\n expiresOnTimestamp: result!.expiresOn!.getTime(),\n };\n }\n\n /**\n * Ensures the validity of the MSAL token\n * @internal\n */\n private ensureValidMsalToken(\n scopes: string | string[],\n msalToken?: MsalToken,\n getTokenOptions?: GetTokenOptions\n ): void {\n const error = (message: string): Error => {\n logger.getToken.info(message);\n return new AuthenticationRequiredError({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n getTokenOptions,\n message,\n });\n };\n if (!msalToken) {\n throw error(\"No response\");\n }\n if (!msalToken.expiresOn) {\n throw error(`Response had no \"expiresOn\" property.`);\n }\n if (!msalToken.accessToken) {\n throw error(`Response had no \"accessToken\" property.`);\n }\n }\n\n private initializeSetAppTokenProvider(): void {\n if (!this.isAppTokenProviderInitialized) {\n this.confidentialApp.SetAppTokenProvider(async (appTokenProviderParameters) => {\n logger.info(\n `SetAppTokenProvider invoked with parameters- ${JSON.stringify(\n appTokenProviderParameters\n )}`\n );\n const getTokenOptions: GetTokenOptions = {\n ...appTokenProviderParameters,\n };\n logger.info(\n `authenticateManagedIdentity invoked with scopes- ${JSON.stringify(\n appTokenProviderParameters.scopes\n )} and getTokenOptions - ${JSON.stringify(getTokenOptions)}`\n );\n const resultToken = await this.authenticateManagedIdentity(\n appTokenProviderParameters.scopes,\n getTokenOptions\n );\n\n if (resultToken) {\n logger.info(`SetAppTokenProvider will save the token in cache`);\n\n const expiresInSeconds = resultToken?.expiresOnTimestamp\n ? Math.floor((resultToken.expiresOnTimestamp - Date.now()) / 1000)\n : 0;\n return {\n accessToken: resultToken?.token,\n expiresInSeconds,\n };\n } else {\n logger.info(\n `SetAppTokenProvider token has \"no_access_token_returned\" as the saved token`\n );\n return {\n accessToken: \"no_access_token_returned\",\n expiresInSeconds: 0,\n };\n }\n });\n this.isAppTokenProviderInitialized = true;\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CredentialLogger, formatError } from \"./logging\";\n\n/**\n * Ensures the scopes value is an array.\n * @internal\n */\nexport function ensureScopes(scopes: string | string[]): string[] {\n return Array.isArray(scopes) ? scopes : [scopes];\n}\n\n/**\n * Throws if the received scope is not valid.\n * @internal\n */\nexport function ensureValidScopeForDevTimeCreds(scope: string, logger: CredentialLogger): void {\n if (!scope.match(/^[0-9a-zA-Z-_.:/]+$/)) {\n const error = new Error(\"Invalid scope was specified by the user or calling client\");\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n}\n\n/**\n * Returns the resource out of a scope.\n * @internal\n */\nexport function getScopeResource(scope: string): string {\n return scope.replace(/\\/.default$/, \"\");\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils\";\nimport { AzureCliCredentialOptions } from \"./azureCliCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport child_process from \"child_process\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\n/**\n * Mockable reference to the CLI credential cliCredentialFunctions\n * @internal\n */\nexport const cliCredentialInternals = {\n /**\n * @internal\n */\n getSafeWorkingDir(): string {\n if (process.platform === \"win32\") {\n if (!process.env.SystemRoot) {\n throw new Error(\"Azure CLI credential expects a 'SystemRoot' environment variable\");\n }\n return process.env.SystemRoot;\n } else {\n return \"/bin\";\n }\n },\n\n /**\n * Gets the access token from Azure CLI\n * @param resource - The resource to use when getting the token\n * @internal\n */\n async getAzureCliAccessToken(\n resource: string,\n tenantId?: string,\n timeout?: number\n ): Promise<{ stdout: string; stderr: string; error: Error | null }> {\n let tenantSection: string[] = [];\n if (tenantId) {\n tenantSection = [\"--tenant\", tenantId];\n }\n return new Promise((resolve, reject) => {\n try {\n child_process.execFile(\n \"az\",\n [\n \"account\",\n \"get-access-token\",\n \"--output\",\n \"json\",\n \"--resource\",\n resource,\n ...tenantSection,\n ],\n { cwd: cliCredentialInternals.getSafeWorkingDir(), shell: true, timeout },\n (error, stdout, stderr) => {\n resolve({ stdout: stdout, stderr: stderr, error });\n }\n );\n } catch (err: any) {\n reject(err);\n }\n });\n },\n};\n\nconst logger = credentialLogger(\"AzureCliCredential\");\n\n/**\n * This credential will use the currently logged-in user login information\n * via the Azure CLI ('az') commandline tool.\n * To do so, it will read the user access token and expire time\n * with Azure CLI command \"az account get-access-token\".\n */\nexport class AzureCliCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzureCliCredential}.\n *\n * To use this credential, ensure that you have already logged\n * in via the 'az' tool using the command \"az login\" from the commandline.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzureCliCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds\n );\n\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n logger.getToken.info(`Using the scope ${scope}`);\n\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n try {\n ensureValidScopeForDevTimeCreds(scope, logger);\n const resource = getScopeResource(scope);\n const obj = await cliCredentialInternals.getAzureCliAccessToken(\n resource,\n tenantId,\n this.timeout\n );\n const specificScope = obj.stderr?.match(\"(.*)az login --scope(.*)\");\n const isLoginError = obj.stderr?.match(\"(.*)az login(.*)\") && !specificScope;\n const isNotInstallError =\n obj.stderr?.match(\"az:(.*)not found\") || obj.stderr?.startsWith(\"'az' is not recognized\");\n\n if (isNotInstallError) {\n const error = new CredentialUnavailableError(\n \"Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n if (isLoginError) {\n const error = new CredentialUnavailableError(\n \"Please run 'az login' from a command prompt to authenticate before using this credential.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n try {\n const responseData = obj.stdout;\n const response: { accessToken: string; expiresOn: string } = JSON.parse(responseData);\n logger.getToken.info(formatSuccess(scopes));\n const returnValue = {\n token: response.accessToken,\n expiresOnTimestamp: new Date(response.expiresOn).getTime(),\n };\n return returnValue;\n } catch (e: any) {\n if (obj.stderr) {\n throw new CredentialUnavailableError(obj.stderr);\n }\n throw e;\n }\n } catch (err: any) {\n const error =\n err.name === \"CredentialUnavailableError\"\n ? err\n : new CredentialUnavailableError(\n (err as Error).message || \"Unknown error while trying to retrieve the access token\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n });\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as childProcess from \"child_process\";\n\n/**\n * Easy to mock childProcess utils.\n * @internal\n */\nexport const processUtils = {\n /**\n * Promisifying childProcess.execFile\n * @internal\n */\n execFile(\n file: string,\n params: string[],\n options?: childProcess.ExecFileOptionsWithStringEncoding\n ): Promise<string | Buffer> {\n return new Promise((resolve, reject) => {\n childProcess.execFile(file, params, options, (error, stdout, stderr) => {\n if (Buffer.isBuffer(stdout)) {\n stdout = stdout.toString(\"utf8\");\n }\n if (Buffer.isBuffer(stderr)) {\n stderr = stderr.toString(\"utf8\");\n }\n if (stderr || error) {\n reject(stderr ? new Error(stderr) : error);\n } else {\n resolve(stdout);\n }\n });\n });\n },\n};\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { ensureValidScopeForDevTimeCreds, getScopeResource } from \"../util/scopeUtils\";\nimport { AzurePowerShellCredentialOptions } from \"./azurePowerShellCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { processUtils } from \"../util/processUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"AzurePowerShellCredential\");\n\nconst isWindows = process.platform === \"win32\";\n\n/**\n * Returns a platform-appropriate command name by appending \".exe\" on Windows.\n *\n * @internal\n */\nexport function formatCommand(commandName: string): string {\n if (isWindows) {\n return `${commandName}.exe`;\n } else {\n return commandName;\n }\n}\n\n/**\n * Receives a list of commands to run, executes them, then returns the outputs.\n * If anything fails, an error is thrown.\n * @internal\n */\nasync function runCommands(commands: string[][], timeout?: number): Promise<string[]> {\n const results: string[] = [];\n\n for (const command of commands) {\n const [file, ...parameters] = command;\n const result = (await processUtils.execFile(file, parameters, {\n encoding: \"utf8\",\n timeout,\n })) as string;\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Known PowerShell errors\n * @internal\n */\nexport const powerShellErrors = {\n login: \"Run Connect-AzAccount to login\",\n installed:\n \"The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory\",\n};\n\n/**\n * Messages to use when throwing in this credential.\n * @internal\n */\nexport const powerShellPublicErrorMessages = {\n login:\n \"Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.\",\n installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: \"Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force\".`,\n troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`,\n};\n\n// PowerShell Azure User not logged in error check.\nconst isLoginError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(`(.*)${powerShellErrors.login}(.*)`);\n\n// Az Module not Installed in Azure PowerShell check.\nconst isNotInstalledError: (err: Error) => RegExpMatchArray | null = (err: Error) =>\n err.message.match(powerShellErrors.installed);\n\n/**\n * The PowerShell commands to be tried, in order.\n *\n * @internal\n */\nexport const commandStack = [formatCommand(\"pwsh\")];\n\nif (isWindows) {\n commandStack.push(formatCommand(\"powershell\"));\n}\n\n/**\n * This credential will use the currently logged-in user information from the\n * Azure PowerShell module. To do so, it will read the user access token and\n * expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}`\n */\nexport class AzurePowerShellCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzurePowerShellCredential}.\n *\n * To use this credential:\n * - Install the Azure Az PowerShell module with:\n * `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`.\n * - You have already logged in to Azure PowerShell using the command\n * `Connect-AzAccount` from the command line.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzurePowerShellCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Gets the access token from Azure PowerShell\n * @param resource - The resource to use when getting the token\n */\n private async getAzurePowerShellAccessToken(\n resource: string,\n tenantId?: string,\n timeout?: number\n ): Promise<{ Token: string; ExpiresOn: string }> {\n // Clone the stack to avoid mutating it while iterating\n for (const powerShellCommand of [...commandStack]) {\n try {\n await runCommands([[powerShellCommand, \"/?\"]], timeout);\n } catch (e: any) {\n // Remove this credential from the original stack so that we don't try it again.\n commandStack.shift();\n continue;\n }\n\n let tenantSection = \"\";\n if (tenantId) {\n tenantSection = `-TenantId \"${tenantId}\"`;\n }\n\n const results = await runCommands([\n [\n powerShellCommand,\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n \"Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru\",\n ],\n [\n powerShellCommand,\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n `Get-AzAccessToken ${tenantSection} -ResourceUrl \"${resource}\" | ConvertTo-Json`,\n ],\n ]);\n\n const result = results[1];\n try {\n return JSON.parse(result);\n } catch (e: any) {\n throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`);\n }\n }\n\n throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`);\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {}\n ): Promise<AccessToken> {\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds\n );\n const scope = typeof scopes === \"string\" ? scopes : scopes[0];\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n try {\n ensureValidScopeForDevTimeCreds(scope, logger);\n logger.getToken.info(`Using the scope ${scope}`);\n const resource = getScopeResource(scope);\n const response = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: response.Token,\n expiresOnTimestamp: new Date(response.ExpiresOn).getTime(),\n };\n } catch (err: any) {\n if (isNotInstalledError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed);\n logger.getToken.info(formatError(scope, error));\n throw error;\n } else if (isLoginError(err)) {\n const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login);\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n const error = new CredentialUnavailableError(\n `${err}. ${powerShellPublicErrorMessages.troubleshoot}`\n );\n logger.getToken.info(formatError(scope, error));\n throw error;\n }\n });\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AggregateAuthenticationError, CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\n\n/**\n * @internal\n */\nexport const logger = credentialLogger(\"ChainedTokenCredential\");\n\n/**\n * Enables multiple `TokenCredential` implementations to be tried in order\n * until one of the getToken methods returns an access token.\n */\nexport class ChainedTokenCredential implements TokenCredential {\n private _sources: TokenCredential[] = [];\n\n /**\n * Creates an instance of ChainedTokenCredential using the given credentials.\n *\n * @param sources - `TokenCredential` implementations to be tried in order.\n *\n * Example usage:\n * ```javascript\n * const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);\n * const secondCredential = new ClientSecretCredential(tenantId, anotherClientId, anotherSecret);\n * const credentialChain = new ChainedTokenCredential(firstCredential, secondCredential);\n * ```\n */\n constructor(...sources: TokenCredential[]) {\n this._sources = sources;\n }\n\n /**\n * Returns the first access token returned by one of the chained\n * `TokenCredential` implementations. Throws an {@link AggregateAuthenticationError}\n * when one or more credentials throws an {@link AuthenticationError} and\n * no credentials have returned an access token.\n *\n * This method is called automatically by Azure SDK client libraries. You may call this method\n * directly, but you must also handle token caching and token refreshing.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * `TokenCredential` implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n const { token } = await this.getTokenInternal(scopes, options);\n return token;\n }\n\n private async getTokenInternal(\n scopes: string | string[],\n options: GetTokenOptions = {}\n ): Promise<{ token: AccessToken; successfulCredential: TokenCredential }> {\n let token: AccessToken | null = null;\n let successfulCredential: TokenCredential;\n const errors: Error[] = [];\n\n return tracingClient.withSpan(\n \"ChainedTokenCredential.getToken\",\n options,\n async (updatedOptions) => {\n for (let i = 0; i < this._sources.length && token === null; i++) {\n try {\n token = await this._sources[i].getToken(scopes, updatedOptions);\n successfulCredential = this._sources[i];\n } catch (err: any) {\n if (\n err.name === \"CredentialUnavailableError\" ||\n err.name === \"AuthenticationRequiredError\"\n ) {\n errors.push(err);\n } else {\n logger.getToken.info(formatError(scopes, err));\n throw err;\n }\n }\n }\n\n if (!token && errors.length > 0) {\n const err = new AggregateAuthenticationError(\n errors,\n \"ChainedTokenCredential authentication failed.\"\n );\n logger.getToken.info(formatError(scopes, err));\n throw err;\n }\n\n logger.getToken.info(\n `Result for ${successfulCredential.constructor.name}: ${formatSuccess(scopes)}`\n );\n\n if (token === null) {\n throw new CredentialUnavailableError(\"Failed to retrieve a valid token\");\n }\n return { token, successfulCredential };\n }\n );\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n ClientCertificateCredentialPEMConfiguration,\n ClientCertificatePEMCertificate,\n ClientCertificatePEMCertificatePath,\n} from \"../../credentials/clientCertificateCredential\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { createHash, createPrivateKey } from \"crypto\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { ClientCredentialRequest } from \"@azure/msal-node\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { formatError } from \"../../util/logging\";\nimport { promisify } from \"util\";\nimport { readFile } from \"fs\";\n\nconst readFileAsync = promisify(readFile);\n\n/**\n * Options that can be passed to configure MSAL to handle client certificates.\n * @internal\n */\nexport interface MsalClientCertificateOptions extends MsalNodeOptions {\n /**\n * Location of the PEM certificate.\n */\n configuration: ClientCertificateCredentialPEMConfiguration;\n /**\n * Option to include x5c header for SubjectName and Issuer name authorization.\n * Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim\n */\n sendCertificateChain?: boolean;\n}\n\n/**\n * Parts of a certificate, as understood by MSAL.\n * @internal\n */\ninterface CertificateParts {\n /**\n * Hex encoded X.509 SHA-1 thumbprint of the certificate\n */\n thumbprint: string;\n /**\n * The PEM encoded private key (string should contain -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY-----\n */\n certificateContents: string;\n /**\n * x5c header.\n */\n x5c: string;\n}\n\n/**\n * Tries to asynchronously load a certificate from the given path.\n *\n * @param configuration - Either the PEM value or the path to the certificate.\n * @param sendCertificateChain - Option to include x5c header for SubjectName and Issuer name authorization.\n * @returns - The certificate parts, or `undefined` if the certificate could not be loaded.\n * @internal\n */\nexport async function parseCertificate(\n configuration: ClientCertificateCredentialPEMConfiguration,\n sendCertificateChain?: boolean\n): Promise<CertificateParts> {\n const certificateParts: Partial<CertificateParts> = {};\n\n const certificate: string | undefined = (configuration as ClientCertificatePEMCertificate)\n .certificate;\n const certificatePath: string | undefined = (configuration as ClientCertificatePEMCertificatePath)\n .certificatePath;\n certificateParts.certificateContents =\n certificate || (await readFileAsync(certificatePath!, \"utf8\"));\n if (sendCertificateChain) {\n certificateParts.x5c = certificateParts.certificateContents;\n }\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/g;\n const publicKeys: string[] = [];\n\n // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c\n let match;\n do {\n match = certificatePattern.exec(certificateParts.certificateContents);\n if (match) {\n publicKeys.push(match[3]);\n }\n } while (match);\n\n if (publicKeys.length === 0) {\n throw new Error(\"The file at the specified path does not contain a PEM-encoded certificate.\");\n }\n\n certificateParts.thumbprint = createHash(\"sha1\")\n .update(Buffer.from(publicKeys[0], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return certificateParts as CertificateParts;\n}\n\n/**\n * MSAL client certificate client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.\n * @internal\n */\nexport class MsalClientCertificate extends MsalNode {\n private configuration: ClientCertificateCredentialPEMConfiguration;\n private sendCertificateChain?: boolean;\n\n constructor(options: MsalClientCertificateOptions) {\n super(options);\n this.requiresConfidential = true;\n this.configuration = options.configuration;\n this.sendCertificateChain = options.sendCertificateChain;\n }\n\n // Changing the MSAL configuration asynchronously\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n try {\n const parts = await parseCertificate(this.configuration, this.sendCertificateChain);\n\n let privateKey: string | undefined;\n if (this.configuration.certificatePassword !== undefined) {\n const privateKeyObject = createPrivateKey({\n key: parts.certificateContents,\n passphrase: this.configuration.certificatePassword,\n format: \"pem\",\n });\n\n privateKey = privateKeyObject\n .export({\n format: \"pem\",\n type: \"pkcs8\",\n })\n .toString();\n } else {\n privateKey = parts.certificateContents;\n }\n\n this.msalConfig.auth.clientCertificate = {\n thumbprint: parts.thumbprint,\n privateKey: privateKey,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n this.logger.info(formatError(\"\", error));\n throw error;\n }\n return super.init(options);\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const clientCredReq: ClientCredentialRequest = {\n scopes,\n correlationId: options.correlationId,\n azureRegion: this.azureRegion,\n authority: options.authority,\n claims: options.claims,\n };\n const result = await this.getApp(\n \"confidential\",\n options.enableCae\n ).acquireTokenByClientCredential(clientCredReq);\n // Even though we're providing the same default in memory persistence cache that we use for DeviceCodeCredential,\n // The Client Credential flow does not return the account information from the authentication service,\n // so each time getToken gets called, we will have to acquire a new token through the service.\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { ClientCertificateCredentialOptions } from \"./clientCertificateCredentialOptions\";\nimport { MsalClientCertificate } from \"../msal/nodeFlows/msalClientCertificate\";\nimport { MsalFlow } from \"../msal/flows\";\nimport { credentialLogger } from \"../util/logging\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst credentialName = \"ClientCertificateCredential\";\nconst logger = credentialLogger(credentialName);\n\n/**\n * Required configuration options for the {@link ClientCertificateCredential}, with the string contents of a PEM certificate\n */\nexport interface ClientCertificatePEMCertificate {\n /**\n * The PEM-encoded public/private key certificate on the filesystem.\n */\n certificate: string;\n\n /**\n * The password for the certificate file.\n */\n certificatePassword?: string;\n}\n/**\n * Required configuration options for the {@link ClientCertificateCredential}, with the path to a PEM certificate.\n */\nexport interface ClientCertificatePEMCertificatePath {\n /**\n * The path to the PEM-encoded public/private key certificate on the filesystem.\n */\n certificatePath: string;\n\n /**\n * The password for the certificate file.\n */\n certificatePassword?: string;\n}\n/**\n * Required configuration options for the {@link ClientCertificateCredential}, with either the string contents of a PEM certificate, or the path to a PEM certificate.\n */\nexport type ClientCertificateCredentialPEMConfiguration =\n | ClientCertificatePEMCertificate\n | ClientCertificatePEMCertificatePath;\n\n/**\n * Enables authentication to Azure Active Directory using a PEM-encoded\n * certificate that is assigned to an App Registration. More information\n * on how to configure certificate authentication can be found here:\n *\n * https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad\n *\n */\nexport class ClientCertificateCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalFlow: MsalFlow;\n\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Azure Active Directory with a certificate.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param certificatePath - The path to a PEM-encoded public/private key certificate on the filesystem.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n certificatePath: string,\n options?: ClientCertificateCredentialOptions\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Azure Active Directory with a certificate.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the path of the certificate on the filesystem.\n * If the type is ignored, we will throw the value of the path to a PEM certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificatePath,\n options?: ClientCertificateCredentialOptions\n );\n /**\n * Creates an instance of the ClientCertificateCredential with the details\n * needed to authenticate against Azure Active Directory with a certificate.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param configuration - Other parameters required, including the PEM-encoded certificate as a string.\n * If the type is ignored, we will throw the value of the PEM-encoded certificate.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n configuration: ClientCertificatePEMCertificate,\n options?: ClientCertificateCredentialOptions\n );\n constructor(\n tenantId: string,\n clientId: string,\n certificatePathOrConfiguration: string | ClientCertificateCredentialPEMConfiguration,\n options: ClientCertificateCredentialOptions = {}\n ) {\n if (!tenantId || !clientId) {\n throw new Error(`${credentialName}: tenantId and clientId are required parameters.`);\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n\n const configuration: ClientCertificateCredentialPEMConfiguration = {\n ...(typeof certificatePathOrConfiguration === \"string\"\n ? {\n certificatePath: certificatePathOrConfiguration,\n }\n : certificatePathOrConfiguration),\n };\n const certificate: string | undefined = (configuration as ClientCertificatePEMCertificate)\n .certificate;\n const certificatePath: string | undefined = (\n configuration as ClientCertificatePEMCertificatePath\n ).certificatePath;\n if (!configuration || !(certificate || certificatePath)) {\n throw new Error(\n `${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`\n );\n }\n if (certificate && certificatePath) {\n throw new Error(\n `${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`\n );\n }\n this.msalFlow = new MsalClientCertificate({\n ...options,\n configuration,\n logger,\n clientId,\n tenantId,\n sendCertificateChain: options.sendCertificateChain,\n tokenCredentialOptions: options,\n });\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger\n );\n\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n return this.msalFlow.getToken(arrayScopes, newOptions);\n });\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\n\n/**\n * Options that can be passed to configure MSAL to handle client secrets.\n * @internal\n */\nexport interface MsalClientSecretOptions extends MsalNodeOptions {\n /**\n * A client secret that was generated for the App Registration.\n */\n clientSecret: string;\n}\n\n/**\n * MSAL client secret client. Calls to MSAL's confidential application's `acquireTokenByClientCredential` during `doGetToken`.\n * @internal\n */\nexport class MsalClientSecret extends MsalNode {\n constructor(options: MsalClientSecretOptions) {\n super(options);\n this.requiresConfidential = true;\n this.msalConfig.auth.clientSecret = options.clientSecret;\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const result = await this.getApp(\n \"confidential\",\n options.enableCae\n ).acquireTokenByClientCredential({\n scopes,\n correlationId: options.correlationId,\n azureRegion: this.azureRegion,\n authority: options.authority,\n claims: options.claims,\n });\n // The Client Credential flow does not return an account,\n // so each time getToken gets called, we will have to acquire a new token through the service.\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { ClientSecretCredentialOptions } from \"./clientSecretCredentialOptions\";\nimport { MsalClientSecret } from \"../msal/nodeFlows/msalClientSecret\";\nimport { MsalFlow } from \"../msal/flows\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"ClientSecretCredential\");\n\n/**\n * Enables authentication to Azure Active Directory using a client secret\n * that was generated for an App Registration. More information on how\n * to configure a client secret can be found here:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application\n *\n */\nexport class ClientSecretCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalFlow: MsalFlow;\n\n /**\n * Creates an instance of the ClientSecretCredential with the details\n * needed to authenticate against Azure Active Directory with a client\n * secret.\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration.\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n clientSecret: string,\n options: ClientSecretCredentialOptions = {}\n ) {\n if (!tenantId || !clientId || !clientSecret) {\n throw new Error(\n \"ClientSecretCredential: tenantId, clientId, and clientSecret are required parameters. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.\"\n );\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n\n this.msalFlow = new MsalClientSecret({\n ...options,\n logger,\n clientId,\n tenantId,\n clientSecret,\n tokenCredentialOptions: options,\n });\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalFlow.getToken(arrayScopes, newOptions);\n }\n );\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through username and password.\n * @internal\n */\nexport interface MsalUsernamePasswordOptions extends MsalNodeOptions {\n username: string;\n password: string;\n}\n\n/**\n * MSAL username and password client. Calls to the MSAL's public application's `acquireTokenByUsernamePassword` during `doGetToken`.\n * @internal\n */\nexport class MsalUsernamePassword extends MsalNode {\n private username: string;\n private password: string;\n\n constructor(options: MsalUsernamePasswordOptions) {\n super(options);\n this.username = options.username;\n this.password = options.password;\n }\n\n protected async doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n try {\n const requestOptions: msalNode.UsernamePasswordRequest = {\n scopes,\n username: this.username,\n password: this.password,\n correlationId: options?.correlationId,\n authority: options?.authority,\n claims: options?.claims,\n };\n const result = await this.getApp(\"public\", options?.enableCae).acquireTokenByUsernamePassword(\n requestOptions\n );\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (error: any) {\n throw this.handleError(scopes, error, options);\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { MsalFlow } from \"../msal/flows\";\nimport { MsalUsernamePassword } from \"../msal/nodeFlows/msalUsernamePassword\";\nimport { UsernamePasswordCredentialOptions } from \"./usernamePasswordCredentialOptions\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"UsernamePasswordCredential\");\n\n/**\n * Enables authentication to Azure Active Directory with a user's\n * username and password. This credential requires a high degree of\n * trust so you should only use it when other, more secure credential\n * types can't be used.\n */\nexport class UsernamePasswordCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalFlow: MsalFlow;\n\n /**\n * Creates an instance of the UsernamePasswordCredential with the details\n * needed to authenticate against Azure Active Directory with a username\n * and password.\n *\n * @param tenantId - The Azure Active Directory tenant (directory).\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param username - The user account's e-mail address (user name).\n * @param password - The user account's account password\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n username: string,\n password: string,\n options: UsernamePasswordCredentialOptions = {}\n ) {\n if (!tenantId || !clientId || !username || !password) {\n throw new Error(\n \"UsernamePasswordCredential: tenantId, clientId, username and password are required parameters. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot.\"\n );\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n\n this.msalFlow = new MsalUsernamePassword({\n ...options,\n logger,\n clientId,\n tenantId,\n username,\n password,\n tokenCredentialOptions: options || {},\n });\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the user provided the option `disableAutomaticAuthentication`,\n * once the token can't be retrieved silently,\n * this method won't attempt to request user interaction to retrieve the token.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalFlow.getToken(arrayScopes, newOptions);\n }\n );\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AuthenticationError, CredentialUnavailableError } from \"../errors\";\nimport { credentialLogger, formatError, formatSuccess, processEnvVars } from \"../util/logging\";\nimport { ClientCertificateCredential } from \"./clientCertificateCredential\";\nimport { ClientSecretCredential } from \"./clientSecretCredential\";\nimport { EnvironmentCredentialOptions } from \"./environmentCredentialOptions\";\nimport { UsernamePasswordCredential } from \"./usernamePasswordCredential\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\n/**\n * Contains the list of all supported environment variable names so that an\n * appropriate error message can be generated when no credentials can be\n * configured.\n *\n * @internal\n */\nexport const AllSupportedEnvironmentVariables = [\n \"AZURE_TENANT_ID\",\n \"AZURE_CLIENT_ID\",\n \"AZURE_CLIENT_SECRET\",\n \"AZURE_CLIENT_CERTIFICATE_PATH\",\n \"AZURE_CLIENT_CERTIFICATE_PASSWORD\",\n \"AZURE_USERNAME\",\n \"AZURE_PASSWORD\",\n \"AZURE_ADDITIONALLY_ALLOWED_TENANTS\",\n];\n\nfunction getAdditionallyAllowedTenants(): string[] {\n const additionallyAllowedValues = process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS ?? \"\";\n return additionallyAllowedValues.split(\";\");\n}\n\nconst credentialName = \"EnvironmentCredential\";\nconst logger = credentialLogger(credentialName);\n\n/**\n * Enables authentication to Azure Active Directory using a client secret or certificate, or as a user\n * with a username and password.\n */\nexport class EnvironmentCredential implements TokenCredential {\n private _credential?:\n | ClientSecretCredential\n | ClientCertificateCredential\n | UsernamePasswordCredential = undefined;\n /**\n * Creates an instance of the EnvironmentCredential class and decides what credential to use depending on the available environment variables.\n *\n * Required environment variables:\n * - `AZURE_TENANT_ID`: The Azure Active Directory tenant (directory) ID.\n * - `AZURE_CLIENT_ID`: The client (application) ID of an App Registration in the tenant.\n *\n * If setting the AZURE_TENANT_ID, then you can also set the additionally allowed tenants\n * - `AZURE_ADDITIONALLY_ALLOWED_TENANTS`: For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens with a single semicolon delimited string. Use * to allow all tenants.\n *\n * Environment variables used for client credential authentication:\n * - `AZURE_CLIENT_SECRET`: A client secret that was generated for the App Registration.\n * - `AZURE_CLIENT_CERTIFICATE_PATH`: The path to a PEM certificate to use during the authentication, instead of the client secret.\n * - `AZURE_CLIENT_CERTIFICATE_PASSWORD`: (optional) password for the certificate file.\n *\n * Alternatively, users can provide environment variables for username and password authentication:\n * - `AZURE_USERNAME`: Username to authenticate with.\n * - `AZURE_PASSWORD`: Password to authenticate with.\n *\n * If the environment variables required to perform the authentication are missing, a {@link CredentialUnavailableError} will be thrown.\n * If the authentication fails, or if there's an unknown error, an {@link AuthenticationError} will be thrown.\n *\n * @param options - Options for configuring the client which makes the authentication request.\n */\n constructor(options?: EnvironmentCredentialOptions) {\n // Keep track of any missing environment variables for error details\n\n const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(\", \");\n logger.info(`Found the following environment variables: ${assigned}`);\n\n const tenantId = process.env.AZURE_TENANT_ID,\n clientId = process.env.AZURE_CLIENT_ID,\n clientSecret = process.env.AZURE_CLIENT_SECRET;\n\n const additionallyAllowedTenantIds = getAdditionallyAllowedTenants();\n const newOptions = { ...options, additionallyAllowedTenantIds };\n\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n\n if (tenantId && clientId && clientSecret) {\n logger.info(\n `Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`\n );\n this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, newOptions);\n return;\n }\n\n const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH;\n const certificatePassword = process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD;\n if (tenantId && clientId && certificatePath) {\n logger.info(\n `Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`\n );\n this._credential = new ClientCertificateCredential(\n tenantId,\n clientId,\n { certificatePath, certificatePassword },\n newOptions\n );\n return;\n }\n\n const username = process.env.AZURE_USERNAME;\n const password = process.env.AZURE_PASSWORD;\n if (tenantId && clientId && username && password) {\n logger.info(\n `Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`\n );\n this._credential = new UsernamePasswordCredential(\n tenantId,\n clientId,\n username,\n password,\n newOptions\n );\n }\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - Optional parameters. See {@link GetTokenOptions}.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n if (this._credential) {\n try {\n const result = await this._credential.getToken(scopes, newOptions);\n logger.getToken.info(formatSuccess(scopes));\n return result;\n } catch (err: any) {\n const authenticationError = new AuthenticationError(400, {\n error: `${credentialName} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`,\n error_description: err.message.toString().split(\"More details:\").join(\"\"),\n });\n logger.getToken.info(formatError(scopes, authenticationError));\n throw authenticationError;\n }\n }\n throw new CredentialUnavailableError(\n `${credentialName} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`\n );\n });\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { credentialLogger, formatError, formatSuccess } from \"../util/logging\";\nimport { AzureDeveloperCliCredentialOptions } from \"./azureDeveloperCliCredentialOptions\";\nimport { CredentialUnavailableError } from \"../errors\";\nimport child_process from \"child_process\";\nimport {\n checkTenantId,\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { tracingClient } from \"../util/tracing\";\nimport { ensureValidScopeForDevTimeCreds } from \"../util/scopeUtils\";\n\n/**\n * Mockable reference to the Developer CLI credential cliCredentialFunctions\n * @internal\n */\nexport const developerCliCredentialInternals = {\n /**\n * @internal\n */\n getSafeWorkingDir(): string {\n if (process.platform === \"win32\") {\n if (!process.env.SystemRoot) {\n throw new Error(\n \"Azure Developer CLI credential expects a 'SystemRoot' environment variable\"\n );\n }\n return process.env.SystemRoot;\n } else {\n return \"/bin\";\n }\n },\n\n /**\n * Gets the access token from Azure Developer CLI\n * @param scopes - The scopes to use when getting the token\n * @internal\n */\n async getAzdAccessToken(\n scopes: string[],\n tenantId?: string,\n timeout?: number\n ): Promise<{ stdout: string; stderr: string; error: Error | null }> {\n let tenantSection: string[] = [];\n if (tenantId) {\n tenantSection = [\"--tenant-id\", tenantId];\n }\n return new Promise((resolve, reject) => {\n try {\n child_process.execFile(\n \"azd\",\n [\n \"auth\",\n \"token\",\n \"--output\",\n \"json\",\n ...scopes.reduce<string[]>(\n (previous, current) => previous.concat(\"--scope\", current),\n []\n ),\n ...tenantSection,\n ],\n {\n cwd: developerCliCredentialInternals.getSafeWorkingDir(),\n timeout,\n },\n (error, stdout, stderr) => {\n resolve({ stdout, stderr, error });\n }\n );\n } catch (err: any) {\n reject(err);\n }\n });\n },\n};\n\nconst logger = credentialLogger(\"AzureDeveloperCliCredential\");\n\n/**\n * Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy\n * resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific\n * to Azure developers. It allows users to authenticate as a user and/or a service principal against\n * <a href=\"https://learn.microsoft.com/azure/active-directory/fundamentals/\">Azure Active Directory (Azure AD)\n * </a>. The AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of\n * the logged-in user or service principal in the Azure Developer CLI. It acts as the Azure Developer CLI logged in user or\n * service principal and executes an Azure CLI command underneath to authenticate the application against\n * Azure Active Directory.\n *\n * <h2> Configure AzureDeveloperCliCredential </h2>\n *\n * To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the\n * commands below:\n *\n * <ol>\n * <li>Run \"azd auth login\" in Azure Developer CLI to authenticate interactively as a user.</li>\n * <li>Run \"azd auth login --client-id clientID --client-secret clientSecret\n * --tenant-id tenantID\" to authenticate as a service principal.</li>\n * </ol>\n *\n * You may need to repeat this process after a certain time period, depending on the refresh token validity in your\n * organization. Generally, the refresh token validity period is a few weeks to a few months.\n * AzureDeveloperCliCredential will prompt you to sign in again.\n */\nexport class AzureDeveloperCliCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private timeout?: number;\n\n /**\n * Creates an instance of the {@link AzureDeveloperCliCredential}.\n *\n * To use this credential, ensure that you have already logged\n * in via the 'azd' tool using the command \"azd auth login\" from the commandline.\n *\n * @param options - Options, to optionally allow multi-tenant requests.\n */\n constructor(options?: AzureDeveloperCliCredentialOptions) {\n if (options?.tenantId) {\n checkTenantId(logger, options?.tenantId);\n this.tenantId = options?.tenantId;\n }\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n this.timeout = options?.processTimeoutInMs;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options: GetTokenOptions = {}\n ): Promise<AccessToken> {\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n options,\n this.additionallyAllowedTenantIds\n );\n if (tenantId) {\n checkTenantId(logger, tenantId);\n }\n let scopeList: string[];\n if (typeof scopes === \"string\") {\n scopeList = [scopes];\n } else {\n scopeList = scopes;\n }\n logger.getToken.info(`Using the scopes ${scopes}`);\n\n return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => {\n try {\n scopeList.forEach((scope) => {\n ensureValidScopeForDevTimeCreds(scope, logger);\n });\n const obj = await developerCliCredentialInternals.getAzdAccessToken(\n scopeList,\n tenantId,\n this.timeout\n );\n const isNotLoggedInError =\n obj.stderr?.match(\"not logged in, run `azd login` to login\") ||\n obj.stderr?.match(\"not logged in, run `azd auth login` to login\");\n const isNotInstallError =\n obj.stderr?.match(\"azd:(.*)not found\") ||\n obj.stderr?.startsWith(\"'azd' is not recognized\");\n\n if (isNotInstallError || (obj.error && (obj.error as any).code === \"ENOENT\")) {\n const error = new CredentialUnavailableError(\n \"Azure Developer CLI couldn't be found. To mitigate this issue, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n if (isNotLoggedInError) {\n const error = new CredentialUnavailableError(\n \"Please run 'azd auth login' from a command prompt to authenticate before using this credential. For more information, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot.\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n\n try {\n const resp: { token: string; expiresOn: string } = JSON.parse(obj.stdout);\n logger.getToken.info(formatSuccess(scopes));\n return {\n token: resp.token,\n expiresOnTimestamp: new Date(resp.expiresOn).getTime(),\n };\n } catch (e: any) {\n if (obj.stderr) {\n throw new CredentialUnavailableError(obj.stderr);\n }\n throw e;\n }\n } catch (err: any) {\n const error =\n err.name === \"CredentialUnavailableError\"\n ? err\n : new CredentialUnavailableError(\n (err as Error).message || \"Unknown error while trying to retrieve the access token\"\n );\n logger.getToken.info(formatError(scopes, error));\n throw error;\n }\n });\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n DefaultAzureCredentialClientIdOptions,\n DefaultAzureCredentialOptions,\n DefaultAzureCredentialResourceIdOptions,\n} from \"./defaultAzureCredentialOptions\";\nimport {\n ManagedIdentityCredential,\n ManagedIdentityCredentialClientIdOptions,\n ManagedIdentityCredentialResourceIdOptions,\n} from \"./managedIdentityCredential\";\nimport { AzureCliCredential } from \"./azureCliCredential\";\nimport { AzurePowerShellCredential } from \"./azurePowerShellCredential\";\nimport { ChainedTokenCredential } from \"./chainedTokenCredential\";\nimport { EnvironmentCredential } from \"./environmentCredential\";\nimport { TokenCredential } from \"@azure/core-auth\";\nimport { AzureDeveloperCliCredential } from \"./azureDeveloperCliCredential\";\nimport { WorkloadIdentityCredential } from \"./workloadIdentityCredential\";\nimport { WorkloadIdentityCredentialOptions } from \"./workloadIdentityCredentialOptions\";\n\n/**\n * The type of a class that implements TokenCredential and accepts either\n * {@link DefaultAzureCredentialClientIdOptions} or\n * {@link DefaultAzureCredentialResourceIdOptions} or\n * {@link DefaultAzureCredentialOptions}.\n */\ninterface DefaultCredentialConstructor {\n new (options?: DefaultAzureCredentialOptions): TokenCredential;\n new (options?: DefaultAzureCredentialResourceIdOptions): TokenCredential;\n new (options?: DefaultAzureCredentialClientIdOptions): TokenCredential;\n}\n\n/**\n * A shim around ManagedIdentityCredential that adapts it to accept\n * `DefaultAzureCredentialOptions`.\n *\n * @internal\n */\nexport class DefaultManagedIdentityCredential extends ManagedIdentityCredential {\n // Constructor overload with just client id options\n constructor(options?: DefaultAzureCredentialClientIdOptions);\n // Constructor overload with just resource id options\n constructor(options?: DefaultAzureCredentialResourceIdOptions);\n // Constructor overload with just the other default options\n // Last constructor overload with Union of all options not required since the above two constructor overloads have optional properties\n constructor(options?: DefaultAzureCredentialOptions) {\n const managedIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.managedIdentityClientId ??\n process.env.AZURE_CLIENT_ID;\n const workloadIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.workloadIdentityClientId ??\n managedIdentityClientId;\n const managedResourceId = (options as DefaultAzureCredentialResourceIdOptions)\n ?.managedIdentityResourceId;\n const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;\n const tenantId = options?.tenantId ?? process.env.AZURE_TENANT_ID;\n // ManagedIdentityCredential throws if both the resourceId and the clientId are provided.\n if (managedResourceId) {\n const managedIdentityResourceIdOptions: ManagedIdentityCredentialResourceIdOptions = {\n ...options,\n resourceId: managedResourceId,\n };\n super(managedIdentityResourceIdOptions);\n } else if (workloadFile && workloadIdentityClientId) {\n const workloadIdentityCredentialOptions: DefaultAzureCredentialOptions = {\n ...options,\n tenantId: tenantId,\n };\n super(workloadIdentityClientId, workloadIdentityCredentialOptions);\n } else if (managedIdentityClientId) {\n const managedIdentityClientOptions: ManagedIdentityCredentialClientIdOptions = {\n ...options,\n clientId: managedIdentityClientId,\n };\n super(managedIdentityClientOptions);\n } else {\n super(options);\n }\n }\n}\n/**\n * A shim around WorkloadIdentityCredential that adapts it to accept\n * `DefaultAzureCredentialOptions`.\n *\n * @internal\n */\nexport class DefaultWorkloadIdentityCredential extends WorkloadIdentityCredential {\n // Constructor overload with just client id options\n constructor(options?: DefaultAzureCredentialClientIdOptions);\n // Constructor overload with just the other default options\n // Last constructor overload with Union of all options not required since the above two constructor overloads have optional properties\n constructor(options?: DefaultAzureCredentialOptions) {\n const managedIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.managedIdentityClientId ??\n process.env.AZURE_CLIENT_ID;\n const workloadIdentityClientId =\n (options as DefaultAzureCredentialClientIdOptions)?.workloadIdentityClientId ??\n managedIdentityClientId;\n const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE;\n const tenantId = options?.tenantId ?? process.env.AZURE_TENANT_ID;\n if (workloadFile && workloadIdentityClientId) {\n const workloadIdentityCredentialOptions: WorkloadIdentityCredentialOptions = {\n ...options,\n tenantId,\n clientId: workloadIdentityClientId,\n tokenFilePath: workloadFile,\n };\n super(workloadIdentityCredentialOptions);\n } else if (tenantId) {\n const workloadIdentityClientTenantOptions: WorkloadIdentityCredentialOptions = {\n ...options,\n tenantId,\n };\n super(workloadIdentityClientTenantOptions);\n } else {\n super(options as WorkloadIdentityCredentialOptions);\n }\n }\n}\n\nexport class DefaultAzureDeveloperCliCredential extends AzureDeveloperCliCredential {\n constructor(options?: DefaultAzureCredentialOptions) {\n super({\n processTimeoutInMs: options?.processTimeoutInMs,\n ...options,\n });\n }\n}\nexport class DefaultAzureCliCredential extends AzureCliCredential {\n constructor(options?: DefaultAzureCredentialOptions) {\n super({\n processTimeoutInMs: options?.processTimeoutInMs,\n ...options,\n });\n }\n}\n\nexport class DefaultAzurePowershellCredential extends AzurePowerShellCredential {\n constructor(options?: DefaultAzureCredentialOptions) {\n super({\n processTimeoutInMs: options?.processTimeoutInMs,\n ...options,\n });\n }\n}\n\nexport const defaultCredentials: DefaultCredentialConstructor[] = [\n EnvironmentCredential,\n DefaultWorkloadIdentityCredential,\n DefaultManagedIdentityCredential,\n DefaultAzureCliCredential,\n DefaultAzurePowershellCredential,\n DefaultAzureDeveloperCliCredential,\n];\n\n/**\n * Provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications that use the Azure SDK.\n */\nexport class DefaultAzureCredential extends ChainedTokenCredential {\n /**\n * Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialClientIdOptions}\n *\n * This credential provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications that use the Azure SDK.\n *\n * The following credential types will be tried, in order:\n *\n * - {@link EnvironmentCredential}\n * - {@link WorkloadIdentityCredential}\n * - {@link ManagedIdentityCredential}\n * - {@link AzureCliCredential}\n * - {@link AzurePowerShellCredential}\n * - {@link AzureDeveloperCliCredential}\n *\n * Consult the documentation of these credential types for more information\n * on how they attempt authentication.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialClientIdOptions}.\n */\n constructor(options?: DefaultAzureCredentialClientIdOptions);\n\n /**\n * Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialResourceIdOptions}\n *\n * This credential provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications that use the Azure SDK.\n *\n * The following credential types will be tried, in order:\n *\n * - {@link EnvironmentCredential}\n * - {@link WorkloadIdentityCredential}\n * - {@link ManagedIdentityCredential}\n * - {@link AzureCliCredential}\n * - {@link AzurePowerShellCredential}\n * - {@link AzureDeveloperCliCredential}\n *\n * Consult the documentation of these credential types for more information\n * on how they attempt authentication.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialResourceIdOptions}.\n */\n constructor(options?: DefaultAzureCredentialResourceIdOptions);\n\n /**\n * Creates an instance of the DefaultAzureCredential class with {@link DefaultAzureCredentialOptions}\n *\n * This credential provides a default {@link ChainedTokenCredential} configuration that should\n * work for most applications that use the Azure SDK.\n *\n * The following credential types will be tried, in order:\n *\n * - {@link EnvironmentCredential}\n * - {@link WorkloadIdentityCredential}\n * - {@link ManagedIdentityCredential}\n * - {@link AzureCliCredential}\n * - {@link AzurePowerShellCredential}\n * - {@link AzureDeveloperCliCredential}\n *\n * Consult the documentation of these credential types for more information\n * on how they attempt authentication.\n *\n * @param options - Optional parameters. See {@link DefaultAzureCredentialOptions}.\n */\n constructor(options?: DefaultAzureCredentialOptions);\n\n constructor(\n options?:\n | DefaultAzureCredentialOptions\n | DefaultAzureCredentialResourceIdOptions\n | DefaultAzureCredentialClientIdOptions\n ) {\n super(...defaultCredentials.map((ctor) => new ctor(options)));\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { credentialLogger, formatError, formatSuccess } from \"../../util/logging\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { CredentialUnavailableError } from \"../../errors\";\nimport { Socket } from \"net\";\nimport http from \"http\";\nimport { msalToPublic } from \"../utils\";\nimport open from \"open\";\nimport stoppable from \"stoppable\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through opening a browser window.\n * @internal\n */\nexport interface MsalOpenBrowserOptions extends MsalNodeOptions {\n redirectUri: string;\n loginHint?: string;\n}\n\n/**\n * A call to open(), but mockable\n * @internal\n */\nexport const interactiveBrowserMockable = {\n open,\n};\n\n/**\n * This MSAL client sets up a web server to listen for redirect callbacks, then calls to the MSAL's public application's `acquireTokenByDeviceCode` during `doGetToken`\n * to trigger the authentication flow, and then respond based on the values obtained from the redirect callback\n * @internal\n */\nexport class MsalOpenBrowser extends MsalNode {\n private redirectUri: string;\n private port: number;\n private hostname: string;\n private loginHint?: string;\n\n constructor(options: MsalOpenBrowserOptions) {\n super(options);\n this.logger = credentialLogger(\"Node.js MSAL Open Browser\");\n this.redirectUri = options.redirectUri;\n this.loginHint = options.loginHint;\n\n const url = new URL(this.redirectUri);\n this.port = parseInt(url.port);\n if (isNaN(this.port)) {\n this.port = 80;\n }\n this.hostname = url.hostname;\n }\n\n private async acquireTokenByCode(\n request: msalNode.AuthorizationCodeRequest,\n enableCae?: boolean\n ): Promise<msalNode.AuthenticationResult | null> {\n return this.getApp(\"public\", enableCae).acquireTokenByCode(request);\n }\n\n protected doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n return new Promise<AccessToken>((resolve, reject) => {\n const socketToDestroy: Socket[] = [];\n\n const requestListener = (req: http.IncomingMessage, res: http.ServerResponse): void => {\n if (!req.url) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n let url: URL;\n try {\n url = new URL(req.url, this.redirectUri);\n } catch (e: any) {\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n return;\n }\n const tokenRequest: msalNode.AuthorizationCodeRequest = {\n code: url.searchParams.get(\"code\")!,\n redirectUri: this.redirectUri,\n scopes: scopes,\n authority: options?.authority,\n codeVerifier: this.pkceCodes?.verifier,\n };\n\n this.acquireTokenByCode(tokenRequest, options?.enableCae)\n .then((authResponse) => {\n if (authResponse?.account) {\n this.account = msalToPublic(this.clientId, authResponse.account);\n }\n const successMessage = `Authentication Complete. You can close the browser and return to the application.`;\n if (authResponse && authResponse.expiresOn) {\n const expiresOnTimestamp = authResponse?.expiresOn.valueOf();\n res.writeHead(200);\n res.end(successMessage);\n this.logger.getToken.info(formatSuccess(scopes));\n\n resolve({\n expiresOnTimestamp,\n token: authResponse.accessToken,\n });\n } else {\n const errorMessage = formatError(\n scopes,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n this.logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n }\n cleanup();\n return;\n })\n .catch(() => {\n const errorMessage = formatError(\n scopes,\n `${url.searchParams.get(\"error\")}. ${url.searchParams.get(\"error_description\")}`\n );\n res.writeHead(500);\n res.end(errorMessage);\n this.logger.getToken.info(errorMessage);\n\n reject(\n new Error(\n `Interactive Browser Authentication Error \"Did not receive token with a valid expiration\"`\n )\n );\n cleanup();\n });\n };\n\n const app = http.createServer(requestListener);\n const server = stoppable(app);\n\n const listen = app.listen(this.port, this.hostname, () =>\n this.logger.info(`InteractiveBrowserCredential listening on port ${this.port}!`)\n );\n\n function cleanup(): void {\n if (listen) {\n listen.close();\n }\n\n for (const socket of socketToDestroy) {\n socket.destroy();\n }\n\n if (server) {\n server.close();\n server.stop();\n }\n }\n\n app.on(\"connection\", (socket) => socketToDestroy.push(socket));\n\n app.on(\"error\", (err) => {\n cleanup();\n const code = (err as any).code;\n if (code === \"EACCES\" || code === \"EADDRINUSE\") {\n reject(\n new CredentialUnavailableError(\n [\n `InteractiveBrowserCredential: Access denied to port ${this.port}.`,\n `Try sending a redirect URI with a different port, as follows:`,\n '`new InteractiveBrowserCredential({ redirectUri: \"http://localhost:1337\" })`',\n ].join(\" \")\n )\n );\n } else {\n reject(\n new CredentialUnavailableError(\n `InteractiveBrowserCredential: Failed to start the necessary web server. Error: ${err.message}`\n )\n );\n }\n });\n\n app.on(\"listening\", () => {\n const openPromise = this.openAuthCodeUrl(scopes, options);\n\n const abortSignal = options?.abortSignal;\n if (abortSignal) {\n abortSignal.addEventListener(\"abort\", () => {\n cleanup();\n reject(new Error(\"Aborted\"));\n });\n }\n\n openPromise.catch((e) => {\n cleanup();\n reject(e);\n });\n });\n });\n }\n\n private pkceCodes?: {\n verifier: string;\n challenge: string;\n };\n\n private async openAuthCodeUrl(\n scopeArray: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<void> {\n // Initialize CryptoProvider instance\n const cryptoProvider = new msalNode.CryptoProvider();\n // Generate PKCE Codes before starting the authorization flow\n this.pkceCodes = await cryptoProvider.generatePkceCodes();\n\n const authCodeUrlParameters: msalNode.AuthorizationUrlRequest = {\n scopes: scopeArray,\n correlationId: options?.correlationId,\n redirectUri: this.redirectUri,\n authority: options?.authority,\n claims: options?.claims,\n loginHint: this.loginHint,\n codeChallenge: this.pkceCodes.challenge,\n codeChallengeMethod: \"S256\", // Use SHA256 Algorithm\n };\n const response = await this.getApp(\"public\", options?.enableCae).getAuthCodeUrl(\n authCodeUrlParameters\n );\n try {\n // A new instance on macOS only which allows it to not hang, does not fix the issue on linux\n await interactiveBrowserMockable.open(response, { wait: true, newInstance: true });\n } catch (e: any) {\n throw new CredentialUnavailableError(\n `InteractiveBrowserCredential: Could not open a browser window. Error: ${e.message}`\n );\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n InteractiveBrowserCredentialInBrowserOptions,\n InteractiveBrowserCredentialNodeOptions,\n} from \"./interactiveBrowserCredentialOptions\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { AuthenticationRecord } from \"../msal/types\";\nimport { MsalFlow } from \"../msal/flows\";\nimport { MsalOpenBrowser } from \"../msal/nodeFlows/msalOpenBrowser\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"InteractiveBrowserCredential\");\n\n/**\n * Enables authentication to Azure Active Directory inside of the web browser\n * using the interactive login flow.\n */\nexport class InteractiveBrowserCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private msalFlow: MsalFlow;\n private disableAutomaticAuthentication?: boolean;\n\n /**\n * Creates an instance of InteractiveBrowserCredential with the details needed.\n *\n * This credential uses the [Authorization Code Flow](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow).\n * On Node.js, it will open a browser window while it listens for a redirect response from the authentication service.\n * On browsers, it authenticates via popups. The `loginStyle` optional parameter can be set to `redirect` to authenticate by redirecting the user to an Azure secure login page, which then will redirect the user back to the web application where the authentication started.\n *\n * For Node.js, if a `clientId` is provided, the Azure Active Directory application will need to be configured to have a \"Mobile and desktop applications\" redirect endpoint.\n * Follow our guide on [setting up Redirect URIs for Desktop apps that calls to web APIs](https://docs.microsoft.com/azure/active-directory/develop/scenario-desktop-app-registration#redirect-uris).\n *\n * @param options - Options for configuring the client which makes the authentication requests.\n */\n constructor(\n options:\n | InteractiveBrowserCredentialNodeOptions\n | InteractiveBrowserCredentialInBrowserOptions = {}\n ) {\n const redirectUri =\n typeof options.redirectUri === \"function\"\n ? options.redirectUri()\n : options.redirectUri || \"http://localhost\";\n\n this.tenantId = options?.tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n\n this.msalFlow = new MsalOpenBrowser({\n ...options,\n tokenCredentialOptions: options,\n logger,\n redirectUri,\n });\n this.disableAutomaticAuthentication = options?.disableAutomaticAuthentication;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the user provided the option `disableAutomaticAuthentication`,\n * once the token can't be retrieved silently,\n * this method won't attempt to request user interaction to retrieve the token.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalFlow.getToken(arrayScopes, {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n });\n }\n );\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the token can't be retrieved silently, this method will require user interaction to retrieve the token.\n *\n * On Node.js, this credential has [Proof Key for Code Exchange (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636) enabled by default.\n * PKCE is a security feature that mitigates authentication code interception attacks.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async authenticate(\n scopes: string | string[],\n options: GetTokenOptions = {}\n ): Promise<AuthenticationRecord | undefined> {\n return tracingClient.withSpan(\n `${this.constructor.name}.authenticate`,\n options,\n async (newOptions) => {\n const arrayScopes = ensureScopes(scopes);\n await this.msalFlow.getToken(arrayScopes, newOptions);\n return this.msalFlow.getActiveAccount();\n }\n );\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as msalNode from \"@azure/msal-node\";\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { DeviceCodePromptCallback } from \"../../credentials/deviceCodeCredentialOptions\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through device codes.\n * @internal\n */\nexport interface MsalDeviceCodeOptions extends MsalNodeOptions {\n userPromptCallback: DeviceCodePromptCallback;\n}\n\n/**\n * MSAL device code client. Calls to the MSAL's public application's `acquireTokenByDeviceCode` during `doGetToken`.\n * @internal\n */\nexport class MsalDeviceCode extends MsalNode {\n private userPromptCallback: DeviceCodePromptCallback;\n\n constructor(options: MsalDeviceCodeOptions) {\n super(options);\n this.userPromptCallback = options.userPromptCallback;\n }\n\n protected async doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n try {\n const requestOptions: msalNode.DeviceCodeRequest = {\n deviceCodeCallback: this.userPromptCallback,\n scopes,\n cancel: false,\n correlationId: options?.correlationId,\n authority: options?.authority,\n claims: options?.claims,\n };\n const promise = this.getApp(\"public\", options?.enableCae).acquireTokenByDeviceCode(\n requestOptions\n );\n const deviceResponse = await this.withCancellation(promise, options?.abortSignal, () => {\n requestOptions.cancel = true;\n });\n return this.handleResult(scopes, this.clientId, deviceResponse || undefined);\n } catch (error: any) {\n throw this.handleError(scopes, error, options);\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { DeviceCodeCredentialOptions, DeviceCodeInfo } from \"./deviceCodeCredentialOptions\";\nimport { AuthenticationRecord } from \"../msal/types\";\nimport { MsalDeviceCode } from \"../msal/nodeFlows/msalDeviceCode\";\nimport { MsalFlow } from \"../msal/flows\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"DeviceCodeCredential\");\n\n/**\n * Method that logs the user code from the DeviceCodeCredential.\n * @param deviceCodeInfo - The device code.\n */\nexport function defaultDeviceCodePromptCallback(deviceCodeInfo: DeviceCodeInfo): void {\n console.log(deviceCodeInfo.message);\n}\n\n/**\n * Enables authentication to Azure Active Directory using a device code\n * that the user can enter into https://microsoft.com/devicelogin.\n */\nexport class DeviceCodeCredential implements TokenCredential {\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n private msalFlow: MsalFlow;\n private disableAutomaticAuthentication?: boolean;\n\n /**\n * Creates an instance of DeviceCodeCredential with the details needed\n * to initiate the device code authorization flow with Azure Active Directory.\n *\n * A message will be logged, giving users a code that they can use to authenticate once they go to https://microsoft.com/devicelogin\n *\n * Developers can configure how this message is shown by passing a custom `userPromptCallback`:\n *\n * ```js\n * const credential = new DeviceCodeCredential({\n * tenantId: env.AZURE_TENANT_ID,\n * clientId: env.AZURE_CLIENT_ID,\n * userPromptCallback: (info) => {\n * console.log(\"CUSTOMIZED PROMPT CALLBACK\", info.message);\n * }\n * });\n * ```\n *\n * @param options - Options for configuring the client which makes the authentication requests.\n */\n constructor(options?: DeviceCodeCredentialOptions) {\n this.tenantId = options?.tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n this.msalFlow = new MsalDeviceCode({\n ...options,\n logger,\n userPromptCallback: options?.userPromptCallback || defaultDeviceCodePromptCallback,\n tokenCredentialOptions: options || {},\n });\n this.disableAutomaticAuthentication = options?.disableAutomaticAuthentication;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the user provided the option `disableAutomaticAuthentication`,\n * once the token can't be retrieved silently,\n * this method won't attempt to request user interaction to retrieve the token.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalFlow.getToken(arrayScopes, {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n });\n }\n );\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * If the token can't be retrieved silently, this method will require user interaction to retrieve the token.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async authenticate(\n scopes: string | string[],\n options: GetTokenOptions = {}\n ): Promise<AuthenticationRecord | undefined> {\n return tracingClient.withSpan(\n `${this.constructor.name}.authenticate`,\n options,\n async (newOptions) => {\n const arrayScopes = Array.isArray(scopes) ? scopes : [scopes];\n await this.msalFlow.getToken(arrayScopes, newOptions);\n return this.msalFlow.getActiveAccount();\n }\n );\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { credentialLogger } from \"../../util/logging\";\n\n/**\n * Options that can be passed to configure MSAL to handle authentication through opening a browser window.\n * @internal\n */\nexport interface MsalAuthorizationCodeOptions extends MsalNodeOptions {\n redirectUri: string;\n authorizationCode: string;\n clientSecret?: string;\n}\n\n/**\n * This MSAL client sets up a web server to listen for redirect callbacks, then calls to the MSAL's public application's `acquireTokenByDeviceCode` during `doGetToken`\n * to trigger the authentication flow, and then respond based on the values obtained from the redirect callback\n * @internal\n */\nexport class MsalAuthorizationCode extends MsalNode {\n private redirectUri: string;\n private authorizationCode: string;\n\n constructor(options: MsalAuthorizationCodeOptions) {\n super(options);\n this.logger = credentialLogger(\"Node.js MSAL Authorization Code\");\n this.redirectUri = options.redirectUri;\n this.authorizationCode = options.authorizationCode;\n if (options.clientSecret) {\n this.msalConfig.auth.clientSecret = options.clientSecret;\n }\n }\n\n async getAuthCodeUrl(options: {\n scopes: string[];\n redirectUri: string;\n enableCae?: boolean;\n }): Promise<string> {\n await this.init();\n return this.getApp(\"confidentialFirst\", options.enableCae).getAuthCodeUrl({\n scopes: options.scopes,\n redirectUri: options.redirectUri,\n });\n }\n\n protected async doGetToken(\n scopes: string[],\n options?: CredentialFlowGetTokenOptions\n ): Promise<AccessToken> {\n try {\n const result = await this.getApp(\"confidentialFirst\", options?.enableCae).acquireTokenByCode({\n scopes,\n redirectUri: this.redirectUri,\n code: this.authorizationCode,\n correlationId: options?.correlationId,\n authority: options?.authority,\n claims: options?.claims,\n });\n // The Client Credential flow does not return an account,\n // so each time getToken gets called, we will have to acquire a new token through the service.\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { AuthorizationCodeCredentialOptions } from \"./authorizationCodeCredentialOptions\";\nimport { MsalAuthorizationCode } from \"../msal/nodeFlows/msalAuthorizationCode\";\nimport { MsalFlow } from \"../msal/flows\";\nimport { checkTenantId } from \"../util/tenantIdUtils\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst logger = credentialLogger(\"AuthorizationCodeCredential\");\n\n/**\n * Enables authentication to Azure Active Directory using an authorization code\n * that was obtained through the authorization code flow, described in more detail\n * in the Azure Active Directory documentation:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow\n */\nexport class AuthorizationCodeCredential implements TokenCredential {\n private msalFlow: MsalFlow;\n private disableAutomaticAuthentication?: boolean;\n private authorizationCode: string;\n private redirectUri: string;\n private tenantId?: string;\n private additionallyAllowedTenantIds: string[];\n\n /**\n * Creates an instance of AuthorizationCodeCredential with the details needed\n * to request an access token using an authentication that was obtained\n * from Azure Active Directory.\n *\n * It is currently necessary for the user of this credential to initiate\n * the authorization code flow to obtain an authorization code to be used\n * with this credential. A full example of this flow is provided here:\n *\n * https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/v2/manual/authorizationCodeSample.ts\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID or name.\n * 'common' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param clientSecret - A client secret that was generated for the App Registration\n * @param authorizationCode - An authorization code that was received from following the\n authorization code flow. This authorization code must not\n have already been used to obtain an access token.\n * @param redirectUri - The redirect URI that was used to request the authorization code.\n Must be the same URI that is configured for the App Registration.\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n clientSecret: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions\n );\n /**\n * Creates an instance of AuthorizationCodeCredential with the details needed\n * to request an access token using an authentication that was obtained\n * from Azure Active Directory.\n *\n * It is currently necessary for the user of this credential to initiate\n * the authorization code flow to obtain an authorization code to be used\n * with this credential. A full example of this flow is provided here:\n *\n * https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/v2/manual/authorizationCodeSample.ts\n *\n * @param tenantId - The Azure Active Directory tenant (directory) ID or name.\n * 'common' may be used when dealing with multi-tenant scenarios.\n * @param clientId - The client (application) ID of an App Registration in the tenant.\n * @param authorizationCode - An authorization code that was received from following the\n authorization code flow. This authorization code must not\n have already been used to obtain an access token.\n * @param redirectUri - The redirect URI that was used to request the authorization code.\n Must be the same URI that is configured for the App Registration.\n * @param options - Options for configuring the client which makes the access token request.\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n authorizationCode: string,\n redirectUri: string,\n options?: AuthorizationCodeCredentialOptions\n );\n /**\n * @hidden\n * @internal\n */\n constructor(\n tenantId: string | \"common\",\n clientId: string,\n clientSecretOrAuthorizationCode: string,\n authorizationCodeOrRedirectUri: string,\n redirectUriOrOptions: string | AuthorizationCodeCredentialOptions | undefined,\n options?: AuthorizationCodeCredentialOptions\n ) {\n checkTenantId(logger, tenantId);\n let clientSecret: string | undefined = clientSecretOrAuthorizationCode;\n\n if (typeof redirectUriOrOptions === \"string\") {\n // the clientId+clientSecret constructor\n this.authorizationCode = authorizationCodeOrRedirectUri;\n this.redirectUri = redirectUriOrOptions;\n // in this case, options are good as they come\n } else {\n // clientId only\n this.authorizationCode = clientSecretOrAuthorizationCode;\n this.redirectUri = authorizationCodeOrRedirectUri as string;\n clientSecret = undefined;\n options = redirectUriOrOptions as AuthorizationCodeCredentialOptions;\n }\n\n // TODO: Validate tenant if provided\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n options?.additionallyAllowedTenants\n );\n\n this.msalFlow = new MsalAuthorizationCode({\n ...options,\n clientSecret,\n clientId,\n tenantId,\n tokenCredentialOptions: options || {},\n logger,\n redirectUri: this.redirectUri,\n authorizationCode: this.authorizationCode,\n });\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(\n `${this.constructor.name}.getToken`,\n options,\n async (newOptions) => {\n const tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds\n );\n newOptions.tenantId = tenantId;\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalFlow.getToken(arrayScopes, {\n ...newOptions,\n disableAutomaticAuthentication: this.disableAutomaticAuthentication,\n });\n }\n );\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MsalNode, MsalNodeOptions } from \"./msalNodeCommon\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { CredentialFlowGetTokenOptions } from \"../credentials\";\nimport { formatError } from \"../../util/logging\";\nimport { parseCertificate } from \"./msalClientCertificate\";\n\n/**\n * Options that can be passed to configure MSAL to handle On-Behalf-Of authentication requests.\n * @internal\n */\nexport interface MsalOnBehalfOfOptions extends MsalNodeOptions {\n /**\n * A client secret that was generated for the App Registration.\n */\n clientSecret?: string;\n /**\n * Location of the PEM certificate.\n */\n certificatePath?: string;\n /**\n * Option to include x5c header for SubjectName and Issuer name authorization.\n * Set this option to send base64 encoded public certificate in the client assertion header as an x5c claim\n */\n sendCertificateChain?: boolean;\n /**\n * The user assertion for the On-Behalf-Of flow.\n */\n userAssertionToken: string;\n}\n\n/**\n * MSAL on behalf of flow. Calls to MSAL's confidential application's `acquireTokenOnBehalfOf` during `doGetToken`.\n * @internal\n */\nexport class MsalOnBehalfOf extends MsalNode {\n private userAssertionToken: string;\n private certificatePath?: string;\n private sendCertificateChain?: boolean;\n private clientSecret?: string;\n\n constructor(options: MsalOnBehalfOfOptions) {\n super(options);\n this.logger.info(\"Initialized MSAL's On-Behalf-Of flow\");\n this.requiresConfidential = true;\n this.userAssertionToken = options.userAssertionToken;\n this.certificatePath = options.certificatePath;\n this.sendCertificateChain = options.sendCertificateChain;\n this.clientSecret = options.clientSecret;\n }\n\n // Changing the MSAL configuration asynchronously\n async init(options?: CredentialFlowGetTokenOptions): Promise<void> {\n if (this.certificatePath) {\n try {\n const parts = await parseCertificate(\n { certificatePath: this.certificatePath },\n this.sendCertificateChain\n );\n this.msalConfig.auth.clientCertificate = {\n thumbprint: parts.thumbprint,\n privateKey: parts.certificateContents,\n x5c: parts.x5c,\n };\n } catch (error: any) {\n this.logger.info(formatError(\"\", error));\n throw error;\n }\n } else {\n this.msalConfig.auth.clientSecret = this.clientSecret;\n }\n return super.init(options);\n }\n\n protected async doGetToken(\n scopes: string[],\n options: CredentialFlowGetTokenOptions = {}\n ): Promise<AccessToken> {\n try {\n const result = await this.getApp(\"confidential\", options.enableCae).acquireTokenOnBehalfOf({\n scopes,\n correlationId: options.correlationId,\n authority: options.authority,\n claims: options.claims,\n oboAssertion: this.userAssertionToken,\n });\n return this.handleResult(scopes, this.clientId, result || undefined);\n } catch (err: any) {\n throw this.handleError(scopes, err, options);\n }\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport {\n OnBehalfOfCredentialCertificateOptions,\n OnBehalfOfCredentialOptions,\n OnBehalfOfCredentialSecretOptions,\n} from \"./onBehalfOfCredentialOptions\";\nimport {\n processMultiTenantRequest,\n resolveAdditionallyAllowedTenantIds,\n} from \"../util/tenantIdUtils\";\nimport { CredentialPersistenceOptions } from \"./credentialPersistenceOptions\";\nimport { MsalFlow } from \"../msal/flows\";\nimport { MsalOnBehalfOf } from \"../msal/nodeFlows/msalOnBehalfOf\";\nimport { MultiTenantTokenCredentialOptions } from \"./multiTenantTokenCredentialOptions\";\nimport { credentialLogger } from \"../util/logging\";\nimport { ensureScopes } from \"../util/scopeUtils\";\nimport { tracingClient } from \"../util/tracing\";\n\nconst credentialName = \"OnBehalfOfCredential\";\nconst logger = credentialLogger(credentialName);\n\n/**\n * Enables authentication to Microsoft Entra ID using the [On Behalf Of flow](https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow).\n */\nexport class OnBehalfOfCredential implements TokenCredential {\n private tenantId: string;\n private additionallyAllowedTenantIds: string[];\n private msalFlow: MsalFlow;\n /**\n * Creates an instance of the {@link OnBehalfOfCredential} with the details\n * needed to authenticate against Azure Active Directory with path to a PEM certificate,\n * and an user assertion.\n *\n * Example using the `KeyClient` from [\\@azure/keyvault-keys](https://www.npmjs.com/package/\\@azure/keyvault-keys):\n *\n * ```ts\n * const tokenCredential = new OnBehalfOfCredential({\n * tenantId,\n * clientId,\n * certificatePath: \"/path/to/certificate.pem\",\n * userAssertionToken: \"access-token\"\n * });\n * const client = new KeyClient(\"vault-url\", tokenCredential);\n *\n * await client.getKey(\"key-name\");\n * ```\n *\n * @param options - Optional parameters, generally common across credentials.\n */\n constructor(\n options: OnBehalfOfCredentialCertificateOptions &\n MultiTenantTokenCredentialOptions &\n CredentialPersistenceOptions\n );\n /**\n * Creates an instance of the {@link OnBehalfOfCredential} with the details\n * needed to authenticate against Azure Active Directory with a client\n * secret and an user assertion.\n *\n * Example using the `KeyClient` from [\\@azure/keyvault-keys](https://www.npmjs.com/package/\\@azure/keyvault-keys):\n *\n * ```ts\n * const tokenCredential = new OnBehalfOfCredential({\n * tenantId,\n * clientId,\n * clientSecret,\n * userAssertionToken: \"access-token\"\n * });\n * const client = new KeyClient(\"vault-url\", tokenCredential);\n *\n * await client.getKey(\"key-name\");\n * ```\n *\n * @param options - Optional parameters, generally common across credentials.\n */\n constructor(\n options: OnBehalfOfCredentialSecretOptions &\n MultiTenantTokenCredentialOptions &\n CredentialPersistenceOptions\n );\n\n constructor(private options: OnBehalfOfCredentialOptions) {\n const { clientSecret } = options as OnBehalfOfCredentialSecretOptions;\n const { certificatePath } = options as OnBehalfOfCredentialCertificateOptions;\n const {\n tenantId,\n clientId,\n userAssertionToken,\n additionallyAllowedTenants: additionallyAllowedTenantIds,\n } = options;\n if (!tenantId || !clientId || !(clientSecret || certificatePath) || !userAssertionToken) {\n throw new Error(\n `${credentialName}: tenantId, clientId, clientSecret (or certificatePath) and userAssertionToken are required parameters.`\n );\n }\n\n this.tenantId = tenantId;\n this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(\n additionallyAllowedTenantIds\n );\n\n this.msalFlow = new MsalOnBehalfOf({\n ...this.options,\n logger,\n tokenCredentialOptions: this.options,\n });\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an access token if successful.\n * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure the underlying network requests.\n */\n async getToken(scopes: string | string[], options: GetTokenOptions = {}): Promise<AccessToken> {\n return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => {\n newOptions.tenantId = processMultiTenantRequest(\n this.tenantId,\n newOptions,\n this.additionallyAllowedTenantIds,\n logger\n );\n\n const arrayScopes = ensureScopes(scopes);\n return this.msalFlow!.getToken(arrayScopes, newOptions);\n });\n }\n}\n", "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport * from \"./plugins/consumer\";\n\nexport { IdentityPlugin } from \"./plugins/provider\";\n\nimport { TokenCredential } from \"@azure/core-auth\";\nimport { DefaultAzureCredential } from \"./credentials/defaultAzureCredential\";\n\nexport {\n AuthenticationError,\n ErrorResponse,\n AggregateAuthenticationError,\n AuthenticationErrorName,\n AggregateAuthenticationErrorName,\n CredentialUnavailableError,\n CredentialUnavailableErrorName,\n AuthenticationRequiredError,\n AuthenticationRequiredErrorOptions,\n} from \"./errors\";\n\nexport { AuthenticationRecord } from \"./msal/types\";\nexport { serializeAuthenticationRecord, deserializeAuthenticationRecord } from \"./msal/utils\";\nexport { TokenCredentialOptions } from \"./tokenCredentialOptions\";\nexport { MultiTenantTokenCredentialOptions } from \"./credentials/multiTenantTokenCredentialOptions\";\nexport { AuthorityValidationOptions } from \"./credentials/authorityValidationOptions\";\n// TODO: Export again once we're ready to release this feature.\n// export { RegionalAuthority } from \"./regionalAuthority\";\n\nexport { InteractiveCredentialOptions } from \"./credentials/interactiveCredentialOptions\";\n\nexport { ChainedTokenCredential } from \"./credentials/chainedTokenCredential\";\n\nexport { ClientSecretCredential } from \"./credentials/clientSecretCredential\";\nexport { ClientSecretCredentialOptions } from \"./credentials/clientSecretCredentialOptions\";\n\nexport { DefaultAzureCredential } from \"./credentials/defaultAzureCredential\";\nexport {\n DefaultAzureCredentialOptions,\n DefaultAzureCredentialClientIdOptions,\n DefaultAzureCredentialResourceIdOptions,\n} from \"./credentials/defaultAzureCredentialOptions\";\n\nexport { EnvironmentCredential } from \"./credentials/environmentCredential\";\nexport { EnvironmentCredentialOptions } from \"./credentials/environmentCredentialOptions\";\n\nexport {\n ClientCertificateCredential,\n ClientCertificateCredentialPEMConfiguration,\n ClientCertificatePEMCertificatePath,\n ClientCertificatePEMCertificate,\n} from \"./credentials/clientCertificateCredential\";\nexport { ClientCertificateCredentialOptions } from \"./credentials/clientCertificateCredentialOptions\";\nexport { ClientAssertionCredential } from \"./credentials/clientAssertionCredential\";\nexport { ClientAssertionCredentialOptions } from \"./credentials/clientAssertionCredentialOptions\";\nexport { CredentialPersistenceOptions } from \"./credentials/credentialPersistenceOptions\";\nexport { AzureCliCredential } from \"./credentials/azureCliCredential\";\nexport { AzureCliCredentialOptions } from \"./credentials/azureCliCredentialOptions\";\nexport { AzureDeveloperCliCredential } from \"./credentials/azureDeveloperCliCredential\";\nexport { AzureDeveloperCliCredentialOptions } from \"./credentials/azureDeveloperCliCredentialOptions\";\nexport { InteractiveBrowserCredential } from \"./credentials/interactiveBrowserCredential\";\nexport {\n InteractiveBrowserCredentialNodeOptions,\n InteractiveBrowserCredentialInBrowserOptions,\n BrowserLoginStyle,\n} from \"./credentials/interactiveBrowserCredentialOptions\";\nexport {\n ManagedIdentityCredential,\n ManagedIdentityCredentialClientIdOptions,\n ManagedIdentityCredentialResourceIdOptions,\n} from \"./credentials/managedIdentityCredential\";\nexport { DeviceCodeCredential } from \"./credentials/deviceCodeCredential\";\nexport {\n DeviceCodePromptCallback,\n DeviceCodeInfo,\n} from \"./credentials/deviceCodeCredentialOptions\";\nexport { DeviceCodeCredentialOptions } from \"./credentials/deviceCodeCredentialOptions\";\n\nexport { AuthorizationCodeCredential } from \"./credentials/authorizationCodeCredential\";\nexport { AuthorizationCodeCredentialOptions } from \"./credentials/authorizationCodeCredentialOptions\";\nexport { AzurePowerShellCredential } from \"./credentials/azurePowerShellCredential\";\nexport { AzurePowerShellCredentialOptions } from \"./credentials/azurePowerShellCredentialOptions\";\nexport {\n OnBehalfOfCredentialOptions,\n OnBehalfOfCredentialSecretOptions,\n OnBehalfOfCredentialCertificateOptions,\n} from \"./credentials/onBehalfOfCredentialOptions\";\nexport { UsernamePasswordCredential } from \"./credentials/usernamePasswordCredential\";\nexport { UsernamePasswordCredentialOptions } from \"./credentials/usernamePasswordCredentialOptions\";\nexport { VisualStudioCodeCredential } from \"./credentials/visualStudioCodeCredential\";\nexport { VisualStudioCodeCredentialOptions } from \"./credentials/visualStudioCodeCredentialOptions\";\nexport { OnBehalfOfCredential } from \"./credentials/onBehalfOfCredential\";\nexport { WorkloadIdentityCredential } from \"./credentials/workloadIdentityCredential\";\nexport { WorkloadIdentityCredentialOptions } from \"./credentials/workloadIdentityCredentialOptions\";\n\nexport { TokenCachePersistenceOptions } from \"./msal/nodeFlows/tokenCachePersistenceOptions\";\n\nexport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-auth\";\nexport { logger } from \"./util/logging\";\n\nexport { AzureAuthorityHosts } from \"./constants\";\n\n/**\n * Returns a new instance of the {@link DefaultAzureCredential}.\n */\nexport function getDefaultAzureCredential(): TokenCredential {\n return new DefaultAzureCredential();\n}\n", "import {\n AzureCliCredential,\n DeviceCodeCredential,\n InteractiveBrowserCredential,\n useIdentityPlugin,\n type AuthenticationRecord,\n type TokenCachePersistenceOptions,\n type TokenCredential,\n} from '@azure/identity';\nimport type { LoginMethod } from '../types/LoginMethod.js';\nimport { cachePersistencePlugin } from '../cache-persistance/cachePersistencePlugin.js';\nimport { getAuthenticationRecord } from './getAuthenticationRecord.js';\nimport { saveAuthenticationRecord } from './saveAuthenticationRecord.js';\n\nconst tokenCachePersistenceOptions: TokenCachePersistenceOptions = {\n enabled: true,\n name: 'cloudpack',\n};\n\nfunction getCredentialInternal(loginMethod: LoginMethod, authenticationRecord?: AuthenticationRecord) {\n switch (loginMethod) {\n case 'interactive':\n return new InteractiveBrowserCredential({\n redirectUri: 'http://localhost:1337',\n authenticationRecord,\n tokenCachePersistenceOptions,\n });\n case 'device-code':\n return new DeviceCodeCredential({\n authenticationRecord,\n tokenCachePersistenceOptions,\n });\n default:\n throw new Error(`Invalid login method: ${loginMethod}`);\n }\n}\n\n/**\n * Gets a credential for the given login method.\n * If the login method is 'azure-cli', it will return an AzureCliCredential.\n * Otherwise, it will return an InteractiveBrowserCredential or a DeviceCodeCredential with persistent token settings.\n * If an authentication record has never been saved before, it will authenticate the credential and save the authentication record.\n */\nexport async function getCredential(loginMethod: LoginMethod, cachePath: string) {\n if (loginMethod == 'azure-cli') {\n return new AzureCliCredential();\n }\n\n useIdentityPlugin(cachePersistencePlugin);\n\n let authenticationRecord = getAuthenticationRecord(cachePath);\n\n const credential = getCredentialInternal(loginMethod, authenticationRecord);\n\n if (!authenticationRecord) {\n console.warn('Cloudpack requires authentication to access Azure resources.');\n\n if (loginMethod == 'interactive') {\n console.warn(\n \"Prepare to sign in \u2013 we're launching a browser page for you. Simply follow the instructions on the login page to seamlessly complete the authentication process.\",\n );\n }\n\n const storageScope = 'https://storage.azure.com/.default';\n authenticationRecord = await credential.authenticate(storageScope);\n const token = await credential.getToken(storageScope);\n\n // Creating a custom credential with the token from the authentication record.\n // This ensures that we can use the token without having to authenticate again. Otherwise, we may have to authenticate again to get the token which can create concurrency issues.\n const storageCustomCredential: TokenCredential = {\n getToken: async () => {\n return Promise.resolve(token);\n },\n };\n\n if (authenticationRecord) {\n saveAuthenticationRecord(cachePath, authenticationRecord);\n }\n\n return storageCustomCredential;\n }\n\n return credential;\n}\n", "/**\n * This file is a fork of https://github.com/altinokdarici/azure-sdk-for-js/tree/main/sdk/identity/identity-cache-persistence\n */\n\n// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport * as path from 'path';\nimport {\n DataProtectionScope,\n FilePersistence,\n FilePersistenceWithDataProtection,\n KeychainPersistence,\n LibSecretPersistence,\n type IPersistence as Persistence,\n} from '@azure/msal-node-extensions';\nimport type { TokenCachePersistenceOptions } from '@azure/identity';\n\n/**\n * Local application data folder\n * Expected values:\n * - Darwin: '/Users/user/'\n * - Windows 8+: 'C:\\Users\\user\\AppData\\Local'\n * - Linux: '/home/user/.local/share'\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\nconst localApplicationDataFolder = process.env.APPDATA?.replace?.(/(.Roaming)*$/, '\\\\Local') ?? process.env.HOME!;\n\n/**\n * Dictionary of values that we use as default as we discover, pick and enable the persistence layer.\n * @internal\n */\nexport const defaultMsalValues = {\n tokenCache: {\n name: 'msal.cache',\n // Expected values:\n // - Darwin: '/Users/user/.IdentityService'\n // - Windows 8+: 'C:\\Users\\user\\AppData\\Local\\.IdentityService'\n // - Linux: '/home/user/.IdentityService'\n directory: path.join(localApplicationDataFolder, '.IdentityService'),\n },\n keyRing: {\n label: 'MSALCache',\n schema: 'msal.cache',\n collection: 'default',\n attributes: {\n MsalClientID: 'Microsoft.Developer.IdentityService',\n 'Microsoft.Developer.IdentityService': '1.0.0.0',\n },\n service: 'Microsoft.Developer.IdentityService',\n account: 'MSALCache',\n },\n keyChain: {\n service: 'Microsoft.Developer.IdentityService',\n account: 'MSALCache',\n },\n};\n\n/**\n * Options that are used by the underlying MSAL cache provider.\n * @internal\n */\nexport type MsalPersistenceOptions = Omit<TokenCachePersistenceOptions, 'enabled'>;\n\n/**\n * A function that returns a persistent token cache instance.\n * @internal\n */\ntype MsalPersistenceFactory = (options?: MsalPersistenceOptions) => Promise<Persistence>;\n\n/**\n * Expected responses:\n * - Darwin: '/Users/user/.IdentityService/<name>'\n * - Windows 8+: 'C:\\Users\\user\\AppData\\Local\\.IdentityService\\<name>'\n * - Linux: '/home/user/.IdentityService/<name>'\n * @internal\n */\nfunction getPersistencePath(name: string): string {\n return path.join(defaultMsalValues.tokenCache.directory, name);\n}\n\n/**\n * Set of the platforms we attempt to deliver persistence on.\n *\n * - On Windows we use DPAPI.\n * - On OSX (Darwin), we try to use the system's Keychain, otherwise if the property `unsafeAllowUnencryptedStorage` is set to true, we use an unencrypted file.\n * - On Linux, we try to use the system's Keyring, otherwise if the property `unsafeAllowUnencryptedStorage` is set to true, we use an unencrypted file.\n *\n * Other platforms _are not supported_ at this time.\n *\n * @internal\n */\nexport const msalPersistencePlatforms: Partial<Record<NodeJS.Platform, MsalPersistenceFactory>> = {\n win32: ({ name = defaultMsalValues.tokenCache.name } = {}): Promise<Persistence> =>\n FilePersistenceWithDataProtection.create(getPersistencePath(name), DataProtectionScope.CurrentUser),\n\n darwin: async (options: MsalPersistenceOptions = {}): Promise<Persistence> => {\n const { name, unsafeAllowUnencryptedStorage } = options;\n const { service, account } = defaultMsalValues.keyChain;\n const persistencePath = getPersistencePath(name || defaultMsalValues.tokenCache.name);\n\n try {\n const persistence = await KeychainPersistence.create(persistencePath, service, account);\n // If we don't encounter an error when trying to read from the keychain, then we should be good to go.\n await persistence.load();\n return persistence;\n } catch {\n // If we got an error while trying to read from the keyring,\n // we will proceed only if the user has specified that unencrypted storage is allowed.\n if (!unsafeAllowUnencryptedStorage) {\n throw new Error('Unable to read from the macOS Keychain.');\n }\n return FilePersistence.create(persistencePath);\n }\n },\n\n linux: async (options: MsalPersistenceOptions = {}): Promise<Persistence> => {\n const { name, unsafeAllowUnencryptedStorage } = options;\n const { service, account } = defaultMsalValues.keyRing;\n const persistencePath = getPersistencePath(name || defaultMsalValues.tokenCache.name);\n\n try {\n const persistence = await LibSecretPersistence.create(persistencePath, service, account);\n // If we don't encounter an error when trying to read from the keyring, then we should be good to go.\n await persistence.load();\n return persistence;\n } catch {\n // If we got an error while trying to read from the keyring,\n // we will proceed only if the user has specified that unencrypted storage is allowed.\n if (!unsafeAllowUnencryptedStorage) {\n throw new Error('Unable to read from the system keyring (libsecret).');\n }\n return FilePersistence.create(persistencePath);\n }\n },\n};\n", "/**\n * This file is a fork of https://github.com/altinokdarici/azure-sdk-for-js/tree/main/sdk/identity/identity-cache-persistence\n */\n\n// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport type { MsalPersistenceOptions } from './platforms.js';\nimport { msalPersistencePlatforms } from './platforms.js';\nimport type { IPersistence as Persistence } from '@azure/msal-node-extensions';\nimport { PersistenceCachePlugin } from '@azure/msal-node-extensions';\nimport type { ICachePlugin as CachePlugin } from '@azure/msal-node';\n\n/**\n * This is used to gain access to the underlying Persistence instance, which we use for testing\n *\n * @returns a raw persistence instance\n * @internal\n */\nexport async function createPersistence(options: MsalPersistenceOptions): Promise<Persistence> {\n const persistence = await msalPersistencePlatforms[process.platform]?.(options);\n\n if (persistence === undefined) {\n throw new Error('no persistence providers are available on this platform');\n }\n\n return persistence;\n}\n\nexport async function createPersistenceCachePlugin(options?: MsalPersistenceOptions): Promise<CachePlugin> {\n const persistence = await createPersistence(options ?? {});\n\n return new PersistenceCachePlugin(persistence, {\n retryNumber: 100,\n retryDelay: 50,\n });\n}\n", "/**\n * This file is a fork of https://github.com/altinokdarici/azure-sdk-for-js/tree/main/sdk/identity/identity-cache-persistence\n */\n\n// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n// import { AzurePluginContext } from '../../identity/src/plugins/provider';\nimport type { IdentityPlugin } from '@azure/identity';\nimport { createPersistenceCachePlugin } from './provider.js';\n\n/**\n * A plugin that provides persistent token caching for `@azure/identity`\n * credentials. The plugin API is compatible with `@azure/identity` versions\n * 2.0.0 and later. Load this plugin using the `useIdentityPlugin`\n * function, imported from `@azure/identity`.\n *\n * In order to enable this functionality, you must also pass\n * `tokenCachePersistenceOptions` to your credential constructors with an\n * `enabled` property set to true.\n *\n * Example:\n *\n * ```javascript\n * import { useIdentityPlugin, DeviceCodeCredential } from \"@azure/identity\";\n * import { cachePersistencePlugin } from \"@azure/identity-cache-persistence\";\n *\n * // Load the plugin\n * useIdentityPlugin(cachePersistencePlugin);\n *\n * const credential = new DeviceCodeCredential({\n * tokenCachePersistenceOptions: {\n * enabled: true\n * }\n * });\n * ```\n */\n\nexport const cachePersistencePlugin: IdentityPlugin = (context) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (context as any).cachePluginControl.setPersistence(createPersistenceCachePlugin);\n};\n", "import { deserializeAuthenticationRecord } from '@azure/identity';\nimport { existsSync, readFileSync } from 'fs';\nimport { getAuthenticationRecordPath } from './getAuthenticationRecordPath.js';\n\n/**\n * Retrieves the authentication record from Cloudpack's global cache folder.\n * @param cachePath - The path to Cloudpack's cache folder.\n * @returns - The authentication record if it exists; otherwise, returns `undefined`.\n */\nexport function getAuthenticationRecord(cachePath: string) {\n const fullPath = getAuthenticationRecordPath(cachePath);\n if (!existsSync(fullPath)) {\n return undefined;\n }\n\n const content = readFileSync(fullPath, 'utf-8');\n return deserializeAuthenticationRecord(content);\n}\n", "import path from 'path';\n\n/**\n * Constructs and returns the full path to the authentication record file within the specified cache folder.\n * @param cachePath - The path to Cloudpack's cache folder.\n * @returns - The full path to the authentication record file.\n */\nexport function getAuthenticationRecordPath(cachePath: string) {\n return path.join(cachePath, 'tokencache.bin');\n}\n", "import { serializeAuthenticationRecord, type AuthenticationRecord } from '@azure/identity';\nimport { existsSync, mkdirSync, writeFileSync } from 'fs';\nimport { getAuthenticationRecordPath } from './getAuthenticationRecordPath.js';\n\n/**\n * Saves the provided authentication record to Cloudpack's global cache folder.\n * Creates the cache folder if it doesn't exist.\n * @param cachePath - The path to Cloudpack's cache folder.\n * @param authRecord - The authentication record to save.\n */\nexport function saveAuthenticationRecord(cachePath: string, authRecord: AuthenticationRecord) {\n const content = serializeAuthenticationRecord(authRecord);\n\n if (!existsSync(cachePath)) {\n mkdirSync(cachePath, { recursive: true });\n }\n\n writeFileSync(getAuthenticationRecordPath(cachePath), content);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;IAsBa;;;;IAAA,mBAAU;;;;;MAKnB,OAAO,kBAAkB,MAAe;AACpC,eAAO,KAAK,UAAU,IAAI;;;;;;MAO9B,OAAO,kBACH,UAAsB;AAEtB,cAAM,WAAoD,CAAA;AAC1D,eAAO,KAAK,QAAQ,EAAE,IAAI,SAAU,KAAG;;AACnC,gBAAM,gBAAgB,SAAS,GAAG;AAClC,mBAAS,GAAG,IAAI;YACZ,iBAAiB,cAAc;YAC/B,aAAa,cAAc;YAC3B,OAAO,cAAc;YACrB,kBAAkB,cAAc;YAChC,UAAU,cAAc;YACxB,gBAAgB,cAAc;YAC9B,MAAM,cAAc;YACpB,aAAa,cAAc;YAC3B,wBAAwB,cAAc;YACtC,uBAAuB,cAAc;YACrC,iBAAgBA,MAAA,cAAc,mBAAd,gBAAAA,IAA8B,IAC1C,CAAC,kBAAiB;AACd,qBAAO,KAAK,UAAU,aAAa;YACvC;;QAGZ,CAAC;AAED,eAAO;;;;;;MAOX,OAAO,kBACH,UAAsB;AAEtB,cAAM,WAAoD,CAAA;AAC1D,eAAO,KAAK,QAAQ,EAAE,IAAI,SAAU,KAAG;AACnC,gBAAM,YAAY,SAAS,GAAG;AAC9B,mBAAS,GAAG,IAAI;YACZ,iBAAiB,UAAU;YAC3B,aAAa,UAAU;YACvB,iBAAiB,UAAU;YAC3B,WAAW,UAAU;YACrB,QAAQ,UAAU;YAClB,OAAO,UAAU;;QAEzB,CAAC;AAED,eAAO;;;;;;MAOX,OAAO,sBACH,SAAyB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Ac,4BAA4B,SAAS,GAAG,OAAO;AAC/D;;;ANJA,IAAM,+BAA6D;AAAA,EACjE,SAAS;AAAA,EACT,MAAM;AACR;AAEA,SAAS,sBAAsB,aAA0B,sBAA6C;AACpG,UAAQ,aAAa;AAAA,IACnB,KAAK;AACH,aAAO,IAAI,8CAA6B;AAAA,QACtC,aAAa;AAAA,QACb;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,KAAK;AACH,aAAO,IAAI,sCAAqB;AAAA,QAC9B;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH;AACE,YAAM,IAAI,MAAM,yBAAyB,WAAW,EAAE;AAAA,EAC1D;AACF;AAQA,eAAsB,cAAc,aAA0B,WAAmB;AAC/E,MAAI,eAAe,aAAa;AAC9B,WAAO,IAAI,oCAAmB;AAAA,EAChC;AAEA,0CAAkB,sBAAsB;AAExC,MAAI,uBAAuB,wBAAwB,SAAS;AAE5D,QAAM,aAAa,sBAAsB,aAAa,oBAAoB;AAE1E,MAAI,CAAC,sBAAsB;AACzB,YAAQ,KAAK,8DAA8D;AAE3E,QAAI,eAAe,eAAe;AAChC,cAAQ;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAEA,UAAM,eAAe;AACrB,2BAAuB,MAAM,WAAW,aAAa,YAAY;AACjE,UAAM,QAAQ,MAAM,WAAW,SAAS,YAAY;AAIpD,UAAM,0BAA2C;AAAA,MAC/C,UAAU,YAAY;AACpB,eAAO,QAAQ,QAAQ,KAAK;AAAA,MAC9B;AAAA,IACF;AAEA,QAAI,sBAAsB;AACxB,+BAAyB,WAAW,oBAAoB;AAAA,IAC1D;AAEA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;",
6
+ "names": ["_a", "AuthErrorCodes.unexpectedError", "AuthErrorCodes.postRequestFailed", "ClientAuthErrorCodes.clientInfoDecodingError", "ClientAuthErrorCodes.clientInfoEmptyError", "ClientAuthErrorCodes.tokenParsingError", "ClientAuthErrorCodes.nullOrEmptyToken", "ClientAuthErrorCodes.endpointResolutionError", "ClientAuthErrorCodes.networkError", "ClientAuthErrorCodes.openIdConfigError", "ClientAuthErrorCodes.hashNotDeserialized", "ClientAuthErrorCodes.invalidState", "ClientAuthErrorCodes.stateMismatch", "ClientAuthErrorCodes.stateNotFound", "ClientAuthErrorCodes.nonceMismatch", "ClientAuthErrorCodes.authTimeNotFound", "ClientAuthErrorCodes.maxAgeTranspired", "ClientAuthErrorCodes.multipleMatchingTokens", "ClientAuthErrorCodes.multipleMatchingAccounts", "ClientAuthErrorCodes.multipleMatchingAppMetadata", "ClientAuthErrorCodes.requestCannotBeMade", "ClientAuthErrorCodes.cannotRemoveEmptyScope", "ClientAuthErrorCodes.cannotAppendScopeSet", "ClientAuthErrorCodes.emptyInputScopeSet", "ClientAuthErrorCodes.deviceCodePollingCancelled", "ClientAuthErrorCodes.deviceCodeExpired", "ClientAuthErrorCodes.deviceCodeUnknownError", "ClientAuthErrorCodes.noAccountInSilentRequest", "ClientAuthErrorCodes.invalidCacheRecord", "ClientAuthErrorCodes.invalidCacheEnvironment", "ClientAuthErrorCodes.noAccountFound", "ClientAuthErrorCodes.noCryptoObject", "ClientAuthErrorCodes.unexpectedCredentialType", "ClientAuthErrorCodes.invalidAssertion", "ClientAuthErrorCodes.invalidClientCredential", "ClientAuthErrorCodes.tokenRefreshRequired", "ClientAuthErrorCodes.userTimeoutReached", "ClientAuthErrorCodes.tokenClaimsCnfRequiredForSignedJwt", "ClientAuthErrorCodes.authorizationCodeMissingFromServerResponse", "ClientAuthErrorCodes.bindingKeyNotRemoved", "ClientAuthErrorCodes.endSessionEndpointNotSupported", "ClientAuthErrorCodes.keyIdMissing", "ClientAuthErrorCodes.noNetworkConnectivity", "ClientAuthErrorCodes.userCanceled", "ClientAuthErrorCodes.missingTenantIdError", "ClientAuthErrorCodes.methodNotImplemented", "ClientAuthErrorCodes.nestedAppAuthBridgeDisabled", "ClientAuthErrorCodes.methodNotImplemented", "LogLevel", "ClientAuthErrorCodes.tokenParsingError", "ClientAuthErrorCodes.nullOrEmptyToken", "ClientAuthErrorCodes.maxAgeTranspired", "_a", "_b", "ClientAuthErrorCodes.tokenClaimsCnfRequiredForSignedJwt", "ClientConfigurationErrorCodes.redirectUriEmpty", "ClientConfigurationErrorCodes.claimsRequestParsingError", "ClientConfigurationErrorCodes.authorityUriInsecure", "ClientConfigurationErrorCodes.urlParseError", "ClientConfigurationErrorCodes.urlEmptyError", "ClientConfigurationErrorCodes.emptyInputScopesError", "ClientConfigurationErrorCodes.invalidPromptValue", "ClientConfigurationErrorCodes.invalidClaims", "ClientConfigurationErrorCodes.tokenRequestEmpty", "ClientConfigurationErrorCodes.logoutRequestEmpty", "ClientConfigurationErrorCodes.invalidCodeChallengeMethod", "ClientConfigurationErrorCodes.pkceParamsMissing", "ClientConfigurationErrorCodes.invalidCloudDiscoveryMetadata", "ClientConfigurationErrorCodes.invalidAuthorityMetadata", "ClientConfigurationErrorCodes.untrustedAuthority", "ClientConfigurationErrorCodes.missingSshJwk", "ClientConfigurationErrorCodes.missingSshKid", "ClientConfigurationErrorCodes.missingNonceAuthenticationHeader", "ClientConfigurationErrorCodes.invalidAuthenticationHeader", "ClientConfigurationErrorCodes.cannotSetOIDCOptions", "ClientConfigurationErrorCodes.cannotAllowNativeBroker", "ClientConfigurationErrorCodes.authorityMismatch", "ClientConfigurationErrorCodes.emptyInputScopesError", "ClientAuthErrorCodes.cannotAppendScopeSet", "ClientAuthErrorCodes.cannotRemoveEmptyScope", "ClientAuthErrorCodes.emptyInputScopeSet", "ClientAuthErrorCodes.clientInfoEmptyError", "ClientAuthErrorCodes.clientInfoDecodingError", "name", "ClientAuthErrorCodes.invalidCacheEnvironment", "_a", "ClientAuthErrorCodes.hashNotDeserialized", "ClientConfigurationErrorCodes.urlEmptyError", "ClientConfigurationErrorCodes.urlParseError", "ClientConfigurationErrorCodes.authorityUriInsecure", "UrlUtils.getDeserializedResponse", "_a", "ClientAuthErrorCodes.invalidCacheRecord", "_a", "ClientAuthErrorCodes.bindingKeyNotRemoved", "ClientAuthErrorCodes.multipleMatchingAppMetadata", "name", "ClientAuthErrorCodes.methodNotImplemented", "ClientAuthErrorCodes.methodNotImplemented", "_a", "ClientAuthErrorCodes.networkError", "CLIENT_INFO", "ClientConfigurationErrorCodes.redirectUriEmpty", "ClientConfigurationErrorCodes.invalidPromptValue", "ClientConfigurationErrorCodes.invalidClaims", "ClientConfigurationErrorCodes.pkceParamsMissing", "ClientConfigurationErrorCodes.invalidCodeChallengeMethod", "AADServerParamKeys.RESPONSE_TYPE", "AADServerParamKeys.RESPONSE_MODE", "AADServerParamKeys.NATIVE_BROKER", "AADServerParamKeys.SCOPE", "AADServerParamKeys.CLIENT_ID", "AADServerParamKeys.REDIRECT_URI", "AADServerParamKeys.POST_LOGOUT_URI", "AADServerParamKeys.ID_TOKEN_HINT", "AADServerParamKeys.DOMAIN_HINT", "AADServerParamKeys.LOGIN_HINT", "AADServerParamKeys.SID", "AADServerParamKeys.CLAIMS", "AADServerParamKeys.CLIENT_REQUEST_ID", "AADServerParamKeys.X_CLIENT_SKU", "AADServerParamKeys.X_CLIENT_VER", "AADServerParamKeys.X_CLIENT_OS", "AADServerParamKeys.X_CLIENT_CPU", "AADServerParamKeys.X_APP_NAME", "AADServerParamKeys.X_APP_VER", "AADServerParamKeys.PROMPT", "AADServerParamKeys.STATE", "AADServerParamKeys.NONCE", "AADServerParamKeys.CODE_CHALLENGE", "AADServerParamKeys.CODE_CHALLENGE_METHOD", "ClientConfigurationErrorCodes.pkceParamsMissing", "AADServerParamKeys.CODE", "AADServerParamKeys.DEVICE_CODE", "AADServerParamKeys.REFRESH_TOKEN", "AADServerParamKeys.CODE_VERIFIER", "AADServerParamKeys.CLIENT_SECRET", "AADServerParamKeys.CLIENT_ASSERTION", "AADServerParamKeys.CLIENT_ASSERTION_TYPE", "AADServerParamKeys.OBO_ASSERTION", "AADServerParamKeys.REQUESTED_TOKEN_USE", "AADServerParamKeys.GRANT_TYPE", "ClientConfigurationErrorCodes.invalidClaims", "AADServerParamKeys.TOKEN_TYPE", "AADServerParamKeys.REQ_CNF", "AADServerParamKeys.X_CLIENT_CURR_TELEM", "AADServerParamKeys.X_CLIENT_LAST_TELEM", "AADServerParamKeys.X_MS_LIB_CAPABILITY", "AADServerParamKeys.LOGOUT_HINT", "e", "_a", "version", "ClientConfigurationErrorCodes.invalidCloudDiscoveryMetadata", "ClientAuthErrorCodes.endpointResolutionError", "ClientAuthErrorCodes.endSessionEndpointNotSupported", "_a", "_b", "CacheHelpers.generateAuthorityMetadataExpiresAt", "CacheHelpers.updateAuthorityEndpointMetadata", "ClientAuthErrorCodes.openIdConfigError", "CacheHelpers.isAuthorityMetadataExpired", "ClientConfigurationErrorCodes.invalidAuthorityMetadata", "CacheHelpers.updateCloudDiscoveryMetadata", "ClientConfigurationErrorCodes.untrustedAuthority", "ClientAuthErrorCodes.endpointResolutionError", "_a", "_b", "InteractionRequiredAuthErrorCodes.interactionRequired", "InteractionRequiredAuthErrorCodes.consentRequired", "InteractionRequiredAuthErrorCodes.loginRequired", "InteractionRequiredAuthErrorCodes.badToken", "InteractionRequiredAuthErrorCodes.noTokensFound", "InteractionRequiredAuthErrorCodes.nativeAccountUnavailable", "InteractionRequiredAuthErrorCodes.refreshTokenExpired", "ClientAuthErrorCodes.noCryptoObject", "ClientAuthErrorCodes.invalidState", "_a", "ClientAuthErrorCodes.stateNotFound", "ClientAuthErrorCodes.invalidState", "ClientAuthErrorCodes.stateMismatch", "_a", "ClientAuthErrorCodes.nonceMismatch", "ClientAuthErrorCodes.authTimeNotFound", "ClientAuthErrorCodes.invalidCacheEnvironment", "CacheHelpers.createIdTokenEntity", "CacheHelpers.createAccessTokenEntity", "CacheHelpers.createRefreshTokenEntity", "ClientAuthErrorCodes.keyIdMissing", "_b", "_a", "ClientAuthErrorCodes.requestCannotBeMade", "_b", "ClientAuthErrorCodes.authorizationCodeMissingFromServerResponse", "ClientConfigurationErrorCodes.logoutRequestEmpty", "AADServerParamKeys.CLIENT_ID", "ClientConfigurationErrorCodes.missingSshJwk", "AADServerParamKeys.RETURN_SPA_CODE", "_a", "_b", "ClientConfigurationErrorCodes.tokenRequestEmpty", "ClientAuthErrorCodes.noAccountInSilentRequest", "InteractionRequiredAuthErrorCodes.noTokensFound", "InteractionRequiredAuthErrorCodes.refreshTokenExpired", "InteractionRequiredAuthErrorCodes.badToken", "AADServerParamKeys.CLIENT_ID", "ClientConfigurationErrorCodes.missingSshJwk", "ClientAuthErrorCodes.tokenRefreshRequired", "_a", "ClientAuthErrorCodes.noAccountInSilentRequest", "_b", "ClientAuthErrorCodes.authTimeNotFound", "_a", "Constants", "headers", "Constants", "body", "DEFAULT_SYSTEM_OPTIONS", "DEFAULT_CACHE_OPTIONS", "DEFAULT_TELEMETRY_OPTIONS", "uuidv4", "crypto", "crypto", "name", "version", "name", "version", "NodeConstants", "Constants", "http", "CommonConstants", "Constants", "Constants", "_a", "CommonConstants", "Buffer", "Buffer", "Buffer", "Buffer", "crypto", "Buffer", "Buffer", "Buffer", "jwt", "name", "name", "version", "version", "version", "version", "version", "version2", "version", "version", "version", "version", "version", "require_valid", "version", "version", "version", "version", "require_semver", "header", "secretOrPublicKey", "_", "require_lodash", "require_lodash", "require_lodash", "require_lodash", "require_lodash", "require_lodash", "validate", "_", "jwt", "_a", "_b", "_a", "_b", "NodeConstants", "_a", "version", "init_dist", "init_packageMetadata", "require_ms", "name", "name", "name", "useColors", "createAgent", "name", "createHttpsProxyAgent", "name", "createAgent", "createHttpProxyAgent", "name", "_a", "_a", "name", "createClientLogger", "isObject", "logger", "coreLogger", "os", "AbortError", "_b", "getRandomIntegerInclusive", "stringToUint8Array", "HttpProxyAgent", "HttpsProxyAgent", "inspect", "isError", "createTracingClient", "getErrorMessage", "__await", "Readable", "stream", "__asyncValues", "randomUUID", "isNode", "Transform", "abortController", "http", "https", "zlib", "_a", "_b", "base64.decodeString", "base64.encodeByteArray", "result", "name", "RestError", "createPipelineFromOptions", "bearerTokenAuthenticationPolicy", "createDefaultHttpClient", "path", "createClientLogger", "createPipelineRequest", "logger", "coreClientLogger", "Constants", "path", "name", "https", "logger", "createClientLogger", "AzureAuthorityHosts", "isNode", "msalCommon", "randomUUID", "AbortError", "serializeAuthenticationRecord", "deserializeAuthenticationRecord", "_a", "createTracingClient", "ServiceClient", "_b", "createPipelineRequest", "createHttpHeaders", "AbortController", "RegionalAuthority", "getLogLevel", "msalNode", "os", "path", "fs", "useIdentityPlugin", "msiName", "prepareRequestOptions", "isError", "delay", "readFileAsync", "readFile", "credentialName", "https", "ConfidentialClientApplication", "child_process", "AzureCliCredential", "isLoginError", "childProcess", "error", "promisify", "createHash", "createPrivateKey", "open", "http", "stoppable", "InteractiveBrowserCredential", "DeviceCodeCredential", "import_identity", "name", "_a", "_b", "path", "import_identity", "existsSync", "existsSync"]
7
+ }