@azure/msal-browser 2.19.0 → 2.19.1

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 (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +212 -212
  3. package/dist/_virtual/_tslib.js +1 -1
  4. package/dist/app/ClientApplication.js +1 -1
  5. package/dist/app/ClientApplication.js.map +1 -1
  6. package/dist/app/IPublicClientApplication.js +1 -1
  7. package/dist/app/IPublicClientApplication.js.map +1 -1
  8. package/dist/app/PublicClientApplication.js +1 -1
  9. package/dist/app/PublicClientApplication.js.map +1 -1
  10. package/dist/cache/AsyncMemoryStorage.js +1 -1
  11. package/dist/cache/AsyncMemoryStorage.js.map +1 -1
  12. package/dist/cache/BrowserCacheManager.d.ts +5 -1
  13. package/dist/cache/BrowserCacheManager.d.ts.map +1 -1
  14. package/dist/cache/BrowserCacheManager.js +20 -1
  15. package/dist/cache/BrowserCacheManager.js.map +1 -1
  16. package/dist/cache/BrowserStorage.js +1 -1
  17. package/dist/cache/BrowserStorage.js.map +1 -1
  18. package/dist/cache/DatabaseStorage.js +1 -1
  19. package/dist/cache/DatabaseStorage.js.map +1 -1
  20. package/dist/cache/MemoryStorage.js +1 -1
  21. package/dist/cache/MemoryStorage.js.map +1 -1
  22. package/dist/cache/TokenCache.js +1 -1
  23. package/dist/cache/TokenCache.js.map +1 -1
  24. package/dist/config/Configuration.js +1 -1
  25. package/dist/config/Configuration.js.map +1 -1
  26. package/dist/crypto/BrowserCrypto.js +1 -1
  27. package/dist/crypto/BrowserCrypto.js.map +1 -1
  28. package/dist/crypto/CryptoOps.js +1 -1
  29. package/dist/crypto/CryptoOps.js.map +1 -1
  30. package/dist/crypto/GuidGenerator.js +1 -1
  31. package/dist/crypto/GuidGenerator.js.map +1 -1
  32. package/dist/crypto/PkceGenerator.js +1 -1
  33. package/dist/crypto/PkceGenerator.js.map +1 -1
  34. package/dist/crypto/SignedHttpRequest.js +1 -1
  35. package/dist/crypto/SignedHttpRequest.js.map +1 -1
  36. package/dist/encode/Base64Decode.js +1 -1
  37. package/dist/encode/Base64Decode.js.map +1 -1
  38. package/dist/encode/Base64Encode.js +1 -1
  39. package/dist/encode/Base64Encode.js.map +1 -1
  40. package/dist/error/BrowserAuthError.js +1 -1
  41. package/dist/error/BrowserAuthError.js.map +1 -1
  42. package/dist/error/BrowserConfigurationAuthError.js +1 -1
  43. package/dist/error/BrowserConfigurationAuthError.js.map +1 -1
  44. package/dist/event/EventHandler.js +1 -1
  45. package/dist/event/EventHandler.js.map +1 -1
  46. package/dist/event/EventMessage.js +1 -1
  47. package/dist/event/EventMessage.js.map +1 -1
  48. package/dist/event/EventType.js +1 -1
  49. package/dist/event/EventType.js.map +1 -1
  50. package/dist/index.cjs.js +2003 -1959
  51. package/dist/index.cjs.js.map +1 -1
  52. package/dist/index.js +1 -1
  53. package/dist/interaction_client/BaseInteractionClient.js +1 -1
  54. package/dist/interaction_client/BaseInteractionClient.js.map +1 -1
  55. package/dist/interaction_client/PopupClient.js +1 -1
  56. package/dist/interaction_client/PopupClient.js.map +1 -1
  57. package/dist/interaction_client/RedirectClient.js +1 -1
  58. package/dist/interaction_client/RedirectClient.js.map +1 -1
  59. package/dist/interaction_client/SilentCacheClient.js +1 -1
  60. package/dist/interaction_client/SilentCacheClient.js.map +1 -1
  61. package/dist/interaction_client/SilentIframeClient.js +1 -1
  62. package/dist/interaction_client/SilentIframeClient.js.map +1 -1
  63. package/dist/interaction_client/SilentRefreshClient.js +1 -1
  64. package/dist/interaction_client/SilentRefreshClient.js.map +1 -1
  65. package/dist/interaction_client/StandardInteractionClient.js +1 -1
  66. package/dist/interaction_client/StandardInteractionClient.js.map +1 -1
  67. package/dist/interaction_handler/InteractionHandler.js +1 -1
  68. package/dist/interaction_handler/InteractionHandler.js.map +1 -1
  69. package/dist/interaction_handler/PopupHandler.js +1 -1
  70. package/dist/interaction_handler/PopupHandler.js.map +1 -1
  71. package/dist/interaction_handler/RedirectHandler.js +1 -1
  72. package/dist/interaction_handler/RedirectHandler.js.map +1 -1
  73. package/dist/interaction_handler/SilentHandler.js +1 -1
  74. package/dist/interaction_handler/SilentHandler.js.map +1 -1
  75. package/dist/navigation/NavigationClient.js +1 -1
  76. package/dist/navigation/NavigationClient.js.map +1 -1
  77. package/dist/network/FetchClient.js +1 -1
  78. package/dist/network/FetchClient.js.map +1 -1
  79. package/dist/network/XhrClient.js +1 -1
  80. package/dist/network/XhrClient.js.map +1 -1
  81. package/dist/packageMetadata.js +1 -1
  82. package/dist/packageMetadata.js.map +1 -1
  83. package/dist/utils/BrowserConstants.js +1 -1
  84. package/dist/utils/BrowserConstants.js.map +1 -1
  85. package/dist/utils/BrowserProtocolUtils.js +1 -1
  86. package/dist/utils/BrowserProtocolUtils.js.map +1 -1
  87. package/dist/utils/BrowserStringUtils.js +1 -1
  88. package/dist/utils/BrowserStringUtils.js.map +1 -1
  89. package/dist/utils/BrowserUtils.js +1 -1
  90. package/dist/utils/BrowserUtils.js.map +1 -1
  91. package/dist/utils/MathUtils.js +1 -1
  92. package/dist/utils/MathUtils.js.map +1 -1
  93. package/dist/utils/PopupUtils.js +1 -1
  94. package/dist/utils/PopupUtils.js.map +1 -1
  95. package/lib/msal-browser.js +2003 -1959
  96. package/lib/msal-browser.js.map +1 -1
  97. package/lib/msal-browser.min.js +22 -22
  98. package/package.json +95 -95
  99. package/CHANGELOG.json +0 -1613
  100. package/CHANGELOG.md +0 -510
@@ -1,4 +1,4 @@
1
- /*! @azure/msal-browser v2.19.0 2021-11-02 */
1
+ /*! @azure/msal-browser v2.19.1 2022-08-03 */
2
2
  'use strict';
3
3
  (function (global, factory) {
4
4
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
@@ -107,7 +107,7 @@
107
107
  return ar;
108
108
  }
109
109
 
110
- /*! @azure/msal-common v5.1.0 2021-11-02 */
110
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
111
111
  /*! *****************************************************************************
112
112
  Copyright (c) Microsoft Corporation.
113
113
 
@@ -194,7 +194,7 @@
194
194
  return r;
195
195
  }
196
196
 
197
- /*! @azure/msal-common v5.1.0 2021-11-02 */
197
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
198
198
 
199
199
  /*
200
200
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -555,7 +555,7 @@
555
555
  CacheOutcome["REFRESH_CACHED_ACCESS_TOKEN"] = "4";
556
556
  })(CacheOutcome || (CacheOutcome = {}));
557
557
 
558
- /*! @azure/msal-common v5.1.0 2021-11-02 */
558
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
559
559
 
560
560
  /*
561
561
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -599,7 +599,7 @@
599
599
  return AuthError;
600
600
  }(Error));
601
601
 
602
- /*! @azure/msal-common v5.1.0 2021-11-02 */
602
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
603
603
 
604
604
  /*
605
605
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -665,7 +665,7 @@
665
665
  }
666
666
  };
667
667
 
668
- /*! @azure/msal-common v5.1.0 2021-11-02 */
668
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
669
669
 
670
670
  /*
671
671
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1127,7 +1127,7 @@
1127
1127
  return ClientAuthError;
1128
1128
  }(AuthError));
1129
1129
 
1130
- /*! @azure/msal-common v5.1.0 2021-11-02 */
1130
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
1131
1131
 
1132
1132
  /*
1133
1133
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1252,7 +1252,7 @@
1252
1252
  return StringUtils;
1253
1253
  }());
1254
1254
 
1255
- /*! @azure/msal-common v5.1.0 2021-11-02 */
1255
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
1256
1256
 
1257
1257
  /*
1258
1258
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1432,12 +1432,12 @@
1432
1432
  return Logger;
1433
1433
  }());
1434
1434
 
1435
- /*! @azure/msal-common v5.1.0 2021-11-02 */
1435
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
1436
1436
  /* eslint-disable header/header */
1437
1437
  var name$1 = "@azure/msal-common";
1438
1438
  var version$1 = "5.1.0";
1439
1439
 
1440
- /*! @azure/msal-common v5.1.0 2021-11-02 */
1440
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
1441
1441
 
1442
1442
  /*
1443
1443
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1581,7 +1581,7 @@
1581
1581
  return CredentialEntity;
1582
1582
  }());
1583
1583
 
1584
- /*! @azure/msal-common v5.1.0 2021-11-02 */
1584
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
1585
1585
 
1586
1586
  /*
1587
1587
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1826,7 +1826,7 @@
1826
1826
  return ClientConfigurationError;
1827
1827
  }(ClientAuthError));
1828
1828
 
1829
- /*! @azure/msal-common v5.1.0 2021-11-02 */
1829
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
1830
1830
 
1831
1831
  /*
1832
1832
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -2010,7 +2010,7 @@
2010
2010
  return ScopeSet;
2011
2011
  }());
2012
2012
 
2013
- /*! @azure/msal-common v5.1.0 2021-11-02 */
2013
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
2014
2014
 
2015
2015
  /*
2016
2016
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -2048,7 +2048,7 @@
2048
2048
  };
2049
2049
  }
2050
2050
 
2051
- /*! @azure/msal-common v5.1.0 2021-11-02 */
2051
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
2052
2052
  /*
2053
2053
  * Copyright (c) Microsoft Corporation. All rights reserved.
2054
2054
  * Licensed under the MIT License.
@@ -2062,7 +2062,7 @@
2062
2062
  AuthorityType[AuthorityType["Adfs"] = 1] = "Adfs";
2063
2063
  })(AuthorityType || (AuthorityType = {}));
2064
2064
 
2065
- /*! @azure/msal-common v5.1.0 2021-11-02 */
2065
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
2066
2066
 
2067
2067
  /*
2068
2068
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -2296,7 +2296,7 @@
2296
2296
  return AccountEntity;
2297
2297
  }());
2298
2298
 
2299
- /*! @azure/msal-common v5.1.0 2021-11-02 */
2299
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
2300
2300
 
2301
2301
  /*
2302
2302
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -2334,7 +2334,7 @@
2334
2334
  return AuthToken;
2335
2335
  }());
2336
2336
 
2337
- /*! @azure/msal-common v5.1.0 2021-11-02 */
2337
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
2338
2338
 
2339
2339
  /*
2340
2340
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -2578,16 +2578,21 @@
2578
2578
  break;
2579
2579
  }
2580
2580
  }
2581
+ /*
2582
+ * At this point, the entity matches the request, update cache key if key schema has changed
2583
+ * Migration code for forwards compatibility with new versions of the library in case of rollback.
2584
+ */
2585
+ var updatedCacheKey = _this.updateCredentialCacheKey(cacheKey, entity);
2581
2586
  switch (credType) {
2582
2587
  case CredentialType.ID_TOKEN:
2583
- matchingCredentials.idTokens[cacheKey] = entity;
2588
+ matchingCredentials.idTokens[updatedCacheKey] = entity;
2584
2589
  break;
2585
2590
  case CredentialType.ACCESS_TOKEN:
2586
2591
  case CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME:
2587
- matchingCredentials.accessTokens[cacheKey] = entity;
2592
+ matchingCredentials.accessTokens[updatedCacheKey] = entity;
2588
2593
  break;
2589
2594
  case CredentialType.REFRESH_TOKEN:
2590
- matchingCredentials.refreshTokens[cacheKey] = entity;
2595
+ matchingCredentials.refreshTokens[updatedCacheKey] = entity;
2591
2596
  break;
2592
2597
  }
2593
2598
  });
@@ -3163,10 +3168,14 @@
3163
3168
  });
3164
3169
  });
3165
3170
  };
3171
+ DefaultStorageClass.prototype.updateCredentialCacheKey = function () {
3172
+ var notImplErr = "Storage interface - updateCredentialCacheKey() has not been implemented for the cacheStorage interface.";
3173
+ throw AuthError.createUnexpectedError(notImplErr);
3174
+ };
3166
3175
  return DefaultStorageClass;
3167
3176
  }(CacheManager));
3168
3177
 
3169
- /*! @azure/msal-common v5.1.0 2021-11-02 */
3178
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
3170
3179
 
3171
3180
  /*
3172
3181
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -3248,7 +3257,7 @@
3248
3257
  return __assign({ clientCapabilities: [] }, authOptions);
3249
3258
  }
3250
3259
 
3251
- /*! @azure/msal-common v5.1.0 2021-11-02 */
3260
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
3252
3261
 
3253
3262
  /*
3254
3263
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -3268,7 +3277,7 @@
3268
3277
  return ServerError;
3269
3278
  }(AuthError));
3270
3279
 
3271
- /*! @azure/msal-common v5.1.0 2021-11-02 */
3280
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
3272
3281
 
3273
3282
  /*
3274
3283
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -3364,7 +3373,7 @@
3364
3373
  return ThrottlingUtils;
3365
3374
  }());
3366
3375
 
3367
- /*! @azure/msal-common v5.1.0 2021-11-02 */
3376
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
3368
3377
 
3369
3378
  /*
3370
3379
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -3413,7 +3422,7 @@
3413
3422
  return NetworkManager;
3414
3423
  }());
3415
3424
 
3416
- /*! @azure/msal-common v5.1.0 2021-11-02 */
3425
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
3417
3426
  /*
3418
3427
  * Copyright (c) Microsoft Corporation. All rights reserved.
3419
3428
  * Licensed under the MIT License.
@@ -3424,7 +3433,7 @@
3424
3433
  CcsCredentialType["UPN"] = "UPN";
3425
3434
  })(CcsCredentialType || (CcsCredentialType = {}));
3426
3435
 
3427
- /*! @azure/msal-common v5.1.0 2021-11-02 */
3436
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
3428
3437
 
3429
3438
  /*
3430
3439
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -3513,7 +3522,7 @@
3513
3522
  return BaseClient;
3514
3523
  }());
3515
3524
 
3516
- /*! @azure/msal-common v5.1.0 2021-11-02 */
3525
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
3517
3526
 
3518
3527
  /*
3519
3528
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -3599,7 +3608,7 @@
3599
3608
  return RequestValidator;
3600
3609
  }());
3601
3610
 
3602
- /*! @azure/msal-common v5.1.0 2021-11-02 */
3611
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
3603
3612
 
3604
3613
  /*
3605
3614
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -3939,7 +3948,7 @@
3939
3948
  return RequestParameterBuilder;
3940
3949
  }());
3941
3950
 
3942
- /*! @azure/msal-common v5.1.0 2021-11-02 */
3951
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
3943
3952
 
3944
3953
  /*
3945
3954
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -4004,7 +4013,7 @@
4004
4013
  return IdTokenEntity;
4005
4014
  }(CredentialEntity));
4006
4015
 
4007
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4016
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4008
4017
  /*
4009
4018
  * Copyright (c) Microsoft Corporation. All rights reserved.
4010
4019
  * Licensed under the MIT License.
@@ -4054,7 +4063,7 @@
4054
4063
  return TimeUtils;
4055
4064
  }());
4056
4065
 
4057
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4066
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4058
4067
 
4059
4068
  /*
4060
4069
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -4161,7 +4170,7 @@
4161
4170
  return AccessTokenEntity;
4162
4171
  }(CredentialEntity));
4163
4172
 
4164
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4173
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4165
4174
 
4166
4175
  /*
4167
4176
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -4228,7 +4237,7 @@
4228
4237
  return RefreshTokenEntity;
4229
4238
  }(CredentialEntity));
4230
4239
 
4231
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4240
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4232
4241
 
4233
4242
  /*
4234
4243
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -4292,7 +4301,7 @@
4292
4301
  return InteractionRequiredAuthError;
4293
4302
  }(AuthError));
4294
4303
 
4295
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4304
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4296
4305
  /*
4297
4306
  * Copyright (c) Microsoft Corporation. All rights reserved.
4298
4307
  * Licensed under the MIT License.
@@ -4308,7 +4317,7 @@
4308
4317
  return CacheRecord;
4309
4318
  }());
4310
4319
 
4311
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4320
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4312
4321
 
4313
4322
  /*
4314
4323
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -4379,7 +4388,7 @@
4379
4388
  return ProtocolUtils;
4380
4389
  }());
4381
4390
 
4382
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4391
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4383
4392
 
4384
4393
  /*
4385
4394
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -4580,7 +4589,7 @@
4580
4589
  return UrlString;
4581
4590
  }());
4582
4591
 
4583
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4592
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4584
4593
 
4585
4594
  /*
4586
4595
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -4655,7 +4664,7 @@
4655
4664
  return PopTokenGenerator;
4656
4665
  }());
4657
4666
 
4658
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4667
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4659
4668
 
4660
4669
  /*
4661
4670
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -4725,7 +4734,7 @@
4725
4734
  return AppMetadataEntity;
4726
4735
  }());
4727
4736
 
4728
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4737
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4729
4738
  /*
4730
4739
  * Copyright (c) Microsoft Corporation. All rights reserved.
4731
4740
  * Licensed under the MIT License.
@@ -4761,7 +4770,7 @@
4761
4770
  return TokenCacheContext;
4762
4771
  }());
4763
4772
 
4764
- /*! @azure/msal-common v5.1.0 2021-11-02 */
4773
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
4765
4774
 
4766
4775
  /*
4767
4776
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -5025,7 +5034,7 @@
5025
5034
  return ResponseHandler;
5026
5035
  }());
5027
5036
 
5028
- /*! @azure/msal-common v5.1.0 2021-11-02 */
5037
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
5029
5038
 
5030
5039
  /*
5031
5040
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -5309,7 +5318,7 @@
5309
5318
  if (request.domainHint) {
5310
5319
  parameterBuilder.addDomainHint(request.domainHint);
5311
5320
  }
5312
- // Add sid or loginHint with preference for sid -> loginHint -> username of AccountInfo object
5321
+ // Add sid or loginHint with preference for login_hint claim (in request) -> sid -> loginHint (upn/email) -> username of AccountInfo object
5313
5322
  if (request.prompt !== PromptValue.SELECT_ACCOUNT) {
5314
5323
  // AAD will throw if prompt=select_account is passed with an account hint
5315
5324
  if (request.sid && request.prompt === PromptValue.NONE) {
@@ -5319,9 +5328,24 @@
5319
5328
  }
5320
5329
  else if (request.account) {
5321
5330
  var accountSid = this.extractAccountSid(request.account);
5322
- // If account and loginHint are provided, we will check account first for sid before adding loginHint
5323
- if (accountSid && request.prompt === PromptValue.NONE) {
5324
- // SessionId is only used in silent calls
5331
+ var accountLoginHintClaim = this.extractLoginHint(request.account);
5332
+ // If login_hint claim is present, use it over sid/username
5333
+ if (accountLoginHintClaim) {
5334
+ this.logger.verbose("createAuthCodeUrlQueryString: login_hint claim present on account");
5335
+ parameterBuilder.addLoginHint(accountLoginHintClaim);
5336
+ try {
5337
+ var clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
5338
+ parameterBuilder.addCcsOid(clientInfo);
5339
+ }
5340
+ catch (e) {
5341
+ this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
5342
+ }
5343
+ }
5344
+ else if (accountSid && request.prompt === PromptValue.NONE) {
5345
+ /*
5346
+ * If account and loginHint are provided, we will check account first for sid before adding loginHint
5347
+ * SessionId is only used in silent calls
5348
+ */
5325
5349
  this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account");
5326
5350
  parameterBuilder.addSid(accountSid);
5327
5351
  try {
@@ -5329,7 +5353,7 @@
5329
5353
  parameterBuilder.addCcsOid(clientInfo);
5330
5354
  }
5331
5355
  catch (e) {
5332
- this.logger.verbose("Could not parse home account ID for CCS Header: " + e);
5356
+ this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
5333
5357
  }
5334
5358
  }
5335
5359
  else if (request.loginHint) {
@@ -5346,7 +5370,7 @@
5346
5370
  parameterBuilder.addCcsOid(clientInfo);
5347
5371
  }
5348
5372
  catch (e) {
5349
- this.logger.verbose("Could not parse home account ID for CCS Header: " + e);
5373
+ this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
5350
5374
  }
5351
5375
  }
5352
5376
  }
@@ -5401,16 +5425,17 @@
5401
5425
  * @param account
5402
5426
  */
5403
5427
  AuthorizationCodeClient.prototype.extractAccountSid = function (account) {
5404
- if (account.idTokenClaims) {
5405
- var tokenClaims = account.idTokenClaims;
5406
- return tokenClaims.sid || null;
5407
- }
5408
- return null;
5428
+ var _a;
5429
+ return ((_a = account.idTokenClaims) === null || _a === void 0 ? void 0 : _a["sid"]) || null;
5430
+ };
5431
+ AuthorizationCodeClient.prototype.extractLoginHint = function (account) {
5432
+ var _a;
5433
+ return ((_a = account.idTokenClaims) === null || _a === void 0 ? void 0 : _a["login_hint"]) || null;
5409
5434
  };
5410
5435
  return AuthorizationCodeClient;
5411
5436
  }(BaseClient));
5412
5437
 
5413
- /*! @azure/msal-common v5.1.0 2021-11-02 */
5438
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
5414
5439
 
5415
5440
  /*
5416
5441
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -5621,7 +5646,7 @@
5621
5646
  return RefreshTokenClient;
5622
5647
  }(BaseClient));
5623
5648
 
5624
- /*! @azure/msal-common v5.1.0 2021-11-02 */
5649
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
5625
5650
 
5626
5651
  /*
5627
5652
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -5744,7 +5769,7 @@
5744
5769
  return SilentFlowClient;
5745
5770
  }(BaseClient));
5746
5771
 
5747
- /*! @azure/msal-common v5.1.0 2021-11-02 */
5772
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
5748
5773
  /*
5749
5774
  * Copyright (c) Microsoft Corporation. All rights reserved.
5750
5775
  * Licensed under the MIT License.
@@ -5755,7 +5780,7 @@
5755
5780
  response.hasOwnProperty("issuer"));
5756
5781
  }
5757
5782
 
5758
- /*! @azure/msal-common v5.1.0 2021-11-02 */
5783
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
5759
5784
  /*
5760
5785
  * Copyright (c) Microsoft Corporation. All rights reserved.
5761
5786
  * Licensed under the MIT License.
@@ -5769,7 +5794,7 @@
5769
5794
  ProtocolMode["OIDC"] = "OIDC";
5770
5795
  })(exports.ProtocolMode || (exports.ProtocolMode = {}));
5771
5796
 
5772
- /*! @azure/msal-common v5.1.0 2021-11-02 */
5797
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
5773
5798
 
5774
5799
  /*
5775
5800
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -5844,7 +5869,7 @@
5844
5869
  return AuthorityMetadataEntity;
5845
5870
  }());
5846
5871
 
5847
- /*! @azure/msal-common v5.1.0 2021-11-02 */
5872
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
5848
5873
  /*
5849
5874
  * Copyright (c) Microsoft Corporation. All rights reserved.
5850
5875
  * Licensed under the MIT License.
@@ -5854,7 +5879,7 @@
5854
5879
  response.hasOwnProperty("metadata"));
5855
5880
  }
5856
5881
 
5857
- /*! @azure/msal-common v5.1.0 2021-11-02 */
5882
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
5858
5883
 
5859
5884
  /*
5860
5885
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -5968,7 +5993,7 @@
5968
5993
  return RegionDiscovery;
5969
5994
  }());
5970
5995
 
5971
- /*! @azure/msal-common v5.1.0 2021-11-02 */
5996
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
5972
5997
 
5973
5998
  /*
5974
5999
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -6534,7 +6559,7 @@
6534
6559
  return Authority;
6535
6560
  }());
6536
6561
 
6537
- /*! @azure/msal-common v5.1.0 2021-11-02 */
6562
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
6538
6563
 
6539
6564
  /*
6540
6565
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -6595,7 +6620,7 @@
6595
6620
  return AuthorityFactory;
6596
6621
  }());
6597
6622
 
6598
- /*! @azure/msal-common v5.1.0 2021-11-02 */
6623
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
6599
6624
 
6600
6625
  /*
6601
6626
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -6626,7 +6651,7 @@
6626
6651
  return ServerTelemetryEntity;
6627
6652
  }());
6628
6653
 
6629
- /*! @azure/msal-common v5.1.0 2021-11-02 */
6654
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
6630
6655
 
6631
6656
  /*
6632
6657
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -6654,7 +6679,7 @@
6654
6679
  return ThrottlingEntity;
6655
6680
  }());
6656
6681
 
6657
- /*! @azure/msal-common v5.1.0 2021-11-02 */
6682
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
6658
6683
 
6659
6684
  /*
6660
6685
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -6671,7 +6696,7 @@
6671
6696
  }
6672
6697
  };
6673
6698
 
6674
- /*! @azure/msal-common v5.1.0 2021-11-02 */
6699
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
6675
6700
 
6676
6701
  /*
6677
6702
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -6730,7 +6755,7 @@
6730
6755
  return AuthenticationHeaderParser;
6731
6756
  }());
6732
6757
 
6733
- /*! @azure/msal-common v5.1.0 2021-11-02 */
6758
+ /*! @azure/msal-common v5.1.1 2022-08-03 */
6734
6759
 
6735
6760
  /*
6736
6761
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -8174,246 +8199,258 @@
8174
8199
  * Licensed under the MIT License.
8175
8200
  */
8176
8201
  /**
8177
- * Storage wrapper for IndexedDB storage in browsers: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
8202
+ * This class implements the Fetch API for GET and POST requests. See more here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
8178
8203
  */
8179
- var DatabaseStorage = /** @class */ (function () {
8180
- function DatabaseStorage() {
8181
- this.dbName = DB_NAME;
8182
- this.version = DB_VERSION;
8183
- this.tableName = DB_TABLE_NAME;
8184
- this.dbOpen = false;
8204
+ var FetchClient = /** @class */ (function () {
8205
+ function FetchClient() {
8185
8206
  }
8186
8207
  /**
8187
- * Opens IndexedDB instance.
8208
+ * Fetch Client for REST endpoints - Get request
8209
+ * @param url
8210
+ * @param headers
8211
+ * @param body
8188
8212
  */
8189
- DatabaseStorage.prototype.open = function () {
8213
+ FetchClient.prototype.sendGetRequestAsync = function (url, options) {
8190
8214
  return __awaiter$1(this, void 0, void 0, function () {
8191
- var _this = this;
8192
- return __generator$1(this, function (_a) {
8193
- return [2 /*return*/, new Promise(function (resolve, reject) {
8194
- var openDB = window.indexedDB.open(_this.dbName, _this.version);
8195
- openDB.addEventListener("upgradeneeded", function (e) {
8196
- var event = e;
8197
- event.target.result.createObjectStore(_this.tableName);
8198
- });
8199
- openDB.addEventListener("success", function (e) {
8200
- var event = e;
8201
- _this.db = event.target.result;
8202
- _this.dbOpen = true;
8203
- resolve();
8204
- });
8205
- openDB.addEventListener("error", function () { return reject(BrowserAuthError.createDatabaseUnavailableError()); });
8206
- })];
8215
+ var response, e_1, _a;
8216
+ return __generator$1(this, function (_b) {
8217
+ switch (_b.label) {
8218
+ case 0:
8219
+ _b.trys.push([0, 2, , 3]);
8220
+ return [4 /*yield*/, fetch(url, {
8221
+ method: HTTP_REQUEST_TYPE.GET,
8222
+ headers: this.getFetchHeaders(options)
8223
+ })];
8224
+ case 1:
8225
+ response = _b.sent();
8226
+ return [3 /*break*/, 3];
8227
+ case 2:
8228
+ e_1 = _b.sent();
8229
+ if (window.navigator.onLine) {
8230
+ throw BrowserAuthError.createGetRequestFailedError(e_1, url);
8231
+ }
8232
+ else {
8233
+ throw BrowserAuthError.createNoNetworkConnectivityError();
8234
+ }
8235
+ case 3:
8236
+ _b.trys.push([3, 5, , 6]);
8237
+ _a = {
8238
+ headers: this.getHeaderDict(response.headers)
8239
+ };
8240
+ return [4 /*yield*/, response.json()];
8241
+ case 4: return [2 /*return*/, (_a.body = (_b.sent()),
8242
+ _a.status = response.status,
8243
+ _a)];
8244
+ case 5:
8245
+ _b.sent();
8246
+ throw BrowserAuthError.createFailedToParseNetworkResponseError(url);
8247
+ case 6: return [2 /*return*/];
8248
+ }
8207
8249
  });
8208
8250
  });
8209
8251
  };
8210
8252
  /**
8211
- * Opens database if it's not already open
8253
+ * Fetch Client for REST endpoints - Post request
8254
+ * @param url
8255
+ * @param headers
8256
+ * @param body
8212
8257
  */
8213
- DatabaseStorage.prototype.validateDbIsOpen = function () {
8258
+ FetchClient.prototype.sendPostRequestAsync = function (url, options) {
8214
8259
  return __awaiter$1(this, void 0, void 0, function () {
8215
- return __generator$1(this, function (_a) {
8216
- switch (_a.label) {
8260
+ var reqBody, response, e_3, _a;
8261
+ return __generator$1(this, function (_b) {
8262
+ switch (_b.label) {
8217
8263
  case 0:
8218
- if (!!this.dbOpen) return [3 /*break*/, 2];
8219
- return [4 /*yield*/, this.open()];
8220
- case 1: return [2 /*return*/, _a.sent()];
8221
- case 2: return [2 /*return*/];
8264
+ reqBody = (options && options.body) || "";
8265
+ _b.label = 1;
8266
+ case 1:
8267
+ _b.trys.push([1, 3, , 4]);
8268
+ return [4 /*yield*/, fetch(url, {
8269
+ method: HTTP_REQUEST_TYPE.POST,
8270
+ headers: this.getFetchHeaders(options),
8271
+ body: reqBody
8272
+ })];
8273
+ case 2:
8274
+ response = _b.sent();
8275
+ return [3 /*break*/, 4];
8276
+ case 3:
8277
+ e_3 = _b.sent();
8278
+ if (window.navigator.onLine) {
8279
+ throw BrowserAuthError.createPostRequestFailedError(e_3, url);
8280
+ }
8281
+ else {
8282
+ throw BrowserAuthError.createNoNetworkConnectivityError();
8283
+ }
8284
+ case 4:
8285
+ _b.trys.push([4, 6, , 7]);
8286
+ _a = {
8287
+ headers: this.getHeaderDict(response.headers)
8288
+ };
8289
+ return [4 /*yield*/, response.json()];
8290
+ case 5: return [2 /*return*/, (_a.body = (_b.sent()),
8291
+ _a.status = response.status,
8292
+ _a)];
8293
+ case 6:
8294
+ _b.sent();
8295
+ throw BrowserAuthError.createFailedToParseNetworkResponseError(url);
8296
+ case 7: return [2 /*return*/];
8222
8297
  }
8223
8298
  });
8224
8299
  });
8225
8300
  };
8226
8301
  /**
8227
- * Retrieves item from IndexedDB instance.
8228
- * @param key
8302
+ * Get Fetch API Headers object from string map
8303
+ * @param inputHeaders
8229
8304
  */
8230
- DatabaseStorage.prototype.getItem = function (key) {
8231
- return __awaiter$1(this, void 0, void 0, function () {
8232
- var _this = this;
8233
- return __generator$1(this, function (_a) {
8234
- switch (_a.label) {
8235
- case 0: return [4 /*yield*/, this.validateDbIsOpen()];
8236
- case 1:
8237
- _a.sent();
8238
- return [2 /*return*/, new Promise(function (resolve, reject) {
8239
- // TODO: Add timeouts?
8240
- if (!_this.db) {
8241
- return reject(BrowserAuthError.createDatabaseNotOpenError());
8242
- }
8243
- var transaction = _this.db.transaction([_this.tableName], "readonly");
8244
- var objectStore = transaction.objectStore(_this.tableName);
8245
- var dbGet = objectStore.get(key);
8246
- dbGet.addEventListener("success", function (e) {
8247
- var event = e;
8248
- resolve(event.target.result);
8249
- });
8250
- dbGet.addEventListener("error", function (e) { return reject(e); });
8251
- })];
8252
- }
8253
- });
8305
+ FetchClient.prototype.getFetchHeaders = function (options) {
8306
+ var headers = new Headers();
8307
+ if (!(options && options.headers)) {
8308
+ return headers;
8309
+ }
8310
+ var optionsHeaders = options.headers;
8311
+ Object.keys(optionsHeaders).forEach(function (key) {
8312
+ headers.append(key, optionsHeaders[key]);
8313
+ });
8314
+ return headers;
8315
+ };
8316
+ FetchClient.prototype.getHeaderDict = function (headers) {
8317
+ var headerDict = {};
8318
+ headers.forEach(function (value, key) {
8319
+ headerDict[key] = value;
8254
8320
  });
8321
+ return headerDict;
8255
8322
  };
8323
+ return FetchClient;
8324
+ }());
8325
+
8326
+ /*
8327
+ * Copyright (c) Microsoft Corporation. All rights reserved.
8328
+ * Licensed under the MIT License.
8329
+ */
8330
+ /**
8331
+ * This client implements the XMLHttpRequest class to send GET and POST requests.
8332
+ */
8333
+ var XhrClient = /** @class */ (function () {
8334
+ function XhrClient() {
8335
+ }
8256
8336
  /**
8257
- * Adds item to IndexedDB under given key
8258
- * @param key
8259
- * @param payload
8337
+ * XhrClient for REST endpoints - Get request
8338
+ * @param url
8339
+ * @param headers
8340
+ * @param body
8260
8341
  */
8261
- DatabaseStorage.prototype.setItem = function (key, payload) {
8342
+ XhrClient.prototype.sendGetRequestAsync = function (url, options) {
8262
8343
  return __awaiter$1(this, void 0, void 0, function () {
8263
- var _this = this;
8264
8344
  return __generator$1(this, function (_a) {
8265
- switch (_a.label) {
8266
- case 0: return [4 /*yield*/, this.validateDbIsOpen()];
8267
- case 1:
8268
- _a.sent();
8269
- return [2 /*return*/, new Promise(function (resolve, reject) {
8270
- // TODO: Add timeouts?
8271
- if (!_this.db) {
8272
- return reject(BrowserAuthError.createDatabaseNotOpenError());
8273
- }
8274
- var transaction = _this.db.transaction([_this.tableName], "readwrite");
8275
- var objectStore = transaction.objectStore(_this.tableName);
8276
- var dbPut = objectStore.put(payload, key);
8277
- dbPut.addEventListener("success", function () { return resolve(); });
8278
- dbPut.addEventListener("error", function (e) { return reject(e); });
8279
- })];
8280
- }
8345
+ return [2 /*return*/, this.sendRequestAsync(url, HTTP_REQUEST_TYPE.GET, options)];
8281
8346
  });
8282
8347
  });
8283
8348
  };
8284
8349
  /**
8285
- * Removes item from IndexedDB under given key
8286
- * @param key
8350
+ * XhrClient for REST endpoints - Post request
8351
+ * @param url
8352
+ * @param headers
8353
+ * @param body
8287
8354
  */
8288
- DatabaseStorage.prototype.removeItem = function (key) {
8355
+ XhrClient.prototype.sendPostRequestAsync = function (url, options) {
8289
8356
  return __awaiter$1(this, void 0, void 0, function () {
8290
- var _this = this;
8291
8357
  return __generator$1(this, function (_a) {
8292
- switch (_a.label) {
8293
- case 0: return [4 /*yield*/, this.validateDbIsOpen()];
8294
- case 1:
8295
- _a.sent();
8296
- return [2 /*return*/, new Promise(function (resolve, reject) {
8297
- if (!_this.db) {
8298
- return reject(BrowserAuthError.createDatabaseNotOpenError());
8299
- }
8300
- var transaction = _this.db.transaction([_this.tableName], "readwrite");
8301
- var objectStore = transaction.objectStore(_this.tableName);
8302
- var dbDelete = objectStore.delete(key);
8303
- dbDelete.addEventListener("success", function () { return resolve(); });
8304
- dbDelete.addEventListener("error", function (e) { return reject(e); });
8305
- })];
8306
- }
8358
+ return [2 /*return*/, this.sendRequestAsync(url, HTTP_REQUEST_TYPE.POST, options)];
8307
8359
  });
8308
8360
  });
8309
8361
  };
8310
8362
  /**
8311
- * Get all the keys from the storage object as an iterable array of strings.
8363
+ * Helper for XhrClient requests.
8364
+ * @param url
8365
+ * @param method
8366
+ * @param options
8312
8367
  */
8313
- DatabaseStorage.prototype.getKeys = function () {
8314
- return __awaiter$1(this, void 0, void 0, function () {
8315
- var _this = this;
8316
- return __generator$1(this, function (_a) {
8317
- switch (_a.label) {
8318
- case 0: return [4 /*yield*/, this.validateDbIsOpen()];
8319
- case 1:
8320
- _a.sent();
8321
- return [2 /*return*/, new Promise(function (resolve, reject) {
8322
- if (!_this.db) {
8323
- return reject(BrowserAuthError.createDatabaseNotOpenError());
8324
- }
8325
- var transaction = _this.db.transaction([_this.tableName], "readonly");
8326
- var objectStore = transaction.objectStore(_this.tableName);
8327
- var dbGetKeys = objectStore.getAllKeys();
8328
- dbGetKeys.addEventListener("success", function (e) {
8329
- var event = e;
8330
- resolve(event.target.result);
8331
- });
8332
- dbGetKeys.addEventListener("error", function (e) { return reject(e); });
8333
- })];
8368
+ XhrClient.prototype.sendRequestAsync = function (url, method, options) {
8369
+ var _this = this;
8370
+ return new Promise(function (resolve, reject) {
8371
+ var xhr = new XMLHttpRequest();
8372
+ xhr.open(method, url, /* async: */ true);
8373
+ _this.setXhrHeaders(xhr, options);
8374
+ xhr.onload = function () {
8375
+ if (xhr.status < 200 || xhr.status >= 300) {
8376
+ if (method === HTTP_REQUEST_TYPE.POST) {
8377
+ reject(BrowserAuthError.createPostRequestFailedError("Failed with status " + xhr.status, url));
8378
+ }
8379
+ else {
8380
+ reject(BrowserAuthError.createGetRequestFailedError("Failed with status " + xhr.status, url));
8381
+ }
8334
8382
  }
8335
- });
8383
+ try {
8384
+ var jsonResponse = JSON.parse(xhr.responseText);
8385
+ var networkResponse = {
8386
+ headers: _this.getHeaderDict(xhr),
8387
+ body: jsonResponse,
8388
+ status: xhr.status
8389
+ };
8390
+ resolve(networkResponse);
8391
+ }
8392
+ catch (e) {
8393
+ reject(BrowserAuthError.createFailedToParseNetworkResponseError(url));
8394
+ }
8395
+ };
8396
+ xhr.onerror = function () {
8397
+ if (window.navigator.onLine) {
8398
+ if (method === HTTP_REQUEST_TYPE.POST) {
8399
+ reject(BrowserAuthError.createPostRequestFailedError("Failed with status " + xhr.status, url));
8400
+ }
8401
+ else {
8402
+ reject(BrowserAuthError.createGetRequestFailedError("Failed with status " + xhr.status, url));
8403
+ }
8404
+ }
8405
+ else {
8406
+ reject(BrowserAuthError.createNoNetworkConnectivityError());
8407
+ }
8408
+ };
8409
+ if (method === HTTP_REQUEST_TYPE.POST && options && options.body) {
8410
+ xhr.send(options.body);
8411
+ }
8412
+ else if (method === HTTP_REQUEST_TYPE.GET) {
8413
+ xhr.send();
8414
+ }
8415
+ else {
8416
+ throw BrowserAuthError.createHttpMethodNotImplementedError(method);
8417
+ }
8336
8418
  });
8337
8419
  };
8338
8420
  /**
8339
- *
8340
- * Checks whether there is an object under the search key in the object store
8421
+ * Helper to set XHR headers for request.
8422
+ * @param xhr
8423
+ * @param options
8341
8424
  */
8342
- DatabaseStorage.prototype.containsKey = function (key) {
8343
- return __awaiter$1(this, void 0, void 0, function () {
8344
- var _this = this;
8345
- return __generator$1(this, function (_a) {
8346
- switch (_a.label) {
8347
- case 0: return [4 /*yield*/, this.validateDbIsOpen()];
8348
- case 1:
8349
- _a.sent();
8350
- return [2 /*return*/, new Promise(function (resolve, reject) {
8351
- if (!_this.db) {
8352
- return reject(BrowserAuthError.createDatabaseNotOpenError());
8353
- }
8354
- var transaction = _this.db.transaction([_this.tableName], "readonly");
8355
- var objectStore = transaction.objectStore(_this.tableName);
8356
- var dbContainsKey = objectStore.count(key);
8357
- dbContainsKey.addEventListener("success", function (e) {
8358
- var event = e;
8359
- resolve(event.target.result === 1);
8360
- });
8361
- dbContainsKey.addEventListener("error", function (e) { return reject(e); });
8362
- })];
8363
- }
8425
+ XhrClient.prototype.setXhrHeaders = function (xhr, options) {
8426
+ if (options && options.headers) {
8427
+ var headers_1 = options.headers;
8428
+ Object.keys(headers_1).forEach(function (key) {
8429
+ xhr.setRequestHeader(key, headers_1[key]);
8364
8430
  });
8365
- });
8431
+ }
8366
8432
  };
8367
8433
  /**
8368
- * Deletes the MSAL database. The database is deleted rather than cleared to make it possible
8369
- * for client applications to downgrade to a previous MSAL version without worrying about forward compatibility issues
8370
- * with IndexedDB database versions.
8434
+ * Gets a string map of the headers received in the response.
8435
+ *
8436
+ * Algorithm comes from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders
8437
+ * @param xhr
8371
8438
  */
8372
- DatabaseStorage.prototype.deleteDatabase = function () {
8373
- return __awaiter$1(this, void 0, void 0, function () {
8374
- return __generator$1(this, function (_a) {
8375
- return [2 /*return*/, new Promise(function (resolve, reject) {
8376
- var deleteDbRequest = window.indexedDB.deleteDatabase(DB_NAME);
8377
- deleteDbRequest.addEventListener("success", function () { return resolve(true); });
8378
- deleteDbRequest.addEventListener("error", function () { return reject(false); });
8379
- })];
8380
- });
8381
- });
8382
- };
8383
- return DatabaseStorage;
8384
- }());
8385
-
8386
- /*
8387
- * Copyright (c) Microsoft Corporation. All rights reserved.
8388
- * Licensed under the MIT License.
8389
- */
8390
- var MemoryStorage = /** @class */ (function () {
8391
- function MemoryStorage() {
8392
- this.cache = new Map();
8393
- }
8394
- MemoryStorage.prototype.getItem = function (key) {
8395
- return this.cache.get(key) || null;
8396
- };
8397
- MemoryStorage.prototype.setItem = function (key, value) {
8398
- this.cache.set(key, value);
8399
- };
8400
- MemoryStorage.prototype.removeItem = function (key) {
8401
- this.cache.delete(key);
8402
- };
8403
- MemoryStorage.prototype.getKeys = function () {
8404
- var cacheKeys = [];
8405
- this.cache.forEach(function (value, key) {
8406
- cacheKeys.push(key);
8439
+ XhrClient.prototype.getHeaderDict = function (xhr) {
8440
+ var headerString = xhr.getAllResponseHeaders();
8441
+ var headerArr = headerString.trim().split(/[\r\n]+/);
8442
+ var headerDict = {};
8443
+ headerArr.forEach(function (value) {
8444
+ var parts = value.split(": ");
8445
+ var headerName = parts.shift();
8446
+ var headerVal = parts.join(": ");
8447
+ if (headerName && headerVal) {
8448
+ headerDict[headerName] = headerVal;
8449
+ }
8407
8450
  });
8408
- return cacheKeys;
8409
- };
8410
- MemoryStorage.prototype.containsKey = function (key) {
8411
- return this.cache.has(key);
8412
- };
8413
- MemoryStorage.prototype.clear = function () {
8414
- this.cache.clear();
8451
+ return headerDict;
8415
8452
  };
8416
- return MemoryStorage;
8453
+ return XhrClient;
8417
8454
  }());
8418
8455
 
8419
8456
  /*
@@ -8421,185 +8458,126 @@
8421
8458
  * Licensed under the MIT License.
8422
8459
  */
8423
8460
  /**
8424
- * This class allows MSAL to store artifacts asynchronously using the DatabaseStorage IndexedDB wrapper,
8425
- * backed up with the more volatile MemoryStorage object for cases in which IndexedDB may be unavailable.
8461
+ * Utility class for browser specific functions
8426
8462
  */
8427
- var AsyncMemoryStorage = /** @class */ (function () {
8428
- function AsyncMemoryStorage(logger) {
8429
- this.inMemoryCache = new MemoryStorage();
8430
- this.indexedDBCache = new DatabaseStorage();
8431
- this.logger = logger;
8463
+ var BrowserUtils = /** @class */ (function () {
8464
+ function BrowserUtils() {
8432
8465
  }
8433
- AsyncMemoryStorage.prototype.handleDatabaseAccessError = function (error) {
8434
- if (error instanceof BrowserAuthError && error.errorCode === BrowserAuthErrorMessage.databaseUnavailable.code) {
8435
- this.logger.error("Could not access persistent storage. This may be caused by browser privacy features which block persistent storage in third-party contexts.");
8466
+ // #region Window Navigation and URL management
8467
+ /**
8468
+ * Clears hash from window url.
8469
+ */
8470
+ BrowserUtils.clearHash = function (contentWindow) {
8471
+ // Office.js sets history.replaceState to null
8472
+ contentWindow.location.hash = Constants.EMPTY_STRING;
8473
+ if (typeof contentWindow.history.replaceState === "function") {
8474
+ // Full removes "#" from url
8475
+ contentWindow.history.replaceState(null, Constants.EMPTY_STRING, "" + contentWindow.location.origin + contentWindow.location.pathname + contentWindow.location.search);
8436
8476
  }
8437
8477
  };
8438
8478
  /**
8439
- * Get the item matching the given key. Tries in-memory cache first, then in the asynchronous
8440
- * storage object if item isn't found in-memory.
8441
- * @param key
8479
+ * Replaces current hash with hash from provided url
8442
8480
  */
8443
- AsyncMemoryStorage.prototype.getItem = function (key) {
8444
- return __awaiter$1(this, void 0, void 0, function () {
8445
- var item, e_1;
8446
- return __generator$1(this, function (_a) {
8447
- switch (_a.label) {
8448
- case 0:
8449
- item = this.inMemoryCache.getItem(key);
8450
- if (!!item) return [3 /*break*/, 4];
8451
- _a.label = 1;
8452
- case 1:
8453
- _a.trys.push([1, 3, , 4]);
8454
- this.logger.verbose("Queried item not found in in-memory cache, now querying persistent storage.");
8455
- return [4 /*yield*/, this.indexedDBCache.getItem(key)];
8456
- case 2: return [2 /*return*/, _a.sent()];
8457
- case 3:
8458
- e_1 = _a.sent();
8459
- this.handleDatabaseAccessError(e_1);
8460
- return [3 /*break*/, 4];
8461
- case 4: return [2 /*return*/, item];
8462
- }
8463
- });
8464
- });
8481
+ BrowserUtils.replaceHash = function (url) {
8482
+ var urlParts = url.split("#");
8483
+ urlParts.shift(); // Remove part before the hash
8484
+ window.location.hash = urlParts.length > 0 ? urlParts.join("#") : "";
8465
8485
  };
8466
8486
  /**
8467
- * Sets the item in the in-memory cache and then tries to set it in the asynchronous
8468
- * storage object with the given key.
8469
- * @param key
8470
- * @param value
8487
+ * Returns boolean of whether the current window is in an iframe or not.
8471
8488
  */
8472
- AsyncMemoryStorage.prototype.setItem = function (key, value) {
8473
- return __awaiter$1(this, void 0, void 0, function () {
8474
- var e_2;
8475
- return __generator$1(this, function (_a) {
8476
- switch (_a.label) {
8477
- case 0:
8478
- this.inMemoryCache.setItem(key, value);
8479
- _a.label = 1;
8480
- case 1:
8481
- _a.trys.push([1, 3, , 4]);
8482
- return [4 /*yield*/, this.indexedDBCache.setItem(key, value)];
8483
- case 2:
8484
- _a.sent();
8485
- return [3 /*break*/, 4];
8486
- case 3:
8487
- e_2 = _a.sent();
8488
- this.handleDatabaseAccessError(e_2);
8489
- return [3 /*break*/, 4];
8490
- case 4: return [2 /*return*/];
8491
- }
8492
- });
8493
- });
8489
+ BrowserUtils.isInIframe = function () {
8490
+ return window.parent !== window;
8494
8491
  };
8495
8492
  /**
8496
- * Removes the item matching the key from the in-memory cache, then tries to remove it from the asynchronous storage object.
8497
- * @param key
8493
+ * Returns boolean of whether or not the current window is a popup opened by msal
8498
8494
  */
8499
- AsyncMemoryStorage.prototype.removeItem = function (key) {
8500
- return __awaiter$1(this, void 0, void 0, function () {
8501
- var e_3;
8502
- return __generator$1(this, function (_a) {
8503
- switch (_a.label) {
8504
- case 0:
8505
- this.inMemoryCache.removeItem(key);
8506
- _a.label = 1;
8507
- case 1:
8508
- _a.trys.push([1, 3, , 4]);
8509
- return [4 /*yield*/, this.indexedDBCache.removeItem(key)];
8510
- case 2:
8511
- _a.sent();
8512
- return [3 /*break*/, 4];
8513
- case 3:
8514
- e_3 = _a.sent();
8515
- this.handleDatabaseAccessError(e_3);
8516
- return [3 /*break*/, 4];
8517
- case 4: return [2 /*return*/];
8518
- }
8519
- });
8520
- });
8495
+ BrowserUtils.isInPopup = function () {
8496
+ return typeof window !== "undefined" && !!window.opener &&
8497
+ window.opener !== window &&
8498
+ typeof window.name === "string" &&
8499
+ window.name.indexOf(BrowserConstants.POPUP_NAME_PREFIX + ".") === 0;
8521
8500
  };
8501
+ // #endregion
8522
8502
  /**
8523
- * Get all the keys from the in-memory cache as an iterable array of strings. If no keys are found, query the keys in the
8524
- * asynchronous storage object.
8503
+ * Returns current window URL as redirect uri
8525
8504
  */
8526
- AsyncMemoryStorage.prototype.getKeys = function () {
8527
- return __awaiter$1(this, void 0, void 0, function () {
8528
- var cacheKeys, e_4;
8529
- return __generator$1(this, function (_a) {
8530
- switch (_a.label) {
8531
- case 0:
8532
- cacheKeys = this.inMemoryCache.getKeys();
8533
- if (!(cacheKeys.length === 0)) return [3 /*break*/, 4];
8534
- _a.label = 1;
8535
- case 1:
8536
- _a.trys.push([1, 3, , 4]);
8537
- this.logger.verbose("In-memory cache is empty, now querying persistent storage.");
8538
- return [4 /*yield*/, this.indexedDBCache.getKeys()];
8539
- case 2: return [2 /*return*/, _a.sent()];
8540
- case 3:
8541
- e_4 = _a.sent();
8542
- this.handleDatabaseAccessError(e_4);
8543
- return [3 /*break*/, 4];
8544
- case 4: return [2 /*return*/, cacheKeys];
8545
- }
8546
- });
8547
- });
8505
+ BrowserUtils.getCurrentUri = function () {
8506
+ return window.location.href.split("?")[0].split("#")[0];
8548
8507
  };
8549
8508
  /**
8550
- * Returns true or false if the given key is present in the cache.
8551
- * @param key
8509
+ * Gets the homepage url for the current window location.
8552
8510
  */
8553
- AsyncMemoryStorage.prototype.containsKey = function (key) {
8554
- return __awaiter$1(this, void 0, void 0, function () {
8555
- var containsKey, e_5;
8556
- return __generator$1(this, function (_a) {
8557
- switch (_a.label) {
8558
- case 0:
8559
- containsKey = this.inMemoryCache.containsKey(key);
8560
- if (!!containsKey) return [3 /*break*/, 4];
8561
- _a.label = 1;
8562
- case 1:
8563
- _a.trys.push([1, 3, , 4]);
8564
- this.logger.verbose("Key not found in in-memory cache, now querying persistent storage.");
8565
- return [4 /*yield*/, this.indexedDBCache.containsKey(key)];
8566
- case 2: return [2 /*return*/, _a.sent()];
8567
- case 3:
8568
- e_5 = _a.sent();
8569
- this.handleDatabaseAccessError(e_5);
8570
- return [3 /*break*/, 4];
8571
- case 4: return [2 /*return*/, containsKey];
8572
- }
8573
- });
8574
- });
8511
+ BrowserUtils.getHomepage = function () {
8512
+ var currentUrl = new UrlString(window.location.href);
8513
+ var urlComponents = currentUrl.getUrlComponents();
8514
+ return urlComponents.Protocol + "//" + urlComponents.HostNameAndPort + "/";
8575
8515
  };
8576
8516
  /**
8577
- * Clears in-memory Map and tries to delete the IndexedDB database.
8517
+ * Returns best compatible network client object.
8578
8518
  */
8579
- AsyncMemoryStorage.prototype.clear = function () {
8580
- return __awaiter$1(this, void 0, void 0, function () {
8581
- var e_6;
8582
- return __generator$1(this, function (_a) {
8583
- switch (_a.label) {
8584
- case 0:
8585
- this.inMemoryCache.clear();
8586
- _a.label = 1;
8587
- case 1:
8588
- _a.trys.push([1, 3, , 4]);
8589
- return [4 /*yield*/, this.indexedDBCache.deleteDatabase()];
8590
- case 2:
8591
- _a.sent();
8592
- return [3 /*break*/, 4];
8593
- case 3:
8594
- e_6 = _a.sent();
8595
- this.handleDatabaseAccessError(e_6);
8596
- return [3 /*break*/, 4];
8597
- case 4: return [2 /*return*/];
8598
- }
8599
- });
8600
- });
8519
+ BrowserUtils.getBrowserNetworkClient = function () {
8520
+ if (window.fetch && window.Headers) {
8521
+ return new FetchClient();
8522
+ }
8523
+ else {
8524
+ return new XhrClient();
8525
+ }
8601
8526
  };
8602
- return AsyncMemoryStorage;
8527
+ /**
8528
+ * Throws error if we have completed an auth and are
8529
+ * attempting another auth request inside an iframe.
8530
+ */
8531
+ BrowserUtils.blockReloadInHiddenIframes = function () {
8532
+ var isResponseHash = UrlString.hashContainsKnownProperties(window.location.hash);
8533
+ // return an error if called from the hidden iframe created by the msal js silent calls
8534
+ if (isResponseHash && BrowserUtils.isInIframe()) {
8535
+ throw BrowserAuthError.createBlockReloadInHiddenIframeError();
8536
+ }
8537
+ };
8538
+ /**
8539
+ * Block redirect operations in iframes unless explicitly allowed
8540
+ * @param interactionType Interaction type for the request
8541
+ * @param allowRedirectInIframe Config value to allow redirects when app is inside an iframe
8542
+ */
8543
+ BrowserUtils.blockRedirectInIframe = function (interactionType, allowRedirectInIframe) {
8544
+ var isIframedApp = BrowserUtils.isInIframe();
8545
+ if (interactionType === exports.InteractionType.Redirect && isIframedApp && !allowRedirectInIframe) {
8546
+ // If we are not in top frame, we shouldn't redirect. This is also handled by the service.
8547
+ throw BrowserAuthError.createRedirectInIframeError(isIframedApp);
8548
+ }
8549
+ };
8550
+ /**
8551
+ * Block redirectUri loaded in popup from calling AcquireToken APIs
8552
+ */
8553
+ BrowserUtils.blockAcquireTokenInPopups = function () {
8554
+ // Popups opened by msal popup APIs are given a name that starts with "msal."
8555
+ if (BrowserUtils.isInPopup()) {
8556
+ throw BrowserAuthError.createBlockAcquireTokenInPopupsError();
8557
+ }
8558
+ };
8559
+ /**
8560
+ * Throws error if token requests are made in non-browser environment
8561
+ * @param isBrowserEnvironment Flag indicating if environment is a browser.
8562
+ */
8563
+ BrowserUtils.blockNonBrowserEnvironment = function (isBrowserEnvironment) {
8564
+ if (!isBrowserEnvironment) {
8565
+ throw BrowserAuthError.createNonBrowserEnvironmentError();
8566
+ }
8567
+ };
8568
+ /**
8569
+ * Returns boolean of whether current browser is an Internet Explorer or Edge browser.
8570
+ */
8571
+ BrowserUtils.detectIEOrEdge = function () {
8572
+ var ua = window.navigator.userAgent;
8573
+ var msie = ua.indexOf("MSIE ");
8574
+ var msie11 = ua.indexOf("Trident/");
8575
+ var msedge = ua.indexOf("Edge/");
8576
+ var isIE = msie > 0 || msie11 > 0;
8577
+ var isEdge = msedge > 0;
8578
+ return isIE || isEdge;
8579
+ };
8580
+ return BrowserUtils;
8603
8581
  }());
8604
8582
 
8605
8583
  /*
@@ -8607,352 +8585,374 @@
8607
8585
  * Licensed under the MIT License.
8608
8586
  */
8609
8587
  /**
8610
- * This class implements MSAL's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and
8611
- * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
8588
+ * BrowserAuthErrorMessage class containing string constants used by error codes and messages.
8612
8589
  */
8613
- var CryptoOps = /** @class */ (function () {
8614
- function CryptoOps(logger) {
8615
- this.logger = logger;
8616
- // Browser crypto needs to be validated first before any other classes can be set.
8617
- this.browserCrypto = new BrowserCrypto(this.logger);
8618
- this.b64Encode = new Base64Encode();
8619
- this.b64Decode = new Base64Decode();
8620
- this.guidGenerator = new GuidGenerator(this.browserCrypto);
8621
- this.pkceGenerator = new PkceGenerator(this.browserCrypto);
8622
- this.cache = {
8623
- asymmetricKeys: new AsyncMemoryStorage(this.logger),
8624
- symmetricKeys: new AsyncMemoryStorage(this.logger)
8625
- };
8590
+ var BrowserConfigurationAuthErrorMessage = {
8591
+ redirectUriNotSet: {
8592
+ code: "redirect_uri_empty",
8593
+ desc: "A redirect URI is required for all calls, and none has been set."
8594
+ },
8595
+ postLogoutUriNotSet: {
8596
+ code: "post_logout_uri_empty",
8597
+ desc: "A post logout redirect has not been set."
8598
+ },
8599
+ storageNotSupportedError: {
8600
+ code: "storage_not_supported",
8601
+ desc: "Given storage configuration option was not supported."
8602
+ },
8603
+ noRedirectCallbacksSet: {
8604
+ code: "no_redirect_callbacks",
8605
+ desc: "No redirect callbacks have been set. Please call setRedirectCallbacks() with the appropriate function arguments before continuing. " +
8606
+ "More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics."
8607
+ },
8608
+ invalidCallbackObject: {
8609
+ code: "invalid_callback_object",
8610
+ desc: "The object passed for the callback was invalid. " +
8611
+ "More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics."
8612
+ },
8613
+ stubPcaInstanceCalled: {
8614
+ code: "stubbed_public_client_application_called",
8615
+ desc: "Stub instance of Public Client Application was called. If using msal-react, please ensure context is not used without a provider. For more visit: aka.ms/msaljs/browser-errors"
8616
+ },
8617
+ inMemRedirectUnavailable: {
8618
+ code: "in_mem_redirect_unavailable",
8619
+ desc: "Redirect cannot be supported. In-memory storage was selected and storeAuthStateInCookie=false, which would cause the library to be unable to handle the incoming hash. If you would like to use the redirect API, please use session/localStorage or set storeAuthStateInCookie=true."
8620
+ }
8621
+ };
8622
+ /**
8623
+ * Browser library error class thrown by the MSAL.js library for SPAs
8624
+ */
8625
+ var BrowserConfigurationAuthError = /** @class */ (function (_super) {
8626
+ __extends$1(BrowserConfigurationAuthError, _super);
8627
+ function BrowserConfigurationAuthError(errorCode, errorMessage) {
8628
+ var _this = _super.call(this, errorCode, errorMessage) || this;
8629
+ _this.name = "BrowserConfigurationAuthError";
8630
+ Object.setPrototypeOf(_this, BrowserConfigurationAuthError.prototype);
8631
+ return _this;
8626
8632
  }
8627
8633
  /**
8628
- * Creates a new random GUID - used to populate state and nonce.
8629
- * @returns string (GUID)
8634
+ * Creates an error thrown when the redirect uri is empty (not set by caller)
8630
8635
  */
8631
- CryptoOps.prototype.createNewGuid = function () {
8632
- return this.guidGenerator.generateGuid();
8636
+ BrowserConfigurationAuthError.createRedirectUriEmptyError = function () {
8637
+ return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.redirectUriNotSet.code, BrowserConfigurationAuthErrorMessage.redirectUriNotSet.desc);
8633
8638
  };
8634
8639
  /**
8635
- * Encodes input string to base64.
8636
- * @param input
8640
+ * Creates an error thrown when the post-logout redirect uri is empty (not set by caller)
8637
8641
  */
8638
- CryptoOps.prototype.base64Encode = function (input) {
8639
- return this.b64Encode.encode(input);
8642
+ BrowserConfigurationAuthError.createPostLogoutRedirectUriEmptyError = function () {
8643
+ return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.postLogoutUriNotSet.code, BrowserConfigurationAuthErrorMessage.postLogoutUriNotSet.desc);
8640
8644
  };
8641
8645
  /**
8642
- * Decodes input string from base64.
8643
- * @param input
8646
+ * Creates error thrown when given storage location is not supported.
8647
+ * @param givenStorageLocation
8644
8648
  */
8645
- CryptoOps.prototype.base64Decode = function (input) {
8646
- return this.b64Decode.decode(input);
8649
+ BrowserConfigurationAuthError.createStorageNotSupportedError = function (givenStorageLocation) {
8650
+ return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.storageNotSupportedError.code, BrowserConfigurationAuthErrorMessage.storageNotSupportedError.desc + " Given Location: " + givenStorageLocation);
8647
8651
  };
8648
8652
  /**
8649
- * Generates PKCE codes used in Authorization Code Flow.
8653
+ * Creates error thrown when redirect callbacks are not set before calling loginRedirect() or acquireTokenRedirect().
8650
8654
  */
8651
- CryptoOps.prototype.generatePkceCodes = function () {
8652
- return __awaiter$1(this, void 0, void 0, function () {
8653
- return __generator$1(this, function (_a) {
8654
- return [2 /*return*/, this.pkceGenerator.generateCodes()];
8655
- });
8656
- });
8655
+ BrowserConfigurationAuthError.createRedirectCallbacksNotSetError = function () {
8656
+ return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.noRedirectCallbacksSet.code, BrowserConfigurationAuthErrorMessage.noRedirectCallbacksSet.desc);
8657
8657
  };
8658
8658
  /**
8659
- * Generates a keypair, stores it and returns a thumbprint
8660
- * @param request
8659
+ * Creates error thrown when the stub instance of PublicClientApplication is called.
8661
8660
  */
8662
- CryptoOps.prototype.getPublicKeyThumbprint = function (request) {
8663
- return __awaiter$1(this, void 0, void 0, function () {
8664
- var keyPair, publicKeyJwk, pubKeyThumprintObj, publicJwkString, publicJwkBuffer, publicJwkHash, privateKeyJwk, unextractablePrivateKey;
8665
- return __generator$1(this, function (_a) {
8666
- switch (_a.label) {
8667
- case 0: return [4 /*yield*/, this.browserCrypto.generateKeyPair(CryptoOps.EXTRACTABLE, CryptoOps.POP_KEY_USAGES)];
8668
- case 1:
8669
- keyPair = _a.sent();
8670
- return [4 /*yield*/, this.browserCrypto.exportJwk(keyPair.publicKey)];
8671
- case 2:
8672
- publicKeyJwk = _a.sent();
8673
- pubKeyThumprintObj = {
8674
- e: publicKeyJwk.e,
8675
- kty: publicKeyJwk.kty,
8676
- n: publicKeyJwk.n
8677
- };
8678
- publicJwkString = BrowserCrypto.getJwkString(pubKeyThumprintObj);
8679
- return [4 /*yield*/, this.browserCrypto.sha256Digest(publicJwkString)];
8680
- case 3:
8681
- publicJwkBuffer = _a.sent();
8682
- publicJwkHash = this.b64Encode.urlEncodeArr(new Uint8Array(publicJwkBuffer));
8683
- return [4 /*yield*/, this.browserCrypto.exportJwk(keyPair.privateKey)];
8684
- case 4:
8685
- privateKeyJwk = _a.sent();
8686
- return [4 /*yield*/, this.browserCrypto.importJwk(privateKeyJwk, false, ["sign"])];
8687
- case 5:
8688
- unextractablePrivateKey = _a.sent();
8689
- // Store Keypair data in keystore
8690
- return [4 /*yield*/, this.cache.asymmetricKeys.setItem(publicJwkHash, {
8691
- privateKey: unextractablePrivateKey,
8692
- publicKey: keyPair.publicKey,
8693
- requestMethod: request.resourceRequestMethod,
8694
- requestUri: request.resourceRequestUri
8695
- })];
8696
- case 6:
8697
- // Store Keypair data in keystore
8698
- _a.sent();
8699
- return [2 /*return*/, publicJwkHash];
8700
- }
8701
- });
8702
- });
8703
- };
8704
- /**
8705
- * Removes cryptographic keypair from key store matching the keyId passed in
8706
- * @param kid
8707
- */
8708
- CryptoOps.prototype.removeTokenBindingKey = function (kid) {
8709
- return __awaiter$1(this, void 0, void 0, function () {
8710
- var keyFound;
8711
- return __generator$1(this, function (_a) {
8712
- switch (_a.label) {
8713
- case 0: return [4 /*yield*/, this.cache.asymmetricKeys.removeItem(kid)];
8714
- case 1:
8715
- _a.sent();
8716
- return [4 /*yield*/, this.cache.asymmetricKeys.containsKey(kid)];
8717
- case 2:
8718
- keyFound = _a.sent();
8719
- return [2 /*return*/, !keyFound];
8720
- }
8721
- });
8722
- });
8723
- };
8724
- /**
8725
- * Removes all cryptographic keys from IndexedDB storage
8726
- */
8727
- CryptoOps.prototype.clearKeystore = function () {
8728
- return __awaiter$1(this, void 0, void 0, function () {
8729
- var dataStoreNames, databaseStorage, _a;
8730
- return __generator$1(this, function (_b) {
8731
- switch (_b.label) {
8732
- case 0:
8733
- dataStoreNames = Object.keys(this.cache);
8734
- databaseStorage = this.cache[dataStoreNames[0]];
8735
- if (!databaseStorage) return [3 /*break*/, 2];
8736
- return [4 /*yield*/, databaseStorage.deleteDatabase()];
8737
- case 1:
8738
- _a = _b.sent();
8739
- return [3 /*break*/, 3];
8740
- case 2:
8741
- _a = false;
8742
- _b.label = 3;
8743
- case 3: return [2 /*return*/, _a];
8744
- }
8745
- });
8746
- });
8661
+ BrowserConfigurationAuthError.createStubPcaInstanceCalledError = function () {
8662
+ return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.stubPcaInstanceCalled.code, BrowserConfigurationAuthErrorMessage.stubPcaInstanceCalled.desc);
8747
8663
  };
8748
- /**
8749
- * Signs the given object as a jwt payload with private key retrieved by given kid.
8750
- * @param payload
8751
- * @param kid
8664
+ /*
8665
+ * Create an error thrown when in-memory storage is used and storeAuthStateInCookie=false.
8752
8666
  */
8753
- CryptoOps.prototype.signJwt = function (payload, kid) {
8754
- return __awaiter$1(this, void 0, void 0, function () {
8755
- var cachedKeyPair, publicKeyJwk, publicKeyJwkString, header, encodedHeader, encodedPayload, tokenString, tokenBuffer, signatureBuffer, encodedSignature;
8756
- return __generator$1(this, function (_a) {
8757
- switch (_a.label) {
8758
- case 0: return [4 /*yield*/, this.cache.asymmetricKeys.getItem(kid)];
8759
- case 1:
8760
- cachedKeyPair = _a.sent();
8761
- if (!cachedKeyPair) {
8762
- throw BrowserAuthError.createSigningKeyNotFoundInStorageError(kid);
8763
- }
8764
- return [4 /*yield*/, this.browserCrypto.exportJwk(cachedKeyPair.publicKey)];
8765
- case 2:
8766
- publicKeyJwk = _a.sent();
8767
- publicKeyJwkString = BrowserCrypto.getJwkString(publicKeyJwk);
8768
- header = {
8769
- alg: publicKeyJwk.alg,
8770
- type: KEY_FORMAT_JWK
8771
- };
8772
- encodedHeader = this.b64Encode.urlEncode(JSON.stringify(header));
8773
- // Generate payload
8774
- payload.cnf = {
8775
- jwk: JSON.parse(publicKeyJwkString)
8776
- };
8777
- encodedPayload = this.b64Encode.urlEncode(JSON.stringify(payload));
8778
- tokenString = encodedHeader + "." + encodedPayload;
8779
- tokenBuffer = BrowserStringUtils.stringToArrayBuffer(tokenString);
8780
- return [4 /*yield*/, this.browserCrypto.sign(cachedKeyPair.privateKey, tokenBuffer)];
8781
- case 3:
8782
- signatureBuffer = _a.sent();
8783
- encodedSignature = this.b64Encode.urlEncodeArr(new Uint8Array(signatureBuffer));
8784
- return [2 /*return*/, tokenString + "." + encodedSignature];
8785
- }
8786
- });
8787
- });
8667
+ BrowserConfigurationAuthError.createInMemoryRedirectUnavailableError = function () {
8668
+ return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.inMemRedirectUnavailable.code, BrowserConfigurationAuthErrorMessage.inMemRedirectUnavailable.desc);
8788
8669
  };
8789
- CryptoOps.POP_KEY_USAGES = ["sign", "verify"];
8790
- CryptoOps.EXTRACTABLE = true;
8791
- return CryptoOps;
8792
- }());
8670
+ return BrowserConfigurationAuthError;
8671
+ }(AuthError));
8793
8672
 
8794
8673
  /*
8795
8674
  * Copyright (c) Microsoft Corporation. All rights reserved.
8796
8675
  * Licensed under the MIT License.
8797
8676
  */
8798
- /**
8799
- * BrowserAuthErrorMessage class containing string constants used by error codes and messages.
8800
- */
8801
- var BrowserConfigurationAuthErrorMessage = {
8802
- redirectUriNotSet: {
8803
- code: "redirect_uri_empty",
8804
- desc: "A redirect URI is required for all calls, and none has been set."
8677
+ var stubbedPublicClientApplication = {
8678
+ acquireTokenPopup: function () {
8679
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8805
8680
  },
8806
- postLogoutUriNotSet: {
8807
- code: "post_logout_uri_empty",
8808
- desc: "A post logout redirect has not been set."
8681
+ acquireTokenRedirect: function () {
8682
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8809
8683
  },
8810
- storageNotSupportedError: {
8811
- code: "storage_not_supported",
8812
- desc: "Given storage configuration option was not supported."
8684
+ acquireTokenSilent: function () {
8685
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8813
8686
  },
8814
- noRedirectCallbacksSet: {
8815
- code: "no_redirect_callbacks",
8816
- desc: "No redirect callbacks have been set. Please call setRedirectCallbacks() with the appropriate function arguments before continuing. " +
8817
- "More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics."
8687
+ getAllAccounts: function () {
8688
+ return [];
8818
8689
  },
8819
- invalidCallbackObject: {
8820
- code: "invalid_callback_object",
8821
- desc: "The object passed for the callback was invalid. " +
8822
- "More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics."
8690
+ getAccountByHomeId: function () {
8691
+ return null;
8823
8692
  },
8824
- stubPcaInstanceCalled: {
8825
- code: "stubbed_public_client_application_called",
8826
- desc: "Stub instance of Public Client Application was called. If using msal-react, please ensure context is not used without a provider. For more visit: aka.ms/msaljs/browser-errors"
8693
+ getAccountByUsername: function () {
8694
+ return null;
8827
8695
  },
8828
- inMemRedirectUnavailable: {
8829
- code: "in_mem_redirect_unavailable",
8830
- desc: "Redirect cannot be supported. In-memory storage was selected and storeAuthStateInCookie=false, which would cause the library to be unable to handle the incoming hash. If you would like to use the redirect API, please use session/localStorage or set storeAuthStateInCookie=true."
8696
+ getAccountByLocalId: function () {
8697
+ return null;
8698
+ },
8699
+ handleRedirectPromise: function () {
8700
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8701
+ },
8702
+ loginPopup: function () {
8703
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8704
+ },
8705
+ loginRedirect: function () {
8706
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8707
+ },
8708
+ logout: function () {
8709
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8710
+ },
8711
+ logoutRedirect: function () {
8712
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8713
+ },
8714
+ logoutPopup: function () {
8715
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8716
+ },
8717
+ ssoSilent: function () {
8718
+ return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
8719
+ },
8720
+ addEventCallback: function () {
8721
+ return null;
8722
+ },
8723
+ removeEventCallback: function () {
8724
+ return;
8725
+ },
8726
+ enableAccountStorageEvents: function () {
8727
+ return;
8728
+ },
8729
+ disableAccountStorageEvents: function () {
8730
+ return;
8731
+ },
8732
+ getTokenCache: function () {
8733
+ throw BrowserConfigurationAuthError.createStubPcaInstanceCalledError();
8734
+ },
8735
+ getLogger: function () {
8736
+ throw BrowserConfigurationAuthError.createStubPcaInstanceCalledError();
8737
+ },
8738
+ setLogger: function () {
8739
+ return;
8740
+ },
8741
+ setActiveAccount: function () {
8742
+ return;
8743
+ },
8744
+ getActiveAccount: function () {
8745
+ return null;
8746
+ },
8747
+ initializeWrapperLibrary: function () {
8748
+ return;
8749
+ },
8750
+ setNavigationClient: function () {
8751
+ return;
8752
+ },
8753
+ getConfiguration: function () {
8754
+ throw BrowserConfigurationAuthError.createStubPcaInstanceCalledError();
8831
8755
  }
8832
- };
8833
- /**
8834
- * Browser library error class thrown by the MSAL.js library for SPAs
8756
+ };
8757
+
8758
+ /*
8759
+ * Copyright (c) Microsoft Corporation. All rights reserved.
8760
+ * Licensed under the MIT License.
8835
8761
  */
8836
- var BrowserConfigurationAuthError = /** @class */ (function (_super) {
8837
- __extends$1(BrowserConfigurationAuthError, _super);
8838
- function BrowserConfigurationAuthError(errorCode, errorMessage) {
8839
- var _this = _super.call(this, errorCode, errorMessage) || this;
8840
- _this.name = "BrowserConfigurationAuthError";
8841
- Object.setPrototypeOf(_this, BrowserConfigurationAuthError.prototype);
8842
- return _this;
8762
+ var NavigationClient = /** @class */ (function () {
8763
+ function NavigationClient() {
8843
8764
  }
8844
8765
  /**
8845
- * Creates an error thrown when the redirect uri is empty (not set by caller)
8846
- */
8847
- BrowserConfigurationAuthError.createRedirectUriEmptyError = function () {
8848
- return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.redirectUriNotSet.code, BrowserConfigurationAuthErrorMessage.redirectUriNotSet.desc);
8849
- };
8850
- /**
8851
- * Creates an error thrown when the post-logout redirect uri is empty (not set by caller)
8852
- */
8853
- BrowserConfigurationAuthError.createPostLogoutRedirectUriEmptyError = function () {
8854
- return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.postLogoutUriNotSet.code, BrowserConfigurationAuthErrorMessage.postLogoutUriNotSet.desc);
8855
- };
8856
- /**
8857
- * Creates error thrown when given storage location is not supported.
8858
- * @param givenStorageLocation
8766
+ * Navigates to other pages within the same web application
8767
+ * @param url
8768
+ * @param options
8859
8769
  */
8860
- BrowserConfigurationAuthError.createStorageNotSupportedError = function (givenStorageLocation) {
8861
- return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.storageNotSupportedError.code, BrowserConfigurationAuthErrorMessage.storageNotSupportedError.desc + " Given Location: " + givenStorageLocation);
8770
+ NavigationClient.prototype.navigateInternal = function (url, options) {
8771
+ return NavigationClient.defaultNavigateWindow(url, options);
8862
8772
  };
8863
8773
  /**
8864
- * Creates error thrown when redirect callbacks are not set before calling loginRedirect() or acquireTokenRedirect().
8774
+ * Navigates to other pages outside the web application i.e. the Identity Provider
8775
+ * @param url
8776
+ * @param options
8865
8777
  */
8866
- BrowserConfigurationAuthError.createRedirectCallbacksNotSetError = function () {
8867
- return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.noRedirectCallbacksSet.code, BrowserConfigurationAuthErrorMessage.noRedirectCallbacksSet.desc);
8778
+ NavigationClient.prototype.navigateExternal = function (url, options) {
8779
+ return NavigationClient.defaultNavigateWindow(url, options);
8868
8780
  };
8869
8781
  /**
8870
- * Creates error thrown when the stub instance of PublicClientApplication is called.
8871
- */
8872
- BrowserConfigurationAuthError.createStubPcaInstanceCalledError = function () {
8873
- return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.stubPcaInstanceCalled.code, BrowserConfigurationAuthErrorMessage.stubPcaInstanceCalled.desc);
8874
- };
8875
- /*
8876
- * Create an error thrown when in-memory storage is used and storeAuthStateInCookie=false.
8782
+ * Default navigation implementation invoked by the internal and external functions
8783
+ * @param url
8784
+ * @param options
8877
8785
  */
8878
- BrowserConfigurationAuthError.createInMemoryRedirectUnavailableError = function () {
8879
- return new BrowserConfigurationAuthError(BrowserConfigurationAuthErrorMessage.inMemRedirectUnavailable.code, BrowserConfigurationAuthErrorMessage.inMemRedirectUnavailable.desc);
8786
+ NavigationClient.defaultNavigateWindow = function (url, options) {
8787
+ if (options.noHistory) {
8788
+ window.location.replace(url);
8789
+ }
8790
+ else {
8791
+ window.location.assign(url);
8792
+ }
8793
+ return new Promise(function (resolve) {
8794
+ setTimeout(function () {
8795
+ resolve(true);
8796
+ }, options.timeout);
8797
+ });
8880
8798
  };
8881
- return BrowserConfigurationAuthError;
8882
- }(AuthError));
8799
+ return NavigationClient;
8800
+ }());
8883
8801
 
8884
8802
  /*
8885
8803
  * Copyright (c) Microsoft Corporation. All rights reserved.
8886
8804
  * Licensed under the MIT License.
8887
8805
  */
8888
- var BrowserStorage = /** @class */ (function () {
8889
- function BrowserStorage(cacheLocation) {
8890
- this.validateWindowStorage(cacheLocation);
8891
- this.windowStorage = window[cacheLocation];
8806
+ exports.EventType = void 0;
8807
+ (function (EventType) {
8808
+ EventType["ACCOUNT_ADDED"] = "msal:accountAdded";
8809
+ EventType["ACCOUNT_REMOVED"] = "msal:accountRemoved";
8810
+ EventType["LOGIN_START"] = "msal:loginStart";
8811
+ EventType["LOGIN_SUCCESS"] = "msal:loginSuccess";
8812
+ EventType["LOGIN_FAILURE"] = "msal:loginFailure";
8813
+ EventType["ACQUIRE_TOKEN_START"] = "msal:acquireTokenStart";
8814
+ EventType["ACQUIRE_TOKEN_SUCCESS"] = "msal:acquireTokenSuccess";
8815
+ EventType["ACQUIRE_TOKEN_FAILURE"] = "msal:acquireTokenFailure";
8816
+ EventType["ACQUIRE_TOKEN_NETWORK_START"] = "msal:acquireTokenFromNetworkStart";
8817
+ EventType["SSO_SILENT_START"] = "msal:ssoSilentStart";
8818
+ EventType["SSO_SILENT_SUCCESS"] = "msal:ssoSilentSuccess";
8819
+ EventType["SSO_SILENT_FAILURE"] = "msal:ssoSilentFailure";
8820
+ EventType["HANDLE_REDIRECT_START"] = "msal:handleRedirectStart";
8821
+ EventType["HANDLE_REDIRECT_END"] = "msal:handleRedirectEnd";
8822
+ EventType["POPUP_OPENED"] = "msal:popupOpened";
8823
+ EventType["LOGOUT_START"] = "msal:logoutStart";
8824
+ EventType["LOGOUT_SUCCESS"] = "msal:logoutSuccess";
8825
+ EventType["LOGOUT_FAILURE"] = "msal:logoutFailure";
8826
+ EventType["LOGOUT_END"] = "msal:logoutEnd";
8827
+ })(exports.EventType || (exports.EventType = {}));
8828
+
8829
+ /*
8830
+ * Copyright (c) Microsoft Corporation. All rights reserved.
8831
+ * Licensed under the MIT License.
8832
+ */
8833
+ var EventMessageUtils = /** @class */ (function () {
8834
+ function EventMessageUtils() {
8892
8835
  }
8893
- BrowserStorage.prototype.validateWindowStorage = function (cacheLocation) {
8894
- if (cacheLocation !== exports.BrowserCacheLocation.LocalStorage && cacheLocation !== exports.BrowserCacheLocation.SessionStorage) {
8895
- throw BrowserConfigurationAuthError.createStorageNotSupportedError(cacheLocation);
8896
- }
8897
- var storageSupported = !!window[cacheLocation];
8898
- if (!storageSupported) {
8899
- throw BrowserConfigurationAuthError.createStorageNotSupportedError(cacheLocation);
8836
+ /**
8837
+ * Gets interaction status from event message
8838
+ * @param message
8839
+ * @param currentStatus
8840
+ */
8841
+ EventMessageUtils.getInteractionStatusFromEvent = function (message, currentStatus) {
8842
+ switch (message.eventType) {
8843
+ case exports.EventType.LOGIN_START:
8844
+ return exports.InteractionStatus.Login;
8845
+ case exports.EventType.SSO_SILENT_START:
8846
+ return exports.InteractionStatus.SsoSilent;
8847
+ case exports.EventType.ACQUIRE_TOKEN_START:
8848
+ if (message.interactionType === exports.InteractionType.Redirect || message.interactionType === exports.InteractionType.Popup) {
8849
+ return exports.InteractionStatus.AcquireToken;
8850
+ }
8851
+ break;
8852
+ case exports.EventType.HANDLE_REDIRECT_START:
8853
+ return exports.InteractionStatus.HandleRedirect;
8854
+ case exports.EventType.LOGOUT_START:
8855
+ return exports.InteractionStatus.Logout;
8856
+ case exports.EventType.SSO_SILENT_SUCCESS:
8857
+ case exports.EventType.SSO_SILENT_FAILURE:
8858
+ if (currentStatus && currentStatus !== exports.InteractionStatus.SsoSilent) {
8859
+ // Prevent this event from clearing any status other than ssoSilent
8860
+ break;
8861
+ }
8862
+ return exports.InteractionStatus.None;
8863
+ case exports.EventType.LOGOUT_END:
8864
+ if (currentStatus && currentStatus !== exports.InteractionStatus.Logout) {
8865
+ // Prevent this event from clearing any status other than logout
8866
+ break;
8867
+ }
8868
+ return exports.InteractionStatus.None;
8869
+ case exports.EventType.HANDLE_REDIRECT_END:
8870
+ if (currentStatus && currentStatus !== exports.InteractionStatus.HandleRedirect) {
8871
+ // Prevent this event from clearing any status other than handleRedirect
8872
+ break;
8873
+ }
8874
+ return exports.InteractionStatus.None;
8875
+ case exports.EventType.LOGIN_SUCCESS:
8876
+ case exports.EventType.LOGIN_FAILURE:
8877
+ case exports.EventType.ACQUIRE_TOKEN_SUCCESS:
8878
+ case exports.EventType.ACQUIRE_TOKEN_FAILURE:
8879
+ if (message.interactionType === exports.InteractionType.Redirect || message.interactionType === exports.InteractionType.Popup) {
8880
+ if (currentStatus && currentStatus !== exports.InteractionStatus.Login && currentStatus !== exports.InteractionStatus.AcquireToken) {
8881
+ // Prevent this event from clearing any status other than login or acquireToken
8882
+ break;
8883
+ }
8884
+ return exports.InteractionStatus.None;
8885
+ }
8886
+ break;
8900
8887
  }
8888
+ return null;
8901
8889
  };
8902
- BrowserStorage.prototype.getItem = function (key) {
8903
- return this.windowStorage.getItem(key);
8904
- };
8905
- BrowserStorage.prototype.setItem = function (key, value) {
8906
- this.windowStorage.setItem(key, value);
8907
- };
8908
- BrowserStorage.prototype.removeItem = function (key) {
8909
- this.windowStorage.removeItem(key);
8910
- };
8911
- BrowserStorage.prototype.getKeys = function () {
8912
- return Object.keys(this.windowStorage);
8913
- };
8914
- BrowserStorage.prototype.containsKey = function (key) {
8915
- return this.windowStorage.hasOwnProperty(key);
8916
- };
8917
- return BrowserStorage;
8890
+ return EventMessageUtils;
8918
8891
  }());
8919
8892
 
8893
+ /* eslint-disable header/header */
8894
+ var name = "@azure/msal-browser";
8895
+ var version = "2.19.0";
8896
+
8920
8897
  /*
8921
8898
  * Copyright (c) Microsoft Corporation. All rights reserved.
8922
8899
  * Licensed under the MIT License.
8923
8900
  */
8924
- var BrowserProtocolUtils = /** @class */ (function () {
8925
- function BrowserProtocolUtils() {
8901
+ var SignedHttpRequest = /** @class */ (function () {
8902
+ function SignedHttpRequest(shrParameters, shrOptions) {
8903
+ var loggerOptions = (shrOptions && shrOptions.loggerOptions) || {};
8904
+ this.logger = new Logger(loggerOptions, name, version);
8905
+ this.cryptoOps = new CryptoOps(this.logger);
8906
+ this.popTokenGenerator = new PopTokenGenerator(this.cryptoOps);
8907
+ this.shrParameters = shrParameters;
8926
8908
  }
8927
8909
  /**
8928
- * Extracts the BrowserStateObject from the state string.
8929
- * @param browserCrypto
8930
- * @param state
8910
+ * Generates and caches a keypair for the given request options.
8911
+ * @returns Public key digest, which should be sent to the token issuer.
8931
8912
  */
8932
- BrowserProtocolUtils.extractBrowserRequestState = function (browserCrypto, state) {
8933
- if (StringUtils.isEmpty(state)) {
8934
- return null;
8935
- }
8936
- try {
8937
- var requestStateObj = ProtocolUtils.parseRequestState(browserCrypto, state);
8938
- return requestStateObj.libraryState.meta;
8939
- }
8940
- catch (e) {
8941
- throw ClientAuthError.createInvalidStateError(state, e);
8942
- }
8913
+ SignedHttpRequest.prototype.generatePublicKeyThumbprint = function () {
8914
+ return __awaiter$1(this, void 0, void 0, function () {
8915
+ var kid;
8916
+ return __generator$1(this, function (_a) {
8917
+ switch (_a.label) {
8918
+ case 0: return [4 /*yield*/, this.popTokenGenerator.generateKid(this.shrParameters)];
8919
+ case 1:
8920
+ kid = (_a.sent()).kid;
8921
+ return [2 /*return*/, kid];
8922
+ }
8923
+ });
8924
+ });
8943
8925
  };
8944
8926
  /**
8945
- * Parses properties of server response from url hash
8946
- * @param locationHash Hash from url
8927
+ * Generates a signed http request for the given payload with the given key.
8928
+ * @param payload Payload to sign (e.g. access token)
8929
+ * @param publicKeyThumbprint Public key digest (from generatePublicKeyThumbprint API)
8930
+ * @param claims Additional claims to include/override in the signed JWT
8931
+ * @returns Pop token signed with the corresponding private key
8947
8932
  */
8948
- BrowserProtocolUtils.parseServerResponseFromHash = function (locationHash) {
8949
- if (!locationHash) {
8950
- return {};
8951
- }
8952
- var hashUrlString = new UrlString(locationHash);
8953
- return UrlString.getDeserializedHash(hashUrlString.getHash());
8933
+ SignedHttpRequest.prototype.signRequest = function (payload, publicKeyThumbprint, claims) {
8934
+ return __awaiter$1(this, void 0, void 0, function () {
8935
+ return __generator$1(this, function (_a) {
8936
+ return [2 /*return*/, this.popTokenGenerator.signPayload(payload, publicKeyThumbprint, this.shrParameters, claims)];
8937
+ });
8938
+ });
8939
+ };
8940
+ /**
8941
+ * Removes cached keys from browser for given public key thumbprint
8942
+ * @param publicKeyThumbprint Public key digest (from generatePublicKeyThumbprint API)
8943
+ * @returns If keys are properly deleted
8944
+ */
8945
+ SignedHttpRequest.prototype.removeKeys = function (publicKeyThumbprint) {
8946
+ return __awaiter$1(this, void 0, void 0, function () {
8947
+ return __generator$1(this, function (_a) {
8948
+ switch (_a.label) {
8949
+ case 0: return [4 /*yield*/, this.cryptoOps.removeTokenBindingKey(publicKeyThumbprint)];
8950
+ case 1: return [2 /*return*/, _a.sent()];
8951
+ }
8952
+ });
8953
+ });
8954
8954
  };
8955
- return BrowserProtocolUtils;
8955
+ return SignedHttpRequest;
8956
8956
  }());
8957
8957
 
8958
8958
  /*
@@ -8960,1283 +8960,1568 @@
8960
8960
  * Licensed under the MIT License.
8961
8961
  */
8962
8962
  /**
8963
- * This class implements the cache storage interface for MSAL through browser local or session storage.
8964
- * Cookies are only used if storeAuthStateInCookie is true, and are only used for
8965
- * parameters such as state and nonce, generally.
8963
+ * Storage wrapper for IndexedDB storage in browsers: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
8966
8964
  */
8967
- var BrowserCacheManager = /** @class */ (function (_super) {
8968
- __extends$1(BrowserCacheManager, _super);
8969
- function BrowserCacheManager(clientId, cacheConfig, cryptoImpl, logger) {
8970
- var _this = _super.call(this, clientId, cryptoImpl) || this;
8971
- // Cookie life calculation (hours * minutes * seconds * ms)
8972
- _this.COOKIE_LIFE_MULTIPLIER = 24 * 60 * 60 * 1000;
8973
- _this.cacheConfig = cacheConfig;
8974
- _this.logger = logger;
8975
- _this.internalStorage = new MemoryStorage();
8976
- _this.browserStorage = _this.setupBrowserStorage(_this.cacheConfig.cacheLocation);
8977
- _this.temporaryCacheStorage = _this.setupTemporaryCacheStorage(_this.cacheConfig.cacheLocation);
8978
- // Migrate any cache entries from older versions of MSAL.
8979
- _this.migrateCacheEntries();
8980
- return _this;
8965
+ var DatabaseStorage = /** @class */ (function () {
8966
+ function DatabaseStorage() {
8967
+ this.dbName = DB_NAME;
8968
+ this.version = DB_VERSION;
8969
+ this.tableName = DB_TABLE_NAME;
8970
+ this.dbOpen = false;
8981
8971
  }
8982
8972
  /**
8983
- * Returns a window storage class implementing the IWindowStorage interface that corresponds to the configured cacheLocation.
8984
- * @param cacheLocation
8973
+ * Opens IndexedDB instance.
8985
8974
  */
8986
- BrowserCacheManager.prototype.setupBrowserStorage = function (cacheLocation) {
8987
- switch (cacheLocation) {
8988
- case exports.BrowserCacheLocation.LocalStorage:
8989
- case exports.BrowserCacheLocation.SessionStorage:
8990
- try {
8991
- // Temporary cache items will always be stored in session storage to mitigate problems caused by multiple tabs
8992
- return new BrowserStorage(cacheLocation);
8993
- }
8994
- catch (e) {
8995
- this.logger.verbose(e);
8996
- break;
8975
+ DatabaseStorage.prototype.open = function () {
8976
+ return __awaiter$1(this, void 0, void 0, function () {
8977
+ var _this = this;
8978
+ return __generator$1(this, function (_a) {
8979
+ return [2 /*return*/, new Promise(function (resolve, reject) {
8980
+ var openDB = window.indexedDB.open(_this.dbName, _this.version);
8981
+ openDB.addEventListener("upgradeneeded", function (e) {
8982
+ var event = e;
8983
+ event.target.result.createObjectStore(_this.tableName);
8984
+ });
8985
+ openDB.addEventListener("success", function (e) {
8986
+ var event = e;
8987
+ _this.db = event.target.result;
8988
+ _this.dbOpen = true;
8989
+ resolve();
8990
+ });
8991
+ openDB.addEventListener("error", function () { return reject(BrowserAuthError.createDatabaseUnavailableError()); });
8992
+ })];
8993
+ });
8994
+ });
8995
+ };
8996
+ /**
8997
+ * Opens database if it's not already open
8998
+ */
8999
+ DatabaseStorage.prototype.validateDbIsOpen = function () {
9000
+ return __awaiter$1(this, void 0, void 0, function () {
9001
+ return __generator$1(this, function (_a) {
9002
+ switch (_a.label) {
9003
+ case 0:
9004
+ if (!!this.dbOpen) return [3 /*break*/, 2];
9005
+ return [4 /*yield*/, this.open()];
9006
+ case 1: return [2 /*return*/, _a.sent()];
9007
+ case 2: return [2 /*return*/];
8997
9008
  }
8998
- case exports.BrowserCacheLocation.MemoryStorage:
8999
- }
9000
- this.cacheConfig.cacheLocation = exports.BrowserCacheLocation.MemoryStorage;
9001
- return new MemoryStorage();
9009
+ });
9010
+ });
9002
9011
  };
9003
9012
  /**
9004
- *
9005
- * @param cacheLocation
9013
+ * Retrieves item from IndexedDB instance.
9014
+ * @param key
9006
9015
  */
9007
- BrowserCacheManager.prototype.setupTemporaryCacheStorage = function (cacheLocation) {
9008
- switch (cacheLocation) {
9009
- case exports.BrowserCacheLocation.LocalStorage:
9010
- case exports.BrowserCacheLocation.SessionStorage:
9011
- try {
9012
- // Temporary cache items will always be stored in session storage to mitigate problems caused by multiple tabs
9013
- return new BrowserStorage(exports.BrowserCacheLocation.SessionStorage);
9016
+ DatabaseStorage.prototype.getItem = function (key) {
9017
+ return __awaiter$1(this, void 0, void 0, function () {
9018
+ var _this = this;
9019
+ return __generator$1(this, function (_a) {
9020
+ switch (_a.label) {
9021
+ case 0: return [4 /*yield*/, this.validateDbIsOpen()];
9022
+ case 1:
9023
+ _a.sent();
9024
+ return [2 /*return*/, new Promise(function (resolve, reject) {
9025
+ // TODO: Add timeouts?
9026
+ if (!_this.db) {
9027
+ return reject(BrowserAuthError.createDatabaseNotOpenError());
9028
+ }
9029
+ var transaction = _this.db.transaction([_this.tableName], "readonly");
9030
+ var objectStore = transaction.objectStore(_this.tableName);
9031
+ var dbGet = objectStore.get(key);
9032
+ dbGet.addEventListener("success", function (e) {
9033
+ var event = e;
9034
+ resolve(event.target.result);
9035
+ });
9036
+ dbGet.addEventListener("error", function (e) { return reject(e); });
9037
+ })];
9014
9038
  }
9015
- catch (e) {
9016
- this.logger.verbose(e);
9017
- return this.internalStorage;
9039
+ });
9040
+ });
9041
+ };
9042
+ /**
9043
+ * Adds item to IndexedDB under given key
9044
+ * @param key
9045
+ * @param payload
9046
+ */
9047
+ DatabaseStorage.prototype.setItem = function (key, payload) {
9048
+ return __awaiter$1(this, void 0, void 0, function () {
9049
+ var _this = this;
9050
+ return __generator$1(this, function (_a) {
9051
+ switch (_a.label) {
9052
+ case 0: return [4 /*yield*/, this.validateDbIsOpen()];
9053
+ case 1:
9054
+ _a.sent();
9055
+ return [2 /*return*/, new Promise(function (resolve, reject) {
9056
+ // TODO: Add timeouts?
9057
+ if (!_this.db) {
9058
+ return reject(BrowserAuthError.createDatabaseNotOpenError());
9059
+ }
9060
+ var transaction = _this.db.transaction([_this.tableName], "readwrite");
9061
+ var objectStore = transaction.objectStore(_this.tableName);
9062
+ var dbPut = objectStore.put(payload, key);
9063
+ dbPut.addEventListener("success", function () { return resolve(); });
9064
+ dbPut.addEventListener("error", function (e) { return reject(e); });
9065
+ })];
9018
9066
  }
9019
- case exports.BrowserCacheLocation.MemoryStorage:
9020
- default:
9021
- return this.internalStorage;
9022
- }
9067
+ });
9068
+ });
9023
9069
  };
9024
9070
  /**
9025
- * Migrate all old cache entries to new schema. No rollback supported.
9026
- * @param storeAuthStateInCookie
9071
+ * Removes item from IndexedDB under given key
9072
+ * @param key
9027
9073
  */
9028
- BrowserCacheManager.prototype.migrateCacheEntries = function () {
9029
- var _this = this;
9030
- var idTokenKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.ID_TOKEN;
9031
- var clientInfoKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.CLIENT_INFO;
9032
- var errorKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.ERROR;
9033
- var errorDescKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.ERROR_DESC;
9034
- var idTokenValue = this.browserStorage.getItem(idTokenKey);
9035
- var clientInfoValue = this.browserStorage.getItem(clientInfoKey);
9036
- var errorValue = this.browserStorage.getItem(errorKey);
9037
- var errorDescValue = this.browserStorage.getItem(errorDescKey);
9038
- var values = [idTokenValue, clientInfoValue, errorValue, errorDescValue];
9039
- var keysToMigrate = [PersistentCacheKeys.ID_TOKEN, PersistentCacheKeys.CLIENT_INFO, PersistentCacheKeys.ERROR, PersistentCacheKeys.ERROR_DESC];
9040
- keysToMigrate.forEach(function (cacheKey, index) { return _this.migrateCacheEntry(cacheKey, values[index]); });
9074
+ DatabaseStorage.prototype.removeItem = function (key) {
9075
+ return __awaiter$1(this, void 0, void 0, function () {
9076
+ var _this = this;
9077
+ return __generator$1(this, function (_a) {
9078
+ switch (_a.label) {
9079
+ case 0: return [4 /*yield*/, this.validateDbIsOpen()];
9080
+ case 1:
9081
+ _a.sent();
9082
+ return [2 /*return*/, new Promise(function (resolve, reject) {
9083
+ if (!_this.db) {
9084
+ return reject(BrowserAuthError.createDatabaseNotOpenError());
9085
+ }
9086
+ var transaction = _this.db.transaction([_this.tableName], "readwrite");
9087
+ var objectStore = transaction.objectStore(_this.tableName);
9088
+ var dbDelete = objectStore.delete(key);
9089
+ dbDelete.addEventListener("success", function () { return resolve(); });
9090
+ dbDelete.addEventListener("error", function (e) { return reject(e); });
9091
+ })];
9092
+ }
9093
+ });
9094
+ });
9041
9095
  };
9042
9096
  /**
9043
- * Utility function to help with migration.
9044
- * @param newKey
9045
- * @param value
9046
- * @param storeAuthStateInCookie
9097
+ * Get all the keys from the storage object as an iterable array of strings.
9047
9098
  */
9048
- BrowserCacheManager.prototype.migrateCacheEntry = function (newKey, value) {
9049
- if (value) {
9050
- this.setTemporaryCache(newKey, value, true);
9051
- }
9099
+ DatabaseStorage.prototype.getKeys = function () {
9100
+ return __awaiter$1(this, void 0, void 0, function () {
9101
+ var _this = this;
9102
+ return __generator$1(this, function (_a) {
9103
+ switch (_a.label) {
9104
+ case 0: return [4 /*yield*/, this.validateDbIsOpen()];
9105
+ case 1:
9106
+ _a.sent();
9107
+ return [2 /*return*/, new Promise(function (resolve, reject) {
9108
+ if (!_this.db) {
9109
+ return reject(BrowserAuthError.createDatabaseNotOpenError());
9110
+ }
9111
+ var transaction = _this.db.transaction([_this.tableName], "readonly");
9112
+ var objectStore = transaction.objectStore(_this.tableName);
9113
+ var dbGetKeys = objectStore.getAllKeys();
9114
+ dbGetKeys.addEventListener("success", function (e) {
9115
+ var event = e;
9116
+ resolve(event.target.result);
9117
+ });
9118
+ dbGetKeys.addEventListener("error", function (e) { return reject(e); });
9119
+ })];
9120
+ }
9121
+ });
9122
+ });
9052
9123
  };
9053
9124
  /**
9054
- * Parses passed value as JSON object, JSON.parse() will throw an error.
9055
- * @param input
9125
+ *
9126
+ * Checks whether there is an object under the search key in the object store
9056
9127
  */
9057
- BrowserCacheManager.prototype.validateAndParseJson = function (jsonValue) {
9058
- try {
9059
- var parsedJson = JSON.parse(jsonValue);
9060
- /**
9061
- * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
9062
- * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
9063
- * of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
9064
- *
9065
- */
9066
- return (parsedJson && typeof parsedJson === "object") ? parsedJson : null;
9067
- }
9068
- catch (error) {
9069
- return null;
9070
- }
9128
+ DatabaseStorage.prototype.containsKey = function (key) {
9129
+ return __awaiter$1(this, void 0, void 0, function () {
9130
+ var _this = this;
9131
+ return __generator$1(this, function (_a) {
9132
+ switch (_a.label) {
9133
+ case 0: return [4 /*yield*/, this.validateDbIsOpen()];
9134
+ case 1:
9135
+ _a.sent();
9136
+ return [2 /*return*/, new Promise(function (resolve, reject) {
9137
+ if (!_this.db) {
9138
+ return reject(BrowserAuthError.createDatabaseNotOpenError());
9139
+ }
9140
+ var transaction = _this.db.transaction([_this.tableName], "readonly");
9141
+ var objectStore = transaction.objectStore(_this.tableName);
9142
+ var dbContainsKey = objectStore.count(key);
9143
+ dbContainsKey.addEventListener("success", function (e) {
9144
+ var event = e;
9145
+ resolve(event.target.result === 1);
9146
+ });
9147
+ dbContainsKey.addEventListener("error", function (e) { return reject(e); });
9148
+ })];
9149
+ }
9150
+ });
9151
+ });
9071
9152
  };
9072
9153
  /**
9073
- * fetches the entry from the browser storage based off the key
9074
- * @param key
9154
+ * Deletes the MSAL database. The database is deleted rather than cleared to make it possible
9155
+ * for client applications to downgrade to a previous MSAL version without worrying about forward compatibility issues
9156
+ * with IndexedDB database versions.
9075
9157
  */
9076
- BrowserCacheManager.prototype.getItem = function (key) {
9077
- return this.browserStorage.getItem(key);
9158
+ DatabaseStorage.prototype.deleteDatabase = function () {
9159
+ return __awaiter$1(this, void 0, void 0, function () {
9160
+ return __generator$1(this, function (_a) {
9161
+ return [2 /*return*/, new Promise(function (resolve, reject) {
9162
+ var deleteDbRequest = window.indexedDB.deleteDatabase(DB_NAME);
9163
+ deleteDbRequest.addEventListener("success", function () { return resolve(true); });
9164
+ deleteDbRequest.addEventListener("error", function () { return reject(false); });
9165
+ })];
9166
+ });
9167
+ });
9078
9168
  };
9079
- /**
9080
- * sets the entry in the browser storage
9081
- * @param key
9082
- * @param value
9083
- */
9084
- BrowserCacheManager.prototype.setItem = function (key, value) {
9085
- this.browserStorage.setItem(key, value);
9169
+ return DatabaseStorage;
9170
+ }());
9171
+
9172
+ /*
9173
+ * Copyright (c) Microsoft Corporation. All rights reserved.
9174
+ * Licensed under the MIT License.
9175
+ */
9176
+ var MemoryStorage = /** @class */ (function () {
9177
+ function MemoryStorage() {
9178
+ this.cache = new Map();
9179
+ }
9180
+ MemoryStorage.prototype.getItem = function (key) {
9181
+ return this.cache.get(key) || null;
9086
9182
  };
9087
- /**
9088
- * fetch the account entity from the platform cache
9089
- * @param accountKey
9090
- */
9091
- BrowserCacheManager.prototype.getAccount = function (accountKey) {
9092
- var account = this.getItem(accountKey);
9093
- if (!account) {
9094
- return null;
9095
- }
9096
- var parsedAccount = this.validateAndParseJson(account);
9097
- if (!parsedAccount || !AccountEntity.isAccountEntity(parsedAccount)) {
9098
- return null;
9099
- }
9100
- return CacheManager.toObject(new AccountEntity(), parsedAccount);
9183
+ MemoryStorage.prototype.setItem = function (key, value) {
9184
+ this.cache.set(key, value);
9101
9185
  };
9102
- /**
9103
- * set account entity in the platform cache
9104
- * @param key
9105
- * @param value
9106
- */
9107
- BrowserCacheManager.prototype.setAccount = function (account) {
9108
- this.logger.trace("BrowserCacheManager.setAccount called");
9109
- var key = account.generateAccountKey();
9110
- this.setItem(key, JSON.stringify(account));
9186
+ MemoryStorage.prototype.removeItem = function (key) {
9187
+ this.cache.delete(key);
9111
9188
  };
9112
- /**
9113
- * generates idToken entity from a string
9114
- * @param idTokenKey
9115
- */
9116
- BrowserCacheManager.prototype.getIdTokenCredential = function (idTokenKey) {
9117
- var value = this.getItem(idTokenKey);
9118
- if (!value) {
9119
- this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit");
9120
- return null;
9121
- }
9122
- var parsedIdToken = this.validateAndParseJson(value);
9123
- if (!parsedIdToken || !IdTokenEntity.isIdTokenEntity(parsedIdToken)) {
9124
- this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit");
9125
- return null;
9126
- }
9127
- this.logger.trace("BrowserCacheManager.getIdTokenCredential: cache hit");
9128
- return CacheManager.toObject(new IdTokenEntity(), parsedIdToken);
9189
+ MemoryStorage.prototype.getKeys = function () {
9190
+ var cacheKeys = [];
9191
+ this.cache.forEach(function (value, key) {
9192
+ cacheKeys.push(key);
9193
+ });
9194
+ return cacheKeys;
9129
9195
  };
9130
- /**
9131
- * set IdToken credential to the platform cache
9132
- * @param idToken
9133
- */
9134
- BrowserCacheManager.prototype.setIdTokenCredential = function (idToken) {
9135
- this.logger.trace("BrowserCacheManager.setIdTokenCredential called");
9136
- var idTokenKey = idToken.generateCredentialKey();
9137
- this.setItem(idTokenKey, JSON.stringify(idToken));
9196
+ MemoryStorage.prototype.containsKey = function (key) {
9197
+ return this.cache.has(key);
9138
9198
  };
9139
- /**
9140
- * generates accessToken entity from a string
9141
- * @param key
9142
- */
9143
- BrowserCacheManager.prototype.getAccessTokenCredential = function (accessTokenKey) {
9144
- var value = this.getItem(accessTokenKey);
9145
- if (!value) {
9146
- this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit");
9147
- return null;
9148
- }
9149
- var parsedAccessToken = this.validateAndParseJson(value);
9150
- if (!parsedAccessToken || !AccessTokenEntity.isAccessTokenEntity(parsedAccessToken)) {
9151
- this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit");
9152
- return null;
9153
- }
9154
- this.logger.trace("BrowserCacheManager.getAccessTokenCredential: cache hit");
9155
- return CacheManager.toObject(new AccessTokenEntity(), parsedAccessToken);
9199
+ MemoryStorage.prototype.clear = function () {
9200
+ this.cache.clear();
9156
9201
  };
9157
- /**
9158
- * set accessToken credential to the platform cache
9159
- * @param accessToken
9160
- */
9161
- BrowserCacheManager.prototype.setAccessTokenCredential = function (accessToken) {
9162
- this.logger.trace("BrowserCacheManager.setAccessTokenCredential called");
9163
- var accessTokenKey = accessToken.generateCredentialKey();
9164
- this.setItem(accessTokenKey, JSON.stringify(accessToken));
9202
+ return MemoryStorage;
9203
+ }());
9204
+
9205
+ /*
9206
+ * Copyright (c) Microsoft Corporation. All rights reserved.
9207
+ * Licensed under the MIT License.
9208
+ */
9209
+ /**
9210
+ * This class allows MSAL to store artifacts asynchronously using the DatabaseStorage IndexedDB wrapper,
9211
+ * backed up with the more volatile MemoryStorage object for cases in which IndexedDB may be unavailable.
9212
+ */
9213
+ var AsyncMemoryStorage = /** @class */ (function () {
9214
+ function AsyncMemoryStorage(logger) {
9215
+ this.inMemoryCache = new MemoryStorage();
9216
+ this.indexedDBCache = new DatabaseStorage();
9217
+ this.logger = logger;
9218
+ }
9219
+ AsyncMemoryStorage.prototype.handleDatabaseAccessError = function (error) {
9220
+ if (error instanceof BrowserAuthError && error.errorCode === BrowserAuthErrorMessage.databaseUnavailable.code) {
9221
+ this.logger.error("Could not access persistent storage. This may be caused by browser privacy features which block persistent storage in third-party contexts.");
9222
+ }
9165
9223
  };
9166
9224
  /**
9167
- * generates refreshToken entity from a string
9168
- * @param refreshTokenKey
9225
+ * Get the item matching the given key. Tries in-memory cache first, then in the asynchronous
9226
+ * storage object if item isn't found in-memory.
9227
+ * @param key
9169
9228
  */
9170
- BrowserCacheManager.prototype.getRefreshTokenCredential = function (refreshTokenKey) {
9171
- var value = this.getItem(refreshTokenKey);
9172
- if (!value) {
9173
- this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit");
9174
- return null;
9175
- }
9176
- var parsedRefreshToken = this.validateAndParseJson(value);
9177
- if (!parsedRefreshToken || !RefreshTokenEntity.isRefreshTokenEntity(parsedRefreshToken)) {
9178
- this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit");
9179
- return null;
9180
- }
9181
- this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: cache hit");
9182
- return CacheManager.toObject(new RefreshTokenEntity(), parsedRefreshToken);
9229
+ AsyncMemoryStorage.prototype.getItem = function (key) {
9230
+ return __awaiter$1(this, void 0, void 0, function () {
9231
+ var item, e_1;
9232
+ return __generator$1(this, function (_a) {
9233
+ switch (_a.label) {
9234
+ case 0:
9235
+ item = this.inMemoryCache.getItem(key);
9236
+ if (!!item) return [3 /*break*/, 4];
9237
+ _a.label = 1;
9238
+ case 1:
9239
+ _a.trys.push([1, 3, , 4]);
9240
+ this.logger.verbose("Queried item not found in in-memory cache, now querying persistent storage.");
9241
+ return [4 /*yield*/, this.indexedDBCache.getItem(key)];
9242
+ case 2: return [2 /*return*/, _a.sent()];
9243
+ case 3:
9244
+ e_1 = _a.sent();
9245
+ this.handleDatabaseAccessError(e_1);
9246
+ return [3 /*break*/, 4];
9247
+ case 4: return [2 /*return*/, item];
9248
+ }
9249
+ });
9250
+ });
9183
9251
  };
9184
9252
  /**
9185
- * set refreshToken credential to the platform cache
9186
- * @param refreshToken
9253
+ * Sets the item in the in-memory cache and then tries to set it in the asynchronous
9254
+ * storage object with the given key.
9255
+ * @param key
9256
+ * @param value
9187
9257
  */
9188
- BrowserCacheManager.prototype.setRefreshTokenCredential = function (refreshToken) {
9189
- this.logger.trace("BrowserCacheManager.setRefreshTokenCredential called");
9190
- var refreshTokenKey = refreshToken.generateCredentialKey();
9191
- this.setItem(refreshTokenKey, JSON.stringify(refreshToken));
9258
+ AsyncMemoryStorage.prototype.setItem = function (key, value) {
9259
+ return __awaiter$1(this, void 0, void 0, function () {
9260
+ var e_2;
9261
+ return __generator$1(this, function (_a) {
9262
+ switch (_a.label) {
9263
+ case 0:
9264
+ this.inMemoryCache.setItem(key, value);
9265
+ _a.label = 1;
9266
+ case 1:
9267
+ _a.trys.push([1, 3, , 4]);
9268
+ return [4 /*yield*/, this.indexedDBCache.setItem(key, value)];
9269
+ case 2:
9270
+ _a.sent();
9271
+ return [3 /*break*/, 4];
9272
+ case 3:
9273
+ e_2 = _a.sent();
9274
+ this.handleDatabaseAccessError(e_2);
9275
+ return [3 /*break*/, 4];
9276
+ case 4: return [2 /*return*/];
9277
+ }
9278
+ });
9279
+ });
9192
9280
  };
9193
9281
  /**
9194
- * fetch appMetadata entity from the platform cache
9195
- * @param appMetadataKey
9282
+ * Removes the item matching the key from the in-memory cache, then tries to remove it from the asynchronous storage object.
9283
+ * @param key
9196
9284
  */
9197
- BrowserCacheManager.prototype.getAppMetadata = function (appMetadataKey) {
9198
- var value = this.getItem(appMetadataKey);
9199
- if (!value) {
9200
- this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit");
9201
- return null;
9202
- }
9203
- var parsedMetadata = this.validateAndParseJson(value);
9204
- if (!parsedMetadata || !AppMetadataEntity.isAppMetadataEntity(appMetadataKey, parsedMetadata)) {
9205
- this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit");
9206
- return null;
9207
- }
9208
- this.logger.trace("BrowserCacheManager.getAppMetadata: cache hit");
9209
- return CacheManager.toObject(new AppMetadataEntity(), parsedMetadata);
9285
+ AsyncMemoryStorage.prototype.removeItem = function (key) {
9286
+ return __awaiter$1(this, void 0, void 0, function () {
9287
+ var e_3;
9288
+ return __generator$1(this, function (_a) {
9289
+ switch (_a.label) {
9290
+ case 0:
9291
+ this.inMemoryCache.removeItem(key);
9292
+ _a.label = 1;
9293
+ case 1:
9294
+ _a.trys.push([1, 3, , 4]);
9295
+ return [4 /*yield*/, this.indexedDBCache.removeItem(key)];
9296
+ case 2:
9297
+ _a.sent();
9298
+ return [3 /*break*/, 4];
9299
+ case 3:
9300
+ e_3 = _a.sent();
9301
+ this.handleDatabaseAccessError(e_3);
9302
+ return [3 /*break*/, 4];
9303
+ case 4: return [2 /*return*/];
9304
+ }
9305
+ });
9306
+ });
9210
9307
  };
9211
9308
  /**
9212
- * set appMetadata entity to the platform cache
9213
- * @param appMetadata
9309
+ * Get all the keys from the in-memory cache as an iterable array of strings. If no keys are found, query the keys in the
9310
+ * asynchronous storage object.
9214
9311
  */
9215
- BrowserCacheManager.prototype.setAppMetadata = function (appMetadata) {
9216
- this.logger.trace("BrowserCacheManager.setAppMetadata called");
9217
- var appMetadataKey = appMetadata.generateAppMetadataKey();
9218
- this.setItem(appMetadataKey, JSON.stringify(appMetadata));
9312
+ AsyncMemoryStorage.prototype.getKeys = function () {
9313
+ return __awaiter$1(this, void 0, void 0, function () {
9314
+ var cacheKeys, e_4;
9315
+ return __generator$1(this, function (_a) {
9316
+ switch (_a.label) {
9317
+ case 0:
9318
+ cacheKeys = this.inMemoryCache.getKeys();
9319
+ if (!(cacheKeys.length === 0)) return [3 /*break*/, 4];
9320
+ _a.label = 1;
9321
+ case 1:
9322
+ _a.trys.push([1, 3, , 4]);
9323
+ this.logger.verbose("In-memory cache is empty, now querying persistent storage.");
9324
+ return [4 /*yield*/, this.indexedDBCache.getKeys()];
9325
+ case 2: return [2 /*return*/, _a.sent()];
9326
+ case 3:
9327
+ e_4 = _a.sent();
9328
+ this.handleDatabaseAccessError(e_4);
9329
+ return [3 /*break*/, 4];
9330
+ case 4: return [2 /*return*/, cacheKeys];
9331
+ }
9332
+ });
9333
+ });
9219
9334
  };
9220
9335
  /**
9221
- * fetch server telemetry entity from the platform cache
9222
- * @param serverTelemetryKey
9336
+ * Returns true or false if the given key is present in the cache.
9337
+ * @param key
9223
9338
  */
9224
- BrowserCacheManager.prototype.getServerTelemetry = function (serverTelemetryKey) {
9225
- var value = this.getItem(serverTelemetryKey);
9226
- if (!value) {
9227
- this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit");
9228
- return null;
9229
- }
9230
- var parsedMetadata = this.validateAndParseJson(value);
9231
- if (!parsedMetadata || !ServerTelemetryEntity.isServerTelemetryEntity(serverTelemetryKey, parsedMetadata)) {
9232
- this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit");
9233
- return null;
9234
- }
9235
- this.logger.trace("BrowserCacheManager.getServerTelemetry: cache hit");
9236
- return CacheManager.toObject(new ServerTelemetryEntity(), parsedMetadata);
9339
+ AsyncMemoryStorage.prototype.containsKey = function (key) {
9340
+ return __awaiter$1(this, void 0, void 0, function () {
9341
+ var containsKey, e_5;
9342
+ return __generator$1(this, function (_a) {
9343
+ switch (_a.label) {
9344
+ case 0:
9345
+ containsKey = this.inMemoryCache.containsKey(key);
9346
+ if (!!containsKey) return [3 /*break*/, 4];
9347
+ _a.label = 1;
9348
+ case 1:
9349
+ _a.trys.push([1, 3, , 4]);
9350
+ this.logger.verbose("Key not found in in-memory cache, now querying persistent storage.");
9351
+ return [4 /*yield*/, this.indexedDBCache.containsKey(key)];
9352
+ case 2: return [2 /*return*/, _a.sent()];
9353
+ case 3:
9354
+ e_5 = _a.sent();
9355
+ this.handleDatabaseAccessError(e_5);
9356
+ return [3 /*break*/, 4];
9357
+ case 4: return [2 /*return*/, containsKey];
9358
+ }
9359
+ });
9360
+ });
9237
9361
  };
9238
9362
  /**
9239
- * set server telemetry entity to the platform cache
9240
- * @param serverTelemetryKey
9241
- * @param serverTelemetry
9363
+ * Clears in-memory Map and tries to delete the IndexedDB database.
9242
9364
  */
9243
- BrowserCacheManager.prototype.setServerTelemetry = function (serverTelemetryKey, serverTelemetry) {
9244
- this.logger.trace("BrowserCacheManager.setServerTelemetry called");
9245
- this.setItem(serverTelemetryKey, JSON.stringify(serverTelemetry));
9365
+ AsyncMemoryStorage.prototype.clear = function () {
9366
+ return __awaiter$1(this, void 0, void 0, function () {
9367
+ var e_6;
9368
+ return __generator$1(this, function (_a) {
9369
+ switch (_a.label) {
9370
+ case 0:
9371
+ this.inMemoryCache.clear();
9372
+ _a.label = 1;
9373
+ case 1:
9374
+ _a.trys.push([1, 3, , 4]);
9375
+ return [4 /*yield*/, this.indexedDBCache.deleteDatabase()];
9376
+ case 2:
9377
+ _a.sent();
9378
+ return [3 /*break*/, 4];
9379
+ case 3:
9380
+ e_6 = _a.sent();
9381
+ this.handleDatabaseAccessError(e_6);
9382
+ return [3 /*break*/, 4];
9383
+ case 4: return [2 /*return*/];
9384
+ }
9385
+ });
9386
+ });
9246
9387
  };
9388
+ return AsyncMemoryStorage;
9389
+ }());
9390
+
9391
+ /*
9392
+ * Copyright (c) Microsoft Corporation. All rights reserved.
9393
+ * Licensed under the MIT License.
9394
+ */
9395
+ /**
9396
+ * This class implements MSAL's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and
9397
+ * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
9398
+ */
9399
+ var CryptoOps = /** @class */ (function () {
9400
+ function CryptoOps(logger) {
9401
+ this.logger = logger;
9402
+ // Browser crypto needs to be validated first before any other classes can be set.
9403
+ this.browserCrypto = new BrowserCrypto(this.logger);
9404
+ this.b64Encode = new Base64Encode();
9405
+ this.b64Decode = new Base64Decode();
9406
+ this.guidGenerator = new GuidGenerator(this.browserCrypto);
9407
+ this.pkceGenerator = new PkceGenerator(this.browserCrypto);
9408
+ this.cache = {
9409
+ asymmetricKeys: new AsyncMemoryStorage(this.logger),
9410
+ symmetricKeys: new AsyncMemoryStorage(this.logger)
9411
+ };
9412
+ }
9247
9413
  /**
9248
- *
9414
+ * Creates a new random GUID - used to populate state and nonce.
9415
+ * @returns string (GUID)
9249
9416
  */
9250
- BrowserCacheManager.prototype.getAuthorityMetadata = function (key) {
9251
- var value = this.internalStorage.getItem(key);
9252
- if (!value) {
9253
- this.logger.trace("BrowserCacheManager.getAuthorityMetadata: called, no cache hit");
9254
- return null;
9255
- }
9256
- var parsedMetadata = this.validateAndParseJson(value);
9257
- if (parsedMetadata && AuthorityMetadataEntity.isAuthorityMetadataEntity(key, parsedMetadata)) {
9258
- this.logger.trace("BrowserCacheManager.getAuthorityMetadata: cache hit");
9259
- return CacheManager.toObject(new AuthorityMetadataEntity(), parsedMetadata);
9260
- }
9261
- return null;
9417
+ CryptoOps.prototype.createNewGuid = function () {
9418
+ return this.guidGenerator.generateGuid();
9262
9419
  };
9263
9420
  /**
9264
- *
9421
+ * Encodes input string to base64.
9422
+ * @param input
9265
9423
  */
9266
- BrowserCacheManager.prototype.getAuthorityMetadataKeys = function () {
9267
- var _this = this;
9268
- var allKeys = this.internalStorage.getKeys();
9269
- return allKeys.filter(function (key) {
9270
- return _this.isAuthorityMetadata(key);
9271
- });
9424
+ CryptoOps.prototype.base64Encode = function (input) {
9425
+ return this.b64Encode.encode(input);
9272
9426
  };
9273
9427
  /**
9274
- * Sets wrapper metadata in memory
9275
- * @param wrapperSKU
9276
- * @param wrapperVersion
9428
+ * Decodes input string from base64.
9429
+ * @param input
9277
9430
  */
9278
- BrowserCacheManager.prototype.setWrapperMetadata = function (wrapperSKU, wrapperVersion) {
9279
- this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_SKU, wrapperSKU);
9280
- this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_VER, wrapperVersion);
9431
+ CryptoOps.prototype.base64Decode = function (input) {
9432
+ return this.b64Decode.decode(input);
9281
9433
  };
9282
9434
  /**
9283
- * Returns wrapper metadata from in-memory storage
9435
+ * Generates PKCE codes used in Authorization Code Flow.
9284
9436
  */
9285
- BrowserCacheManager.prototype.getWrapperMetadata = function () {
9286
- var sku = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_SKU) || "";
9287
- var version = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_VER) || "";
9288
- return [sku, version];
9437
+ CryptoOps.prototype.generatePkceCodes = function () {
9438
+ return __awaiter$1(this, void 0, void 0, function () {
9439
+ return __generator$1(this, function (_a) {
9440
+ return [2 /*return*/, this.pkceGenerator.generateCodes()];
9441
+ });
9442
+ });
9289
9443
  };
9290
9444
  /**
9291
- *
9292
- * @param entity
9445
+ * Generates a keypair, stores it and returns a thumbprint
9446
+ * @param request
9293
9447
  */
9294
- BrowserCacheManager.prototype.setAuthorityMetadata = function (key, entity) {
9295
- this.logger.trace("BrowserCacheManager.setAuthorityMetadata called");
9296
- this.internalStorage.setItem(key, JSON.stringify(entity));
9448
+ CryptoOps.prototype.getPublicKeyThumbprint = function (request) {
9449
+ return __awaiter$1(this, void 0, void 0, function () {
9450
+ var keyPair, publicKeyJwk, pubKeyThumprintObj, publicJwkString, publicJwkBuffer, publicJwkHash, privateKeyJwk, unextractablePrivateKey;
9451
+ return __generator$1(this, function (_a) {
9452
+ switch (_a.label) {
9453
+ case 0: return [4 /*yield*/, this.browserCrypto.generateKeyPair(CryptoOps.EXTRACTABLE, CryptoOps.POP_KEY_USAGES)];
9454
+ case 1:
9455
+ keyPair = _a.sent();
9456
+ return [4 /*yield*/, this.browserCrypto.exportJwk(keyPair.publicKey)];
9457
+ case 2:
9458
+ publicKeyJwk = _a.sent();
9459
+ pubKeyThumprintObj = {
9460
+ e: publicKeyJwk.e,
9461
+ kty: publicKeyJwk.kty,
9462
+ n: publicKeyJwk.n
9463
+ };
9464
+ publicJwkString = BrowserCrypto.getJwkString(pubKeyThumprintObj);
9465
+ return [4 /*yield*/, this.browserCrypto.sha256Digest(publicJwkString)];
9466
+ case 3:
9467
+ publicJwkBuffer = _a.sent();
9468
+ publicJwkHash = this.b64Encode.urlEncodeArr(new Uint8Array(publicJwkBuffer));
9469
+ return [4 /*yield*/, this.browserCrypto.exportJwk(keyPair.privateKey)];
9470
+ case 4:
9471
+ privateKeyJwk = _a.sent();
9472
+ return [4 /*yield*/, this.browserCrypto.importJwk(privateKeyJwk, false, ["sign"])];
9473
+ case 5:
9474
+ unextractablePrivateKey = _a.sent();
9475
+ // Store Keypair data in keystore
9476
+ return [4 /*yield*/, this.cache.asymmetricKeys.setItem(publicJwkHash, {
9477
+ privateKey: unextractablePrivateKey,
9478
+ publicKey: keyPair.publicKey,
9479
+ requestMethod: request.resourceRequestMethod,
9480
+ requestUri: request.resourceRequestUri
9481
+ })];
9482
+ case 6:
9483
+ // Store Keypair data in keystore
9484
+ _a.sent();
9485
+ return [2 /*return*/, publicJwkHash];
9486
+ }
9487
+ });
9488
+ });
9297
9489
  };
9298
9490
  /**
9299
- * Gets the active account
9491
+ * Removes cryptographic keypair from key store matching the keyId passed in
9492
+ * @param kid
9300
9493
  */
9301
- BrowserCacheManager.prototype.getActiveAccount = function () {
9302
- var activeAccountIdKey = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT);
9303
- var activeAccountId = this.browserStorage.getItem(activeAccountIdKey);
9304
- if (!activeAccountId) {
9305
- return null;
9306
- }
9307
- return this.getAccountInfoByFilter({ localAccountId: activeAccountId })[0] || null;
9494
+ CryptoOps.prototype.removeTokenBindingKey = function (kid) {
9495
+ return __awaiter$1(this, void 0, void 0, function () {
9496
+ var keyFound;
9497
+ return __generator$1(this, function (_a) {
9498
+ switch (_a.label) {
9499
+ case 0: return [4 /*yield*/, this.cache.asymmetricKeys.removeItem(kid)];
9500
+ case 1:
9501
+ _a.sent();
9502
+ return [4 /*yield*/, this.cache.asymmetricKeys.containsKey(kid)];
9503
+ case 2:
9504
+ keyFound = _a.sent();
9505
+ return [2 /*return*/, !keyFound];
9506
+ }
9507
+ });
9508
+ });
9308
9509
  };
9309
9510
  /**
9310
- * Sets the active account's localAccountId in cache
9311
- * @param account
9511
+ * Removes all cryptographic keys from IndexedDB storage
9312
9512
  */
9313
- BrowserCacheManager.prototype.setActiveAccount = function (account) {
9314
- var activeAccountIdKey = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT);
9315
- if (account) {
9316
- this.logger.verbose("setActiveAccount: Active account set");
9317
- this.browserStorage.setItem(activeAccountIdKey, account.localAccountId);
9318
- }
9319
- else {
9320
- this.logger.verbose("setActiveAccount: No account passed, active account not set");
9321
- this.browserStorage.removeItem(activeAccountIdKey);
9322
- }
9513
+ CryptoOps.prototype.clearKeystore = function () {
9514
+ return __awaiter$1(this, void 0, void 0, function () {
9515
+ var dataStoreNames, databaseStorage, _a;
9516
+ return __generator$1(this, function (_b) {
9517
+ switch (_b.label) {
9518
+ case 0:
9519
+ dataStoreNames = Object.keys(this.cache);
9520
+ databaseStorage = this.cache[dataStoreNames[0]];
9521
+ if (!databaseStorage) return [3 /*break*/, 2];
9522
+ return [4 /*yield*/, databaseStorage.deleteDatabase()];
9523
+ case 1:
9524
+ _a = _b.sent();
9525
+ return [3 /*break*/, 3];
9526
+ case 2:
9527
+ _a = false;
9528
+ _b.label = 3;
9529
+ case 3: return [2 /*return*/, _a];
9530
+ }
9531
+ });
9532
+ });
9323
9533
  };
9324
9534
  /**
9325
- * Gets a list of accounts that match all of the filters provided
9326
- * @param account
9535
+ * Signs the given object as a jwt payload with private key retrieved by given kid.
9536
+ * @param payload
9537
+ * @param kid
9327
9538
  */
9328
- BrowserCacheManager.prototype.getAccountInfoByFilter = function (accountFilter) {
9329
- var allAccounts = this.getAllAccounts();
9330
- return allAccounts.filter(function (accountObj) {
9331
- if (accountFilter.username && accountFilter.username.toLowerCase() !== accountObj.username.toLowerCase()) {
9332
- return false;
9333
- }
9334
- if (accountFilter.homeAccountId && accountFilter.homeAccountId !== accountObj.homeAccountId) {
9335
- return false;
9336
- }
9337
- if (accountFilter.localAccountId && accountFilter.localAccountId !== accountObj.localAccountId) {
9338
- return false;
9339
- }
9340
- if (accountFilter.tenantId && accountFilter.tenantId !== accountObj.tenantId) {
9341
- return false;
9342
- }
9343
- if (accountFilter.environment && accountFilter.environment !== accountObj.environment) {
9344
- return false;
9345
- }
9346
- return true;
9539
+ CryptoOps.prototype.signJwt = function (payload, kid) {
9540
+ return __awaiter$1(this, void 0, void 0, function () {
9541
+ var cachedKeyPair, publicKeyJwk, publicKeyJwkString, header, encodedHeader, encodedPayload, tokenString, tokenBuffer, signatureBuffer, encodedSignature;
9542
+ return __generator$1(this, function (_a) {
9543
+ switch (_a.label) {
9544
+ case 0: return [4 /*yield*/, this.cache.asymmetricKeys.getItem(kid)];
9545
+ case 1:
9546
+ cachedKeyPair = _a.sent();
9547
+ if (!cachedKeyPair) {
9548
+ throw BrowserAuthError.createSigningKeyNotFoundInStorageError(kid);
9549
+ }
9550
+ return [4 /*yield*/, this.browserCrypto.exportJwk(cachedKeyPair.publicKey)];
9551
+ case 2:
9552
+ publicKeyJwk = _a.sent();
9553
+ publicKeyJwkString = BrowserCrypto.getJwkString(publicKeyJwk);
9554
+ header = {
9555
+ alg: publicKeyJwk.alg,
9556
+ type: KEY_FORMAT_JWK
9557
+ };
9558
+ encodedHeader = this.b64Encode.urlEncode(JSON.stringify(header));
9559
+ // Generate payload
9560
+ payload.cnf = {
9561
+ jwk: JSON.parse(publicKeyJwkString)
9562
+ };
9563
+ encodedPayload = this.b64Encode.urlEncode(JSON.stringify(payload));
9564
+ tokenString = encodedHeader + "." + encodedPayload;
9565
+ tokenBuffer = BrowserStringUtils.stringToArrayBuffer(tokenString);
9566
+ return [4 /*yield*/, this.browserCrypto.sign(cachedKeyPair.privateKey, tokenBuffer)];
9567
+ case 3:
9568
+ signatureBuffer = _a.sent();
9569
+ encodedSignature = this.b64Encode.urlEncodeArr(new Uint8Array(signatureBuffer));
9570
+ return [2 /*return*/, tokenString + "." + encodedSignature];
9571
+ }
9572
+ });
9347
9573
  });
9348
9574
  };
9349
- /**
9350
- * fetch throttling entity from the platform cache
9351
- * @param throttlingCacheKey
9352
- */
9353
- BrowserCacheManager.prototype.getThrottlingCache = function (throttlingCacheKey) {
9354
- var value = this.getItem(throttlingCacheKey);
9355
- if (!value) {
9356
- this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit");
9357
- return null;
9575
+ CryptoOps.POP_KEY_USAGES = ["sign", "verify"];
9576
+ CryptoOps.EXTRACTABLE = true;
9577
+ return CryptoOps;
9578
+ }());
9579
+
9580
+ /*
9581
+ * Copyright (c) Microsoft Corporation. All rights reserved.
9582
+ * Licensed under the MIT License.
9583
+ */
9584
+ var BrowserStorage = /** @class */ (function () {
9585
+ function BrowserStorage(cacheLocation) {
9586
+ this.validateWindowStorage(cacheLocation);
9587
+ this.windowStorage = window[cacheLocation];
9588
+ }
9589
+ BrowserStorage.prototype.validateWindowStorage = function (cacheLocation) {
9590
+ if (cacheLocation !== exports.BrowserCacheLocation.LocalStorage && cacheLocation !== exports.BrowserCacheLocation.SessionStorage) {
9591
+ throw BrowserConfigurationAuthError.createStorageNotSupportedError(cacheLocation);
9358
9592
  }
9359
- var parsedThrottlingCache = this.validateAndParseJson(value);
9360
- if (!parsedThrottlingCache || !ThrottlingEntity.isThrottlingEntity(throttlingCacheKey, parsedThrottlingCache)) {
9361
- this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit");
9362
- return null;
9593
+ var storageSupported = !!window[cacheLocation];
9594
+ if (!storageSupported) {
9595
+ throw BrowserConfigurationAuthError.createStorageNotSupportedError(cacheLocation);
9363
9596
  }
9364
- this.logger.trace("BrowserCacheManager.getThrottlingCache: cache hit");
9365
- return CacheManager.toObject(new ThrottlingEntity(), parsedThrottlingCache);
9366
9597
  };
9367
- /**
9368
- * set throttling entity to the platform cache
9369
- * @param throttlingCacheKey
9370
- * @param throttlingCache
9371
- */
9372
- BrowserCacheManager.prototype.setThrottlingCache = function (throttlingCacheKey, throttlingCache) {
9373
- this.logger.trace("BrowserCacheManager.setThrottlingCache called");
9374
- this.setItem(throttlingCacheKey, JSON.stringify(throttlingCache));
9598
+ BrowserStorage.prototype.getItem = function (key) {
9599
+ return this.windowStorage.getItem(key);
9600
+ };
9601
+ BrowserStorage.prototype.setItem = function (key, value) {
9602
+ this.windowStorage.setItem(key, value);
9603
+ };
9604
+ BrowserStorage.prototype.removeItem = function (key) {
9605
+ this.windowStorage.removeItem(key);
9606
+ };
9607
+ BrowserStorage.prototype.getKeys = function () {
9608
+ return Object.keys(this.windowStorage);
9609
+ };
9610
+ BrowserStorage.prototype.containsKey = function (key) {
9611
+ return this.windowStorage.hasOwnProperty(key);
9375
9612
  };
9613
+ return BrowserStorage;
9614
+ }());
9615
+
9616
+ /*
9617
+ * Copyright (c) Microsoft Corporation. All rights reserved.
9618
+ * Licensed under the MIT License.
9619
+ */
9620
+ var BrowserProtocolUtils = /** @class */ (function () {
9621
+ function BrowserProtocolUtils() {
9622
+ }
9376
9623
  /**
9377
- * Gets cache item with given key.
9378
- * Will retrieve from cookies if storeAuthStateInCookie is set to true.
9379
- * @param key
9624
+ * Extracts the BrowserStateObject from the state string.
9625
+ * @param browserCrypto
9626
+ * @param state
9380
9627
  */
9381
- BrowserCacheManager.prototype.getTemporaryCache = function (cacheKey, generateKey) {
9382
- var key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
9383
- if (this.cacheConfig.storeAuthStateInCookie) {
9384
- var itemCookie = this.getItemCookie(key);
9385
- if (itemCookie) {
9386
- this.logger.trace("BrowserCacheManager.getTemporaryCache: storeAuthStateInCookies set to true, retrieving from cookies");
9387
- return itemCookie;
9388
- }
9389
- }
9390
- var value = this.temporaryCacheStorage.getItem(key);
9391
- if (!value) {
9392
- // If temp cache item not found in session/memory, check local storage for items set by old versions
9393
- if (this.cacheConfig.cacheLocation === exports.BrowserCacheLocation.LocalStorage) {
9394
- var item = this.browserStorage.getItem(key);
9395
- if (item) {
9396
- this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item found in local storage");
9397
- return item;
9398
- }
9399
- }
9400
- this.logger.trace("BrowserCacheManager.getTemporaryCache: No cache item found in local storage");
9628
+ BrowserProtocolUtils.extractBrowserRequestState = function (browserCrypto, state) {
9629
+ if (StringUtils.isEmpty(state)) {
9401
9630
  return null;
9402
9631
  }
9403
- this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item returned");
9404
- return value;
9632
+ try {
9633
+ var requestStateObj = ProtocolUtils.parseRequestState(browserCrypto, state);
9634
+ return requestStateObj.libraryState.meta;
9635
+ }
9636
+ catch (e) {
9637
+ throw ClientAuthError.createInvalidStateError(state, e);
9638
+ }
9405
9639
  };
9406
9640
  /**
9407
- * Sets the cache item with the key and value given.
9408
- * Stores in cookie if storeAuthStateInCookie is set to true.
9409
- * This can cause cookie overflow if used incorrectly.
9410
- * @param key
9411
- * @param value
9641
+ * Parses properties of server response from url hash
9642
+ * @param locationHash Hash from url
9412
9643
  */
9413
- BrowserCacheManager.prototype.setTemporaryCache = function (cacheKey, value, generateKey) {
9414
- var key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
9415
- this.temporaryCacheStorage.setItem(key, value);
9416
- if (this.cacheConfig.storeAuthStateInCookie) {
9417
- this.logger.trace("BrowserCacheManager.setTemporaryCache: storeAuthStateInCookie set to true, setting item cookie");
9418
- this.setItemCookie(key, value);
9644
+ BrowserProtocolUtils.parseServerResponseFromHash = function (locationHash) {
9645
+ if (!locationHash) {
9646
+ return {};
9419
9647
  }
9648
+ var hashUrlString = new UrlString(locationHash);
9649
+ return UrlString.getDeserializedHash(hashUrlString.getHash());
9420
9650
  };
9651
+ return BrowserProtocolUtils;
9652
+ }());
9653
+
9654
+ /*
9655
+ * Copyright (c) Microsoft Corporation. All rights reserved.
9656
+ * Licensed under the MIT License.
9657
+ */
9658
+ /**
9659
+ * This class implements the cache storage interface for MSAL through browser local or session storage.
9660
+ * Cookies are only used if storeAuthStateInCookie is true, and are only used for
9661
+ * parameters such as state and nonce, generally.
9662
+ */
9663
+ var BrowserCacheManager = /** @class */ (function (_super) {
9664
+ __extends$1(BrowserCacheManager, _super);
9665
+ function BrowserCacheManager(clientId, cacheConfig, cryptoImpl, logger) {
9666
+ var _this = _super.call(this, clientId, cryptoImpl) || this;
9667
+ // Cookie life calculation (hours * minutes * seconds * ms)
9668
+ _this.COOKIE_LIFE_MULTIPLIER = 24 * 60 * 60 * 1000;
9669
+ _this.cacheConfig = cacheConfig;
9670
+ _this.logger = logger;
9671
+ _this.internalStorage = new MemoryStorage();
9672
+ _this.browserStorage = _this.setupBrowserStorage(_this.cacheConfig.cacheLocation);
9673
+ _this.temporaryCacheStorage = _this.setupTemporaryCacheStorage(_this.cacheConfig.cacheLocation);
9674
+ // Migrate any cache entries from older versions of MSAL.
9675
+ _this.migrateCacheEntries();
9676
+ return _this;
9677
+ }
9421
9678
  /**
9422
- * Removes the cache item with the given key.
9423
- * Will also clear the cookie item if storeAuthStateInCookie is set to true.
9424
- * @param key
9679
+ * Returns a window storage class implementing the IWindowStorage interface that corresponds to the configured cacheLocation.
9680
+ * @param cacheLocation
9425
9681
  */
9426
- BrowserCacheManager.prototype.removeItem = function (key) {
9427
- this.browserStorage.removeItem(key);
9428
- this.temporaryCacheStorage.removeItem(key);
9429
- if (this.cacheConfig.storeAuthStateInCookie) {
9430
- this.logger.trace("BrowserCacheManager.removeItem: storeAuthStateInCookie is true, clearing item cookie");
9431
- this.clearItemCookie(key);
9682
+ BrowserCacheManager.prototype.setupBrowserStorage = function (cacheLocation) {
9683
+ switch (cacheLocation) {
9684
+ case exports.BrowserCacheLocation.LocalStorage:
9685
+ case exports.BrowserCacheLocation.SessionStorage:
9686
+ try {
9687
+ // Temporary cache items will always be stored in session storage to mitigate problems caused by multiple tabs
9688
+ return new BrowserStorage(cacheLocation);
9689
+ }
9690
+ catch (e) {
9691
+ this.logger.verbose(e);
9692
+ break;
9693
+ }
9694
+ case exports.BrowserCacheLocation.MemoryStorage:
9432
9695
  }
9433
- return true;
9696
+ this.cacheConfig.cacheLocation = exports.BrowserCacheLocation.MemoryStorage;
9697
+ return new MemoryStorage();
9434
9698
  };
9435
9699
  /**
9436
- * Checks whether key is in cache.
9437
- * @param key
9700
+ *
9701
+ * @param cacheLocation
9438
9702
  */
9439
- BrowserCacheManager.prototype.containsKey = function (key) {
9440
- return this.browserStorage.containsKey(key) || this.temporaryCacheStorage.containsKey(key);
9703
+ BrowserCacheManager.prototype.setupTemporaryCacheStorage = function (cacheLocation) {
9704
+ switch (cacheLocation) {
9705
+ case exports.BrowserCacheLocation.LocalStorage:
9706
+ case exports.BrowserCacheLocation.SessionStorage:
9707
+ try {
9708
+ // Temporary cache items will always be stored in session storage to mitigate problems caused by multiple tabs
9709
+ return new BrowserStorage(exports.BrowserCacheLocation.SessionStorage);
9710
+ }
9711
+ catch (e) {
9712
+ this.logger.verbose(e);
9713
+ return this.internalStorage;
9714
+ }
9715
+ case exports.BrowserCacheLocation.MemoryStorage:
9716
+ default:
9717
+ return this.internalStorage;
9718
+ }
9441
9719
  };
9442
9720
  /**
9443
- * Gets all keys in window.
9721
+ * Migrate all old cache entries to new schema. No rollback supported.
9722
+ * @param storeAuthStateInCookie
9444
9723
  */
9445
- BrowserCacheManager.prototype.getKeys = function () {
9446
- return __spread(this.browserStorage.getKeys(), this.temporaryCacheStorage.getKeys());
9724
+ BrowserCacheManager.prototype.migrateCacheEntries = function () {
9725
+ var _this = this;
9726
+ var idTokenKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.ID_TOKEN;
9727
+ var clientInfoKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.CLIENT_INFO;
9728
+ var errorKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.ERROR;
9729
+ var errorDescKey = Constants.CACHE_PREFIX + "." + PersistentCacheKeys.ERROR_DESC;
9730
+ var idTokenValue = this.browserStorage.getItem(idTokenKey);
9731
+ var clientInfoValue = this.browserStorage.getItem(clientInfoKey);
9732
+ var errorValue = this.browserStorage.getItem(errorKey);
9733
+ var errorDescValue = this.browserStorage.getItem(errorDescKey);
9734
+ var values = [idTokenValue, clientInfoValue, errorValue, errorDescValue];
9735
+ var keysToMigrate = [PersistentCacheKeys.ID_TOKEN, PersistentCacheKeys.CLIENT_INFO, PersistentCacheKeys.ERROR, PersistentCacheKeys.ERROR_DESC];
9736
+ keysToMigrate.forEach(function (cacheKey, index) { return _this.migrateCacheEntry(cacheKey, values[index]); });
9447
9737
  };
9448
9738
  /**
9449
- * Clears all cache entries created by MSAL.
9739
+ * Utility function to help with migration.
9740
+ * @param newKey
9741
+ * @param value
9742
+ * @param storeAuthStateInCookie
9450
9743
  */
9451
- BrowserCacheManager.prototype.clear = function () {
9452
- return __awaiter$1(this, void 0, void 0, function () {
9453
- var _this = this;
9454
- return __generator$1(this, function (_a) {
9455
- switch (_a.label) {
9456
- case 0:
9457
- // Removes all accounts and their credentials
9458
- return [4 /*yield*/, this.removeAllAccounts()];
9459
- case 1:
9460
- // Removes all accounts and their credentials
9461
- _a.sent();
9462
- this.removeAppMetadata();
9463
- // Removes all remaining MSAL cache items
9464
- this.getKeys().forEach(function (cacheKey) {
9465
- // Check if key contains msal prefix; For now, we are clearing all the cache items created by MSAL.js
9466
- if ((_this.browserStorage.containsKey(cacheKey) || _this.temporaryCacheStorage.containsKey(cacheKey)) && ((cacheKey.indexOf(Constants.CACHE_PREFIX) !== -1) || (cacheKey.indexOf(_this.clientId) !== -1))) {
9467
- _this.removeItem(cacheKey);
9468
- }
9469
- });
9470
- this.internalStorage.clear();
9471
- return [2 /*return*/];
9472
- }
9473
- });
9474
- });
9744
+ BrowserCacheManager.prototype.migrateCacheEntry = function (newKey, value) {
9745
+ if (value) {
9746
+ this.setTemporaryCache(newKey, value, true);
9747
+ }
9475
9748
  };
9476
9749
  /**
9477
- * Add value to cookies
9478
- * @param cookieName
9479
- * @param cookieValue
9480
- * @param expires
9750
+ * Parses passed value as JSON object, JSON.parse() will throw an error.
9751
+ * @param input
9481
9752
  */
9482
- BrowserCacheManager.prototype.setItemCookie = function (cookieName, cookieValue, expires) {
9483
- var cookieStr = encodeURIComponent(cookieName) + "=" + encodeURIComponent(cookieValue) + ";path=/;";
9484
- if (expires) {
9485
- var expireTime = this.getCookieExpirationTime(expires);
9486
- cookieStr += "expires=" + expireTime + ";";
9753
+ BrowserCacheManager.prototype.validateAndParseJson = function (jsonValue) {
9754
+ try {
9755
+ var parsedJson = JSON.parse(jsonValue);
9756
+ /**
9757
+ * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
9758
+ * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
9759
+ * of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
9760
+ *
9761
+ */
9762
+ return (parsedJson && typeof parsedJson === "object") ? parsedJson : null;
9487
9763
  }
9488
- if (this.cacheConfig.secureCookies) {
9489
- cookieStr += "Secure;";
9764
+ catch (error) {
9765
+ return null;
9490
9766
  }
9491
- document.cookie = cookieStr;
9492
9767
  };
9493
9768
  /**
9494
- * Get one item by key from cookies
9495
- * @param cookieName
9769
+ * fetches the entry from the browser storage based off the key
9770
+ * @param key
9496
9771
  */
9497
- BrowserCacheManager.prototype.getItemCookie = function (cookieName) {
9498
- var name = encodeURIComponent(cookieName) + "=";
9499
- var cookieList = document.cookie.split(";");
9500
- for (var i = 0; i < cookieList.length; i++) {
9501
- var cookie = cookieList[i];
9502
- while (cookie.charAt(0) === " ") {
9503
- cookie = cookie.substring(1);
9504
- }
9505
- if (cookie.indexOf(name) === 0) {
9506
- return decodeURIComponent(cookie.substring(name.length, cookie.length));
9507
- }
9508
- }
9509
- return "";
9772
+ BrowserCacheManager.prototype.getItem = function (key) {
9773
+ return this.browserStorage.getItem(key);
9510
9774
  };
9511
9775
  /**
9512
- * Clear all msal-related cookies currently set in the browser. Should only be used to clear temporary cache items.
9776
+ * sets the entry in the browser storage
9777
+ * @param key
9778
+ * @param value
9513
9779
  */
9514
- BrowserCacheManager.prototype.clearMsalCookies = function () {
9515
- var _this = this;
9516
- var cookiePrefix = Constants.CACHE_PREFIX + "." + this.clientId;
9517
- var cookieList = document.cookie.split(";");
9518
- cookieList.forEach(function (cookie) {
9519
- while (cookie.charAt(0) === " ") {
9520
- // eslint-disable-next-line no-param-reassign
9521
- cookie = cookie.substring(1);
9522
- }
9523
- if (cookie.indexOf(cookiePrefix) === 0) {
9524
- var cookieKey = cookie.split("=")[0];
9525
- _this.clearItemCookie(cookieKey);
9526
- }
9527
- });
9780
+ BrowserCacheManager.prototype.setItem = function (key, value) {
9781
+ this.browserStorage.setItem(key, value);
9528
9782
  };
9529
9783
  /**
9530
- * Clear an item in the cookies by key
9531
- * @param cookieName
9784
+ * fetch the account entity from the platform cache
9785
+ * @param accountKey
9532
9786
  */
9533
- BrowserCacheManager.prototype.clearItemCookie = function (cookieName) {
9534
- this.setItemCookie(cookieName, "", -1);
9787
+ BrowserCacheManager.prototype.getAccount = function (accountKey) {
9788
+ var account = this.getItem(accountKey);
9789
+ if (!account) {
9790
+ return null;
9791
+ }
9792
+ var parsedAccount = this.validateAndParseJson(account);
9793
+ if (!parsedAccount || !AccountEntity.isAccountEntity(parsedAccount)) {
9794
+ return null;
9795
+ }
9796
+ return CacheManager.toObject(new AccountEntity(), parsedAccount);
9535
9797
  };
9536
9798
  /**
9537
- * Get cookie expiration time
9538
- * @param cookieLifeDays
9799
+ * set account entity in the platform cache
9800
+ * @param key
9801
+ * @param value
9539
9802
  */
9540
- BrowserCacheManager.prototype.getCookieExpirationTime = function (cookieLifeDays) {
9541
- var today = new Date();
9542
- var expr = new Date(today.getTime() + cookieLifeDays * this.COOKIE_LIFE_MULTIPLIER);
9543
- return expr.toUTCString();
9803
+ BrowserCacheManager.prototype.setAccount = function (account) {
9804
+ this.logger.trace("BrowserCacheManager.setAccount called");
9805
+ var key = account.generateAccountKey();
9806
+ this.setItem(key, JSON.stringify(account));
9544
9807
  };
9545
9808
  /**
9546
- * Gets the cache object referenced by the browser
9809
+ * generates idToken entity from a string
9810
+ * @param idTokenKey
9547
9811
  */
9548
- BrowserCacheManager.prototype.getCache = function () {
9549
- return this.browserStorage;
9812
+ BrowserCacheManager.prototype.getIdTokenCredential = function (idTokenKey) {
9813
+ var value = this.getItem(idTokenKey);
9814
+ if (!value) {
9815
+ this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit");
9816
+ return null;
9817
+ }
9818
+ var parsedIdToken = this.validateAndParseJson(value);
9819
+ if (!parsedIdToken || !IdTokenEntity.isIdTokenEntity(parsedIdToken)) {
9820
+ this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit");
9821
+ return null;
9822
+ }
9823
+ this.logger.trace("BrowserCacheManager.getIdTokenCredential: cache hit");
9824
+ return CacheManager.toObject(new IdTokenEntity(), parsedIdToken);
9550
9825
  };
9551
9826
  /**
9552
- * interface compat, we cannot overwrite browser cache; Functionality is supported by individual entities in browser
9827
+ * set IdToken credential to the platform cache
9828
+ * @param idToken
9553
9829
  */
9554
- BrowserCacheManager.prototype.setCache = function () {
9555
- // sets nothing
9830
+ BrowserCacheManager.prototype.setIdTokenCredential = function (idToken) {
9831
+ this.logger.trace("BrowserCacheManager.setIdTokenCredential called");
9832
+ var idTokenKey = idToken.generateCredentialKey();
9833
+ this.setItem(idTokenKey, JSON.stringify(idToken));
9556
9834
  };
9557
9835
  /**
9558
- * Prepend msal.<client-id> to each key; Skip for any JSON object as Key (defined schemas do not need the key appended: AccessToken Keys or the upcoming schema)
9836
+ * generates accessToken entity from a string
9559
9837
  * @param key
9560
- * @param addInstanceId
9561
9838
  */
9562
- BrowserCacheManager.prototype.generateCacheKey = function (key) {
9563
- var generatedKey = this.validateAndParseJson(key);
9564
- if (!generatedKey) {
9565
- if (StringUtils.startsWith(key, Constants.CACHE_PREFIX) || StringUtils.startsWith(key, PersistentCacheKeys.ADAL_ID_TOKEN)) {
9566
- return key;
9567
- }
9568
- return Constants.CACHE_PREFIX + "." + this.clientId + "." + key;
9839
+ BrowserCacheManager.prototype.getAccessTokenCredential = function (accessTokenKey) {
9840
+ var value = this.getItem(accessTokenKey);
9841
+ if (!value) {
9842
+ this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit");
9843
+ return null;
9569
9844
  }
9570
- return JSON.stringify(key);
9845
+ var parsedAccessToken = this.validateAndParseJson(value);
9846
+ if (!parsedAccessToken || !AccessTokenEntity.isAccessTokenEntity(parsedAccessToken)) {
9847
+ this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit");
9848
+ return null;
9849
+ }
9850
+ this.logger.trace("BrowserCacheManager.getAccessTokenCredential: cache hit");
9851
+ return CacheManager.toObject(new AccessTokenEntity(), parsedAccessToken);
9571
9852
  };
9572
9853
  /**
9573
- * Create authorityKey to cache authority
9574
- * @param state
9854
+ * set accessToken credential to the platform cache
9855
+ * @param accessToken
9575
9856
  */
9576
- BrowserCacheManager.prototype.generateAuthorityKey = function (stateString) {
9577
- var stateId = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString).libraryState.id;
9578
- return this.generateCacheKey(TemporaryCacheKeys.AUTHORITY + "." + stateId);
9857
+ BrowserCacheManager.prototype.setAccessTokenCredential = function (accessToken) {
9858
+ this.logger.trace("BrowserCacheManager.setAccessTokenCredential called");
9859
+ var accessTokenKey = accessToken.generateCredentialKey();
9860
+ this.setItem(accessTokenKey, JSON.stringify(accessToken));
9579
9861
  };
9580
9862
  /**
9581
- * Create Nonce key to cache nonce
9582
- * @param state
9863
+ * generates refreshToken entity from a string
9864
+ * @param refreshTokenKey
9583
9865
  */
9584
- BrowserCacheManager.prototype.generateNonceKey = function (stateString) {
9585
- var stateId = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString).libraryState.id;
9586
- return this.generateCacheKey(TemporaryCacheKeys.NONCE_IDTOKEN + "." + stateId);
9866
+ BrowserCacheManager.prototype.getRefreshTokenCredential = function (refreshTokenKey) {
9867
+ var value = this.getItem(refreshTokenKey);
9868
+ if (!value) {
9869
+ this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit");
9870
+ return null;
9871
+ }
9872
+ var parsedRefreshToken = this.validateAndParseJson(value);
9873
+ if (!parsedRefreshToken || !RefreshTokenEntity.isRefreshTokenEntity(parsedRefreshToken)) {
9874
+ this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit");
9875
+ return null;
9876
+ }
9877
+ this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: cache hit");
9878
+ return CacheManager.toObject(new RefreshTokenEntity(), parsedRefreshToken);
9587
9879
  };
9588
9880
  /**
9589
- * Creates full cache key for the request state
9590
- * @param stateString State string for the request
9881
+ * set refreshToken credential to the platform cache
9882
+ * @param refreshToken
9591
9883
  */
9592
- BrowserCacheManager.prototype.generateStateKey = function (stateString) {
9593
- // Use the library state id to key temp storage for uniqueness for multiple concurrent requests
9594
- var stateId = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString).libraryState.id;
9595
- return this.generateCacheKey(TemporaryCacheKeys.REQUEST_STATE + "." + stateId);
9884
+ BrowserCacheManager.prototype.setRefreshTokenCredential = function (refreshToken) {
9885
+ this.logger.trace("BrowserCacheManager.setRefreshTokenCredential called");
9886
+ var refreshTokenKey = refreshToken.generateCredentialKey();
9887
+ this.setItem(refreshTokenKey, JSON.stringify(refreshToken));
9596
9888
  };
9597
9889
  /**
9598
- * Gets the cached authority based on the cached state. Returns empty if no cached state found.
9890
+ * fetch appMetadata entity from the platform cache
9891
+ * @param appMetadataKey
9599
9892
  */
9600
- BrowserCacheManager.prototype.getCachedAuthority = function (cachedState) {
9601
- var stateCacheKey = this.generateStateKey(cachedState);
9602
- var state = this.getTemporaryCache(stateCacheKey);
9603
- if (!state) {
9893
+ BrowserCacheManager.prototype.getAppMetadata = function (appMetadataKey) {
9894
+ var value = this.getItem(appMetadataKey);
9895
+ if (!value) {
9896
+ this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit");
9604
9897
  return null;
9605
9898
  }
9606
- var authorityCacheKey = this.generateAuthorityKey(state);
9607
- return this.getTemporaryCache(authorityCacheKey);
9899
+ var parsedMetadata = this.validateAndParseJson(value);
9900
+ if (!parsedMetadata || !AppMetadataEntity.isAppMetadataEntity(appMetadataKey, parsedMetadata)) {
9901
+ this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit");
9902
+ return null;
9903
+ }
9904
+ this.logger.trace("BrowserCacheManager.getAppMetadata: cache hit");
9905
+ return CacheManager.toObject(new AppMetadataEntity(), parsedMetadata);
9608
9906
  };
9609
9907
  /**
9610
- * Updates account, authority, and state in cache
9611
- * @param serverAuthenticationRequest
9612
- * @param account
9908
+ * set appMetadata entity to the platform cache
9909
+ * @param appMetadata
9613
9910
  */
9614
- BrowserCacheManager.prototype.updateCacheEntries = function (state, nonce, authorityInstance, loginHint, account) {
9615
- this.logger.trace("BrowserCacheManager.updateCacheEntries called");
9616
- // Cache the request state
9617
- var stateCacheKey = this.generateStateKey(state);
9618
- this.setTemporaryCache(stateCacheKey, state, false);
9619
- // Cache the nonce
9620
- var nonceCacheKey = this.generateNonceKey(state);
9621
- this.setTemporaryCache(nonceCacheKey, nonce, false);
9622
- // Cache authorityKey
9623
- var authorityCacheKey = this.generateAuthorityKey(state);
9624
- this.setTemporaryCache(authorityCacheKey, authorityInstance, false);
9625
- if (account) {
9626
- var ccsCredential = {
9627
- credential: account.homeAccountId,
9628
- type: CcsCredentialType.HOME_ACCOUNT_ID
9629
- };
9630
- this.setTemporaryCache(TemporaryCacheKeys.CCS_CREDENTIAL, JSON.stringify(ccsCredential), true);
9631
- }
9632
- else if (!StringUtils.isEmpty(loginHint)) {
9633
- var ccsCredential = {
9634
- credential: loginHint,
9635
- type: CcsCredentialType.UPN
9636
- };
9637
- this.setTemporaryCache(TemporaryCacheKeys.CCS_CREDENTIAL, JSON.stringify(ccsCredential), true);
9638
- }
9911
+ BrowserCacheManager.prototype.setAppMetadata = function (appMetadata) {
9912
+ this.logger.trace("BrowserCacheManager.setAppMetadata called");
9913
+ var appMetadataKey = appMetadata.generateAppMetadataKey();
9914
+ this.setItem(appMetadataKey, JSON.stringify(appMetadata));
9639
9915
  };
9640
9916
  /**
9641
- * Reset all temporary cache items
9642
- * @param state
9917
+ * fetch server telemetry entity from the platform cache
9918
+ * @param serverTelemetryKey
9643
9919
  */
9644
- BrowserCacheManager.prototype.resetRequestCache = function (state) {
9645
- var _this = this;
9646
- this.logger.trace("BrowserCacheManager.resetRequestCache called");
9647
- // check state and remove associated cache items
9648
- if (!StringUtils.isEmpty(state)) {
9649
- this.getKeys().forEach(function (key) {
9650
- if (key.indexOf(state) !== -1) {
9651
- _this.removeItem(key);
9652
- }
9653
- });
9920
+ BrowserCacheManager.prototype.getServerTelemetry = function (serverTelemetryKey) {
9921
+ var value = this.getItem(serverTelemetryKey);
9922
+ if (!value) {
9923
+ this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit");
9924
+ return null;
9654
9925
  }
9655
- // delete generic interactive request parameters
9656
- if (state) {
9657
- this.removeItem(this.generateStateKey(state));
9658
- this.removeItem(this.generateNonceKey(state));
9659
- this.removeItem(this.generateAuthorityKey(state));
9926
+ var parsedMetadata = this.validateAndParseJson(value);
9927
+ if (!parsedMetadata || !ServerTelemetryEntity.isServerTelemetryEntity(serverTelemetryKey, parsedMetadata)) {
9928
+ this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit");
9929
+ return null;
9660
9930
  }
9661
- this.removeItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
9662
- this.removeItem(this.generateCacheKey(TemporaryCacheKeys.ORIGIN_URI));
9663
- this.removeItem(this.generateCacheKey(TemporaryCacheKeys.URL_HASH));
9664
- this.removeItem(this.generateCacheKey(TemporaryCacheKeys.CORRELATION_ID));
9665
- this.removeItem(this.generateCacheKey(TemporaryCacheKeys.CCS_CREDENTIAL));
9666
- this.setInteractionInProgress(false);
9931
+ this.logger.trace("BrowserCacheManager.getServerTelemetry: cache hit");
9932
+ return CacheManager.toObject(new ServerTelemetryEntity(), parsedMetadata);
9667
9933
  };
9668
9934
  /**
9669
- * Removes temporary cache for the provided state
9670
- * @param stateString
9935
+ * set server telemetry entity to the platform cache
9936
+ * @param serverTelemetryKey
9937
+ * @param serverTelemetry
9671
9938
  */
9672
- BrowserCacheManager.prototype.cleanRequestByState = function (stateString) {
9673
- this.logger.trace("BrowserCacheManager.cleanRequestByState called");
9674
- // Interaction is completed - remove interaction status.
9675
- if (stateString) {
9676
- var stateKey = this.generateStateKey(stateString);
9677
- var cachedState = this.temporaryCacheStorage.getItem(stateKey);
9678
- this.logger.infoPii("BrowserCacheManager.cleanRequestByState: Removing temporary cache items for state: " + cachedState);
9679
- this.resetRequestCache(cachedState || "");
9939
+ BrowserCacheManager.prototype.setServerTelemetry = function (serverTelemetryKey, serverTelemetry) {
9940
+ this.logger.trace("BrowserCacheManager.setServerTelemetry called");
9941
+ this.setItem(serverTelemetryKey, JSON.stringify(serverTelemetry));
9942
+ };
9943
+ /**
9944
+ *
9945
+ */
9946
+ BrowserCacheManager.prototype.getAuthorityMetadata = function (key) {
9947
+ var value = this.internalStorage.getItem(key);
9948
+ if (!value) {
9949
+ this.logger.trace("BrowserCacheManager.getAuthorityMetadata: called, no cache hit");
9950
+ return null;
9680
9951
  }
9681
- this.clearMsalCookies();
9952
+ var parsedMetadata = this.validateAndParseJson(value);
9953
+ if (parsedMetadata && AuthorityMetadataEntity.isAuthorityMetadataEntity(key, parsedMetadata)) {
9954
+ this.logger.trace("BrowserCacheManager.getAuthorityMetadata: cache hit");
9955
+ return CacheManager.toObject(new AuthorityMetadataEntity(), parsedMetadata);
9956
+ }
9957
+ return null;
9682
9958
  };
9683
9959
  /**
9684
- * Looks in temporary cache for any state values with the provided interactionType and removes all temporary cache items for that state
9685
- * Used in scenarios where temp cache needs to be cleaned but state is not known, such as clicking browser back button.
9686
- * @param interactionType
9960
+ *
9687
9961
  */
9688
- BrowserCacheManager.prototype.cleanRequestByInteractionType = function (interactionType) {
9962
+ BrowserCacheManager.prototype.getAuthorityMetadataKeys = function () {
9689
9963
  var _this = this;
9690
- this.logger.trace("BrowserCacheManager.cleanRequestByInteractionType called");
9691
- // Loop through all keys to find state key
9692
- this.getKeys().forEach(function (key) {
9693
- // If this key is not the state key, move on
9694
- if (key.indexOf(TemporaryCacheKeys.REQUEST_STATE) === -1) {
9695
- return;
9696
- }
9697
- // Retrieve state value, return if not a valid value
9698
- var stateValue = _this.temporaryCacheStorage.getItem(key);
9699
- if (!stateValue) {
9700
- return;
9701
- }
9702
- // Extract state and ensure it matches given InteractionType, then clean request cache
9703
- var parsedState = BrowserProtocolUtils.extractBrowserRequestState(_this.cryptoImpl, stateValue);
9704
- if (parsedState && parsedState.interactionType === interactionType) {
9705
- _this.logger.infoPii("BrowserCacheManager.cleanRequestByInteractionType: Removing temporary cache items for state: " + stateValue);
9706
- _this.resetRequestCache(stateValue);
9707
- }
9964
+ var allKeys = this.internalStorage.getKeys();
9965
+ return allKeys.filter(function (key) {
9966
+ return _this.isAuthorityMetadata(key);
9708
9967
  });
9709
- this.clearMsalCookies();
9710
- };
9711
- BrowserCacheManager.prototype.cacheCodeRequest = function (authCodeRequest, browserCrypto) {
9712
- this.logger.trace("BrowserCacheManager.cacheCodeRequest called");
9713
- var encodedValue = browserCrypto.base64Encode(JSON.stringify(authCodeRequest));
9714
- this.setTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, encodedValue, true);
9715
9968
  };
9716
9969
  /**
9717
- * Gets the token exchange parameters from the cache. Throws an error if nothing is found.
9970
+ * Sets wrapper metadata in memory
9971
+ * @param wrapperSKU
9972
+ * @param wrapperVersion
9718
9973
  */
9719
- BrowserCacheManager.prototype.getCachedRequest = function (state, browserCrypto) {
9720
- this.logger.trace("BrowserCacheManager.getCachedRequest called");
9721
- // Get token request from cache and parse as TokenExchangeParameters.
9722
- var encodedTokenRequest = this.getTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, true);
9723
- if (!encodedTokenRequest) {
9724
- throw BrowserAuthError.createNoTokenRequestCacheError();
9725
- }
9726
- var parsedRequest = this.validateAndParseJson(browserCrypto.base64Decode(encodedTokenRequest));
9727
- if (!parsedRequest) {
9728
- throw BrowserAuthError.createUnableToParseTokenRequestCacheError();
9729
- }
9730
- this.removeItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
9731
- // Get cached authority and use if no authority is cached with request.
9732
- if (StringUtils.isEmpty(parsedRequest.authority)) {
9733
- var authorityCacheKey = this.generateAuthorityKey(state);
9734
- var cachedAuthority = this.getTemporaryCache(authorityCacheKey);
9735
- if (!cachedAuthority) {
9736
- throw BrowserAuthError.createNoCachedAuthorityError();
9737
- }
9738
- parsedRequest.authority = cachedAuthority;
9739
- }
9740
- return parsedRequest;
9974
+ BrowserCacheManager.prototype.setWrapperMetadata = function (wrapperSKU, wrapperVersion) {
9975
+ this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_SKU, wrapperSKU);
9976
+ this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_VER, wrapperVersion);
9741
9977
  };
9742
- BrowserCacheManager.prototype.isInteractionInProgress = function (matchClientId) {
9743
- var clientId = this.getInteractionInProgress();
9744
- if (matchClientId) {
9745
- return clientId === this.clientId;
9746
- }
9747
- else {
9748
- return !!clientId;
9749
- }
9978
+ /**
9979
+ * Returns wrapper metadata from in-memory storage
9980
+ */
9981
+ BrowserCacheManager.prototype.getWrapperMetadata = function () {
9982
+ var sku = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_SKU) || "";
9983
+ var version = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_VER) || "";
9984
+ return [sku, version];
9750
9985
  };
9751
- BrowserCacheManager.prototype.getInteractionInProgress = function () {
9752
- var key = Constants.CACHE_PREFIX + "." + TemporaryCacheKeys.INTERACTION_STATUS_KEY;
9753
- return this.getTemporaryCache(key, false);
9986
+ /**
9987
+ *
9988
+ * @param entity
9989
+ */
9990
+ BrowserCacheManager.prototype.setAuthorityMetadata = function (key, entity) {
9991
+ this.logger.trace("BrowserCacheManager.setAuthorityMetadata called");
9992
+ this.internalStorage.setItem(key, JSON.stringify(entity));
9754
9993
  };
9755
- BrowserCacheManager.prototype.setInteractionInProgress = function (inProgress) {
9756
- var clientId = this.getInteractionInProgress();
9757
- // Ensure we don't overwrite interaction in progress for a different clientId
9758
- var key = Constants.CACHE_PREFIX + "." + TemporaryCacheKeys.INTERACTION_STATUS_KEY;
9759
- if (inProgress && !clientId) {
9760
- // No interaction is in progress
9761
- this.setTemporaryCache(key, this.clientId, false);
9762
- }
9763
- else if (!inProgress && clientId === this.clientId) {
9764
- this.removeItem(key);
9994
+ /**
9995
+ * Gets the active account
9996
+ */
9997
+ BrowserCacheManager.prototype.getActiveAccount = function () {
9998
+ var activeAccountIdKey = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT);
9999
+ var activeAccountId = this.browserStorage.getItem(activeAccountIdKey);
10000
+ if (!activeAccountId) {
10001
+ return null;
9765
10002
  }
10003
+ return this.getAccountInfoByFilter({ localAccountId: activeAccountId })[0] || null;
9766
10004
  };
9767
10005
  /**
9768
- * Returns username retrieved from ADAL or MSAL v1 idToken
10006
+ * Sets the active account's localAccountId in cache
10007
+ * @param account
9769
10008
  */
9770
- BrowserCacheManager.prototype.getLegacyLoginHint = function () {
9771
- // Only check for adal/msal token if no SSO params are being used
9772
- var adalIdTokenString = this.getTemporaryCache(PersistentCacheKeys.ADAL_ID_TOKEN);
9773
- if (adalIdTokenString) {
9774
- this.browserStorage.removeItem(PersistentCacheKeys.ADAL_ID_TOKEN);
9775
- this.logger.verbose("Cached ADAL id token retrieved.");
10009
+ BrowserCacheManager.prototype.setActiveAccount = function (account) {
10010
+ var activeAccountIdKey = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT);
10011
+ if (account) {
10012
+ this.logger.verbose("setActiveAccount: Active account set");
10013
+ this.browserStorage.setItem(activeAccountIdKey, account.localAccountId);
9776
10014
  }
9777
- // Check for cached MSAL v1 id token
9778
- var msalIdTokenString = this.getTemporaryCache(PersistentCacheKeys.ID_TOKEN, true);
9779
- if (msalIdTokenString) {
9780
- this.removeItem(this.generateCacheKey(PersistentCacheKeys.ID_TOKEN));
9781
- this.logger.verbose("Cached MSAL.js v1 id token retrieved");
10015
+ else {
10016
+ this.logger.verbose("setActiveAccount: No account passed, active account not set");
10017
+ this.browserStorage.removeItem(activeAccountIdKey);
9782
10018
  }
9783
- var cachedIdTokenString = msalIdTokenString || adalIdTokenString;
9784
- if (cachedIdTokenString) {
9785
- var cachedIdToken = new AuthToken(cachedIdTokenString, this.cryptoImpl);
9786
- if (cachedIdToken.claims && cachedIdToken.claims.preferred_username) {
9787
- this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, setting ADAL/MSAL v1 preferred_username as loginHint");
9788
- return cachedIdToken.claims.preferred_username;
10019
+ };
10020
+ /**
10021
+ * Gets a list of accounts that match all of the filters provided
10022
+ * @param account
10023
+ */
10024
+ BrowserCacheManager.prototype.getAccountInfoByFilter = function (accountFilter) {
10025
+ var allAccounts = this.getAllAccounts();
10026
+ return allAccounts.filter(function (accountObj) {
10027
+ if (accountFilter.username && accountFilter.username.toLowerCase() !== accountObj.username.toLowerCase()) {
10028
+ return false;
9789
10029
  }
9790
- else if (cachedIdToken.claims && cachedIdToken.claims.upn) {
9791
- this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, setting ADAL/MSAL v1 upn as loginHint");
9792
- return cachedIdToken.claims.upn;
10030
+ if (accountFilter.homeAccountId && accountFilter.homeAccountId !== accountObj.homeAccountId) {
10031
+ return false;
9793
10032
  }
9794
- else {
9795
- this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, however, no account hint claim found. Enable preferred_username or upn id token claim to get SSO.");
10033
+ if (accountFilter.localAccountId && accountFilter.localAccountId !== accountObj.localAccountId) {
10034
+ return false;
9796
10035
  }
9797
- }
9798
- return null;
10036
+ if (accountFilter.tenantId && accountFilter.tenantId !== accountObj.tenantId) {
10037
+ return false;
10038
+ }
10039
+ if (accountFilter.environment && accountFilter.environment !== accountObj.environment) {
10040
+ return false;
10041
+ }
10042
+ return true;
10043
+ });
9799
10044
  };
9800
- return BrowserCacheManager;
9801
- }(CacheManager));
9802
- var DEFAULT_BROWSER_CACHE_MANAGER = function (clientId, logger) {
9803
- var cacheOptions = {
9804
- cacheLocation: exports.BrowserCacheLocation.MemoryStorage,
9805
- storeAuthStateInCookie: false,
9806
- secureCookies: false
10045
+ /**
10046
+ * fetch throttling entity from the platform cache
10047
+ * @param throttlingCacheKey
10048
+ */
10049
+ BrowserCacheManager.prototype.getThrottlingCache = function (throttlingCacheKey) {
10050
+ var value = this.getItem(throttlingCacheKey);
10051
+ if (!value) {
10052
+ this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit");
10053
+ return null;
10054
+ }
10055
+ var parsedThrottlingCache = this.validateAndParseJson(value);
10056
+ if (!parsedThrottlingCache || !ThrottlingEntity.isThrottlingEntity(throttlingCacheKey, parsedThrottlingCache)) {
10057
+ this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit");
10058
+ return null;
10059
+ }
10060
+ this.logger.trace("BrowserCacheManager.getThrottlingCache: cache hit");
10061
+ return CacheManager.toObject(new ThrottlingEntity(), parsedThrottlingCache);
9807
10062
  };
9808
- return new BrowserCacheManager(clientId, cacheOptions, DEFAULT_CRYPTO_IMPLEMENTATION, logger);
9809
- };
9810
-
9811
- /*
9812
- * Copyright (c) Microsoft Corporation. All rights reserved.
9813
- * Licensed under the MIT License.
9814
- */
9815
- /**
9816
- * This class implements the Fetch API for GET and POST requests. See more here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
9817
- */
9818
- var FetchClient = /** @class */ (function () {
9819
- function FetchClient() {
9820
- }
9821
10063
  /**
9822
- * Fetch Client for REST endpoints - Get request
9823
- * @param url
9824
- * @param headers
9825
- * @param body
10064
+ * set throttling entity to the platform cache
10065
+ * @param throttlingCacheKey
10066
+ * @param throttlingCache
9826
10067
  */
9827
- FetchClient.prototype.sendGetRequestAsync = function (url, options) {
9828
- return __awaiter$1(this, void 0, void 0, function () {
9829
- var response, e_1, _a;
9830
- return __generator$1(this, function (_b) {
9831
- switch (_b.label) {
9832
- case 0:
9833
- _b.trys.push([0, 2, , 3]);
9834
- return [4 /*yield*/, fetch(url, {
9835
- method: HTTP_REQUEST_TYPE.GET,
9836
- headers: this.getFetchHeaders(options)
9837
- })];
9838
- case 1:
9839
- response = _b.sent();
9840
- return [3 /*break*/, 3];
9841
- case 2:
9842
- e_1 = _b.sent();
9843
- if (window.navigator.onLine) {
9844
- throw BrowserAuthError.createGetRequestFailedError(e_1, url);
9845
- }
9846
- else {
9847
- throw BrowserAuthError.createNoNetworkConnectivityError();
9848
- }
9849
- case 3:
9850
- _b.trys.push([3, 5, , 6]);
9851
- _a = {
9852
- headers: this.getHeaderDict(response.headers)
9853
- };
9854
- return [4 /*yield*/, response.json()];
9855
- case 4: return [2 /*return*/, (_a.body = (_b.sent()),
9856
- _a.status = response.status,
9857
- _a)];
9858
- case 5:
9859
- _b.sent();
9860
- throw BrowserAuthError.createFailedToParseNetworkResponseError(url);
9861
- case 6: return [2 /*return*/];
9862
- }
9863
- });
9864
- });
10068
+ BrowserCacheManager.prototype.setThrottlingCache = function (throttlingCacheKey, throttlingCache) {
10069
+ this.logger.trace("BrowserCacheManager.setThrottlingCache called");
10070
+ this.setItem(throttlingCacheKey, JSON.stringify(throttlingCache));
9865
10071
  };
9866
10072
  /**
9867
- * Fetch Client for REST endpoints - Post request
9868
- * @param url
9869
- * @param headers
9870
- * @param body
10073
+ * Gets cache item with given key.
10074
+ * Will retrieve from cookies if storeAuthStateInCookie is set to true.
10075
+ * @param key
9871
10076
  */
9872
- FetchClient.prototype.sendPostRequestAsync = function (url, options) {
9873
- return __awaiter$1(this, void 0, void 0, function () {
9874
- var reqBody, response, e_3, _a;
9875
- return __generator$1(this, function (_b) {
9876
- switch (_b.label) {
9877
- case 0:
9878
- reqBody = (options && options.body) || "";
9879
- _b.label = 1;
9880
- case 1:
9881
- _b.trys.push([1, 3, , 4]);
9882
- return [4 /*yield*/, fetch(url, {
9883
- method: HTTP_REQUEST_TYPE.POST,
9884
- headers: this.getFetchHeaders(options),
9885
- body: reqBody
9886
- })];
9887
- case 2:
9888
- response = _b.sent();
9889
- return [3 /*break*/, 4];
9890
- case 3:
9891
- e_3 = _b.sent();
9892
- if (window.navigator.onLine) {
9893
- throw BrowserAuthError.createPostRequestFailedError(e_3, url);
9894
- }
9895
- else {
9896
- throw BrowserAuthError.createNoNetworkConnectivityError();
9897
- }
9898
- case 4:
9899
- _b.trys.push([4, 6, , 7]);
9900
- _a = {
9901
- headers: this.getHeaderDict(response.headers)
9902
- };
9903
- return [4 /*yield*/, response.json()];
9904
- case 5: return [2 /*return*/, (_a.body = (_b.sent()),
9905
- _a.status = response.status,
9906
- _a)];
9907
- case 6:
9908
- _b.sent();
9909
- throw BrowserAuthError.createFailedToParseNetworkResponseError(url);
9910
- case 7: return [2 /*return*/];
10077
+ BrowserCacheManager.prototype.getTemporaryCache = function (cacheKey, generateKey) {
10078
+ var key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
10079
+ if (this.cacheConfig.storeAuthStateInCookie) {
10080
+ var itemCookie = this.getItemCookie(key);
10081
+ if (itemCookie) {
10082
+ this.logger.trace("BrowserCacheManager.getTemporaryCache: storeAuthStateInCookies set to true, retrieving from cookies");
10083
+ return itemCookie;
10084
+ }
10085
+ }
10086
+ var value = this.temporaryCacheStorage.getItem(key);
10087
+ if (!value) {
10088
+ // If temp cache item not found in session/memory, check local storage for items set by old versions
10089
+ if (this.cacheConfig.cacheLocation === exports.BrowserCacheLocation.LocalStorage) {
10090
+ var item = this.browserStorage.getItem(key);
10091
+ if (item) {
10092
+ this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item found in local storage");
10093
+ return item;
9911
10094
  }
9912
- });
9913
- });
10095
+ }
10096
+ this.logger.trace("BrowserCacheManager.getTemporaryCache: No cache item found in local storage");
10097
+ return null;
10098
+ }
10099
+ this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item returned");
10100
+ return value;
9914
10101
  };
9915
10102
  /**
9916
- * Get Fetch API Headers object from string map
9917
- * @param inputHeaders
10103
+ * Sets the cache item with the key and value given.
10104
+ * Stores in cookie if storeAuthStateInCookie is set to true.
10105
+ * This can cause cookie overflow if used incorrectly.
10106
+ * @param key
10107
+ * @param value
9918
10108
  */
9919
- FetchClient.prototype.getFetchHeaders = function (options) {
9920
- var headers = new Headers();
9921
- if (!(options && options.headers)) {
9922
- return headers;
10109
+ BrowserCacheManager.prototype.setTemporaryCache = function (cacheKey, value, generateKey) {
10110
+ var key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
10111
+ this.temporaryCacheStorage.setItem(key, value);
10112
+ if (this.cacheConfig.storeAuthStateInCookie) {
10113
+ this.logger.trace("BrowserCacheManager.setTemporaryCache: storeAuthStateInCookie set to true, setting item cookie");
10114
+ this.setItemCookie(key, value);
9923
10115
  }
9924
- var optionsHeaders = options.headers;
9925
- Object.keys(optionsHeaders).forEach(function (key) {
9926
- headers.append(key, optionsHeaders[key]);
9927
- });
9928
- return headers;
9929
10116
  };
9930
- FetchClient.prototype.getHeaderDict = function (headers) {
9931
- var headerDict = {};
9932
- headers.forEach(function (value, key) {
9933
- headerDict[key] = value;
9934
- });
9935
- return headerDict;
10117
+ /**
10118
+ * Removes the cache item with the given key.
10119
+ * Will also clear the cookie item if storeAuthStateInCookie is set to true.
10120
+ * @param key
10121
+ */
10122
+ BrowserCacheManager.prototype.removeItem = function (key) {
10123
+ this.browserStorage.removeItem(key);
10124
+ this.temporaryCacheStorage.removeItem(key);
10125
+ if (this.cacheConfig.storeAuthStateInCookie) {
10126
+ this.logger.trace("BrowserCacheManager.removeItem: storeAuthStateInCookie is true, clearing item cookie");
10127
+ this.clearItemCookie(key);
10128
+ }
10129
+ return true;
10130
+ };
10131
+ /**
10132
+ * Checks whether key is in cache.
10133
+ * @param key
10134
+ */
10135
+ BrowserCacheManager.prototype.containsKey = function (key) {
10136
+ return this.browserStorage.containsKey(key) || this.temporaryCacheStorage.containsKey(key);
9936
10137
  };
9937
- return FetchClient;
9938
- }());
9939
-
9940
- /*
9941
- * Copyright (c) Microsoft Corporation. All rights reserved.
9942
- * Licensed under the MIT License.
9943
- */
9944
- /**
9945
- * This client implements the XMLHttpRequest class to send GET and POST requests.
9946
- */
9947
- var XhrClient = /** @class */ (function () {
9948
- function XhrClient() {
9949
- }
9950
10138
  /**
9951
- * XhrClient for REST endpoints - Get request
9952
- * @param url
9953
- * @param headers
9954
- * @param body
10139
+ * Gets all keys in window.
9955
10140
  */
9956
- XhrClient.prototype.sendGetRequestAsync = function (url, options) {
9957
- return __awaiter$1(this, void 0, void 0, function () {
9958
- return __generator$1(this, function (_a) {
9959
- return [2 /*return*/, this.sendRequestAsync(url, HTTP_REQUEST_TYPE.GET, options)];
9960
- });
9961
- });
10141
+ BrowserCacheManager.prototype.getKeys = function () {
10142
+ return __spread(this.browserStorage.getKeys(), this.temporaryCacheStorage.getKeys());
9962
10143
  };
9963
10144
  /**
9964
- * XhrClient for REST endpoints - Post request
9965
- * @param url
9966
- * @param headers
9967
- * @param body
10145
+ * Clears all cache entries created by MSAL.
9968
10146
  */
9969
- XhrClient.prototype.sendPostRequestAsync = function (url, options) {
10147
+ BrowserCacheManager.prototype.clear = function () {
9970
10148
  return __awaiter$1(this, void 0, void 0, function () {
10149
+ var _this = this;
9971
10150
  return __generator$1(this, function (_a) {
9972
- return [2 /*return*/, this.sendRequestAsync(url, HTTP_REQUEST_TYPE.POST, options)];
10151
+ switch (_a.label) {
10152
+ case 0:
10153
+ // Removes all accounts and their credentials
10154
+ return [4 /*yield*/, this.removeAllAccounts()];
10155
+ case 1:
10156
+ // Removes all accounts and their credentials
10157
+ _a.sent();
10158
+ this.removeAppMetadata();
10159
+ // Removes all remaining MSAL cache items
10160
+ this.getKeys().forEach(function (cacheKey) {
10161
+ // Check if key contains msal prefix; For now, we are clearing all the cache items created by MSAL.js
10162
+ if ((_this.browserStorage.containsKey(cacheKey) || _this.temporaryCacheStorage.containsKey(cacheKey)) && ((cacheKey.indexOf(Constants.CACHE_PREFIX) !== -1) || (cacheKey.indexOf(_this.clientId) !== -1))) {
10163
+ _this.removeItem(cacheKey);
10164
+ }
10165
+ });
10166
+ this.internalStorage.clear();
10167
+ return [2 /*return*/];
10168
+ }
9973
10169
  });
9974
10170
  });
9975
10171
  };
9976
10172
  /**
9977
- * Helper for XhrClient requests.
9978
- * @param url
9979
- * @param method
9980
- * @param options
10173
+ * Add value to cookies
10174
+ * @param cookieName
10175
+ * @param cookieValue
10176
+ * @param expires
9981
10177
  */
9982
- XhrClient.prototype.sendRequestAsync = function (url, method, options) {
9983
- var _this = this;
9984
- return new Promise(function (resolve, reject) {
9985
- var xhr = new XMLHttpRequest();
9986
- xhr.open(method, url, /* async: */ true);
9987
- _this.setXhrHeaders(xhr, options);
9988
- xhr.onload = function () {
9989
- if (xhr.status < 200 || xhr.status >= 300) {
9990
- if (method === HTTP_REQUEST_TYPE.POST) {
9991
- reject(BrowserAuthError.createPostRequestFailedError("Failed with status " + xhr.status, url));
9992
- }
9993
- else {
9994
- reject(BrowserAuthError.createGetRequestFailedError("Failed with status " + xhr.status, url));
9995
- }
9996
- }
9997
- try {
9998
- var jsonResponse = JSON.parse(xhr.responseText);
9999
- var networkResponse = {
10000
- headers: _this.getHeaderDict(xhr),
10001
- body: jsonResponse,
10002
- status: xhr.status
10003
- };
10004
- resolve(networkResponse);
10005
- }
10006
- catch (e) {
10007
- reject(BrowserAuthError.createFailedToParseNetworkResponseError(url));
10008
- }
10009
- };
10010
- xhr.onerror = function () {
10011
- if (window.navigator.onLine) {
10012
- if (method === HTTP_REQUEST_TYPE.POST) {
10013
- reject(BrowserAuthError.createPostRequestFailedError("Failed with status " + xhr.status, url));
10014
- }
10015
- else {
10016
- reject(BrowserAuthError.createGetRequestFailedError("Failed with status " + xhr.status, url));
10017
- }
10018
- }
10019
- else {
10020
- reject(BrowserAuthError.createNoNetworkConnectivityError());
10021
- }
10022
- };
10023
- if (method === HTTP_REQUEST_TYPE.POST && options && options.body) {
10024
- xhr.send(options.body);
10025
- }
10026
- else if (method === HTTP_REQUEST_TYPE.GET) {
10027
- xhr.send();
10028
- }
10029
- else {
10030
- throw BrowserAuthError.createHttpMethodNotImplementedError(method);
10031
- }
10032
- });
10178
+ BrowserCacheManager.prototype.setItemCookie = function (cookieName, cookieValue, expires) {
10179
+ var cookieStr = encodeURIComponent(cookieName) + "=" + encodeURIComponent(cookieValue) + ";path=/;";
10180
+ if (expires) {
10181
+ var expireTime = this.getCookieExpirationTime(expires);
10182
+ cookieStr += "expires=" + expireTime + ";";
10183
+ }
10184
+ if (this.cacheConfig.secureCookies) {
10185
+ cookieStr += "Secure;";
10186
+ }
10187
+ document.cookie = cookieStr;
10033
10188
  };
10034
10189
  /**
10035
- * Helper to set XHR headers for request.
10036
- * @param xhr
10037
- * @param options
10190
+ * Get one item by key from cookies
10191
+ * @param cookieName
10038
10192
  */
10039
- XhrClient.prototype.setXhrHeaders = function (xhr, options) {
10040
- if (options && options.headers) {
10041
- var headers_1 = options.headers;
10042
- Object.keys(headers_1).forEach(function (key) {
10043
- xhr.setRequestHeader(key, headers_1[key]);
10044
- });
10193
+ BrowserCacheManager.prototype.getItemCookie = function (cookieName) {
10194
+ var name = encodeURIComponent(cookieName) + "=";
10195
+ var cookieList = document.cookie.split(";");
10196
+ for (var i = 0; i < cookieList.length; i++) {
10197
+ var cookie = cookieList[i];
10198
+ while (cookie.charAt(0) === " ") {
10199
+ cookie = cookie.substring(1);
10200
+ }
10201
+ if (cookie.indexOf(name) === 0) {
10202
+ return decodeURIComponent(cookie.substring(name.length, cookie.length));
10203
+ }
10045
10204
  }
10205
+ return "";
10046
10206
  };
10047
10207
  /**
10048
- * Gets a string map of the headers received in the response.
10049
- *
10050
- * Algorithm comes from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders
10051
- * @param xhr
10208
+ * Clear all msal-related cookies currently set in the browser. Should only be used to clear temporary cache items.
10052
10209
  */
10053
- XhrClient.prototype.getHeaderDict = function (xhr) {
10054
- var headerString = xhr.getAllResponseHeaders();
10055
- var headerArr = headerString.trim().split(/[\r\n]+/);
10056
- var headerDict = {};
10057
- headerArr.forEach(function (value) {
10058
- var parts = value.split(": ");
10059
- var headerName = parts.shift();
10060
- var headerVal = parts.join(": ");
10061
- if (headerName && headerVal) {
10062
- headerDict[headerName] = headerVal;
10210
+ BrowserCacheManager.prototype.clearMsalCookies = function () {
10211
+ var _this = this;
10212
+ var cookiePrefix = Constants.CACHE_PREFIX + "." + this.clientId;
10213
+ var cookieList = document.cookie.split(";");
10214
+ cookieList.forEach(function (cookie) {
10215
+ while (cookie.charAt(0) === " ") {
10216
+ // eslint-disable-next-line no-param-reassign
10217
+ cookie = cookie.substring(1);
10218
+ }
10219
+ if (cookie.indexOf(cookiePrefix) === 0) {
10220
+ var cookieKey = cookie.split("=")[0];
10221
+ _this.clearItemCookie(cookieKey);
10063
10222
  }
10064
10223
  });
10065
- return headerDict;
10066
10224
  };
10067
- return XhrClient;
10068
- }());
10069
-
10070
- /*
10071
- * Copyright (c) Microsoft Corporation. All rights reserved.
10072
- * Licensed under the MIT License.
10073
- */
10074
- /**
10075
- * Utility class for browser specific functions
10076
- */
10077
- var BrowserUtils = /** @class */ (function () {
10078
- function BrowserUtils() {
10079
- }
10080
- // #region Window Navigation and URL management
10081
10225
  /**
10082
- * Clears hash from window url.
10226
+ * Clear an item in the cookies by key
10227
+ * @param cookieName
10083
10228
  */
10084
- BrowserUtils.clearHash = function (contentWindow) {
10085
- // Office.js sets history.replaceState to null
10086
- contentWindow.location.hash = Constants.EMPTY_STRING;
10087
- if (typeof contentWindow.history.replaceState === "function") {
10088
- // Full removes "#" from url
10089
- contentWindow.history.replaceState(null, Constants.EMPTY_STRING, "" + contentWindow.location.origin + contentWindow.location.pathname + contentWindow.location.search);
10090
- }
10229
+ BrowserCacheManager.prototype.clearItemCookie = function (cookieName) {
10230
+ this.setItemCookie(cookieName, "", -1);
10091
10231
  };
10092
10232
  /**
10093
- * Replaces current hash with hash from provided url
10233
+ * Get cookie expiration time
10234
+ * @param cookieLifeDays
10094
10235
  */
10095
- BrowserUtils.replaceHash = function (url) {
10096
- var urlParts = url.split("#");
10097
- urlParts.shift(); // Remove part before the hash
10098
- window.location.hash = urlParts.length > 0 ? urlParts.join("#") : "";
10236
+ BrowserCacheManager.prototype.getCookieExpirationTime = function (cookieLifeDays) {
10237
+ var today = new Date();
10238
+ var expr = new Date(today.getTime() + cookieLifeDays * this.COOKIE_LIFE_MULTIPLIER);
10239
+ return expr.toUTCString();
10099
10240
  };
10100
10241
  /**
10101
- * Returns boolean of whether the current window is in an iframe or not.
10242
+ * Gets the cache object referenced by the browser
10102
10243
  */
10103
- BrowserUtils.isInIframe = function () {
10104
- return window.parent !== window;
10244
+ BrowserCacheManager.prototype.getCache = function () {
10245
+ return this.browserStorage;
10105
10246
  };
10106
10247
  /**
10107
- * Returns boolean of whether or not the current window is a popup opened by msal
10248
+ * interface compat, we cannot overwrite browser cache; Functionality is supported by individual entities in browser
10108
10249
  */
10109
- BrowserUtils.isInPopup = function () {
10110
- return typeof window !== "undefined" && !!window.opener &&
10111
- window.opener !== window &&
10112
- typeof window.name === "string" &&
10113
- window.name.indexOf(BrowserConstants.POPUP_NAME_PREFIX + ".") === 0;
10250
+ BrowserCacheManager.prototype.setCache = function () {
10251
+ // sets nothing
10114
10252
  };
10115
- // #endregion
10116
10253
  /**
10117
- * Returns current window URL as redirect uri
10254
+ * Prepend msal.<client-id> to each key; Skip for any JSON object as Key (defined schemas do not need the key appended: AccessToken Keys or the upcoming schema)
10255
+ * @param key
10256
+ * @param addInstanceId
10118
10257
  */
10119
- BrowserUtils.getCurrentUri = function () {
10120
- return window.location.href.split("?")[0].split("#")[0];
10258
+ BrowserCacheManager.prototype.generateCacheKey = function (key) {
10259
+ var generatedKey = this.validateAndParseJson(key);
10260
+ if (!generatedKey) {
10261
+ if (StringUtils.startsWith(key, Constants.CACHE_PREFIX) || StringUtils.startsWith(key, PersistentCacheKeys.ADAL_ID_TOKEN)) {
10262
+ return key;
10263
+ }
10264
+ return Constants.CACHE_PREFIX + "." + this.clientId + "." + key;
10265
+ }
10266
+ return JSON.stringify(key);
10121
10267
  };
10122
10268
  /**
10123
- * Gets the homepage url for the current window location.
10269
+ * Create authorityKey to cache authority
10270
+ * @param state
10124
10271
  */
10125
- BrowserUtils.getHomepage = function () {
10126
- var currentUrl = new UrlString(window.location.href);
10127
- var urlComponents = currentUrl.getUrlComponents();
10128
- return urlComponents.Protocol + "//" + urlComponents.HostNameAndPort + "/";
10272
+ BrowserCacheManager.prototype.generateAuthorityKey = function (stateString) {
10273
+ var stateId = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString).libraryState.id;
10274
+ return this.generateCacheKey(TemporaryCacheKeys.AUTHORITY + "." + stateId);
10129
10275
  };
10130
10276
  /**
10131
- * Returns best compatible network client object.
10277
+ * Create Nonce key to cache nonce
10278
+ * @param state
10132
10279
  */
10133
- BrowserUtils.getBrowserNetworkClient = function () {
10134
- if (window.fetch && window.Headers) {
10135
- return new FetchClient();
10136
- }
10137
- else {
10138
- return new XhrClient();
10139
- }
10280
+ BrowserCacheManager.prototype.generateNonceKey = function (stateString) {
10281
+ var stateId = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString).libraryState.id;
10282
+ return this.generateCacheKey(TemporaryCacheKeys.NONCE_IDTOKEN + "." + stateId);
10140
10283
  };
10141
10284
  /**
10142
- * Throws error if we have completed an auth and are
10143
- * attempting another auth request inside an iframe.
10285
+ * Creates full cache key for the request state
10286
+ * @param stateString State string for the request
10144
10287
  */
10145
- BrowserUtils.blockReloadInHiddenIframes = function () {
10146
- var isResponseHash = UrlString.hashContainsKnownProperties(window.location.hash);
10147
- // return an error if called from the hidden iframe created by the msal js silent calls
10148
- if (isResponseHash && BrowserUtils.isInIframe()) {
10149
- throw BrowserAuthError.createBlockReloadInHiddenIframeError();
10150
- }
10288
+ BrowserCacheManager.prototype.generateStateKey = function (stateString) {
10289
+ // Use the library state id to key temp storage for uniqueness for multiple concurrent requests
10290
+ var stateId = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString).libraryState.id;
10291
+ return this.generateCacheKey(TemporaryCacheKeys.REQUEST_STATE + "." + stateId);
10151
10292
  };
10152
10293
  /**
10153
- * Block redirect operations in iframes unless explicitly allowed
10154
- * @param interactionType Interaction type for the request
10155
- * @param allowRedirectInIframe Config value to allow redirects when app is inside an iframe
10294
+ * Gets the cached authority based on the cached state. Returns empty if no cached state found.
10156
10295
  */
10157
- BrowserUtils.blockRedirectInIframe = function (interactionType, allowRedirectInIframe) {
10158
- var isIframedApp = BrowserUtils.isInIframe();
10159
- if (interactionType === exports.InteractionType.Redirect && isIframedApp && !allowRedirectInIframe) {
10160
- // If we are not in top frame, we shouldn't redirect. This is also handled by the service.
10161
- throw BrowserAuthError.createRedirectInIframeError(isIframedApp);
10296
+ BrowserCacheManager.prototype.getCachedAuthority = function (cachedState) {
10297
+ var stateCacheKey = this.generateStateKey(cachedState);
10298
+ var state = this.getTemporaryCache(stateCacheKey);
10299
+ if (!state) {
10300
+ return null;
10162
10301
  }
10302
+ var authorityCacheKey = this.generateAuthorityKey(state);
10303
+ return this.getTemporaryCache(authorityCacheKey);
10163
10304
  };
10164
10305
  /**
10165
- * Block redirectUri loaded in popup from calling AcquireToken APIs
10306
+ * Updates account, authority, and state in cache
10307
+ * @param serverAuthenticationRequest
10308
+ * @param account
10166
10309
  */
10167
- BrowserUtils.blockAcquireTokenInPopups = function () {
10168
- // Popups opened by msal popup APIs are given a name that starts with "msal."
10169
- if (BrowserUtils.isInPopup()) {
10170
- throw BrowserAuthError.createBlockAcquireTokenInPopupsError();
10310
+ BrowserCacheManager.prototype.updateCacheEntries = function (state, nonce, authorityInstance, loginHint, account) {
10311
+ this.logger.trace("BrowserCacheManager.updateCacheEntries called");
10312
+ // Cache the request state
10313
+ var stateCacheKey = this.generateStateKey(state);
10314
+ this.setTemporaryCache(stateCacheKey, state, false);
10315
+ // Cache the nonce
10316
+ var nonceCacheKey = this.generateNonceKey(state);
10317
+ this.setTemporaryCache(nonceCacheKey, nonce, false);
10318
+ // Cache authorityKey
10319
+ var authorityCacheKey = this.generateAuthorityKey(state);
10320
+ this.setTemporaryCache(authorityCacheKey, authorityInstance, false);
10321
+ if (account) {
10322
+ var ccsCredential = {
10323
+ credential: account.homeAccountId,
10324
+ type: CcsCredentialType.HOME_ACCOUNT_ID
10325
+ };
10326
+ this.setTemporaryCache(TemporaryCacheKeys.CCS_CREDENTIAL, JSON.stringify(ccsCredential), true);
10327
+ }
10328
+ else if (!StringUtils.isEmpty(loginHint)) {
10329
+ var ccsCredential = {
10330
+ credential: loginHint,
10331
+ type: CcsCredentialType.UPN
10332
+ };
10333
+ this.setTemporaryCache(TemporaryCacheKeys.CCS_CREDENTIAL, JSON.stringify(ccsCredential), true);
10171
10334
  }
10172
10335
  };
10173
10336
  /**
10174
- * Throws error if token requests are made in non-browser environment
10175
- * @param isBrowserEnvironment Flag indicating if environment is a browser.
10337
+ * Reset all temporary cache items
10338
+ * @param state
10176
10339
  */
10177
- BrowserUtils.blockNonBrowserEnvironment = function (isBrowserEnvironment) {
10178
- if (!isBrowserEnvironment) {
10179
- throw BrowserAuthError.createNonBrowserEnvironmentError();
10340
+ BrowserCacheManager.prototype.resetRequestCache = function (state) {
10341
+ var _this = this;
10342
+ this.logger.trace("BrowserCacheManager.resetRequestCache called");
10343
+ // check state and remove associated cache items
10344
+ if (!StringUtils.isEmpty(state)) {
10345
+ this.getKeys().forEach(function (key) {
10346
+ if (key.indexOf(state) !== -1) {
10347
+ _this.removeItem(key);
10348
+ }
10349
+ });
10180
10350
  }
10351
+ // delete generic interactive request parameters
10352
+ if (state) {
10353
+ this.removeItem(this.generateStateKey(state));
10354
+ this.removeItem(this.generateNonceKey(state));
10355
+ this.removeItem(this.generateAuthorityKey(state));
10356
+ }
10357
+ this.removeItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
10358
+ this.removeItem(this.generateCacheKey(TemporaryCacheKeys.ORIGIN_URI));
10359
+ this.removeItem(this.generateCacheKey(TemporaryCacheKeys.URL_HASH));
10360
+ this.removeItem(this.generateCacheKey(TemporaryCacheKeys.CORRELATION_ID));
10361
+ this.removeItem(this.generateCacheKey(TemporaryCacheKeys.CCS_CREDENTIAL));
10362
+ this.setInteractionInProgress(false);
10181
10363
  };
10182
10364
  /**
10183
- * Returns boolean of whether current browser is an Internet Explorer or Edge browser.
10365
+ * Removes temporary cache for the provided state
10366
+ * @param stateString
10184
10367
  */
10185
- BrowserUtils.detectIEOrEdge = function () {
10186
- var ua = window.navigator.userAgent;
10187
- var msie = ua.indexOf("MSIE ");
10188
- var msie11 = ua.indexOf("Trident/");
10189
- var msedge = ua.indexOf("Edge/");
10190
- var isIE = msie > 0 || msie11 > 0;
10191
- var isEdge = msedge > 0;
10192
- return isIE || isEdge;
10368
+ BrowserCacheManager.prototype.cleanRequestByState = function (stateString) {
10369
+ this.logger.trace("BrowserCacheManager.cleanRequestByState called");
10370
+ // Interaction is completed - remove interaction status.
10371
+ if (stateString) {
10372
+ var stateKey = this.generateStateKey(stateString);
10373
+ var cachedState = this.temporaryCacheStorage.getItem(stateKey);
10374
+ this.logger.infoPii("BrowserCacheManager.cleanRequestByState: Removing temporary cache items for state: " + cachedState);
10375
+ this.resetRequestCache(cachedState || "");
10376
+ }
10377
+ this.clearMsalCookies();
10193
10378
  };
10194
- return BrowserUtils;
10195
- }());
10196
-
10197
- /*
10198
- * Copyright (c) Microsoft Corporation. All rights reserved.
10199
- * Licensed under the MIT License.
10200
- */
10201
- var NavigationClient = /** @class */ (function () {
10202
- function NavigationClient() {
10203
- }
10204
10379
  /**
10205
- * Navigates to other pages within the same web application
10206
- * @param url
10207
- * @param options
10380
+ * Looks in temporary cache for any state values with the provided interactionType and removes all temporary cache items for that state
10381
+ * Used in scenarios where temp cache needs to be cleaned but state is not known, such as clicking browser back button.
10382
+ * @param interactionType
10208
10383
  */
10209
- NavigationClient.prototype.navigateInternal = function (url, options) {
10210
- return NavigationClient.defaultNavigateWindow(url, options);
10384
+ BrowserCacheManager.prototype.cleanRequestByInteractionType = function (interactionType) {
10385
+ var _this = this;
10386
+ this.logger.trace("BrowserCacheManager.cleanRequestByInteractionType called");
10387
+ // Loop through all keys to find state key
10388
+ this.getKeys().forEach(function (key) {
10389
+ // If this key is not the state key, move on
10390
+ if (key.indexOf(TemporaryCacheKeys.REQUEST_STATE) === -1) {
10391
+ return;
10392
+ }
10393
+ // Retrieve state value, return if not a valid value
10394
+ var stateValue = _this.temporaryCacheStorage.getItem(key);
10395
+ if (!stateValue) {
10396
+ return;
10397
+ }
10398
+ // Extract state and ensure it matches given InteractionType, then clean request cache
10399
+ var parsedState = BrowserProtocolUtils.extractBrowserRequestState(_this.cryptoImpl, stateValue);
10400
+ if (parsedState && parsedState.interactionType === interactionType) {
10401
+ _this.logger.infoPii("BrowserCacheManager.cleanRequestByInteractionType: Removing temporary cache items for state: " + stateValue);
10402
+ _this.resetRequestCache(stateValue);
10403
+ }
10404
+ });
10405
+ this.clearMsalCookies();
10406
+ };
10407
+ BrowserCacheManager.prototype.cacheCodeRequest = function (authCodeRequest, browserCrypto) {
10408
+ this.logger.trace("BrowserCacheManager.cacheCodeRequest called");
10409
+ var encodedValue = browserCrypto.base64Encode(JSON.stringify(authCodeRequest));
10410
+ this.setTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, encodedValue, true);
10211
10411
  };
10212
10412
  /**
10213
- * Navigates to other pages outside the web application i.e. the Identity Provider
10214
- * @param url
10215
- * @param options
10413
+ * Gets the token exchange parameters from the cache. Throws an error if nothing is found.
10216
10414
  */
10217
- NavigationClient.prototype.navigateExternal = function (url, options) {
10218
- return NavigationClient.defaultNavigateWindow(url, options);
10415
+ BrowserCacheManager.prototype.getCachedRequest = function (state, browserCrypto) {
10416
+ this.logger.trace("BrowserCacheManager.getCachedRequest called");
10417
+ // Get token request from cache and parse as TokenExchangeParameters.
10418
+ var encodedTokenRequest = this.getTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, true);
10419
+ if (!encodedTokenRequest) {
10420
+ throw BrowserAuthError.createNoTokenRequestCacheError();
10421
+ }
10422
+ var parsedRequest = this.validateAndParseJson(browserCrypto.base64Decode(encodedTokenRequest));
10423
+ if (!parsedRequest) {
10424
+ throw BrowserAuthError.createUnableToParseTokenRequestCacheError();
10425
+ }
10426
+ this.removeItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
10427
+ // Get cached authority and use if no authority is cached with request.
10428
+ if (StringUtils.isEmpty(parsedRequest.authority)) {
10429
+ var authorityCacheKey = this.generateAuthorityKey(state);
10430
+ var cachedAuthority = this.getTemporaryCache(authorityCacheKey);
10431
+ if (!cachedAuthority) {
10432
+ throw BrowserAuthError.createNoCachedAuthorityError();
10433
+ }
10434
+ parsedRequest.authority = cachedAuthority;
10435
+ }
10436
+ return parsedRequest;
10437
+ };
10438
+ BrowserCacheManager.prototype.isInteractionInProgress = function (matchClientId) {
10439
+ var clientId = this.getInteractionInProgress();
10440
+ if (matchClientId) {
10441
+ return clientId === this.clientId;
10442
+ }
10443
+ else {
10444
+ return !!clientId;
10445
+ }
10446
+ };
10447
+ BrowserCacheManager.prototype.getInteractionInProgress = function () {
10448
+ var key = Constants.CACHE_PREFIX + "." + TemporaryCacheKeys.INTERACTION_STATUS_KEY;
10449
+ return this.getTemporaryCache(key, false);
10450
+ };
10451
+ BrowserCacheManager.prototype.setInteractionInProgress = function (inProgress) {
10452
+ var clientId = this.getInteractionInProgress();
10453
+ // Ensure we don't overwrite interaction in progress for a different clientId
10454
+ var key = Constants.CACHE_PREFIX + "." + TemporaryCacheKeys.INTERACTION_STATUS_KEY;
10455
+ if (inProgress && !clientId) {
10456
+ // No interaction is in progress
10457
+ this.setTemporaryCache(key, this.clientId, false);
10458
+ }
10459
+ else if (!inProgress && clientId === this.clientId) {
10460
+ this.removeItem(key);
10461
+ }
10219
10462
  };
10220
10463
  /**
10221
- * Default navigation implementation invoked by the internal and external functions
10222
- * @param url
10223
- * @param options
10464
+ * Returns username retrieved from ADAL or MSAL v1 idToken
10224
10465
  */
10225
- NavigationClient.defaultNavigateWindow = function (url, options) {
10226
- if (options.noHistory) {
10227
- window.location.replace(url);
10466
+ BrowserCacheManager.prototype.getLegacyLoginHint = function () {
10467
+ // Only check for adal/msal token if no SSO params are being used
10468
+ var adalIdTokenString = this.getTemporaryCache(PersistentCacheKeys.ADAL_ID_TOKEN);
10469
+ if (adalIdTokenString) {
10470
+ this.browserStorage.removeItem(PersistentCacheKeys.ADAL_ID_TOKEN);
10471
+ this.logger.verbose("Cached ADAL id token retrieved.");
10228
10472
  }
10229
- else {
10230
- window.location.assign(url);
10473
+ // Check for cached MSAL v1 id token
10474
+ var msalIdTokenString = this.getTemporaryCache(PersistentCacheKeys.ID_TOKEN, true);
10475
+ if (msalIdTokenString) {
10476
+ this.removeItem(this.generateCacheKey(PersistentCacheKeys.ID_TOKEN));
10477
+ this.logger.verbose("Cached MSAL.js v1 id token retrieved");
10231
10478
  }
10232
- return new Promise(function (resolve) {
10233
- setTimeout(function () {
10234
- resolve(true);
10235
- }, options.timeout);
10236
- });
10479
+ var cachedIdTokenString = msalIdTokenString || adalIdTokenString;
10480
+ if (cachedIdTokenString) {
10481
+ var cachedIdToken = new AuthToken(cachedIdTokenString, this.cryptoImpl);
10482
+ if (cachedIdToken.claims && cachedIdToken.claims.preferred_username) {
10483
+ this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, setting ADAL/MSAL v1 preferred_username as loginHint");
10484
+ return cachedIdToken.claims.preferred_username;
10485
+ }
10486
+ else if (cachedIdToken.claims && cachedIdToken.claims.upn) {
10487
+ this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, setting ADAL/MSAL v1 upn as loginHint");
10488
+ return cachedIdToken.claims.upn;
10489
+ }
10490
+ else {
10491
+ this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, however, no account hint claim found. Enable preferred_username or upn id token claim to get SSO.");
10492
+ }
10493
+ }
10494
+ return null;
10495
+ };
10496
+ /**
10497
+ * Updates a credential's cache key if the current cache key is outdated
10498
+ */
10499
+ BrowserCacheManager.prototype.updateCredentialCacheKey = function (currentCacheKey, credential) {
10500
+ var updatedCacheKey = credential.generateCredentialKey();
10501
+ if (currentCacheKey !== updatedCacheKey) {
10502
+ var cacheItem = this.getItem(currentCacheKey);
10503
+ if (cacheItem) {
10504
+ this.removeItem(currentCacheKey);
10505
+ this.setItem(updatedCacheKey, cacheItem);
10506
+ this.logger.verbose("Updated an outdated " + credential.credentialType + " cache key");
10507
+ return updatedCacheKey;
10508
+ }
10509
+ else {
10510
+ this.logger.error("Attempted to update an outdated " + credential.credentialType + " cache key but no item matching the outdated key was found in storage");
10511
+ }
10512
+ }
10513
+ return currentCacheKey;
10237
10514
  };
10238
- return NavigationClient;
10239
- }());
10515
+ return BrowserCacheManager;
10516
+ }(CacheManager));
10517
+ var DEFAULT_BROWSER_CACHE_MANAGER = function (clientId, logger) {
10518
+ var cacheOptions = {
10519
+ cacheLocation: exports.BrowserCacheLocation.MemoryStorage,
10520
+ storeAuthStateInCookie: false,
10521
+ secureCookies: false
10522
+ };
10523
+ return new BrowserCacheManager(clientId, cacheOptions, DEFAULT_CRYPTO_IMPLEMENTATION, logger);
10524
+ };
10240
10525
 
10241
10526
  /*
10242
10527
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -10295,37 +10580,6 @@
10295
10580
  return overlayedConfig;
10296
10581
  }
10297
10582
 
10298
- /* eslint-disable header/header */
10299
- var name = "@azure/msal-browser";
10300
- var version = "2.19.0";
10301
-
10302
- /*
10303
- * Copyright (c) Microsoft Corporation. All rights reserved.
10304
- * Licensed under the MIT License.
10305
- */
10306
- exports.EventType = void 0;
10307
- (function (EventType) {
10308
- EventType["ACCOUNT_ADDED"] = "msal:accountAdded";
10309
- EventType["ACCOUNT_REMOVED"] = "msal:accountRemoved";
10310
- EventType["LOGIN_START"] = "msal:loginStart";
10311
- EventType["LOGIN_SUCCESS"] = "msal:loginSuccess";
10312
- EventType["LOGIN_FAILURE"] = "msal:loginFailure";
10313
- EventType["ACQUIRE_TOKEN_START"] = "msal:acquireTokenStart";
10314
- EventType["ACQUIRE_TOKEN_SUCCESS"] = "msal:acquireTokenSuccess";
10315
- EventType["ACQUIRE_TOKEN_FAILURE"] = "msal:acquireTokenFailure";
10316
- EventType["ACQUIRE_TOKEN_NETWORK_START"] = "msal:acquireTokenFromNetworkStart";
10317
- EventType["SSO_SILENT_START"] = "msal:ssoSilentStart";
10318
- EventType["SSO_SILENT_SUCCESS"] = "msal:ssoSilentSuccess";
10319
- EventType["SSO_SILENT_FAILURE"] = "msal:ssoSilentFailure";
10320
- EventType["HANDLE_REDIRECT_START"] = "msal:handleRedirectStart";
10321
- EventType["HANDLE_REDIRECT_END"] = "msal:handleRedirectEnd";
10322
- EventType["POPUP_OPENED"] = "msal:popupOpened";
10323
- EventType["LOGOUT_START"] = "msal:logoutStart";
10324
- EventType["LOGOUT_SUCCESS"] = "msal:logoutSuccess";
10325
- EventType["LOGOUT_FAILURE"] = "msal:logoutFailure";
10326
- EventType["LOGOUT_END"] = "msal:logoutEnd";
10327
- })(exports.EventType || (exports.EventType = {}));
10328
-
10329
10583
  /*
10330
10584
  * Copyright (c) Microsoft Corporation. All rights reserved.
10331
10585
  * Licensed under the MIT License.
@@ -12948,216 +13202,6 @@
12948
13202
  return PublicClientApplication;
12949
13203
  }(ClientApplication));
12950
13204
 
12951
- /*
12952
- * Copyright (c) Microsoft Corporation. All rights reserved.
12953
- * Licensed under the MIT License.
12954
- */
12955
- var stubbedPublicClientApplication = {
12956
- acquireTokenPopup: function () {
12957
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12958
- },
12959
- acquireTokenRedirect: function () {
12960
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12961
- },
12962
- acquireTokenSilent: function () {
12963
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12964
- },
12965
- getAllAccounts: function () {
12966
- return [];
12967
- },
12968
- getAccountByHomeId: function () {
12969
- return null;
12970
- },
12971
- getAccountByUsername: function () {
12972
- return null;
12973
- },
12974
- getAccountByLocalId: function () {
12975
- return null;
12976
- },
12977
- handleRedirectPromise: function () {
12978
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12979
- },
12980
- loginPopup: function () {
12981
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12982
- },
12983
- loginRedirect: function () {
12984
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12985
- },
12986
- logout: function () {
12987
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12988
- },
12989
- logoutRedirect: function () {
12990
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12991
- },
12992
- logoutPopup: function () {
12993
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12994
- },
12995
- ssoSilent: function () {
12996
- return Promise.reject(BrowserConfigurationAuthError.createStubPcaInstanceCalledError());
12997
- },
12998
- addEventCallback: function () {
12999
- return null;
13000
- },
13001
- removeEventCallback: function () {
13002
- return;
13003
- },
13004
- enableAccountStorageEvents: function () {
13005
- return;
13006
- },
13007
- disableAccountStorageEvents: function () {
13008
- return;
13009
- },
13010
- getTokenCache: function () {
13011
- throw BrowserConfigurationAuthError.createStubPcaInstanceCalledError();
13012
- },
13013
- getLogger: function () {
13014
- throw BrowserConfigurationAuthError.createStubPcaInstanceCalledError();
13015
- },
13016
- setLogger: function () {
13017
- return;
13018
- },
13019
- setActiveAccount: function () {
13020
- return;
13021
- },
13022
- getActiveAccount: function () {
13023
- return null;
13024
- },
13025
- initializeWrapperLibrary: function () {
13026
- return;
13027
- },
13028
- setNavigationClient: function () {
13029
- return;
13030
- },
13031
- getConfiguration: function () {
13032
- throw BrowserConfigurationAuthError.createStubPcaInstanceCalledError();
13033
- }
13034
- };
13035
-
13036
- /*
13037
- * Copyright (c) Microsoft Corporation. All rights reserved.
13038
- * Licensed under the MIT License.
13039
- */
13040
- var EventMessageUtils = /** @class */ (function () {
13041
- function EventMessageUtils() {
13042
- }
13043
- /**
13044
- * Gets interaction status from event message
13045
- * @param message
13046
- * @param currentStatus
13047
- */
13048
- EventMessageUtils.getInteractionStatusFromEvent = function (message, currentStatus) {
13049
- switch (message.eventType) {
13050
- case exports.EventType.LOGIN_START:
13051
- return exports.InteractionStatus.Login;
13052
- case exports.EventType.SSO_SILENT_START:
13053
- return exports.InteractionStatus.SsoSilent;
13054
- case exports.EventType.ACQUIRE_TOKEN_START:
13055
- if (message.interactionType === exports.InteractionType.Redirect || message.interactionType === exports.InteractionType.Popup) {
13056
- return exports.InteractionStatus.AcquireToken;
13057
- }
13058
- break;
13059
- case exports.EventType.HANDLE_REDIRECT_START:
13060
- return exports.InteractionStatus.HandleRedirect;
13061
- case exports.EventType.LOGOUT_START:
13062
- return exports.InteractionStatus.Logout;
13063
- case exports.EventType.SSO_SILENT_SUCCESS:
13064
- case exports.EventType.SSO_SILENT_FAILURE:
13065
- if (currentStatus && currentStatus !== exports.InteractionStatus.SsoSilent) {
13066
- // Prevent this event from clearing any status other than ssoSilent
13067
- break;
13068
- }
13069
- return exports.InteractionStatus.None;
13070
- case exports.EventType.LOGOUT_END:
13071
- if (currentStatus && currentStatus !== exports.InteractionStatus.Logout) {
13072
- // Prevent this event from clearing any status other than logout
13073
- break;
13074
- }
13075
- return exports.InteractionStatus.None;
13076
- case exports.EventType.HANDLE_REDIRECT_END:
13077
- if (currentStatus && currentStatus !== exports.InteractionStatus.HandleRedirect) {
13078
- // Prevent this event from clearing any status other than handleRedirect
13079
- break;
13080
- }
13081
- return exports.InteractionStatus.None;
13082
- case exports.EventType.LOGIN_SUCCESS:
13083
- case exports.EventType.LOGIN_FAILURE:
13084
- case exports.EventType.ACQUIRE_TOKEN_SUCCESS:
13085
- case exports.EventType.ACQUIRE_TOKEN_FAILURE:
13086
- if (message.interactionType === exports.InteractionType.Redirect || message.interactionType === exports.InteractionType.Popup) {
13087
- if (currentStatus && currentStatus !== exports.InteractionStatus.Login && currentStatus !== exports.InteractionStatus.AcquireToken) {
13088
- // Prevent this event from clearing any status other than login or acquireToken
13089
- break;
13090
- }
13091
- return exports.InteractionStatus.None;
13092
- }
13093
- break;
13094
- }
13095
- return null;
13096
- };
13097
- return EventMessageUtils;
13098
- }());
13099
-
13100
- /*
13101
- * Copyright (c) Microsoft Corporation. All rights reserved.
13102
- * Licensed under the MIT License.
13103
- */
13104
- var SignedHttpRequest = /** @class */ (function () {
13105
- function SignedHttpRequest(shrParameters, shrOptions) {
13106
- var loggerOptions = (shrOptions && shrOptions.loggerOptions) || {};
13107
- this.logger = new Logger(loggerOptions, name, version);
13108
- this.cryptoOps = new CryptoOps(this.logger);
13109
- this.popTokenGenerator = new PopTokenGenerator(this.cryptoOps);
13110
- this.shrParameters = shrParameters;
13111
- }
13112
- /**
13113
- * Generates and caches a keypair for the given request options.
13114
- * @returns Public key digest, which should be sent to the token issuer.
13115
- */
13116
- SignedHttpRequest.prototype.generatePublicKeyThumbprint = function () {
13117
- return __awaiter$1(this, void 0, void 0, function () {
13118
- var kid;
13119
- return __generator$1(this, function (_a) {
13120
- switch (_a.label) {
13121
- case 0: return [4 /*yield*/, this.popTokenGenerator.generateKid(this.shrParameters)];
13122
- case 1:
13123
- kid = (_a.sent()).kid;
13124
- return [2 /*return*/, kid];
13125
- }
13126
- });
13127
- });
13128
- };
13129
- /**
13130
- * Generates a signed http request for the given payload with the given key.
13131
- * @param payload Payload to sign (e.g. access token)
13132
- * @param publicKeyThumbprint Public key digest (from generatePublicKeyThumbprint API)
13133
- * @param claims Additional claims to include/override in the signed JWT
13134
- * @returns Pop token signed with the corresponding private key
13135
- */
13136
- SignedHttpRequest.prototype.signRequest = function (payload, publicKeyThumbprint, claims) {
13137
- return __awaiter$1(this, void 0, void 0, function () {
13138
- return __generator$1(this, function (_a) {
13139
- return [2 /*return*/, this.popTokenGenerator.signPayload(payload, publicKeyThumbprint, this.shrParameters, claims)];
13140
- });
13141
- });
13142
- };
13143
- /**
13144
- * Removes cached keys from browser for given public key thumbprint
13145
- * @param publicKeyThumbprint Public key digest (from generatePublicKeyThumbprint API)
13146
- * @returns If keys are properly deleted
13147
- */
13148
- SignedHttpRequest.prototype.removeKeys = function (publicKeyThumbprint) {
13149
- return __awaiter$1(this, void 0, void 0, function () {
13150
- return __generator$1(this, function (_a) {
13151
- switch (_a.label) {
13152
- case 0: return [4 /*yield*/, this.cryptoOps.removeTokenBindingKey(publicKeyThumbprint)];
13153
- case 1: return [2 /*return*/, _a.sent()];
13154
- }
13155
- });
13156
- });
13157
- };
13158
- return SignedHttpRequest;
13159
- }());
13160
-
13161
13205
  exports.AccountEntity = AccountEntity;
13162
13206
  exports.AuthError = AuthError;
13163
13207
  exports.AuthErrorMessage = AuthErrorMessage;