UNPKG

335 kBJavaScriptView Raw
1/*! msal v1.4.18 2023-05-01 */
2'use strict';
3(function webpackUniversalModuleDefinition(root, factory) {
4 if(typeof exports === 'object' && typeof module === 'object')
5 module.exports = factory();
6 else if(typeof define === 'function' && define.amd)
7 define("Msal", [], factory);
8 else if(typeof exports === 'object')
9 exports["Msal"] = factory();
10 else
11 root["Msal"] = factory();
12})(self, function() {
13return /******/ (function() { // webpackBootstrap
14/******/ "use strict";
15/******/ var __webpack_modules__ = ({
16
17/***/ 795:
18/***/ (function(__unused_webpack_module, exports) {
19
20
21/*! *****************************************************************************
22Copyright (c) Microsoft Corporation.
23
24Permission to use, copy, modify, and/or distribute this software for any
25purpose with or without fee is hereby granted.
26
27THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
28REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
29AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
30INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
31LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
32OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
33PERFORMANCE OF THIS SOFTWARE.
34***************************************************************************** */
35/* global Reflect, Promise */
36Object.defineProperty(exports, "__esModule", ({ value: true }));
37exports.__classPrivateFieldSet = exports.__classPrivateFieldGet = exports.__importDefault = exports.__importStar = exports.__makeTemplateObject = exports.__asyncValues = exports.__asyncDelegator = exports.__asyncGenerator = exports.__await = exports.__spreadArrays = exports.__spread = exports.__read = exports.__values = exports.__exportStar = exports.__createBinding = exports.__generator = exports.__awaiter = exports.__metadata = exports.__param = exports.__decorate = exports.__rest = exports.__assign = exports.__extends = void 0;
38var extendStatics = function (d, b) {
39 extendStatics = Object.setPrototypeOf ||
40 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41 function (d, b) { for (var p in b)
42 if (b.hasOwnProperty(p))
43 d[p] = b[p]; };
44 return extendStatics(d, b);
45};
46function __extends(d, b) {
47 extendStatics(d, b);
48 function __() { this.constructor = d; }
49 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
50}
51exports.__extends = __extends;
52exports.__assign = function () {
53 exports.__assign = Object.assign || function __assign(t) {
54 for (var s, i = 1, n = arguments.length; i < n; i++) {
55 s = arguments[i];
56 for (var p in s)
57 if (Object.prototype.hasOwnProperty.call(s, p))
58 t[p] = s[p];
59 }
60 return t;
61 };
62 return exports.__assign.apply(this, arguments);
63};
64function __rest(s, e) {
65 var t = {};
66 for (var p in s)
67 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
68 t[p] = s[p];
69 if (s != null && typeof Object.getOwnPropertySymbols === "function")
70 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
71 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
72 t[p[i]] = s[p[i]];
73 }
74 return t;
75}
76exports.__rest = __rest;
77function __decorate(decorators, target, key, desc) {
78 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
79 if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
80 r = Reflect.decorate(decorators, target, key, desc);
81 else
82 for (var i = decorators.length - 1; i >= 0; i--)
83 if (d = decorators[i])
84 r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
85 return c > 3 && r && Object.defineProperty(target, key, r), r;
86}
87exports.__decorate = __decorate;
88function __param(paramIndex, decorator) {
89 return function (target, key) { decorator(target, key, paramIndex); };
90}
91exports.__param = __param;
92function __metadata(metadataKey, metadataValue) {
93 if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
94 return Reflect.metadata(metadataKey, metadataValue);
95}
96exports.__metadata = __metadata;
97function __awaiter(thisArg, _arguments, P, generator) {
98 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
99 return new (P || (P = Promise))(function (resolve, reject) {
100 function fulfilled(value) { try {
101 step(generator.next(value));
102 }
103 catch (e) {
104 reject(e);
105 } }
106 function rejected(value) { try {
107 step(generator["throw"](value));
108 }
109 catch (e) {
110 reject(e);
111 } }
112 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
113 step((generator = generator.apply(thisArg, _arguments || [])).next());
114 });
115}
116exports.__awaiter = __awaiter;
117function __generator(thisArg, body) {
118 var _ = { label: 0, sent: function () { if (t[0] & 1)
119 throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
120 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
121 function verb(n) { return function (v) { return step([n, v]); }; }
122 function step(op) {
123 if (f)
124 throw new TypeError("Generator is already executing.");
125 while (_)
126 try {
127 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
128 return t;
129 if (y = 0, t)
130 op = [op[0] & 2, t.value];
131 switch (op[0]) {
132 case 0:
133 case 1:
134 t = op;
135 break;
136 case 4:
137 _.label++;
138 return { value: op[1], done: false };
139 case 5:
140 _.label++;
141 y = op[1];
142 op = [0];
143 continue;
144 case 7:
145 op = _.ops.pop();
146 _.trys.pop();
147 continue;
148 default:
149 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
150 _ = 0;
151 continue;
152 }
153 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
154 _.label = op[1];
155 break;
156 }
157 if (op[0] === 6 && _.label < t[1]) {
158 _.label = t[1];
159 t = op;
160 break;
161 }
162 if (t && _.label < t[2]) {
163 _.label = t[2];
164 _.ops.push(op);
165 break;
166 }
167 if (t[2])
168 _.ops.pop();
169 _.trys.pop();
170 continue;
171 }
172 op = body.call(thisArg, _);
173 }
174 catch (e) {
175 op = [6, e];
176 y = 0;
177 }
178 finally {
179 f = t = 0;
180 }
181 if (op[0] & 5)
182 throw op[1];
183 return { value: op[0] ? op[1] : void 0, done: true };
184 }
185}
186exports.__generator = __generator;
187function __createBinding(o, m, k, k2) {
188 if (k2 === undefined)
189 k2 = k;
190 o[k2] = m[k];
191}
192exports.__createBinding = __createBinding;
193function __exportStar(m, exports) {
194 for (var p in m)
195 if (p !== "default" && !exports.hasOwnProperty(p))
196 exports[p] = m[p];
197}
198exports.__exportStar = __exportStar;
199function __values(o) {
200 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
201 if (m)
202 return m.call(o);
203 if (o && typeof o.length === "number")
204 return {
205 next: function () {
206 if (o && i >= o.length)
207 o = void 0;
208 return { value: o && o[i++], done: !o };
209 }
210 };
211 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
212}
213exports.__values = __values;
214function __read(o, n) {
215 var m = typeof Symbol === "function" && o[Symbol.iterator];
216 if (!m)
217 return o;
218 var i = m.call(o), r, ar = [], e;
219 try {
220 while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
221 ar.push(r.value);
222 }
223 catch (error) {
224 e = { error: error };
225 }
226 finally {
227 try {
228 if (r && !r.done && (m = i["return"]))
229 m.call(i);
230 }
231 finally {
232 if (e)
233 throw e.error;
234 }
235 }
236 return ar;
237}
238exports.__read = __read;
239function __spread() {
240 for (var ar = [], i = 0; i < arguments.length; i++)
241 ar = ar.concat(__read(arguments[i]));
242 return ar;
243}
244exports.__spread = __spread;
245function __spreadArrays() {
246 for (var s = 0, i = 0, il = arguments.length; i < il; i++)
247 s += arguments[i].length;
248 for (var r = Array(s), k = 0, i = 0; i < il; i++)
249 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
250 r[k] = a[j];
251 return r;
252}
253exports.__spreadArrays = __spreadArrays;
254;
255function __await(v) {
256 return this instanceof __await ? (this.v = v, this) : new __await(v);
257}
258exports.__await = __await;
259function __asyncGenerator(thisArg, _arguments, generator) {
260 if (!Symbol.asyncIterator)
261 throw new TypeError("Symbol.asyncIterator is not defined.");
262 var g = generator.apply(thisArg, _arguments || []), i, q = [];
263 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
264 function verb(n) { if (g[n])
265 i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
266 function resume(n, v) { try {
267 step(g[n](v));
268 }
269 catch (e) {
270 settle(q[0][3], e);
271 } }
272 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
273 function fulfill(value) { resume("next", value); }
274 function reject(value) { resume("throw", value); }
275 function settle(f, v) { if (f(v), q.shift(), q.length)
276 resume(q[0][0], q[0][1]); }
277}
278exports.__asyncGenerator = __asyncGenerator;
279function __asyncDelegator(o) {
280 var i, p;
281 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
282 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
283}
284exports.__asyncDelegator = __asyncDelegator;
285function __asyncValues(o) {
286 if (!Symbol.asyncIterator)
287 throw new TypeError("Symbol.asyncIterator is not defined.");
288 var m = o[Symbol.asyncIterator], i;
289 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
290 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
291 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
292}
293exports.__asyncValues = __asyncValues;
294function __makeTemplateObject(cooked, raw) {
295 if (Object.defineProperty) {
296 Object.defineProperty(cooked, "raw", { value: raw });
297 }
298 else {
299 cooked.raw = raw;
300 }
301 return cooked;
302}
303exports.__makeTemplateObject = __makeTemplateObject;
304;
305function __importStar(mod) {
306 if (mod && mod.__esModule)
307 return mod;
308 var result = {};
309 if (mod != null)
310 for (var k in mod)
311 if (Object.hasOwnProperty.call(mod, k))
312 result[k] = mod[k];
313 result.default = mod;
314 return result;
315}
316exports.__importStar = __importStar;
317function __importDefault(mod) {
318 return (mod && mod.__esModule) ? mod : { default: mod };
319}
320exports.__importDefault = __importDefault;
321function __classPrivateFieldGet(receiver, privateMap) {
322 if (!privateMap.has(receiver)) {
323 throw new TypeError("attempted to get private field on non-instance");
324 }
325 return privateMap.get(receiver);
326}
327exports.__classPrivateFieldGet = __classPrivateFieldGet;
328function __classPrivateFieldSet(receiver, privateMap, value) {
329 if (!privateMap.has(receiver)) {
330 throw new TypeError("attempted to set private field on non-instance");
331 }
332 privateMap.set(receiver, value);
333 return value;
334}
335exports.__classPrivateFieldSet = __classPrivateFieldSet;
336
337
338/***/ }),
339
340/***/ 630:
341/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
342
343
344/*
345 * Copyright (c) Microsoft Corporation. All rights reserved.
346 * Licensed under the MIT License.
347 */
348Object.defineProperty(exports, "__esModule", ({ value: true }));
349exports.Account = void 0;
350var CryptoUtils_1 = __webpack_require__(453);
351var StringUtils_1 = __webpack_require__(454);
352/**
353 * accountIdentifier combination of idToken.uid and idToken.utid
354 * homeAccountIdentifier combination of clientInfo.uid and clientInfo.utid
355 * userName idToken.preferred_username
356 * name idToken.name
357 * idToken idToken
358 * sid idToken.sid - session identifier
359 * environment idtoken.issuer (the authority that issues the token)
360 */
361var Account = /** @class */ (function () {
362 /**
363 * Creates an Account Object
364 * @praram accountIdentifier
365 * @param homeAccountIdentifier
366 * @param userName
367 * @param name
368 * @param idToken
369 * @param sid
370 * @param environment
371 */
372 function Account(accountIdentifier, homeAccountIdentifier, userName, name, idTokenClaims, sid, environment) {
373 this.accountIdentifier = accountIdentifier;
374 this.homeAccountIdentifier = homeAccountIdentifier;
375 this.userName = userName;
376 this.name = name;
377 // will be deprecated soon
378 this.idToken = idTokenClaims;
379 this.idTokenClaims = idTokenClaims;
380 this.sid = sid;
381 this.environment = environment;
382 }
383 /**
384 * @hidden
385 * @param idToken
386 * @param clientInfo
387 */
388 Account.createAccount = function (idToken, clientInfo) {
389 // create accountIdentifier
390 var accountIdentifier = idToken.objectId || idToken.subject;
391 // create homeAccountIdentifier
392 var uid = clientInfo ? clientInfo.uid : "";
393 var utid = clientInfo ? clientInfo.utid : "";
394 var homeAccountIdentifier;
395 if (!StringUtils_1.StringUtils.isEmpty(uid)) {
396 homeAccountIdentifier = StringUtils_1.StringUtils.isEmpty(utid) ? CryptoUtils_1.CryptoUtils.base64Encode(uid) : CryptoUtils_1.CryptoUtils.base64Encode(uid) + "." + CryptoUtils_1.CryptoUtils.base64Encode(utid);
397 }
398 return new Account(accountIdentifier, homeAccountIdentifier, idToken.preferredName, idToken.name, idToken.claims, idToken.sid, idToken.issuer);
399 };
400 /**
401 * Utils function to compare two Account objects - used to check if the same user account is logged in
402 *
403 * @param a1: Account object
404 * @param a2: Account object
405 */
406 Account.compareAccounts = function (a1, a2) {
407 if (!a1 || !a2) {
408 return false;
409 }
410 if (a1.homeAccountIdentifier && a2.homeAccountIdentifier) {
411 if (a1.homeAccountIdentifier === a2.homeAccountIdentifier) {
412 return true;
413 }
414 }
415 return false;
416 };
417 return Account;
418}());
419exports.Account = Account;
420
421
422/***/ }),
423
424/***/ 681:
425/***/ (function(__unused_webpack_module, exports) {
426
427
428/*
429 * Copyright (c) Microsoft Corporation. All rights reserved.
430 * Licensed under the MIT License.
431 */
432Object.defineProperty(exports, "__esModule", ({ value: true }));
433exports.buildResponseStateOnly = void 0;
434function buildResponseStateOnly(state) {
435 return {
436 uniqueId: "",
437 tenantId: "",
438 tokenType: "",
439 idToken: null,
440 idTokenClaims: null,
441 accessToken: "",
442 scopes: null,
443 expiresOn: null,
444 account: null,
445 accountState: state,
446 fromCache: false
447 };
448}
449exports.buildResponseStateOnly = buildResponseStateOnly;
450
451
452/***/ }),
453
454/***/ 733:
455/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
456
457
458/*
459 * Copyright (c) Microsoft Corporation. All rights reserved.
460 * Licensed under the MIT License.
461 */
462Object.defineProperty(exports, "__esModule", ({ value: true }));
463exports.validateClaimsRequest = void 0;
464var ClientConfigurationError_1 = __webpack_require__(550);
465function validateClaimsRequest(request) {
466 if (!request.claimsRequest) {
467 return;
468 }
469 try {
470 JSON.parse(request.claimsRequest);
471 }
472 catch (e) {
473 throw ClientConfigurationError_1.ClientConfigurationError.createClaimsRequestParsingError(e);
474 }
475 // TODO: More validation will be added when the server team tells us how they have actually implemented claims
476}
477exports.validateClaimsRequest = validateClaimsRequest;
478
479
480/***/ }),
481
482/***/ 271:
483/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
484
485
486/*
487 * Copyright (c) Microsoft Corporation. All rights reserved.
488 * Licensed under the MIT License.
489 */
490Object.defineProperty(exports, "__esModule", ({ value: true }));
491exports.ClientInfo = void 0;
492var CryptoUtils_1 = __webpack_require__(453);
493var ClientAuthError_1 = __webpack_require__(356);
494var StringUtils_1 = __webpack_require__(454);
495/**
496 * @hidden
497 */
498var ClientInfo = /** @class */ (function () {
499 function ClientInfo(rawClientInfo, authority) {
500 if (!rawClientInfo || StringUtils_1.StringUtils.isEmpty(rawClientInfo)) {
501 this.uid = "";
502 this.utid = "";
503 return;
504 }
505 try {
506 var decodedClientInfo = CryptoUtils_1.CryptoUtils.base64Decode(rawClientInfo);
507 var clientInfo = JSON.parse(decodedClientInfo);
508 if (clientInfo) {
509 if (clientInfo.hasOwnProperty("uid")) {
510 this.uid = authority ? ClientInfo.stripPolicyFromUid(clientInfo.uid, authority) : clientInfo.uid;
511 }
512 if (clientInfo.hasOwnProperty("utid")) {
513 this.utid = clientInfo.utid;
514 }
515 }
516 }
517 catch (e) {
518 throw ClientAuthError_1.ClientAuthError.createClientInfoDecodingError(e);
519 }
520 }
521 Object.defineProperty(ClientInfo.prototype, "uid", {
522 get: function () {
523 return this._uid ? this._uid : "";
524 },
525 set: function (uid) {
526 this._uid = uid;
527 },
528 enumerable: false,
529 configurable: true
530 });
531 Object.defineProperty(ClientInfo.prototype, "utid", {
532 get: function () {
533 return this._utid ? this._utid : "";
534 },
535 set: function (utid) {
536 this._utid = utid;
537 },
538 enumerable: false,
539 configurable: true
540 });
541 ClientInfo.createClientInfoFromIdToken = function (idToken, authority) {
542 var clientInfo = {
543 uid: idToken.subject,
544 utid: ""
545 };
546 return new ClientInfo(CryptoUtils_1.CryptoUtils.base64Encode(JSON.stringify(clientInfo)), authority);
547 };
548 ClientInfo.stripPolicyFromUid = function (uid, authority) {
549 var uidSegments = uid.split("-");
550 // Reverse the url segments so the last one is more easily accessible
551 var urlSegments = authority.split("/").reverse();
552 var policy = "";
553 if (!StringUtils_1.StringUtils.isEmpty(urlSegments[0])) {
554 policy = urlSegments[0];
555 }
556 else if (urlSegments.length > 1) {
557 // If the original url had a trailing slash, urlSegments[0] would be "" so take the next element
558 policy = urlSegments[1];
559 }
560 if (uidSegments[uidSegments.length - 1] === policy) {
561 // If the last segment of uid matches the last segment of authority url, remove the last segment of uid
562 return uidSegments.slice(0, uidSegments.length - 1).join("-");
563 }
564 return uid;
565 };
566 ClientInfo.prototype.encodeClientInfo = function () {
567 var clientInfo = JSON.stringify({ uid: this.uid, utid: this.utid });
568 return CryptoUtils_1.CryptoUtils.base64Encode(clientInfo);
569 };
570 return ClientInfo;
571}());
572exports.ClientInfo = ClientInfo;
573
574
575/***/ }),
576
577/***/ 875:
578/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
579
580
581/*
582 * Copyright (c) Microsoft Corporation. All rights reserved.
583 * Licensed under the MIT License.
584 */
585Object.defineProperty(exports, "__esModule", ({ value: true }));
586exports.buildConfiguration = void 0;
587var tslib_1 = __webpack_require__(795);
588var Logger_1 = __webpack_require__(89);
589var UrlUtils_1 = __webpack_require__(741);
590/**
591 * Defaults for the Configuration Options
592 */
593var FRAME_TIMEOUT = 6000;
594var OFFSET = 300;
595var NAVIGATE_FRAME_WAIT = 500;
596var DEFAULT_AUTH_OPTIONS = {
597 clientId: "",
598 authority: null,
599 validateAuthority: true,
600 authorityMetadata: "",
601 knownAuthorities: [],
602 redirectUri: function () { return UrlUtils_1.UrlUtils.getCurrentUrl(); },
603 postLogoutRedirectUri: function () { return UrlUtils_1.UrlUtils.getCurrentUrl(); },
604 navigateToLoginRequestUrl: true
605};
606var DEFAULT_CACHE_OPTIONS = {
607 cacheLocation: "sessionStorage",
608 storeAuthStateInCookie: false
609};
610var DEFAULT_SYSTEM_OPTIONS = {
611 logger: new Logger_1.Logger(null),
612 loadFrameTimeout: FRAME_TIMEOUT,
613 tokenRenewalOffsetSeconds: OFFSET,
614 navigateFrameWait: NAVIGATE_FRAME_WAIT
615};
616var DEFAULT_FRAMEWORK_OPTIONS = {
617 isAngular: false,
618 unprotectedResources: new Array(),
619 protectedResourceMap: new Map()
620};
621/**
622 * MSAL function that sets the default options when not explicitly configured from app developer
623 *
624 * @param TAuthOptions
625 * @param TCacheOptions
626 * @param TSystemOptions
627 * @param TFrameworkOptions
628 * @param TAuthorityDataOptions
629 *
630 * @returns TConfiguration object
631 */
632function buildConfiguration(_a) {
633 var auth = _a.auth, _b = _a.cache, cache = _b === void 0 ? {} : _b, _c = _a.system, system = _c === void 0 ? {} : _c, _d = _a.framework, framework = _d === void 0 ? {} : _d;
634 var overlayedConfig = {
635 auth: tslib_1.__assign(tslib_1.__assign({}, DEFAULT_AUTH_OPTIONS), auth),
636 cache: tslib_1.__assign(tslib_1.__assign({}, DEFAULT_CACHE_OPTIONS), cache),
637 system: tslib_1.__assign(tslib_1.__assign({}, DEFAULT_SYSTEM_OPTIONS), system),
638 framework: tslib_1.__assign(tslib_1.__assign({}, DEFAULT_FRAMEWORK_OPTIONS), framework)
639 };
640 return overlayedConfig;
641}
642exports.buildConfiguration = buildConfiguration;
643
644
645/***/ }),
646
647/***/ 881:
648/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
649
650
651/*
652 * Copyright (c) Microsoft Corporation. All rights reserved.
653 * Licensed under the MIT License.
654 */
655Object.defineProperty(exports, "__esModule", ({ value: true }));
656exports.IdToken = void 0;
657var ClientAuthError_1 = __webpack_require__(356);
658var TokenUtils_1 = __webpack_require__(94);
659var StringUtils_1 = __webpack_require__(454);
660/**
661 * @hidden
662 */
663var IdToken = /** @class */ (function () {
664 /* tslint:disable:no-string-literal */
665 function IdToken(rawIdToken) {
666 if (StringUtils_1.StringUtils.isEmpty(rawIdToken)) {
667 throw ClientAuthError_1.ClientAuthError.createIdTokenNullOrEmptyError(rawIdToken);
668 }
669 try {
670 this.rawIdToken = rawIdToken;
671 this.claims = TokenUtils_1.TokenUtils.extractIdToken(rawIdToken);
672 if (this.claims) {
673 if (this.claims.hasOwnProperty("iss")) {
674 this.issuer = this.claims["iss"];
675 }
676 if (this.claims.hasOwnProperty("oid")) {
677 this.objectId = this.claims["oid"];
678 }
679 if (this.claims.hasOwnProperty("sub")) {
680 this.subject = this.claims["sub"];
681 }
682 if (this.claims.hasOwnProperty("tid")) {
683 this.tenantId = this.claims["tid"];
684 }
685 if (this.claims.hasOwnProperty("ver")) {
686 this.version = this.claims["ver"];
687 }
688 if (this.claims.hasOwnProperty("preferred_username")) {
689 this.preferredName = this.claims["preferred_username"];
690 }
691 else if (this.claims.hasOwnProperty("upn")) {
692 this.preferredName = this.claims["upn"];
693 }
694 if (this.claims.hasOwnProperty("name")) {
695 this.name = this.claims["name"];
696 }
697 if (this.claims.hasOwnProperty("nonce")) {
698 this.nonce = this.claims["nonce"];
699 }
700 if (this.claims.hasOwnProperty("exp")) {
701 this.expiration = this.claims["exp"];
702 }
703 if (this.claims.hasOwnProperty("home_oid")) {
704 this.homeObjectId = this.claims["home_oid"];
705 }
706 if (this.claims.hasOwnProperty("sid")) {
707 this.sid = this.claims["sid"];
708 }
709 if (this.claims.hasOwnProperty("cloud_instance_host_name")) {
710 this.cloudInstance = this.claims["cloud_instance_host_name"];
711 }
712 /* tslint:enable:no-string-literal */
713 }
714 }
715 catch (e) {
716 /*
717 * TODO: This error here won't really every be thrown, since extractIdToken() returns null if the decodeJwt() fails.
718 * Need to add better error handling here to account for being unable to decode jwts.
719 */
720 throw ClientAuthError_1.ClientAuthError.createIdTokenParsingError(e);
721 }
722 }
723 return IdToken;
724}());
725exports.IdToken = IdToken;
726
727
728/***/ }),
729
730/***/ 89:
731/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
732
733
734/*
735 * Copyright (c) Microsoft Corporation. All rights reserved.
736 * Licensed under the MIT License.
737 */
738Object.defineProperty(exports, "__esModule", ({ value: true }));
739exports.Logger = exports.LogLevel = void 0;
740var StringUtils_1 = __webpack_require__(454);
741var packageMetadata_1 = __webpack_require__(700);
742var LogLevel;
743(function (LogLevel) {
744 LogLevel[LogLevel["Error"] = 0] = "Error";
745 LogLevel[LogLevel["Warning"] = 1] = "Warning";
746 LogLevel[LogLevel["Info"] = 2] = "Info";
747 LogLevel[LogLevel["Verbose"] = 3] = "Verbose";
748})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
749var Logger = /** @class */ (function () {
750 function Logger(localCallback, options) {
751 if (options === void 0) { options = {}; }
752 /**
753 * @hidden
754 */
755 this.level = LogLevel.Info;
756 var _a = options.correlationId, correlationId = _a === void 0 ? "" : _a, _b = options.level, level = _b === void 0 ? LogLevel.Info : _b, _c = options.piiLoggingEnabled, piiLoggingEnabled = _c === void 0 ? false : _c;
757 this.localCallback = localCallback;
758 this.correlationId = correlationId;
759 this.level = level;
760 this.piiLoggingEnabled = piiLoggingEnabled;
761 }
762 /**
763 * @hidden
764 */
765 Logger.prototype.logMessage = function (logLevel, logMessage, containsPii) {
766 if ((logLevel > this.level) || (!this.piiLoggingEnabled && containsPii)) {
767 return;
768 }
769 var timestamp = new Date().toUTCString();
770 var log;
771 if (!StringUtils_1.StringUtils.isEmpty(this.correlationId)) {
772 log = timestamp + ":" + this.correlationId + "-" + packageMetadata_1.version + "-" + LogLevel[logLevel] + (containsPii ? "-pii" : "") + " " + logMessage;
773 }
774 else {
775 log = timestamp + ":" + packageMetadata_1.version + "-" + LogLevel[logLevel] + (containsPii ? "-pii" : "") + " " + logMessage;
776 }
777 this.executeCallback(logLevel, log, containsPii);
778 };
779 /**
780 * @hidden
781 */
782 Logger.prototype.executeCallback = function (level, message, containsPii) {
783 if (this.localCallback) {
784 this.localCallback(level, message, containsPii);
785 }
786 };
787 /**
788 * @hidden
789 */
790 Logger.prototype.error = function (message) {
791 this.logMessage(LogLevel.Error, message, false);
792 };
793 /**
794 * @hidden
795 */
796 Logger.prototype.errorPii = function (message) {
797 this.logMessage(LogLevel.Error, message, true);
798 };
799 /**
800 * @hidden
801 */
802 Logger.prototype.warning = function (message) {
803 this.logMessage(LogLevel.Warning, message, false);
804 };
805 /**
806 * @hidden
807 */
808 Logger.prototype.warningPii = function (message) {
809 this.logMessage(LogLevel.Warning, message, true);
810 };
811 /**
812 * @hidden
813 */
814 Logger.prototype.info = function (message) {
815 this.logMessage(LogLevel.Info, message, false);
816 };
817 /**
818 * @hidden
819 */
820 Logger.prototype.infoPii = function (message) {
821 this.logMessage(LogLevel.Info, message, true);
822 };
823 /**
824 * @hidden
825 */
826 Logger.prototype.verbose = function (message) {
827 this.logMessage(LogLevel.Verbose, message, false);
828 };
829 /**
830 * @hidden
831 */
832 Logger.prototype.verbosePii = function (message) {
833 this.logMessage(LogLevel.Verbose, message, true);
834 };
835 Logger.prototype.isPiiLoggingEnabled = function () {
836 return this.piiLoggingEnabled;
837 };
838 return Logger;
839}());
840exports.Logger = Logger;
841
842
843/***/ }),
844
845/***/ 55:
846/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
847
848
849/*
850 * Copyright (c) Microsoft Corporation. All rights reserved.
851 * Licensed under the MIT License.
852 */
853Object.defineProperty(exports, "__esModule", ({ value: true }));
854exports.ScopeSet = void 0;
855var tslib_1 = __webpack_require__(795);
856var ClientConfigurationError_1 = __webpack_require__(550);
857var Constants_1 = __webpack_require__(91);
858var ScopeSet = /** @class */ (function () {
859 function ScopeSet() {
860 }
861 /**
862 * Check if there are dup scopes in a given request
863 *
864 * @param cachedScopes
865 * @param scopes
866 */
867 // TODO: Rename this, intersecting scopes isn't a great name for duplicate checker
868 ScopeSet.isIntersectingScopes = function (cachedScopes, scopes) {
869 var convertedCachedScopes = this.trimAndConvertArrayToLowerCase(tslib_1.__spreadArrays(cachedScopes));
870 var requestScopes = this.trimAndConvertArrayToLowerCase(tslib_1.__spreadArrays(scopes));
871 for (var i = 0; i < requestScopes.length; i++) {
872 if (convertedCachedScopes.indexOf(requestScopes[i].toLowerCase()) > -1) {
873 return true;
874 }
875 }
876 return false;
877 };
878 /**
879 * Check if a given scope is present in the request
880 *
881 * @param cachedScopes
882 * @param scopes
883 */
884 ScopeSet.containsScope = function (cachedScopes, scopes) {
885 var convertedCachedScopes = this.trimAndConvertArrayToLowerCase(tslib_1.__spreadArrays(cachedScopes));
886 var requestScopes = this.trimAndConvertArrayToLowerCase(tslib_1.__spreadArrays(scopes));
887 return requestScopes.every(function (value) { return convertedCachedScopes.indexOf(value.toString().toLowerCase()) >= 0; });
888 };
889 /**
890 * Trims and converts string to lower case
891 *
892 * @param scopes
893 */
894 // TODO: Rename this, too generic name for a function that only deals with scopes
895 ScopeSet.trimAndConvertToLowerCase = function (scope) {
896 return scope.trim().toLowerCase();
897 };
898 /**
899 * Performs trimAndConvertToLowerCase on string array
900 * @param scopes
901 */
902 ScopeSet.trimAndConvertArrayToLowerCase = function (scopes) {
903 var _this = this;
904 return scopes.map(function (scope) { return _this.trimAndConvertToLowerCase(scope); });
905 };
906 /**
907 * Trims each scope in scopes array
908 * @param scopes
909 */
910 ScopeSet.trimScopes = function (scopes) {
911 return scopes.map(function (scope) { return scope.trim(); });
912 };
913 /**
914 * Remove one element from a scope array
915 *
916 * @param scopes
917 * @param scope
918 */
919 // TODO: Rename this, too generic name for a function that only deals with scopes
920 ScopeSet.removeElement = function (scopes, scope) {
921 var scopeVal = this.trimAndConvertToLowerCase(scope);
922 return scopes.filter(function (value) { return value !== scopeVal; });
923 };
924 /**
925 * Parse the scopes into a formatted scopeList
926 * @param scopes
927 */
928 ScopeSet.parseScope = function (scopes) {
929 var scopeList = "";
930 if (scopes) {
931 for (var i = 0; i < scopes.length; ++i) {
932 scopeList += (i !== scopes.length - 1) ? scopes[i] + " " : scopes[i];
933 }
934 }
935 return scopeList;
936 };
937 /**
938 * @hidden
939 *
940 * Used to validate the scopes input parameter requested by the developer.
941 * @param {Array<string>} scopes - Developer requested permissions. Not all scopes are guaranteed to be included in the access token returned.
942 * @param {boolean} scopesRequired - Boolean indicating whether the scopes array is required or not
943 * @ignore
944 */
945 ScopeSet.validateInputScope = function (scopes, scopesRequired) {
946 if (!scopes) {
947 if (scopesRequired) {
948 throw ClientConfigurationError_1.ClientConfigurationError.createScopesRequiredError(scopes);
949 }
950 else {
951 return;
952 }
953 }
954 // Check that scopes is an array object (also throws error if scopes == null)
955 if (!Array.isArray(scopes)) {
956 throw ClientConfigurationError_1.ClientConfigurationError.createScopesNonArrayError(scopes);
957 }
958 // Check that scopes is not an empty array
959 if (scopes.length < 1 && scopesRequired) {
960 throw ClientConfigurationError_1.ClientConfigurationError.createEmptyScopesArrayError(scopes.toString());
961 }
962 };
963 /**
964 * @hidden
965 *
966 * Extracts scope value from the state sent with the authentication request.
967 * @param {string} state
968 * @returns {string} scope.
969 * @ignore
970 */
971 ScopeSet.getScopeFromState = function (state) {
972 if (state) {
973 var splitIndex = state.indexOf(Constants_1.Constants.resourceDelimiter);
974 if (splitIndex > -1 && splitIndex + 1 < state.length) {
975 return state.substring(splitIndex + 1);
976 }
977 }
978 return "";
979 };
980 /**
981 * @ignore
982 * Appends extraScopesToConsent if passed
983 * @param {@link AuthenticationParameters}
984 */
985 ScopeSet.appendScopes = function (reqScopes, reqExtraScopesToConsent) {
986 if (reqScopes) {
987 var convertedExtraScopes = reqExtraScopesToConsent ? this.trimAndConvertArrayToLowerCase(tslib_1.__spreadArrays(reqExtraScopesToConsent)) : null;
988 var convertedReqScopes = this.trimAndConvertArrayToLowerCase(tslib_1.__spreadArrays(reqScopes));
989 return convertedExtraScopes ? tslib_1.__spreadArrays(convertedReqScopes, convertedExtraScopes) : convertedReqScopes;
990 }
991 return null;
992 };
993 // #endregion
994 /**
995 * @ignore
996 * Returns true if the scopes array only contains openid and/or profile
997 */
998 ScopeSet.onlyContainsOidcScopes = function (scopes) {
999 var scopesCount = scopes.length;
1000 var oidcScopesFound = 0;
1001 if (scopes.indexOf(Constants_1.Constants.openidScope) > -1) {
1002 oidcScopesFound += 1;
1003 }
1004 if (scopes.indexOf(Constants_1.Constants.profileScope) > -1) {
1005 oidcScopesFound += 1;
1006 }
1007 return (scopesCount > 0 && scopesCount === oidcScopesFound);
1008 };
1009 /**
1010 * @ignore
1011 * Returns true if the scopes array only contains openid and/or profile
1012 */
1013 ScopeSet.containsAnyOidcScopes = function (scopes) {
1014 var containsOpenIdScope = scopes.indexOf(Constants_1.Constants.openidScope) > -1;
1015 var containsProfileScope = scopes.indexOf(Constants_1.Constants.profileScope) > -1;
1016 return (containsOpenIdScope || containsProfileScope);
1017 };
1018 /**
1019 * @ignore
1020 * Returns true if the clientId is the only scope in the array
1021 */
1022 ScopeSet.onlyContainsClientId = function (scopes, clientId) {
1023 // Double negation to force false value returned in case scopes is null
1024 return !!scopes && (scopes.indexOf(clientId) > -1 && scopes.length === 1);
1025 };
1026 /**
1027 * @ignore
1028 * Adds missing OIDC scopes to scopes array without duplication. Since STS requires OIDC scopes for
1029 * all implicit flow requests, 'openid' and 'profile' should always be included in the final request
1030 */
1031 ScopeSet.appendDefaultScopes = function (scopes) {
1032 var extendedScopes = scopes;
1033 if (extendedScopes.indexOf(Constants_1.Constants.openidScope) === -1) {
1034 extendedScopes.push(Constants_1.Constants.openidScope);
1035 }
1036 if (extendedScopes.indexOf(Constants_1.Constants.profileScope) === -1) {
1037 extendedScopes.push(Constants_1.Constants.profileScope);
1038 }
1039 return extendedScopes;
1040 };
1041 /**
1042 * @ignore
1043 * Removes present OIDC scopes from scopes array.
1044 */
1045 ScopeSet.removeDefaultScopes = function (scopes) {
1046 return scopes.filter(function (scope) {
1047 return (scope !== Constants_1.Constants.openidScope && scope !== Constants_1.Constants.profileScope);
1048 });
1049 };
1050 /**
1051 * @ignore
1052 * Removes clientId from scopes array if included as only scope. If it's not the only scope, it is treated as a resource scope.
1053 * @param scopes Array<string>: Pre-normalized scopes array
1054 * @param clientId string: The application's clientId that is searched for in the scopes array
1055 */
1056 ScopeSet.translateClientIdIfSingleScope = function (scopes, clientId) {
1057 return this.onlyContainsClientId(scopes, clientId) ? Constants_1.Constants.oidcScopes : scopes;
1058 };
1059 return ScopeSet;
1060}());
1061exports.ScopeSet = ScopeSet;
1062
1063
1064/***/ }),
1065
1066/***/ 436:
1067/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
1068
1069
1070/*
1071 * Copyright (c) Microsoft Corporation. All rights reserved.
1072 * Licensed under the MIT License.
1073 */
1074Object.defineProperty(exports, "__esModule", ({ value: true }));
1075exports.ServerRequestParameters = void 0;
1076var tslib_1 = __webpack_require__(795);
1077var CryptoUtils_1 = __webpack_require__(453);
1078var Constants_1 = __webpack_require__(91);
1079var ScopeSet_1 = __webpack_require__(55);
1080var packageMetadata_1 = __webpack_require__(700);
1081/**
1082 * Nonce: OIDC Nonce definition: https://openid.net/specs/openid-connect-core-1_0.html#IDToken
1083 * State: OAuth Spec: https://tools.ietf.org/html/rfc6749#section-10.12
1084 * @hidden
1085 */
1086var ServerRequestParameters = /** @class */ (function () {
1087 /**
1088 * Constructor
1089 * @param authority
1090 * @param clientId
1091 * @param scope
1092 * @param responseType
1093 * @param redirectUri
1094 * @param state
1095 */
1096 function ServerRequestParameters(authority, clientId, responseType, redirectUri, scopes, state, correlationId) {
1097 this.authorityInstance = authority;
1098 this.clientId = clientId;
1099 this.nonce = CryptoUtils_1.CryptoUtils.createNewGuid();
1100 // set scope to clientId if null
1101 this.scopes = scopes ? tslib_1.__spreadArrays(scopes) : Constants_1.Constants.oidcScopes;
1102 this.scopes = ScopeSet_1.ScopeSet.trimScopes(this.scopes);
1103 // set state (already set at top level)
1104 this.state = state;
1105 // set correlationId
1106 this.correlationId = correlationId;
1107 // telemetry information
1108 this.xClientSku = "MSAL.JS";
1109 this.xClientVer = packageMetadata_1.version;
1110 this.responseType = responseType;
1111 this.redirectUri = redirectUri;
1112 }
1113 Object.defineProperty(ServerRequestParameters.prototype, "authority", {
1114 get: function () {
1115 return this.authorityInstance ? this.authorityInstance.CanonicalAuthority : null;
1116 },
1117 enumerable: false,
1118 configurable: true
1119 });
1120 /**
1121 * @hidden
1122 * @ignore
1123 *
1124 * Utility to populate QueryParameters and ExtraQueryParameters to ServerRequestParamerers
1125 * @param request
1126 * @param serverAuthenticationRequest
1127 */
1128 ServerRequestParameters.prototype.populateQueryParams = function (account, request, adalIdTokenObject, silentCall) {
1129 var queryParameters = {};
1130 if (request) {
1131 // add the prompt parameter to serverRequestParameters if passed
1132 if (request.prompt) {
1133 this.promptValue = request.prompt;
1134 }
1135 // Add claims challenge to serverRequestParameters if passed
1136 if (request.claimsRequest) {
1137 this.claimsValue = request.claimsRequest;
1138 }
1139 // if the developer provides one of these, give preference to developer choice
1140 if (ServerRequestParameters.isSSOParam(request)) {
1141 queryParameters = this.constructUnifiedCacheQueryParameter(request, null);
1142 }
1143 }
1144 if (adalIdTokenObject) {
1145 queryParameters = this.constructUnifiedCacheQueryParameter(null, adalIdTokenObject);
1146 }
1147 /*
1148 * adds sid/login_hint if not populated
1149 * this.logger.verbose("Calling addHint parameters");
1150 */
1151 queryParameters = this.addHintParameters(account, queryParameters);
1152 // sanity check for developer passed extraQueryParameters
1153 var eQParams = request ? request.extraQueryParameters : null;
1154 // Populate the extraQueryParameters to be sent to the server
1155 this.queryParameters = ServerRequestParameters.generateQueryParametersString(queryParameters);
1156 this.extraQueryParameters = ServerRequestParameters.generateQueryParametersString(eQParams, silentCall);
1157 };
1158 // #region QueryParam helpers
1159 /**
1160 * Constructs extraQueryParameters to be sent to the server for the AuthenticationParameters set by the developer
1161 * in any login() or acquireToken() calls
1162 * @param idTokenObject
1163 * @param extraQueryParameters
1164 * @param sid
1165 * @param loginHint
1166 */
1167 // TODO: check how this behaves when domain_hint only is sent in extraparameters and idToken has no upn.
1168 ServerRequestParameters.prototype.constructUnifiedCacheQueryParameter = function (request, idTokenObject) {
1169 var _a;
1170 // preference order: account > sid > login_hint
1171 var ssoType;
1172 var ssoData;
1173 var serverReqParam = {};
1174 // if account info is passed, account.login_hint claim > account.sid > account.username
1175 if (request) {
1176 if (request.account) {
1177 var account = request.account;
1178 if ((_a = account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.login_hint) {
1179 ssoType = Constants_1.SSOTypes.LOGIN_HINT;
1180 ssoData = account.idTokenClaims.login_hint;
1181 }
1182 else if (account.sid) {
1183 ssoType = Constants_1.SSOTypes.SID;
1184 ssoData = account.sid;
1185 }
1186 else if (account.userName) {
1187 ssoType = Constants_1.SSOTypes.LOGIN_HINT;
1188 ssoData = account.userName;
1189 }
1190 }
1191 // sid from request
1192 else if (request.sid) {
1193 ssoType = Constants_1.SSOTypes.SID;
1194 ssoData = request.sid;
1195 }
1196 // loginHint from request
1197 else if (request.loginHint) {
1198 ssoType = Constants_1.SSOTypes.LOGIN_HINT;
1199 ssoData = request.loginHint;
1200 }
1201 }
1202 // adalIdToken retrieved from cache
1203 else if (idTokenObject) {
1204 if (idTokenObject.hasOwnProperty(Constants_1.Constants.upn)) {
1205 ssoType = Constants_1.SSOTypes.ID_TOKEN;
1206 ssoData = idTokenObject["upn"];
1207 }
1208 }
1209 serverReqParam = this.addSSOParameter(ssoType, ssoData);
1210 return serverReqParam;
1211 };
1212 /**
1213 * @hidden
1214 *
1215 * Adds login_hint to authorization URL which is used to pre-fill the username field of sign in page for the user if known ahead of time
1216 * domain_hint if added skips the email based discovery process of the user - only supported for interactive calls in implicit_flow
1217 * domain_req utid received as part of the clientInfo
1218 * login_req uid received as part of clientInfo
1219 * Also does a sanity check for extraQueryParameters passed by the user to ensure no repeat queryParameters
1220 *
1221 * @param {@link Account} account - Account for which the token is requested
1222 * @param queryparams
1223 * @param {@link ServerRequestParameters}
1224 * @ignore
1225 */
1226 ServerRequestParameters.prototype.addHintParameters = function (account, params) {
1227 var _a, _b;
1228 /*
1229 * This is a final check for all queryParams added so far; preference order: sid > login_hint
1230 * sid cannot be passed along with login_hint or domain_hint, hence we check both are not populated yet in queryParameters
1231 */
1232 var qParams = params;
1233 if (account) {
1234 if (!qParams[Constants_1.SSOTypes.SID] && !qParams[Constants_1.SSOTypes.LOGIN_HINT]) {
1235 if ((_a = account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.login_hint) {
1236 // Use login_hint claim if available over sid or email/upn
1237 qParams = this.addSSOParameter(Constants_1.SSOTypes.LOGIN_HINT, (_b = account.idTokenClaims) === null || _b === void 0 ? void 0 : _b.login_hint, qParams);
1238 }
1239 else if (account.sid && this.promptValue === Constants_1.PromptState.NONE) {
1240 // sid - populate only if login_hint is not already populated and the account has sid
1241 qParams = this.addSSOParameter(Constants_1.SSOTypes.SID, account.sid, qParams);
1242 }
1243 else if (account.userName) {
1244 // Add username/upn as loginHint if nothing else available
1245 qParams = this.addSSOParameter(Constants_1.SSOTypes.LOGIN_HINT, account.userName, qParams);
1246 }
1247 }
1248 }
1249 return qParams;
1250 };
1251 /**
1252 * Add SID to extraQueryParameters
1253 * @param sid
1254 */
1255 ServerRequestParameters.prototype.addSSOParameter = function (ssoType, ssoData, params) {
1256 var ssoParam = params || {};
1257 if (!ssoData) {
1258 return ssoParam;
1259 }
1260 switch (ssoType) {
1261 case Constants_1.SSOTypes.SID: {
1262 ssoParam[Constants_1.SSOTypes.SID] = ssoData;
1263 break;
1264 }
1265 case Constants_1.SSOTypes.ID_TOKEN: {
1266 ssoParam[Constants_1.SSOTypes.LOGIN_HINT] = ssoData;
1267 break;
1268 }
1269 case Constants_1.SSOTypes.LOGIN_HINT: {
1270 ssoParam[Constants_1.SSOTypes.LOGIN_HINT] = ssoData;
1271 break;
1272 }
1273 }
1274 return ssoParam;
1275 };
1276 /**
1277 * Utility to generate a QueryParameterString from a Key-Value mapping of extraQueryParameters passed
1278 * @param extraQueryParameters
1279 */
1280 ServerRequestParameters.generateQueryParametersString = function (queryParameters, silentCall) {
1281 var paramsString = null;
1282 if (queryParameters) {
1283 Object.keys(queryParameters).forEach(function (key) {
1284 // sid cannot be passed along with login_hint or domain_hint
1285 if (key === Constants_1.Constants.domain_hint && (silentCall || queryParameters[Constants_1.SSOTypes.SID])) {
1286 return;
1287 }
1288 if (!paramsString) {
1289 paramsString = key + "=" + encodeURIComponent(queryParameters[key]);
1290 }
1291 else {
1292 paramsString += "&" + key + "=" + encodeURIComponent(queryParameters[key]);
1293 }
1294 });
1295 }
1296 return paramsString;
1297 };
1298 // #endregion
1299 /**
1300 * Check to see if there are SSO params set in the Request
1301 * @param request
1302 */
1303 ServerRequestParameters.isSSOParam = function (request) {
1304 return !!(request && (request.account || request.sid || request.loginHint));
1305 };
1306 /**
1307 * Returns the correct response_type string attribute for an acquireToken request configuration
1308 * @param accountsMatch boolean: Determines whether the account in the request matches the cached account
1309 * @param scopes Array<string>: AuthenticationRequest scopes configuration
1310 * @param loginScopesOnly boolean: True if the scopes array ONLY contains the clientId or any combination of OIDC scopes, without resource scopes
1311 */
1312 ServerRequestParameters.determineResponseType = function (accountsMatch, scopes) {
1313 // Supports getting an id_token by sending in clientId as only scope or OIDC scopes as only scopes
1314 if (ScopeSet_1.ScopeSet.onlyContainsOidcScopes(scopes)) {
1315 return Constants_1.ResponseTypes.id_token;
1316 }
1317 // If accounts match, check if OIDC scopes are included, otherwise return id_token_token
1318 return (accountsMatch) ? this.responseTypeForMatchingAccounts(scopes) : Constants_1.ResponseTypes.id_token_token;
1319 };
1320 /**
1321 * Returns the correct response_type string attribute for an acquireToken request configuration that contains an
1322 * account that matches the account in the MSAL cache.
1323 * @param scopes Array<string>: AuthenticationRequest scopes configuration
1324 */
1325 ServerRequestParameters.responseTypeForMatchingAccounts = function (scopes) {
1326 // Opt-into also requesting an ID token by sending in 'openid', 'profile' or both along with resource scopes when login is not necessary.
1327 return (ScopeSet_1.ScopeSet.containsAnyOidcScopes(scopes)) ? Constants_1.ResponseTypes.id_token_token : Constants_1.ResponseTypes.token;
1328 };
1329 return ServerRequestParameters;
1330}());
1331exports.ServerRequestParameters = ServerRequestParameters;
1332
1333
1334/***/ }),
1335
1336/***/ 463:
1337/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
1338
1339
1340/*
1341 * Copyright (c) Microsoft Corporation. All rights reserved.
1342 * Licensed under the MIT License.
1343 */
1344Object.defineProperty(exports, "__esModule", ({ value: true }));
1345exports.UserAgentApplication = void 0;
1346var tslib_1 = __webpack_require__(795);
1347var AccessTokenKey_1 = __webpack_require__(29);
1348var AccessTokenValue_1 = __webpack_require__(192);
1349var ServerRequestParameters_1 = __webpack_require__(436);
1350var Authority_1 = __webpack_require__(660);
1351var ClientInfo_1 = __webpack_require__(271);
1352var IdToken_1 = __webpack_require__(881);
1353var AuthCache_1 = __webpack_require__(226);
1354var Account_1 = __webpack_require__(630);
1355var ScopeSet_1 = __webpack_require__(55);
1356var StringUtils_1 = __webpack_require__(454);
1357var WindowUtils_1 = __webpack_require__(758);
1358var TokenUtils_1 = __webpack_require__(94);
1359var TimeUtils_1 = __webpack_require__(78);
1360var UrlUtils_1 = __webpack_require__(741);
1361var RequestUtils_1 = __webpack_require__(52);
1362var ResponseUtils_1 = __webpack_require__(756);
1363var AuthorityFactory_1 = __webpack_require__(951);
1364var Configuration_1 = __webpack_require__(875);
1365var ClientConfigurationError_1 = __webpack_require__(550);
1366var AuthError_1 = __webpack_require__(986);
1367var ClientAuthError_1 = __webpack_require__(356);
1368var ServerError_1 = __webpack_require__(447);
1369var InteractionRequiredAuthError_1 = __webpack_require__(961);
1370var AuthResponse_1 = __webpack_require__(681);
1371var TelemetryManager_1 = tslib_1.__importDefault(__webpack_require__(478));
1372var ApiEvent_1 = __webpack_require__(663);
1373var Constants_1 = __webpack_require__(91);
1374var CryptoUtils_1 = __webpack_require__(453);
1375var TrustedAuthority_1 = __webpack_require__(405);
1376var AuthCacheUtils_1 = __webpack_require__(49);
1377// default authority
1378var DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common";
1379/**
1380 * UserAgentApplication class
1381 *
1382 * Object Instance that the developer can use to make loginXX OR acquireTokenXX functions
1383 */
1384var UserAgentApplication = /** @class */ (function () {
1385 /**
1386 * @constructor
1387 * Constructor for the UserAgentApplication used to instantiate the UserAgentApplication object
1388 *
1389 * Important attributes in the Configuration object for auth are:
1390 * - clientID: the application ID of your application.
1391 * You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
1392 * - authority: the authority URL for your application.
1393 *
1394 * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
1395 * It is of the form https://login.microsoftonline.com/&lt;Enter_the_Tenant_Info_Here&gt;.
1396 * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
1397 * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
1398 * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
1399 * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
1400 *
1401 *
1402 * In Azure B2C, authority is of the form https://&lt;instance&gt;/tfp/&lt;tenant&gt;/&lt;policyName&gt;/
1403 *
1404 * @param {@link (Configuration:type)} configuration object for the MSAL UserAgentApplication instance
1405 */
1406 function UserAgentApplication(configuration) {
1407 // callbacks for token/error
1408 this.authResponseCallback = null;
1409 this.tokenReceivedCallback = null;
1410 this.errorReceivedCallback = null;
1411 // Set the Configuration
1412 this.config = Configuration_1.buildConfiguration(configuration);
1413 this.logger = this.config.system.logger;
1414 this.clientId = this.config.auth.clientId;
1415 this.inCookie = this.config.cache.storeAuthStateInCookie;
1416 this.telemetryManager = this.getTelemetryManagerFromConfig(this.config.system.telemetry, this.clientId);
1417 TrustedAuthority_1.TrustedAuthority.setTrustedAuthoritiesFromConfig(this.config.auth.validateAuthority, this.config.auth.knownAuthorities);
1418 AuthorityFactory_1.AuthorityFactory.saveMetadataFromConfig(this.config.auth.authority, this.config.auth.authorityMetadata);
1419 // if no authority is passed, set the default: "https://login.microsoftonline.com/common"
1420 this.authority = this.config.auth.authority || DEFAULT_AUTHORITY;
1421 // cache keys msal - typescript throws an error if any value other than "localStorage" or "sessionStorage" is passed
1422 this.cacheStorage = new AuthCache_1.AuthCache(this.clientId, this.config.cache.cacheLocation, this.inCookie);
1423 // Initialize window handling code
1424 if (!window.activeRenewals) {
1425 window.activeRenewals = {};
1426 }
1427 if (!window.renewStates) {
1428 window.renewStates = [];
1429 }
1430 if (!window.callbackMappedToRenewStates) {
1431 window.callbackMappedToRenewStates = {};
1432 }
1433 if (!window.promiseMappedToRenewStates) {
1434 window.promiseMappedToRenewStates = {};
1435 }
1436 window.msal = this;
1437 var urlHash = window.location.hash;
1438 var urlContainsHash = UrlUtils_1.UrlUtils.urlContainsHash(urlHash);
1439 // check if back button is pressed
1440 WindowUtils_1.WindowUtils.checkIfBackButtonIsPressed(this.cacheStorage);
1441 // On the server 302 - Redirect, handle this
1442 if (urlContainsHash && this.cacheStorage.isInteractionInProgress(true)) {
1443 var stateInfo = this.getResponseState(urlHash);
1444 if (stateInfo.method === Constants_1.Constants.interactionTypeRedirect) {
1445 this.handleRedirectAuthenticationResponse(urlHash);
1446 }
1447 }
1448 }
1449 Object.defineProperty(UserAgentApplication.prototype, "authority", {
1450 /**
1451 * Method to manage the authority URL.
1452 *
1453 * @returns {string} authority
1454 */
1455 get: function () {
1456 return this.authorityInstance.CanonicalAuthority;
1457 },
1458 /**
1459 * setter for the authority URL
1460 * @param {string} authority
1461 */
1462 // If the developer passes an authority, create an instance
1463 set: function (val) {
1464 this.authorityInstance = AuthorityFactory_1.AuthorityFactory.CreateInstance(val, this.config.auth.validateAuthority);
1465 },
1466 enumerable: false,
1467 configurable: true
1468 });
1469 /**
1470 * Get the current authority instance from the MSAL configuration object
1471 *
1472 * @returns {@link Authority} authority instance
1473 */
1474 UserAgentApplication.prototype.getAuthorityInstance = function () {
1475 return this.authorityInstance;
1476 };
1477 UserAgentApplication.prototype.handleRedirectCallback = function (authOrTokenCallback, errorReceivedCallback) {
1478 if (!authOrTokenCallback) {
1479 throw ClientConfigurationError_1.ClientConfigurationError.createInvalidCallbackObjectError(authOrTokenCallback);
1480 }
1481 // Set callbacks
1482 if (errorReceivedCallback) {
1483 this.tokenReceivedCallback = authOrTokenCallback;
1484 this.errorReceivedCallback = errorReceivedCallback;
1485 this.logger.warning("This overload for callback is deprecated - please change the format of the callbacks to a single callback as shown: (err: AuthError, response: AuthResponse).");
1486 }
1487 else {
1488 this.authResponseCallback = authOrTokenCallback;
1489 }
1490 if (this.redirectError) {
1491 this.authErrorHandler(Constants_1.Constants.interactionTypeRedirect, this.redirectError, this.redirectResponse);
1492 }
1493 else if (this.redirectResponse) {
1494 this.authResponseHandler(Constants_1.Constants.interactionTypeRedirect, this.redirectResponse);
1495 }
1496 };
1497 /**
1498 * Public API to verify if the URL contains the hash with known properties
1499 * @param hash
1500 */
1501 UserAgentApplication.prototype.urlContainsHash = function (hash) {
1502 this.logger.verbose("UrlContainsHash has been called");
1503 return UrlUtils_1.UrlUtils.urlContainsHash(hash);
1504 };
1505 UserAgentApplication.prototype.authResponseHandler = function (interactionType, response, resolve) {
1506 this.logger.verbose("AuthResponseHandler has been called");
1507 this.cacheStorage.setInteractionInProgress(false);
1508 if (interactionType === Constants_1.Constants.interactionTypeRedirect) {
1509 this.logger.verbose("Interaction type is redirect");
1510 if (this.errorReceivedCallback) {
1511 this.logger.verbose("Two callbacks were provided to handleRedirectCallback, calling success callback with response");
1512 this.tokenReceivedCallback(response);
1513 }
1514 else if (this.authResponseCallback) {
1515 this.logger.verbose("One callback was provided to handleRedirectCallback, calling authResponseCallback with response");
1516 this.authResponseCallback(null, response);
1517 }
1518 }
1519 else if (interactionType === Constants_1.Constants.interactionTypePopup) {
1520 this.logger.verbose("Interaction type is popup, resolving");
1521 resolve(response);
1522 }
1523 else {
1524 throw ClientAuthError_1.ClientAuthError.createInvalidInteractionTypeError();
1525 }
1526 };
1527 UserAgentApplication.prototype.authErrorHandler = function (interactionType, authErr, response, reject) {
1528 this.logger.verbose("AuthErrorHandler has been called");
1529 // set interaction_status to complete
1530 this.cacheStorage.setInteractionInProgress(false);
1531 if (interactionType === Constants_1.Constants.interactionTypeRedirect) {
1532 this.logger.verbose("Interaction type is redirect");
1533 if (this.errorReceivedCallback) {
1534 this.logger.verbose("Two callbacks were provided to handleRedirectCallback, calling error callback");
1535 this.errorReceivedCallback(authErr, response.accountState);
1536 }
1537 else if (this.authResponseCallback) {
1538 this.logger.verbose("One callback was provided to handleRedirectCallback, calling authResponseCallback with error");
1539 this.authResponseCallback(authErr, response);
1540 }
1541 else {
1542 this.logger.verbose("handleRedirectCallback has not been called and no callbacks are registered, throwing error");
1543 throw authErr;
1544 }
1545 }
1546 else if (interactionType === Constants_1.Constants.interactionTypePopup) {
1547 this.logger.verbose("Interaction type is popup, rejecting");
1548 reject(authErr);
1549 }
1550 else {
1551 throw ClientAuthError_1.ClientAuthError.createInvalidInteractionTypeError();
1552 }
1553 };
1554 // #endregion
1555 /**
1556 * Use when initiating the login process by redirecting the user's browser to the authorization endpoint.
1557 * @param {@link (AuthenticationParameters:type)}
1558 */
1559 UserAgentApplication.prototype.loginRedirect = function (userRequest) {
1560 this.logger.verbose("LoginRedirect has been called");
1561 // validate request
1562 var request = RequestUtils_1.RequestUtils.validateRequest(userRequest, true, this.clientId, Constants_1.Constants.interactionTypeRedirect);
1563 this.acquireTokenInteractive(Constants_1.Constants.interactionTypeRedirect, true, request, null, null);
1564 };
1565 /**
1566 * Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint.
1567 * @param {@link (AuthenticationParameters:type)}
1568 *
1569 * To renew idToken, please pass clientId as the only scope in the Authentication Parameters
1570 */
1571 UserAgentApplication.prototype.acquireTokenRedirect = function (userRequest) {
1572 this.logger.verbose("AcquireTokenRedirect has been called");
1573 // validate request
1574 var request = RequestUtils_1.RequestUtils.validateRequest(userRequest, false, this.clientId, Constants_1.Constants.interactionTypeRedirect);
1575 this.acquireTokenInteractive(Constants_1.Constants.interactionTypeRedirect, false, request, null, null);
1576 };
1577 /**
1578 * Use when initiating the login process via opening a popup window in the user's browser
1579 *
1580 * @param {@link (AuthenticationParameters:type)}
1581 *
1582 * @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
1583 */
1584 UserAgentApplication.prototype.loginPopup = function (userRequest) {
1585 var _this = this;
1586 this.logger.verbose("LoginPopup has been called");
1587 // validate request
1588 var request = RequestUtils_1.RequestUtils.validateRequest(userRequest, true, this.clientId, Constants_1.Constants.interactionTypePopup);
1589 var apiEvent = this.telemetryManager.createAndStartApiEvent(request.correlationId, ApiEvent_1.API_EVENT_IDENTIFIER.LoginPopup);
1590 return new Promise(function (resolve, reject) {
1591 _this.acquireTokenInteractive(Constants_1.Constants.interactionTypePopup, true, request, resolve, reject);
1592 })
1593 .then(function (resp) {
1594 _this.logger.verbose("Successfully logged in");
1595 _this.telemetryManager.stopAndFlushApiEvent(request.correlationId, apiEvent, true);
1596 return resp;
1597 })
1598 .catch(function (error) {
1599 _this.cacheStorage.resetTempCacheItems(request.state);
1600 _this.telemetryManager.stopAndFlushApiEvent(request.correlationId, apiEvent, false, error.errorCode);
1601 throw error;
1602 });
1603 };
1604 /**
1605 * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
1606 * @param {@link AuthenticationParameters}
1607 *
1608 * To renew idToken, please pass clientId as the only scope in the Authentication Parameters
1609 * @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
1610 */
1611 UserAgentApplication.prototype.acquireTokenPopup = function (userRequest) {
1612 var _this = this;
1613 this.logger.verbose("AcquireTokenPopup has been called");
1614 // validate request
1615 var request = RequestUtils_1.RequestUtils.validateRequest(userRequest, false, this.clientId, Constants_1.Constants.interactionTypePopup);
1616 var apiEvent = this.telemetryManager.createAndStartApiEvent(request.correlationId, ApiEvent_1.API_EVENT_IDENTIFIER.AcquireTokenPopup);
1617 return new Promise(function (resolve, reject) {
1618 _this.acquireTokenInteractive(Constants_1.Constants.interactionTypePopup, false, request, resolve, reject);
1619 })
1620 .then(function (resp) {
1621 _this.logger.verbose("Successfully acquired token");
1622 _this.telemetryManager.stopAndFlushApiEvent(request.correlationId, apiEvent, true);
1623 return resp;
1624 })
1625 .catch(function (error) {
1626 _this.cacheStorage.resetTempCacheItems(request.state);
1627 _this.telemetryManager.stopAndFlushApiEvent(request.correlationId, apiEvent, false, error.errorCode);
1628 throw error;
1629 });
1630 };
1631 // #region Acquire Token
1632 /**
1633 * Use when initiating the login process or when you want to obtain an access_token for your API,
1634 * either by redirecting the user's browser window to the authorization endpoint or via opening a popup window in the user's browser.
1635 * @param {@link (AuthenticationParameters:type)}
1636 *
1637 * To renew idToken, please pass clientId as the only scope in the Authentication Parameters
1638 */
1639 UserAgentApplication.prototype.acquireTokenInteractive = function (interactionType, isLoginCall, request, resolve, reject) {
1640 var _this = this;
1641 this.logger.verbose("AcquireTokenInteractive has been called");
1642 // block the request if made from the hidden iframe
1643 WindowUtils_1.WindowUtils.blockReloadInHiddenIframes();
1644 try {
1645 this.cacheStorage.setInteractionInProgress(true);
1646 }
1647 catch (e) {
1648 // If already in progress, do not proceed
1649 var thrownError = isLoginCall ? ClientAuthError_1.ClientAuthError.createLoginInProgressError() : ClientAuthError_1.ClientAuthError.createAcquireTokenInProgressError();
1650 var stateOnlyResponse = AuthResponse_1.buildResponseStateOnly(this.getAccountState(request.state));
1651 this.cacheStorage.resetTempCacheItems(request.state);
1652 this.authErrorHandler(interactionType, thrownError, stateOnlyResponse, reject);
1653 return;
1654 }
1655 if (interactionType === Constants_1.Constants.interactionTypeRedirect) {
1656 this.cacheStorage.setItem(Constants_1.TemporaryCacheKeys.REDIRECT_REQUEST, "" + Constants_1.Constants.inProgress + Constants_1.Constants.resourceDelimiter + request.state);
1657 }
1658 // Get the account object if a session exists
1659 var account;
1660 if (request && request.account && !isLoginCall) {
1661 account = request.account;
1662 this.logger.verbose("Account set from request");
1663 }
1664 else {
1665 account = this.getAccount();
1666 this.logger.verbose("Account set from MSAL Cache");
1667 }
1668 // If no session exists, prompt the user to login.
1669 if (!account && !ServerRequestParameters_1.ServerRequestParameters.isSSOParam(request)) {
1670 if (isLoginCall) {
1671 // extract ADAL id_token if exists
1672 var adalIdToken = this.extractADALIdToken();
1673 // silent login if ADAL id_token is retrieved successfully - SSO
1674 if (adalIdToken && !request.scopes) {
1675 this.logger.info("ADAL's idToken exists. Extracting login information from ADAL's idToken");
1676 var tokenRequest = this.buildIDTokenRequest(request);
1677 this.silentLogin = true;
1678 this.acquireTokenSilent(tokenRequest).then(function (response) {
1679 _this.silentLogin = false;
1680 _this.logger.info("Unified cache call is successful");
1681 _this.authResponseHandler(interactionType, response, resolve);
1682 return;
1683 }, function (error) {
1684 _this.silentLogin = false;
1685 _this.logger.error("Error occurred during unified cache ATS: " + error);
1686 // proceed to login since ATS failed
1687 _this.acquireTokenHelper(null, interactionType, isLoginCall, request, resolve, reject);
1688 });
1689 }
1690 // No ADAL token found, proceed to login
1691 else {
1692 this.logger.verbose("Login call but no token found, proceed to login");
1693 this.acquireTokenHelper(null, interactionType, isLoginCall, request, resolve, reject);
1694 }
1695 }
1696 // AcquireToken call, but no account or context given, so throw error
1697 else {
1698 this.logger.verbose("AcquireToken call, no context or account given");
1699 this.logger.info("User login is required");
1700 var stateOnlyResponse = AuthResponse_1.buildResponseStateOnly(this.getAccountState(request.state));
1701 this.cacheStorage.resetTempCacheItems(request.state);
1702 this.authErrorHandler(interactionType, ClientAuthError_1.ClientAuthError.createUserLoginRequiredError(), stateOnlyResponse, reject);
1703 return;
1704 }
1705 }
1706 // User session exists
1707 else {
1708 this.logger.verbose("User session exists, login not required");
1709 this.acquireTokenHelper(account, interactionType, isLoginCall, request, resolve, reject);
1710 }
1711 };
1712 /**
1713 * @hidden
1714 * @ignore
1715 * Helper function to acquireToken
1716 *
1717 */
1718 UserAgentApplication.prototype.acquireTokenHelper = function (account, interactionType, isLoginCall, request, resolve, reject) {
1719 return tslib_1.__awaiter(this, void 0, Promise, function () {
1720 var requestSignature, serverAuthenticationRequest, acquireTokenAuthority, popUpWindow, responseType, loginStartPage, urlNavigate, hash, error_1, navigate, err_1;
1721 return tslib_1.__generator(this, function (_a) {
1722 switch (_a.label) {
1723 case 0:
1724 this.logger.verbose("AcquireTokenHelper has been called");
1725 this.logger.verbose("Interaction type: " + interactionType + ". isLoginCall: " + isLoginCall);
1726 requestSignature = request.scopes ? request.scopes.join(" ").toLowerCase() : Constants_1.Constants.oidcScopes.join(" ");
1727 this.logger.verbosePii("Request signature: " + requestSignature);
1728 acquireTokenAuthority = (request && request.authority) ? AuthorityFactory_1.AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority, request.authorityMetadata) : this.authorityInstance;
1729 _a.label = 1;
1730 case 1:
1731 _a.trys.push([1, 11, , 12]);
1732 if (!!acquireTokenAuthority.hasCachedMetadata()) return [3 /*break*/, 3];
1733 this.logger.verbose("No cached metadata for authority");
1734 return [4 /*yield*/, AuthorityFactory_1.AuthorityFactory.saveMetadataFromNetwork(acquireTokenAuthority, this.telemetryManager, request.correlationId)];
1735 case 2:
1736 _a.sent();
1737 return [3 /*break*/, 4];
1738 case 3:
1739 this.logger.verbose("Cached metadata found for authority");
1740 _a.label = 4;
1741 case 4:
1742 responseType = isLoginCall ? Constants_1.ResponseTypes.id_token : this.getTokenType(account, request.scopes);
1743 loginStartPage = request.redirectStartPage || window.location.href;
1744 serverAuthenticationRequest = new ServerRequestParameters_1.ServerRequestParameters(acquireTokenAuthority, this.clientId, responseType, this.getRedirectUri(request && request.redirectUri), request.scopes, request.state, request.correlationId);
1745 this.logger.verbose("Finished building server authentication request");
1746 this.updateCacheEntries(serverAuthenticationRequest, account, isLoginCall, loginStartPage);
1747 this.logger.verbose("Updating cache entries");
1748 // populate QueryParameters (sid/login_hint) and any other extraQueryParameters set by the developer
1749 serverAuthenticationRequest.populateQueryParams(account, request);
1750 this.logger.verbose("Query parameters populated from account");
1751 urlNavigate = UrlUtils_1.UrlUtils.createNavigateUrl(serverAuthenticationRequest) + Constants_1.Constants.response_mode_fragment;
1752 // set state in cache
1753 if (interactionType === Constants_1.Constants.interactionTypeRedirect) {
1754 if (!isLoginCall) {
1755 this.cacheStorage.setItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.STATE_ACQ_TOKEN, request.state), serverAuthenticationRequest.state, this.inCookie);
1756 this.logger.verbose("State cached for redirect");
1757 this.logger.verbosePii("State cached: " + serverAuthenticationRequest.state);
1758 }
1759 else {
1760 this.logger.verbose("Interaction type redirect but login call is true. State not cached");
1761 }
1762 }
1763 else if (interactionType === Constants_1.Constants.interactionTypePopup) {
1764 window.renewStates.push(serverAuthenticationRequest.state);
1765 window.requestType = isLoginCall ? Constants_1.Constants.login : Constants_1.Constants.renewToken;
1766 this.logger.verbose("State saved to window");
1767 this.logger.verbosePii("State saved: " + serverAuthenticationRequest.state);
1768 // Register callback to capture results from server
1769 this.registerCallback(serverAuthenticationRequest.state, requestSignature, resolve, reject);
1770 }
1771 else {
1772 this.logger.verbose("Invalid interaction error. State not cached");
1773 throw ClientAuthError_1.ClientAuthError.createInvalidInteractionTypeError();
1774 }
1775 if (!(interactionType === Constants_1.Constants.interactionTypePopup)) return [3 /*break*/, 9];
1776 this.logger.verbose("Interaction type is popup. Generating popup window");
1777 // Generate a popup window
1778 try {
1779 popUpWindow = this.openPopup(urlNavigate, "msal", Constants_1.Constants.popUpWidth, Constants_1.Constants.popUpHeight);
1780 // Push popup window handle onto stack for tracking
1781 WindowUtils_1.WindowUtils.trackPopup(popUpWindow);
1782 }
1783 catch (e) {
1784 this.logger.info(ClientAuthError_1.ClientAuthErrorMessage.popUpWindowError.code + ":" + ClientAuthError_1.ClientAuthErrorMessage.popUpWindowError.desc);
1785 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.ERROR, ClientAuthError_1.ClientAuthErrorMessage.popUpWindowError.code);
1786 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.ERROR_DESC, ClientAuthError_1.ClientAuthErrorMessage.popUpWindowError.desc);
1787 if (reject) {
1788 reject(ClientAuthError_1.ClientAuthError.createPopupWindowError());
1789 return [2 /*return*/];
1790 }
1791 }
1792 if (!popUpWindow) return [3 /*break*/, 8];
1793 _a.label = 5;
1794 case 5:
1795 _a.trys.push([5, 7, , 8]);
1796 return [4 /*yield*/, WindowUtils_1.WindowUtils.monitorPopupForHash(popUpWindow, this.config.system.loadFrameTimeout, urlNavigate, this.logger)];
1797 case 6:
1798 hash = _a.sent();
1799 this.handleAuthenticationResponse(hash);
1800 // Request completed successfully, set to completed
1801 this.cacheStorage.setInteractionInProgress(false);
1802 this.logger.info("Closing popup window");
1803 // TODO: Check how this can be extracted for any framework specific code?
1804 if (this.config.framework.isAngular) {
1805 this.broadcast("msal:popUpHashChanged", hash);
1806 }
1807 WindowUtils_1.WindowUtils.closePopups();
1808 return [3 /*break*/, 8];
1809 case 7:
1810 error_1 = _a.sent();
1811 if (reject) {
1812 reject(error_1);
1813 }
1814 if (this.config.framework.isAngular) {
1815 this.broadcast("msal:popUpClosed", error_1.errorCode + Constants_1.Constants.resourceDelimiter + error_1.errorMessage);
1816 }
1817 else {
1818 // Request failed, set to canceled
1819 this.cacheStorage.setInteractionInProgress(false);
1820 popUpWindow.close();
1821 }
1822 return [3 /*break*/, 8];
1823 case 8: return [3 /*break*/, 10];
1824 case 9:
1825 // If onRedirectNavigate is implemented, invoke it and provide urlNavigate
1826 if (request.onRedirectNavigate) {
1827 this.logger.verbose("Invoking onRedirectNavigate callback");
1828 navigate = request.onRedirectNavigate(urlNavigate);
1829 // Returning false from onRedirectNavigate will stop navigation
1830 if (navigate !== false) {
1831 this.logger.verbose("onRedirectNavigate did not return false, navigating");
1832 this.navigateWindow(urlNavigate);
1833 }
1834 else {
1835 this.logger.verbose("onRedirectNavigate returned false, stopping navigation");
1836 }
1837 }
1838 else {
1839 // Otherwise, perform navigation
1840 this.logger.verbose("Navigating window to urlNavigate");
1841 this.navigateWindow(urlNavigate);
1842 }
1843 _a.label = 10;
1844 case 10: return [3 /*break*/, 12];
1845 case 11:
1846 err_1 = _a.sent();
1847 this.logger.error(err_1);
1848 this.cacheStorage.resetTempCacheItems(request.state);
1849 this.authErrorHandler(interactionType, ClientAuthError_1.ClientAuthError.createEndpointResolutionError(err_1.toString), AuthResponse_1.buildResponseStateOnly(request.state), reject);
1850 if (popUpWindow) {
1851 popUpWindow.close();
1852 }
1853 return [3 /*break*/, 12];
1854 case 12: return [2 /*return*/];
1855 }
1856 });
1857 });
1858 };
1859 /**
1860 * API interfacing idToken request when applications already have a session/hint acquired by authorization client applications
1861 * @param request
1862 */
1863 UserAgentApplication.prototype.ssoSilent = function (request) {
1864 this.logger.verbose("ssoSilent has been called");
1865 // throw an error on an empty request
1866 if (!request) {
1867 throw ClientConfigurationError_1.ClientConfigurationError.createEmptyRequestError();
1868 }
1869 // throw an error on no hints passed
1870 if (!request.sid && !request.loginHint) {
1871 throw ClientConfigurationError_1.ClientConfigurationError.createSsoSilentError();
1872 }
1873 return this.acquireTokenSilent(tslib_1.__assign(tslib_1.__assign({}, request), { scopes: Constants_1.Constants.oidcScopes }));
1874 };
1875 /**
1876 * Use this function to obtain a token before every call to the API / resource provider
1877 *
1878 * MSAL return's a cached token when available
1879 * Or it send's a request to the STS to obtain a new token using a hidden iframe.
1880 *
1881 * @param {@link AuthenticationParameters}
1882 *
1883 * To renew idToken, please pass clientId as the only scope in the Authentication Parameters
1884 * @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
1885 *
1886 */
1887 UserAgentApplication.prototype.acquireTokenSilent = function (userRequest) {
1888 var _this = this;
1889 this.logger.verbose("AcquireTokenSilent has been called");
1890 // validate the request
1891 var request = RequestUtils_1.RequestUtils.validateRequest(userRequest, false, this.clientId, Constants_1.Constants.interactionTypeSilent);
1892 var apiEvent = this.telemetryManager.createAndStartApiEvent(request.correlationId, ApiEvent_1.API_EVENT_IDENTIFIER.AcquireTokenSilent);
1893 var requestSignature = RequestUtils_1.RequestUtils.createRequestSignature(request);
1894 return new Promise(function (resolve, reject) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
1895 var scope, account, adalIdToken, responseType, serverAuthenticationRequest, adalIdTokenObject, userContainedClaims, authErr, cacheResultResponse, logMessage, err_2;
1896 return tslib_1.__generator(this, function (_a) {
1897 switch (_a.label) {
1898 case 0:
1899 // block the request if made from the hidden iframe
1900 WindowUtils_1.WindowUtils.blockReloadInHiddenIframes();
1901 scope = request.scopes.join(" ").toLowerCase();
1902 this.logger.verbosePii("Serialized scopes: " + scope);
1903 if (request.account) {
1904 account = request.account;
1905 this.logger.verbose("Account set from request");
1906 }
1907 else {
1908 account = this.getAccount();
1909 this.logger.verbose("Account set from MSAL Cache");
1910 }
1911 adalIdToken = this.cacheStorage.getItem(Constants_1.Constants.adalIdToken);
1912 // In the event of no account being passed in the config, no session id, and no pre-existing adalIdToken, user will need to log in
1913 if (!account && !(request.sid || request.loginHint) && StringUtils_1.StringUtils.isEmpty(adalIdToken)) {
1914 this.logger.info("User login is required");
1915 // The promise rejects with a UserLoginRequiredError, which should be caught and user should be prompted to log in interactively
1916 return [2 /*return*/, reject(ClientAuthError_1.ClientAuthError.createUserLoginRequiredError())];
1917 }
1918 responseType = this.getTokenType(account, request.scopes);
1919 this.logger.verbose("Response type: " + responseType);
1920 serverAuthenticationRequest = new ServerRequestParameters_1.ServerRequestParameters(AuthorityFactory_1.AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority, request.authorityMetadata), this.clientId, responseType, this.getRedirectUri(request.redirectUri), request.scopes, request.state, request.correlationId);
1921 this.logger.verbose("Finished building server authentication request");
1922 // populate QueryParameters (sid/login_hint) and any other extraQueryParameters set by the developer
1923 if (ServerRequestParameters_1.ServerRequestParameters.isSSOParam(request) || account) {
1924 serverAuthenticationRequest.populateQueryParams(account, request, null, true);
1925 this.logger.verbose("Query parameters populated from existing SSO or account");
1926 }
1927 // if user didn't pass login_hint/sid and adal's idtoken is present, extract the login_hint from the adalIdToken
1928 else if (!account && !StringUtils_1.StringUtils.isEmpty(adalIdToken)) {
1929 adalIdTokenObject = TokenUtils_1.TokenUtils.extractIdToken(adalIdToken);
1930 this.logger.verbose("ADAL's idToken exists. Extracting login information from ADAL's idToken to populate query parameters");
1931 serverAuthenticationRequest.populateQueryParams(account, null, adalIdTokenObject, true);
1932 }
1933 else {
1934 this.logger.verbose("No additional query parameters added");
1935 }
1936 userContainedClaims = request.claimsRequest || serverAuthenticationRequest.claimsValue;
1937 // If request.forceRefresh is set to true, force a request for a new token instead of getting it from the cache
1938 if (!userContainedClaims && !request.forceRefresh) {
1939 try {
1940 cacheResultResponse = this.getCachedToken(serverAuthenticationRequest, account);
1941 }
1942 catch (e) {
1943 authErr = e;
1944 }
1945 }
1946 if (!cacheResultResponse) return [3 /*break*/, 1];
1947 this.logger.verbose("Token found in cache lookup");
1948 this.logger.verbosePii("Scopes found: " + JSON.stringify(cacheResultResponse.scopes));
1949 resolve(cacheResultResponse);
1950 return [2 /*return*/, null];
1951 case 1:
1952 if (!authErr) return [3 /*break*/, 2];
1953 this.logger.infoPii(authErr.errorCode + ":" + authErr.errorMessage);
1954 reject(authErr);
1955 return [2 /*return*/, null];
1956 case 2:
1957 logMessage = void 0;
1958 if (userContainedClaims) {
1959 logMessage = "Skipped cache lookup since claims were given";
1960 }
1961 else if (request.forceRefresh) {
1962 logMessage = "Skipped cache lookup since request.forceRefresh option was set to true";
1963 }
1964 else {
1965 logMessage = "No valid token found in cache lookup";
1966 }
1967 this.logger.verbose(logMessage);
1968 // Cache result can return null if cache is empty. In that case, set authority to default value if no authority is passed to the API.
1969 if (!serverAuthenticationRequest.authorityInstance) {
1970 serverAuthenticationRequest.authorityInstance = request.authority ?
1971 AuthorityFactory_1.AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority, request.authorityMetadata)
1972 : this.authorityInstance;
1973 }
1974 this.logger.verbosePii("Authority instance: " + serverAuthenticationRequest.authority);
1975 _a.label = 3;
1976 case 3:
1977 _a.trys.push([3, 7, , 8]);
1978 if (!!serverAuthenticationRequest.authorityInstance.hasCachedMetadata()) return [3 /*break*/, 5];
1979 this.logger.verbose("No cached metadata for authority");
1980 return [4 /*yield*/, AuthorityFactory_1.AuthorityFactory.saveMetadataFromNetwork(serverAuthenticationRequest.authorityInstance, this.telemetryManager, request.correlationId)];
1981 case 4:
1982 _a.sent();
1983 this.logger.verbose("Authority has been updated with endpoint discovery response");
1984 return [3 /*break*/, 6];
1985 case 5:
1986 this.logger.verbose("Cached metadata found for authority");
1987 _a.label = 6;
1988 case 6:
1989 /*
1990 * refresh attempt with iframe
1991 * Already renewing for this scope, callback when we get the token.
1992 */
1993 if (window.activeRenewals[requestSignature]) {
1994 this.logger.verbose("Renewing token in progress. Registering callback");
1995 // Active renewals contains the state for each renewal.
1996 this.registerCallback(window.activeRenewals[requestSignature], requestSignature, resolve, reject);
1997 }
1998 else {
1999 if (request.scopes && ScopeSet_1.ScopeSet.onlyContainsOidcScopes(request.scopes)) {
2000 /*
2001 * App uses idToken to send to api endpoints
2002 * Default scope is tracked as OIDC scopes to store this token
2003 */
2004 this.logger.verbose("OpenID Connect scopes only, renewing idToken");
2005 this.silentLogin = true;
2006 this.renewIdToken(requestSignature, resolve, reject, account, serverAuthenticationRequest);
2007 }
2008 else {
2009 // renew access token
2010 this.logger.verbose("Renewing access token");
2011 this.renewToken(requestSignature, resolve, reject, account, serverAuthenticationRequest);
2012 }
2013 }
2014 return [3 /*break*/, 8];
2015 case 7:
2016 err_2 = _a.sent();
2017 this.logger.error(err_2);
2018 reject(ClientAuthError_1.ClientAuthError.createEndpointResolutionError(err_2.toString()));
2019 return [2 /*return*/, null];
2020 case 8: return [2 /*return*/];
2021 }
2022 });
2023 }); })
2024 .then(function (res) {
2025 _this.logger.verbose("Successfully acquired token");
2026 _this.telemetryManager.stopAndFlushApiEvent(request.correlationId, apiEvent, true);
2027 return res;
2028 })
2029 .catch(function (error) {
2030 _this.cacheStorage.resetTempCacheItems(request.state);
2031 _this.telemetryManager.stopAndFlushApiEvent(request.correlationId, apiEvent, false, error.errorCode);
2032 throw error;
2033 });
2034 };
2035 // #endregion
2036 // #region Popup Window Creation
2037 /**
2038 * @hidden
2039 *
2040 * Configures popup window for login.
2041 *
2042 * @param urlNavigate
2043 * @param title
2044 * @param popUpWidth
2045 * @param popUpHeight
2046 * @ignore
2047 * @hidden
2048 */
2049 UserAgentApplication.prototype.openPopup = function (urlNavigate, title, popUpWidth, popUpHeight) {
2050 this.logger.verbose("OpenPopup has been called");
2051 try {
2052 /**
2053 * adding winLeft and winTop to account for dual monitor
2054 * using screenLeft and screenTop for IE8 and earlier
2055 */
2056 var winLeft = window.screenLeft ? window.screenLeft : window.screenX;
2057 var winTop = window.screenTop ? window.screenTop : window.screenY;
2058 /**
2059 * window.innerWidth displays browser window"s height and width excluding toolbars
2060 * using document.documentElement.clientWidth for IE8 and earlier
2061 */
2062 var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
2063 var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
2064 var left = ((width / 2) - (popUpWidth / 2)) + winLeft;
2065 var top = ((height / 2) - (popUpHeight / 2)) + winTop;
2066 // open the window
2067 var popupWindow = window.open(urlNavigate, title, "width=" + popUpWidth + ", height=" + popUpHeight + ", top=" + top + ", left=" + left + ", scrollbars=yes");
2068 if (!popupWindow) {
2069 throw ClientAuthError_1.ClientAuthError.createPopupWindowError();
2070 }
2071 if (popupWindow.focus) {
2072 popupWindow.focus();
2073 }
2074 return popupWindow;
2075 }
2076 catch (e) {
2077 this.cacheStorage.setInteractionInProgress(false);
2078 throw ClientAuthError_1.ClientAuthError.createPopupWindowError(e.toString());
2079 }
2080 };
2081 // #endregion
2082 // #region Iframe Management
2083 /**
2084 * @hidden
2085 * Calling _loadFrame but with a timeout to signal failure in loadframeStatus. Callbacks are left.
2086 * registered when network errors occur and subsequent token requests for same resource are registered to the pending request.
2087 * @ignore
2088 */
2089 UserAgentApplication.prototype.loadIframeTimeout = function (urlNavigate, frameName, requestSignature) {
2090 return tslib_1.__awaiter(this, void 0, Promise, function () {
2091 var expectedState, iframe, _a, hash, error_2;
2092 return tslib_1.__generator(this, function (_b) {
2093 switch (_b.label) {
2094 case 0:
2095 expectedState = window.activeRenewals[requestSignature];
2096 this.logger.verbosePii("Set loading state to pending for: " + requestSignature + ":" + expectedState);
2097 this.cacheStorage.setItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.RENEW_STATUS, expectedState), Constants_1.Constants.inProgress);
2098 if (!this.config.system.navigateFrameWait) return [3 /*break*/, 2];
2099 return [4 /*yield*/, WindowUtils_1.WindowUtils.loadFrame(urlNavigate, frameName, this.config.system.navigateFrameWait, this.logger)];
2100 case 1:
2101 _a = _b.sent();
2102 return [3 /*break*/, 3];
2103 case 2:
2104 _a = WindowUtils_1.WindowUtils.loadFrameSync(urlNavigate, frameName, this.logger);
2105 _b.label = 3;
2106 case 3:
2107 iframe = _a;
2108 _b.label = 4;
2109 case 4:
2110 _b.trys.push([4, 6, , 7]);
2111 return [4 /*yield*/, WindowUtils_1.WindowUtils.monitorIframeForHash(iframe.contentWindow, this.config.system.loadFrameTimeout, urlNavigate, this.logger)];
2112 case 5:
2113 hash = _b.sent();
2114 if (hash) {
2115 this.handleAuthenticationResponse(hash);
2116 }
2117 return [3 /*break*/, 7];
2118 case 6:
2119 error_2 = _b.sent();
2120 if (this.cacheStorage.getItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.RENEW_STATUS, expectedState)) === Constants_1.Constants.inProgress) {
2121 // fail the iframe session if it's in pending state
2122 this.logger.verbose("Loading frame has timed out after: " + (this.config.system.loadFrameTimeout / 1000) + " seconds for scope/authority " + requestSignature + ":" + expectedState);
2123 // Error after timeout
2124 if (expectedState && window.callbackMappedToRenewStates[expectedState]) {
2125 window.callbackMappedToRenewStates[expectedState](null, error_2);
2126 }
2127 this.cacheStorage.removeItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.RENEW_STATUS, expectedState));
2128 }
2129 WindowUtils_1.WindowUtils.removeHiddenIframe(iframe);
2130 throw error_2;
2131 case 7:
2132 WindowUtils_1.WindowUtils.removeHiddenIframe(iframe);
2133 return [2 /*return*/];
2134 }
2135 });
2136 });
2137 };
2138 // #endregion
2139 // #region General Helpers
2140 /**
2141 * @hidden
2142 * Used to redirect the browser to the STS authorization endpoint
2143 * @param {string} urlNavigate - URL of the authorization endpoint
2144 */
2145 UserAgentApplication.prototype.navigateWindow = function (urlNavigate, popupWindow) {
2146 // Navigate if valid URL
2147 if (urlNavigate && !StringUtils_1.StringUtils.isEmpty(urlNavigate)) {
2148 var navigateWindow = popupWindow ? popupWindow : window;
2149 var logMessage = popupWindow ? "Navigated Popup window to:" + urlNavigate : "Navigate to:" + urlNavigate;
2150 this.logger.infoPii(logMessage);
2151 navigateWindow.location.assign(urlNavigate);
2152 }
2153 else {
2154 this.logger.info("Navigate url is empty");
2155 throw AuthError_1.AuthError.createUnexpectedError("Navigate url is empty");
2156 }
2157 };
2158 /**
2159 * @hidden
2160 * Used to add the developer requested callback to the array of callbacks for the specified scopes. The updated array is stored on the window object
2161 * @param {string} expectedState - Unique state identifier (guid).
2162 * @param {string} scope - Developer requested permissions. Not all scopes are guaranteed to be included in the access token returned.
2163 * @param {Function} resolve - The resolve function of the promise object.
2164 * @param {Function} reject - The reject function of the promise object.
2165 * @ignore
2166 */
2167 UserAgentApplication.prototype.registerCallback = function (expectedState, requestSignature, resolve, reject) {
2168 var _this = this;
2169 // track active renewals
2170 window.activeRenewals[requestSignature] = expectedState;
2171 // initialize callbacks mapped array
2172 if (!window.promiseMappedToRenewStates[expectedState]) {
2173 window.promiseMappedToRenewStates[expectedState] = [];
2174 }
2175 // indexing on the current state, push the callback params to callbacks mapped
2176 window.promiseMappedToRenewStates[expectedState].push({ resolve: resolve, reject: reject });
2177 // Store the server response in the current window??
2178 if (!window.callbackMappedToRenewStates[expectedState]) {
2179 window.callbackMappedToRenewStates[expectedState] = function (response, error) {
2180 // reset active renewals
2181 delete window.activeRenewals[requestSignature];
2182 // for all promiseMappedtoRenewStates for a given 'state' - call the reject/resolve with error/token respectively
2183 for (var i = 0; i < window.promiseMappedToRenewStates[expectedState].length; ++i) {
2184 try {
2185 if (error) {
2186 window.promiseMappedToRenewStates[expectedState][i].reject(error);
2187 }
2188 else if (response) {
2189 window.promiseMappedToRenewStates[expectedState][i].resolve(response);
2190 }
2191 else {
2192 _this.cacheStorage.resetTempCacheItems(expectedState);
2193 throw AuthError_1.AuthError.createUnexpectedError("Error and response are both null");
2194 }
2195 }
2196 catch (e) {
2197 _this.logger.warning(e);
2198 }
2199 }
2200 // reset
2201 delete window.promiseMappedToRenewStates[expectedState];
2202 delete window.callbackMappedToRenewStates[expectedState];
2203 };
2204 }
2205 };
2206 // #endregion
2207 // #region Logout
2208 /**
2209 * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
2210 * Default behaviour is to redirect the user to `window.location.href`.
2211 */
2212 UserAgentApplication.prototype.logout = function (correlationId) {
2213 this.logger.verbose("Logout has been called");
2214 this.logoutAsync(correlationId);
2215 };
2216 /**
2217 * Async version of logout(). Use to log out the current user.
2218 * @param correlationId Request correlationId
2219 */
2220 UserAgentApplication.prototype.logoutAsync = function (correlationId) {
2221 return tslib_1.__awaiter(this, void 0, Promise, function () {
2222 var requestCorrelationId, apiEvent, correlationIdParam, postLogoutQueryParam, urlNavigate, error_3;
2223 return tslib_1.__generator(this, function (_a) {
2224 switch (_a.label) {
2225 case 0:
2226 requestCorrelationId = correlationId || CryptoUtils_1.CryptoUtils.createNewGuid();
2227 apiEvent = this.telemetryManager.createAndStartApiEvent(requestCorrelationId, ApiEvent_1.API_EVENT_IDENTIFIER.Logout);
2228 this.clearCache();
2229 this.account = null;
2230 _a.label = 1;
2231 case 1:
2232 _a.trys.push([1, 5, , 6]);
2233 if (!!this.authorityInstance.hasCachedMetadata()) return [3 /*break*/, 3];
2234 this.logger.verbose("No cached metadata for authority");
2235 return [4 /*yield*/, AuthorityFactory_1.AuthorityFactory.saveMetadataFromNetwork(this.authorityInstance, this.telemetryManager, correlationId)];
2236 case 2:
2237 _a.sent();
2238 return [3 /*break*/, 4];
2239 case 3:
2240 this.logger.verbose("Cached metadata found for authority");
2241 _a.label = 4;
2242 case 4:
2243 correlationIdParam = "client-request-id=" + requestCorrelationId;
2244 postLogoutQueryParam = void 0;
2245 if (this.getPostLogoutRedirectUri()) {
2246 postLogoutQueryParam = "&post_logout_redirect_uri=" + encodeURIComponent(this.getPostLogoutRedirectUri());
2247 this.logger.verbose("redirectUri found and set");
2248 }
2249 else {
2250 postLogoutQueryParam = "";
2251 this.logger.verbose("No redirectUri set for app. postLogoutQueryParam is empty");
2252 }
2253 urlNavigate = void 0;
2254 if (this.authorityInstance.EndSessionEndpoint) {
2255 urlNavigate = this.authorityInstance.EndSessionEndpoint + "?" + correlationIdParam + postLogoutQueryParam;
2256 this.logger.verbose("EndSessionEndpoint found and urlNavigate set");
2257 this.logger.verbosePii("urlNavigate set to: " + this.authorityInstance.EndSessionEndpoint);
2258 }
2259 else {
2260 urlNavigate = this.authority + "oauth2/v2.0/logout?" + correlationIdParam + postLogoutQueryParam;
2261 this.logger.verbose("No endpoint, urlNavigate set to default");
2262 }
2263 this.telemetryManager.stopAndFlushApiEvent(requestCorrelationId, apiEvent, true);
2264 this.logger.verbose("Navigating window to urlNavigate");
2265 this.navigateWindow(urlNavigate);
2266 return [3 /*break*/, 6];
2267 case 5:
2268 error_3 = _a.sent();
2269 this.telemetryManager.stopAndFlushApiEvent(requestCorrelationId, apiEvent, false, error_3.errorCode);
2270 return [3 /*break*/, 6];
2271 case 6: return [2 /*return*/];
2272 }
2273 });
2274 });
2275 };
2276 /**
2277 * @hidden
2278 * Clear all access tokens and ID tokens in the cache.
2279 * @ignore
2280 */
2281 UserAgentApplication.prototype.clearCache = function () {
2282 this.logger.verbose("Clearing cache");
2283 window.renewStates = [];
2284 var tokenCacheItems = this.cacheStorage.getAllTokens(Constants_1.Constants.clientId, Constants_1.Constants.homeAccountIdentifier);
2285 for (var i = 0; i < tokenCacheItems.length; i++) {
2286 this.cacheStorage.removeItem(JSON.stringify(tokenCacheItems[i].key));
2287 }
2288 this.cacheStorage.resetCacheItems();
2289 this.cacheStorage.clearMsalCookie();
2290 this.logger.verbose("Cache cleared");
2291 };
2292 /**
2293 * @hidden
2294 * Clear a given access token from the cache.
2295 *
2296 * @param accessToken
2297 */
2298 UserAgentApplication.prototype.clearCacheForScope = function (accessToken) {
2299 this.logger.verbose("Clearing access token from cache");
2300 var accessTokenItems = this.cacheStorage.getAllAccessTokens(Constants_1.Constants.clientId, Constants_1.Constants.homeAccountIdentifier);
2301 for (var i = 0; i < accessTokenItems.length; i++) {
2302 var token = accessTokenItems[i];
2303 if (token.value.accessToken === accessToken) {
2304 this.cacheStorage.removeItem(JSON.stringify(token.key));
2305 this.logger.verbosePii("Access token removed: " + token.key);
2306 }
2307 }
2308 };
2309 // #endregion
2310 // #region Response
2311 /**
2312 * @hidden
2313 * @ignore
2314 * Checks if the redirect response is received from the STS. In case of redirect, the url fragment has either id_token, access_token or error.
2315 * @param {string} hash - Hash passed from redirect page.
2316 * @returns {Boolean} - true if response contains id_token, access_token or error, false otherwise.
2317 */
2318 UserAgentApplication.prototype.isCallback = function (hash) {
2319 this.logger.info("isCallback will be deprecated in favor of urlContainsHash in MSAL.js v2.0.");
2320 this.logger.verbose("isCallback has been called");
2321 return UrlUtils_1.UrlUtils.urlContainsHash(hash);
2322 };
2323 /**
2324 * @hidden
2325 * Used to call the constructor callback with the token/error
2326 * @param {string} [hash=window.location.hash] - Hash fragment of Url.
2327 */
2328 UserAgentApplication.prototype.processCallBack = function (hash, respStateInfo, parentCallback) {
2329 this.logger.info("ProcessCallBack has been called. Processing callback from redirect response");
2330 // get the state info from the hash
2331 var stateInfo = respStateInfo;
2332 if (!stateInfo) {
2333 this.logger.verbose("StateInfo is null, getting stateInfo from hash");
2334 stateInfo = this.getResponseState(hash);
2335 }
2336 var response;
2337 var authErr;
2338 // Save the token info from the hash
2339 try {
2340 response = this.saveTokenFromHash(hash, stateInfo);
2341 }
2342 catch (err) {
2343 authErr = err;
2344 }
2345 try {
2346 // Clear the cookie in the hash
2347 this.cacheStorage.clearMsalCookie(stateInfo.state);
2348 var accountState = this.getAccountState(stateInfo.state);
2349 if (response) {
2350 if ((stateInfo.requestType === Constants_1.Constants.renewToken) || response.accessToken) {
2351 if (window.parent !== window) {
2352 this.logger.verbose("Window is in iframe, acquiring token silently");
2353 }
2354 else {
2355 this.logger.verbose("Acquiring token interactive in progress");
2356 }
2357 this.logger.verbose("Response tokenType set to " + Constants_1.ServerHashParamKeys.ACCESS_TOKEN);
2358 response.tokenType = Constants_1.ServerHashParamKeys.ACCESS_TOKEN;
2359 }
2360 else if (stateInfo.requestType === Constants_1.Constants.login) {
2361 this.logger.verbose("Response tokenType set to " + Constants_1.ServerHashParamKeys.ID_TOKEN);
2362 response.tokenType = Constants_1.ServerHashParamKeys.ID_TOKEN;
2363 }
2364 if (!parentCallback) {
2365 this.logger.verbose("Setting redirectResponse");
2366 this.redirectResponse = response;
2367 return;
2368 }
2369 }
2370 else if (!parentCallback) {
2371 this.logger.verbose("Response is null, setting redirectResponse with state");
2372 this.redirectResponse = AuthResponse_1.buildResponseStateOnly(accountState);
2373 this.redirectError = authErr;
2374 this.cacheStorage.resetTempCacheItems(stateInfo.state);
2375 return;
2376 }
2377 this.logger.verbose("Calling callback provided to processCallback");
2378 parentCallback(response, authErr);
2379 }
2380 catch (err) {
2381 this.logger.error("Error occurred in token received callback function: " + err);
2382 throw ClientAuthError_1.ClientAuthError.createErrorInCallbackFunction(err.toString());
2383 }
2384 };
2385 /**
2386 * @hidden
2387 * This method must be called for processing the response received from the STS if using popups or iframes. It extracts the hash, processes the token or error
2388 * information and saves it in the cache. It then resolves the promises with the result.
2389 * @param {string} [hash=window.location.hash] - Hash fragment of Url.
2390 */
2391 UserAgentApplication.prototype.handleAuthenticationResponse = function (hash) {
2392 this.logger.verbose("HandleAuthenticationResponse has been called");
2393 // retrieve the hash
2394 var locationHash = hash || window.location.hash;
2395 // if (window.parent !== window), by using self, window.parent becomes equal to window in getResponseState method specifically
2396 var stateInfo = this.getResponseState(locationHash);
2397 this.logger.verbose("Obtained state from response");
2398 var tokenResponseCallback = window.callbackMappedToRenewStates[stateInfo.state];
2399 this.processCallBack(locationHash, stateInfo, tokenResponseCallback);
2400 };
2401 /**
2402 * @hidden
2403 * This method must be called for processing the response received from the STS when using redirect flows. It extracts the hash, processes the token or error
2404 * information and saves it in the cache. The result can then be accessed by user registered callbacks.
2405 * @param {string} [hash=window.location.hash] - Hash fragment of Url.
2406 */
2407 UserAgentApplication.prototype.handleRedirectAuthenticationResponse = function (hash) {
2408 this.logger.info("Returned from redirect url");
2409 this.logger.verbose("HandleRedirectAuthenticationResponse has been called");
2410 // clear hash from window
2411 WindowUtils_1.WindowUtils.clearUrlFragment(window);
2412 this.logger.verbose("Window.location.hash cleared");
2413 // if (window.parent !== window), by using self, window.parent becomes equal to window in getResponseState method specifically
2414 var stateInfo = this.getResponseState(hash);
2415 // if set to navigate to loginRequest page post login
2416 if (this.config.auth.navigateToLoginRequestUrl && window.parent === window) {
2417 this.logger.verbose("Window.parent is equal to window, not in popup or iframe. Navigation to login request url after login turned on");
2418 var loginRequestUrl = this.cacheStorage.getItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.LOGIN_REQUEST, stateInfo.state), this.inCookie);
2419 // Redirect to home page if login request url is null (real null or the string null)
2420 if (!loginRequestUrl || loginRequestUrl === "null") {
2421 this.logger.error("Unable to get valid login request url from cache, redirecting to home page");
2422 window.location.assign("/");
2423 return;
2424 }
2425 else {
2426 this.logger.verbose("Valid login request url obtained from cache");
2427 var currentUrl = UrlUtils_1.UrlUtils.removeHashFromUrl(window.location.href);
2428 var finalRedirectUrl = UrlUtils_1.UrlUtils.removeHashFromUrl(loginRequestUrl);
2429 if (currentUrl !== finalRedirectUrl) {
2430 this.logger.verbose("Current url is not login request url, navigating");
2431 this.logger.verbosePii("CurrentUrl: " + currentUrl + ", finalRedirectUrl: " + finalRedirectUrl);
2432 window.location.assign("" + finalRedirectUrl + hash);
2433 return;
2434 }
2435 else {
2436 this.logger.verbose("Current url matches login request url");
2437 var loginRequestUrlComponents = UrlUtils_1.UrlUtils.GetUrlComponents(loginRequestUrl);
2438 if (loginRequestUrlComponents.Hash) {
2439 this.logger.verbose("Login request url contains hash, resetting non-msal hash");
2440 window.location.hash = loginRequestUrlComponents.Hash;
2441 }
2442 }
2443 }
2444 }
2445 else if (!this.config.auth.navigateToLoginRequestUrl) {
2446 this.logger.verbose("Default navigation to start page after login turned off");
2447 }
2448 this.processCallBack(hash, stateInfo, null);
2449 };
2450 /**
2451 * @hidden
2452 * Creates a stateInfo object from the URL fragment and returns it.
2453 * @param {string} hash - Hash passed from redirect page
2454 * @returns {TokenResponse} an object created from the redirect response from AAD comprising of the keys - parameters, requestType, stateMatch, stateResponse and valid.
2455 * @ignore
2456 */
2457 UserAgentApplication.prototype.getResponseState = function (hash) {
2458 this.logger.verbose("GetResponseState has been called");
2459 var parameters = UrlUtils_1.UrlUtils.deserializeHash(hash);
2460 var stateResponse;
2461 if (!parameters) {
2462 throw AuthError_1.AuthError.createUnexpectedError("Hash was not parsed correctly.");
2463 }
2464 if (parameters.hasOwnProperty(Constants_1.ServerHashParamKeys.STATE)) {
2465 this.logger.verbose("Hash contains state. Creating stateInfo object");
2466 var parsedState = RequestUtils_1.RequestUtils.parseLibraryState(parameters["state"]);
2467 stateResponse = {
2468 requestType: Constants_1.Constants.unknown,
2469 state: parameters["state"],
2470 timestamp: parsedState.ts,
2471 method: parsedState.method,
2472 stateMatch: false
2473 };
2474 }
2475 else {
2476 throw AuthError_1.AuthError.createUnexpectedError("Hash does not contain state.");
2477 }
2478 /*
2479 * async calls can fire iframe and login request at the same time if developer does not use the API as expected
2480 * incoming callback needs to be looked up to find the request type
2481 */
2482 // loginRedirect
2483 if (stateResponse.state === this.cacheStorage.getItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.STATE_LOGIN, stateResponse.state), this.inCookie) || stateResponse.state === this.silentAuthenticationState) {
2484 this.logger.verbose("State matches cached state, setting requestType to login");
2485 stateResponse.requestType = Constants_1.Constants.login;
2486 stateResponse.stateMatch = true;
2487 return stateResponse;
2488 }
2489 // acquireTokenRedirect
2490 else if (stateResponse.state === this.cacheStorage.getItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.STATE_ACQ_TOKEN, stateResponse.state), this.inCookie)) {
2491 this.logger.verbose("State matches cached state, setting requestType to renewToken");
2492 stateResponse.requestType = Constants_1.Constants.renewToken;
2493 stateResponse.stateMatch = true;
2494 return stateResponse;
2495 }
2496 // external api requests may have many renewtoken requests for different resource
2497 if (!stateResponse.stateMatch) {
2498 this.logger.verbose("State does not match cached state, setting requestType to type from window");
2499 stateResponse.requestType = window.requestType;
2500 var statesInParentContext = window.renewStates;
2501 for (var i = 0; i < statesInParentContext.length; i++) {
2502 if (statesInParentContext[i] === stateResponse.state) {
2503 this.logger.verbose("Matching state found for request");
2504 stateResponse.stateMatch = true;
2505 break;
2506 }
2507 }
2508 if (!stateResponse.stateMatch) {
2509 this.logger.verbose("Matching state not found for request");
2510 }
2511 }
2512 return stateResponse;
2513 };
2514 // #endregion
2515 // #region Token Processing (Extract to TokenProcessing.ts)
2516 /**
2517 * @hidden
2518 * Used to get token for the specified set of scopes from the cache
2519 * @param {@link ServerRequestParameters} - Request sent to the STS to obtain an id_token/access_token
2520 * @param {Account} account - Account for which the scopes were requested
2521 */
2522 UserAgentApplication.prototype.getCachedToken = function (serverAuthenticationRequest, account) {
2523 this.logger.verbose("GetCachedToken has been called");
2524 var scopes = serverAuthenticationRequest.scopes;
2525 /**
2526 * Id Token should be returned in every acquireTokenSilent call. The only exception is a response_type = token
2527 * request when a valid ID Token is not present in the cache.
2528 */
2529 var idToken = this.getCachedIdToken(serverAuthenticationRequest, account);
2530 var authResponse = this.getCachedAccessToken(serverAuthenticationRequest, account, scopes);
2531 var accountState = this.getAccountState(serverAuthenticationRequest.state);
2532 return ResponseUtils_1.ResponseUtils.buildAuthResponse(idToken, authResponse, serverAuthenticationRequest, account, scopes, accountState);
2533 };
2534 /**
2535 * @hidden
2536 *
2537 * Uses passed in authority to further filter an array of tokenCacheItems until only the token being searched for remains, then returns that tokenCacheItem.
2538 * This method will throw if authority filtering still yields multiple matching tokens and will return null if not tokens match the authority passed in.
2539 *
2540 * @param authority
2541 * @param tokenCacheItems
2542 * @param request
2543 * @param requestScopes
2544 * @param tokenType
2545 */
2546 UserAgentApplication.prototype.getTokenCacheItemByAuthority = function (authority, tokenCacheItems, requestScopes, tokenType) {
2547 var _this = this;
2548 var filteredAuthorityItems;
2549 if (UrlUtils_1.UrlUtils.isCommonAuthority(authority) || UrlUtils_1.UrlUtils.isOrganizationsAuthority(authority) || UrlUtils_1.UrlUtils.isConsumersAuthority(authority)) {
2550 filteredAuthorityItems = AuthCacheUtils_1.AuthCacheUtils.filterTokenCacheItemsByDomain(tokenCacheItems, UrlUtils_1.UrlUtils.GetUrlComponents(authority).HostNameAndPort);
2551 }
2552 else {
2553 filteredAuthorityItems = AuthCacheUtils_1.AuthCacheUtils.filterTokenCacheItemsByAuthority(tokenCacheItems, authority);
2554 }
2555 if (filteredAuthorityItems.length === 1) {
2556 return filteredAuthorityItems[0];
2557 }
2558 else if (filteredAuthorityItems.length > 1) {
2559 this.logger.warning("Multiple matching tokens found. Cleaning cache and requesting a new token.");
2560 filteredAuthorityItems.forEach(function (accessTokenCacheItem) {
2561 _this.cacheStorage.removeItem(JSON.stringify(accessTokenCacheItem.key));
2562 });
2563 return null;
2564 }
2565 else {
2566 this.logger.verbose("No matching tokens of type " + tokenType + " found");
2567 return null;
2568 }
2569 };
2570 /**
2571 *
2572 * @hidden
2573 *
2574 * Searches the token cache for an ID Token that matches the request parameter and returns it as an IdToken object.
2575 *
2576 * @param serverAuthenticationRequest
2577 * @param account
2578 */
2579 UserAgentApplication.prototype.getCachedIdToken = function (serverAuthenticationRequest, account) {
2580 this.logger.verbose("Getting all cached tokens of type ID Token");
2581 var idTokenCacheItems = this.cacheStorage.getAllIdTokens(this.clientId, account ? account.homeAccountIdentifier : null);
2582 var matchAuthority = serverAuthenticationRequest.authority || this.authority;
2583 var idTokenCacheItem = this.getTokenCacheItemByAuthority(matchAuthority, idTokenCacheItems, null, Constants_1.ServerHashParamKeys.ID_TOKEN);
2584 if (idTokenCacheItem) {
2585 this.logger.verbose("Evaluating ID token found");
2586 var idTokenIsStillValid = this.evaluateTokenExpiration(idTokenCacheItem);
2587 if (idTokenIsStillValid) {
2588 this.logger.verbose("ID token expiration is within offset, using ID token found in cache");
2589 var idTokenValue = idTokenCacheItem.value;
2590 if (idTokenValue) {
2591 this.logger.verbose("ID Token found in cache is valid and unexpired");
2592 }
2593 else {
2594 this.logger.verbose("ID Token found in cache is invalid");
2595 }
2596 return (idTokenValue) ? new IdToken_1.IdToken(idTokenValue.idToken) : null;
2597 }
2598 else {
2599 this.logger.verbose("Cached ID token is expired, removing from cache");
2600 this.cacheStorage.removeItem(JSON.stringify(idTokenCacheItem.key));
2601 return null;
2602 }
2603 }
2604 else {
2605 this.logger.verbose("No tokens found");
2606 return null;
2607 }
2608 };
2609 /**
2610 *
2611 * @hidden
2612 *
2613 * Searches the token cache for an access token that matches the request parameters and returns it as an AuthResponse.
2614 *
2615 * @param serverAuthenticationRequest
2616 * @param account
2617 * @param scopes
2618 */
2619 UserAgentApplication.prototype.getCachedAccessToken = function (serverAuthenticationRequest, account, scopes) {
2620 this.logger.verbose("Getting all cached tokens of type Access Token");
2621 var tokenCacheItems = this.cacheStorage.getAllAccessTokens(this.clientId, account ? account.homeAccountIdentifier : null);
2622 var scopeFilteredTokenCacheItems = AuthCacheUtils_1.AuthCacheUtils.filterTokenCacheItemsByScope(tokenCacheItems, scopes);
2623 var matchAuthority = serverAuthenticationRequest.authority || this.authority;
2624 // serverAuthenticationRequest.authority can only be common or organizations if not null
2625 var accessTokenCacheItem = this.getTokenCacheItemByAuthority(matchAuthority, scopeFilteredTokenCacheItems, scopes, Constants_1.ServerHashParamKeys.ACCESS_TOKEN);
2626 if (!accessTokenCacheItem) {
2627 this.logger.verbose("No matching token found when filtering by scope and authority");
2628 return null;
2629 }
2630 else {
2631 serverAuthenticationRequest.authorityInstance = AuthorityFactory_1.AuthorityFactory.CreateInstance(accessTokenCacheItem.key.authority, this.config.auth.validateAuthority);
2632 this.logger.verbose("Evaluating access token found");
2633 var tokenIsStillValid = this.evaluateTokenExpiration(accessTokenCacheItem);
2634 // The response value will stay null if token retrieved from the cache is expired, otherwise it will be populated with said token's data
2635 if (tokenIsStillValid) {
2636 this.logger.verbose("Access token expiration is within offset, using access token found in cache");
2637 var responseAccount = account || this.getAccount();
2638 if (!responseAccount) {
2639 throw AuthError_1.AuthError.createUnexpectedError("Account should not be null here.");
2640 }
2641 var aState = this.getAccountState(serverAuthenticationRequest.state);
2642 var response = {
2643 uniqueId: "",
2644 tenantId: "",
2645 tokenType: Constants_1.ServerHashParamKeys.ACCESS_TOKEN,
2646 idToken: null,
2647 idTokenClaims: null,
2648 accessToken: accessTokenCacheItem.value.accessToken,
2649 scopes: accessTokenCacheItem.key.scopes.split(" "),
2650 expiresOn: new Date(Number(accessTokenCacheItem.value.expiresIn) * 1000),
2651 account: responseAccount,
2652 accountState: aState,
2653 fromCache: true
2654 };
2655 return response;
2656 }
2657 else {
2658 this.logger.verbose("Access token expired, removing from cache");
2659 this.cacheStorage.removeItem(JSON.stringify(accessTokenCacheItem.key));
2660 return null;
2661 }
2662 }
2663 };
2664 /**
2665 * Returns true if the token passed in is within the acceptable expiration time offset, false if it is expired.
2666 * @param tokenCacheItem
2667 * @param serverAuthenticationRequest
2668 */
2669 UserAgentApplication.prototype.evaluateTokenExpiration = function (tokenCacheItem) {
2670 var expiration = Number(tokenCacheItem.value.expiresIn);
2671 return TokenUtils_1.TokenUtils.validateExpirationIsWithinOffset(expiration, this.config.system.tokenRenewalOffsetSeconds);
2672 };
2673 /**
2674 * @hidden
2675 * Check if ADAL id_token exists and return if exists.
2676 *
2677 */
2678 UserAgentApplication.prototype.extractADALIdToken = function () {
2679 this.logger.verbose("ExtractADALIdToken has been called");
2680 var adalIdToken = this.cacheStorage.getItem(Constants_1.Constants.adalIdToken);
2681 return (!StringUtils_1.StringUtils.isEmpty(adalIdToken)) ? TokenUtils_1.TokenUtils.extractIdToken(adalIdToken) : null;
2682 };
2683 /**
2684 * @hidden
2685 * Acquires access token using a hidden iframe.
2686 * @ignore
2687 */
2688 UserAgentApplication.prototype.renewToken = function (requestSignature, resolve, reject, account, serverAuthenticationRequest) {
2689 this.logger.verbose("RenewToken has been called");
2690 this.logger.verbosePii("RenewToken scope and authority: " + requestSignature);
2691 var frameName = WindowUtils_1.WindowUtils.generateFrameName(Constants_1.FramePrefix.TOKEN_FRAME, requestSignature);
2692 WindowUtils_1.WindowUtils.addHiddenIFrame(frameName, this.logger);
2693 this.updateCacheEntries(serverAuthenticationRequest, account, false);
2694 this.logger.verbosePii("RenewToken expected state: " + serverAuthenticationRequest.state);
2695 // Build urlNavigate with "prompt=none" and navigate to URL in hidden iFrame
2696 var urlNavigate = UrlUtils_1.UrlUtils.urlRemoveQueryStringParameter(UrlUtils_1.UrlUtils.createNavigateUrl(serverAuthenticationRequest), Constants_1.Constants.prompt) + Constants_1.Constants.prompt_none + Constants_1.Constants.response_mode_fragment;
2697 window.renewStates.push(serverAuthenticationRequest.state);
2698 window.requestType = Constants_1.Constants.renewToken;
2699 this.logger.verbose("Set window.renewState and requestType");
2700 this.registerCallback(serverAuthenticationRequest.state, requestSignature, resolve, reject);
2701 this.logger.infoPii("Navigate to: " + urlNavigate);
2702 this.loadIframeTimeout(urlNavigate, frameName, requestSignature).catch(function (error) { return reject(error); });
2703 };
2704 /**
2705 * @hidden
2706 * Renews idtoken for app's own backend when clientId is passed as a single scope in the scopes array.
2707 * @ignore
2708 */
2709 UserAgentApplication.prototype.renewIdToken = function (requestSignature, resolve, reject, account, serverAuthenticationRequest) {
2710 this.logger.info("RenewIdToken has been called");
2711 var frameName = WindowUtils_1.WindowUtils.generateFrameName(Constants_1.FramePrefix.ID_TOKEN_FRAME, requestSignature);
2712 WindowUtils_1.WindowUtils.addHiddenIFrame(frameName, this.logger);
2713 this.updateCacheEntries(serverAuthenticationRequest, account, false);
2714 this.logger.verbose("RenewIdToken expected state: " + serverAuthenticationRequest.state);
2715 // Build urlNavigate with "prompt=none" and navigate to URL in hidden iFrame
2716 var urlNavigate = UrlUtils_1.UrlUtils.urlRemoveQueryStringParameter(UrlUtils_1.UrlUtils.createNavigateUrl(serverAuthenticationRequest), Constants_1.Constants.prompt) + Constants_1.Constants.prompt_none + Constants_1.Constants.response_mode_fragment;
2717 if (this.silentLogin) {
2718 this.logger.verbose("Silent login is true, set silentAuthenticationState");
2719 window.requestType = Constants_1.Constants.login;
2720 this.silentAuthenticationState = serverAuthenticationRequest.state;
2721 }
2722 else {
2723 this.logger.verbose("Not silent login, set window.renewState and requestType");
2724 window.requestType = Constants_1.Constants.renewToken;
2725 window.renewStates.push(serverAuthenticationRequest.state);
2726 }
2727 // note: scope here is clientId
2728 this.registerCallback(serverAuthenticationRequest.state, requestSignature, resolve, reject);
2729 this.logger.infoPii("Navigate to:\" " + urlNavigate);
2730 this.loadIframeTimeout(urlNavigate, frameName, requestSignature).catch(function (error) { return reject(error); });
2731 };
2732 /**
2733 * @hidden
2734 *
2735 * This method builds an Access Token Cache item and saves it to the cache, returning the original
2736 * AuthResponse augmented with a parsed expiresOn attribute.
2737 *
2738 * @param response The AuthResponse object that contains the token to be saved
2739 * @param authority The authority under which the ID token will be cached
2740 * @param scopes The scopes to be added to the cache item key (undefined for ID token cache items)
2741 * @param clientInfo Client Info object that is used to generate the homeAccountIdentifier
2742 * @param expiration Token expiration timestamp
2743 */
2744 UserAgentApplication.prototype.saveToken = function (response, authority, scopes, clientInfo, expiration) {
2745 var accessTokenKey = new AccessTokenKey_1.AccessTokenKey(authority, this.clientId, scopes, clientInfo.uid, clientInfo.utid);
2746 var accessTokenValue = new AccessTokenValue_1.AccessTokenValue(response.accessToken, response.idToken.rawIdToken, expiration.toString(), clientInfo.encodeClientInfo());
2747 this.cacheStorage.setItem(JSON.stringify(accessTokenKey), JSON.stringify(accessTokenValue));
2748 if (expiration) {
2749 this.logger.verbose("New expiration set for token");
2750 response.expiresOn = new Date(expiration * 1000);
2751 }
2752 else {
2753 this.logger.error("Could not parse expiresIn parameter for access token");
2754 }
2755 return response;
2756 };
2757 /**
2758 * @hidden
2759 *
2760 * This method sets up the elements of an ID Token cache item and calls saveToken to save it in
2761 * Access Token Cache item format for the client application to use.
2762 *
2763 * @param response The AuthResponse object that will be used to build the cache item
2764 * @param authority The authority under which the ID token will be cached
2765 * @param parameters The response's Hash Params, which contain the ID token returned from the server
2766 * @param clientInfo Client Info object that is used to generate the homeAccountIdentifier
2767 * @param idTokenObj ID Token object from which the ID token's expiration is extracted
2768 */
2769 /* tslint:disable:no-string-literal */
2770 UserAgentApplication.prototype.saveIdToken = function (response, authority, parameters, clientInfo, idTokenObj) {
2771 this.logger.verbose("SaveIdToken has been called");
2772 var idTokenResponse = tslib_1.__assign({}, response);
2773 // Scopes are undefined so they don't show up in ID token cache key
2774 var scopes;
2775 idTokenResponse.scopes = Constants_1.Constants.oidcScopes;
2776 idTokenResponse.accessToken = parameters[Constants_1.ServerHashParamKeys.ID_TOKEN];
2777 var expiration = Number(idTokenObj.expiration);
2778 // Set ID Token item in cache
2779 this.logger.verbose("Saving ID token to cache");
2780 return this.saveToken(idTokenResponse, authority, scopes, clientInfo, expiration);
2781 };
2782 /**
2783 * @hidden
2784 *
2785 * This method sets up the elements of an Access Token cache item and calls saveToken to save it to the cache
2786 *
2787 * @param response The AuthResponse object that will be used to build the cache item
2788 * @param authority The authority under which the access token will be cached
2789 * @param parameters The response's Hash Params, which contain the access token returned from the server
2790 * @param clientInfo Client Info object that is used to generate the homeAccountIdentifier
2791 */
2792 /* tslint:disable:no-string-literal */
2793 UserAgentApplication.prototype.saveAccessToken = function (response, authority, parameters, clientInfo) {
2794 this.logger.verbose("SaveAccessToken has been called");
2795 var accessTokenResponse = tslib_1.__assign({}, response);
2796 // read the scopes
2797 var scope = parameters[Constants_1.ServerHashParamKeys.SCOPE];
2798 var consentedScopes = scope.split(" ");
2799 // retrieve all access tokens from the cache, remove the dup scopes
2800 var accessTokenCacheItems = this.cacheStorage.getAllAccessTokens(this.clientId, authority);
2801 this.logger.verbose("Retrieving all access tokens from cache and removing duplicates");
2802 for (var i = 0; i < accessTokenCacheItems.length; i++) {
2803 var accessTokenCacheItem = accessTokenCacheItems[i];
2804 if (accessTokenCacheItem.key.homeAccountIdentifier === response.account.homeAccountIdentifier) {
2805 var cachedScopes = accessTokenCacheItem.key.scopes.split(" ");
2806 if (ScopeSet_1.ScopeSet.isIntersectingScopes(cachedScopes, consentedScopes)) {
2807 this.cacheStorage.removeItem(JSON.stringify(accessTokenCacheItem.key));
2808 }
2809 }
2810 }
2811 accessTokenResponse.accessToken = parameters[Constants_1.ServerHashParamKeys.ACCESS_TOKEN];
2812 accessTokenResponse.scopes = consentedScopes;
2813 var expiresIn = TimeUtils_1.TimeUtils.parseExpiresIn(parameters[Constants_1.ServerHashParamKeys.EXPIRES_IN]);
2814 var parsedState = RequestUtils_1.RequestUtils.parseLibraryState(parameters[Constants_1.ServerHashParamKeys.STATE]);
2815 var expiration = parsedState.ts + expiresIn;
2816 this.logger.verbose("Saving access token to cache");
2817 return this.saveToken(accessTokenResponse, authority, scope, clientInfo, expiration);
2818 };
2819 /**
2820 * @hidden
2821 * Saves token or error received in the response from AAD in the cache. In case of id_token, it also creates the account object.
2822 * @ignore
2823 */
2824 UserAgentApplication.prototype.saveTokenFromHash = function (hash, stateInfo) {
2825 this.logger.verbose("SaveTokenFromHash has been called");
2826 this.logger.info("State status: " + stateInfo.stateMatch + "; Request type: " + stateInfo.requestType);
2827 var response = {
2828 uniqueId: "",
2829 tenantId: "",
2830 tokenType: "",
2831 idToken: null,
2832 idTokenClaims: null,
2833 accessToken: null,
2834 scopes: [],
2835 expiresOn: null,
2836 account: null,
2837 accountState: "",
2838 fromCache: false
2839 };
2840 var error;
2841 var hashParams = UrlUtils_1.UrlUtils.deserializeHash(hash);
2842 var authorityKey = "";
2843 var acquireTokenAccountKey = "";
2844 var idTokenObj = null;
2845 // If server returns an error
2846 if (hashParams.hasOwnProperty(Constants_1.ServerHashParamKeys.ERROR_DESCRIPTION) || hashParams.hasOwnProperty(Constants_1.ServerHashParamKeys.ERROR)) {
2847 this.logger.verbose("Server returned an error");
2848 this.logger.infoPii("Error : " + hashParams[Constants_1.ServerHashParamKeys.ERROR] + "; Error description: " + hashParams[Constants_1.ServerHashParamKeys.ERROR_DESCRIPTION]);
2849 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.ERROR, hashParams[Constants_1.ServerHashParamKeys.ERROR]);
2850 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.ERROR_DESC, hashParams[Constants_1.ServerHashParamKeys.ERROR_DESCRIPTION]);
2851 // login
2852 if (stateInfo.requestType === Constants_1.Constants.login) {
2853 this.logger.verbose("RequestType is login, caching login error, generating authorityKey");
2854 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.LOGIN_ERROR, hashParams[Constants_1.ServerHashParamKeys.ERROR_DESCRIPTION] + ":" + hashParams[Constants_1.ServerHashParamKeys.ERROR]);
2855 authorityKey = AuthCache_1.AuthCache.generateAuthorityKey(stateInfo.state);
2856 }
2857 // acquireToken
2858 if (stateInfo.requestType === Constants_1.Constants.renewToken) {
2859 this.logger.verbose("RequestType is renewToken, generating acquireTokenAccountKey");
2860 authorityKey = AuthCache_1.AuthCache.generateAuthorityKey(stateInfo.state);
2861 var account = this.getAccount();
2862 var accountId = void 0;
2863 if (account && !StringUtils_1.StringUtils.isEmpty(account.homeAccountIdentifier)) {
2864 accountId = account.homeAccountIdentifier;
2865 this.logger.verbose("AccountId is set");
2866 }
2867 else {
2868 accountId = Constants_1.Constants.no_account;
2869 this.logger.verbose("AccountId is set as no_account");
2870 }
2871 acquireTokenAccountKey = AuthCache_1.AuthCache.generateAcquireTokenAccountKey(accountId, stateInfo.state);
2872 }
2873 var hashErr = hashParams[Constants_1.ServerHashParamKeys.ERROR];
2874 var hashErrDesc = hashParams[Constants_1.ServerHashParamKeys.ERROR_DESCRIPTION];
2875 if (InteractionRequiredAuthError_1.InteractionRequiredAuthError.isInteractionRequiredError(hashErr) ||
2876 InteractionRequiredAuthError_1.InteractionRequiredAuthError.isInteractionRequiredError(hashErrDesc)) {
2877 error = new InteractionRequiredAuthError_1.InteractionRequiredAuthError(hashParams[Constants_1.ServerHashParamKeys.ERROR], hashParams[Constants_1.ServerHashParamKeys.ERROR_DESCRIPTION]);
2878 }
2879 else {
2880 error = new ServerError_1.ServerError(hashParams[Constants_1.ServerHashParamKeys.ERROR], hashParams[Constants_1.ServerHashParamKeys.ERROR_DESCRIPTION]);
2881 }
2882 }
2883 // If the server returns "Success"
2884 else {
2885 this.logger.verbose("Server returns success");
2886 // Verify the state from redirect and record tokens to storage if exists
2887 if (stateInfo.stateMatch) {
2888 this.logger.info("State is right");
2889 if (hashParams.hasOwnProperty(Constants_1.ServerHashParamKeys.SESSION_STATE)) {
2890 this.logger.verbose("Fragment has session state, caching");
2891 this.cacheStorage.setItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.SESSION_STATE, stateInfo.state), hashParams[Constants_1.ServerHashParamKeys.SESSION_STATE]);
2892 }
2893 response.accountState = this.getAccountState(stateInfo.state);
2894 var clientInfo = void 0;
2895 // Process access_token
2896 if (hashParams.hasOwnProperty(Constants_1.ServerHashParamKeys.ACCESS_TOKEN)) {
2897 this.logger.info("Fragment has access token");
2898 response.accessToken = hashParams[Constants_1.ServerHashParamKeys.ACCESS_TOKEN];
2899 if (hashParams.hasOwnProperty(Constants_1.ServerHashParamKeys.SCOPE)) {
2900 response.scopes = hashParams[Constants_1.ServerHashParamKeys.SCOPE].split(" ");
2901 }
2902 // retrieve the id_token from response if present
2903 if (hashParams.hasOwnProperty(Constants_1.ServerHashParamKeys.ID_TOKEN)) {
2904 this.logger.verbose("Fragment has id_token");
2905 idTokenObj = new IdToken_1.IdToken(hashParams[Constants_1.ServerHashParamKeys.ID_TOKEN]);
2906 }
2907 else {
2908 this.logger.verbose("No idToken on fragment, getting idToken from cache");
2909 idTokenObj = new IdToken_1.IdToken(this.cacheStorage.getItem(Constants_1.PersistentCacheKeys.IDTOKEN));
2910 }
2911 response = ResponseUtils_1.ResponseUtils.setResponseIdToken(response, idTokenObj);
2912 // set authority
2913 var authority = this.populateAuthority(stateInfo.state, this.inCookie, this.cacheStorage, idTokenObj);
2914 this.logger.verbose("Got authority from cache");
2915 // retrieve client_info - if it is not found, generate the uid and utid from idToken
2916 if (hashParams.hasOwnProperty(Constants_1.ServerHashParamKeys.CLIENT_INFO)) {
2917 this.logger.verbose("Fragment has clientInfo");
2918 clientInfo = new ClientInfo_1.ClientInfo(hashParams[Constants_1.ServerHashParamKeys.CLIENT_INFO], authority);
2919 }
2920 else if (this.authorityInstance.AuthorityType === Authority_1.AuthorityType.Adfs) {
2921 clientInfo = ClientInfo_1.ClientInfo.createClientInfoFromIdToken(idTokenObj, authority);
2922 }
2923 else {
2924 this.logger.warning("ClientInfo not received in the response from AAD");
2925 }
2926 response.account = Account_1.Account.createAccount(idTokenObj, clientInfo);
2927 this.logger.verbose("Account object created from response");
2928 var accountKey = void 0;
2929 if (response.account && !StringUtils_1.StringUtils.isEmpty(response.account.homeAccountIdentifier)) {
2930 this.logger.verbose("AccountKey set");
2931 accountKey = response.account.homeAccountIdentifier;
2932 }
2933 else {
2934 this.logger.verbose("AccountKey set as no_account");
2935 accountKey = Constants_1.Constants.no_account;
2936 }
2937 acquireTokenAccountKey = AuthCache_1.AuthCache.generateAcquireTokenAccountKey(accountKey, stateInfo.state);
2938 var acquireTokenAccountKey_noaccount = AuthCache_1.AuthCache.generateAcquireTokenAccountKey(Constants_1.Constants.no_account, stateInfo.state);
2939 this.logger.verbose("AcquireTokenAccountKey generated");
2940 var cachedAccount = this.cacheStorage.getItem(acquireTokenAccountKey);
2941 var acquireTokenAccount = void 0;
2942 // Check with the account in the Cache
2943 if (!StringUtils_1.StringUtils.isEmpty(cachedAccount)) {
2944 acquireTokenAccount = JSON.parse(cachedAccount);
2945 this.logger.verbose("AcquireToken request account retrieved from cache");
2946 if (response.account && acquireTokenAccount && Account_1.Account.compareAccounts(response.account, acquireTokenAccount)) {
2947 response = this.saveAccessToken(response, authority, hashParams, clientInfo);
2948 this.logger.info("The user object received in the response is the same as the one passed in the acquireToken request");
2949 }
2950 else {
2951 this.logger.warning("The account object created from the response is not the same as the one passed in the acquireToken request");
2952 }
2953 }
2954 else if (!StringUtils_1.StringUtils.isEmpty(this.cacheStorage.getItem(acquireTokenAccountKey_noaccount))) {
2955 this.logger.verbose("No acquireToken account retrieved from cache");
2956 response = this.saveAccessToken(response, authority, hashParams, clientInfo);
2957 }
2958 }
2959 // Process id_token
2960 if (hashParams.hasOwnProperty(Constants_1.ServerHashParamKeys.ID_TOKEN)) {
2961 this.logger.info("Fragment has idToken");
2962 // set the idToken
2963 idTokenObj = new IdToken_1.IdToken(hashParams[Constants_1.ServerHashParamKeys.ID_TOKEN]);
2964 // set authority
2965 var authority = this.populateAuthority(stateInfo.state, this.inCookie, this.cacheStorage, idTokenObj);
2966 response = ResponseUtils_1.ResponseUtils.setResponseIdToken(response, idTokenObj);
2967 if (hashParams.hasOwnProperty(Constants_1.ServerHashParamKeys.CLIENT_INFO)) {
2968 this.logger.verbose("Fragment has clientInfo");
2969 clientInfo = new ClientInfo_1.ClientInfo(hashParams[Constants_1.ServerHashParamKeys.CLIENT_INFO], authority);
2970 }
2971 else if (this.authorityInstance.AuthorityType === Authority_1.AuthorityType.Adfs) {
2972 clientInfo = ClientInfo_1.ClientInfo.createClientInfoFromIdToken(idTokenObj, authority);
2973 }
2974 else {
2975 this.logger.warning("ClientInfo not received in the response from AAD");
2976 }
2977 this.account = Account_1.Account.createAccount(idTokenObj, clientInfo);
2978 response.account = this.account;
2979 this.logger.verbose("Account object created from response");
2980 if (idTokenObj && idTokenObj.nonce) {
2981 this.logger.verbose("IdToken has nonce");
2982 // check nonce integrity if idToken has nonce - throw an error if not matched
2983 var cachedNonce = this.cacheStorage.getItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.NONCE_IDTOKEN, stateInfo.state), this.inCookie);
2984 if (idTokenObj.nonce !== cachedNonce) {
2985 this.account = null;
2986 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.LOGIN_ERROR, "Nonce Mismatch. Expected Nonce: " + cachedNonce + "," + "Actual Nonce: " + idTokenObj.nonce);
2987 this.logger.error("Nonce Mismatch. Expected Nonce: " + cachedNonce + ", Actual Nonce: " + idTokenObj.nonce);
2988 error = ClientAuthError_1.ClientAuthError.createNonceMismatchError(cachedNonce, idTokenObj.nonce);
2989 }
2990 // Save the token
2991 else {
2992 this.logger.verbose("Nonce matches, saving idToken to cache");
2993 this.cacheStorage.setItem(Constants_1.PersistentCacheKeys.IDTOKEN, hashParams[Constants_1.ServerHashParamKeys.ID_TOKEN], this.inCookie);
2994 this.cacheStorage.setItem(Constants_1.PersistentCacheKeys.CLIENT_INFO, clientInfo.encodeClientInfo(), this.inCookie);
2995 // Save idToken as access token item for app itself
2996 this.saveIdToken(response, authority, hashParams, clientInfo, idTokenObj);
2997 }
2998 }
2999 else {
3000 this.logger.verbose("No idToken or no nonce. Cache key for Authority set as state");
3001 authorityKey = stateInfo.state;
3002 acquireTokenAccountKey = stateInfo.state;
3003 this.logger.error("Invalid id_token received in the response");
3004 error = ClientAuthError_1.ClientAuthError.createInvalidIdTokenError(idTokenObj);
3005 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.ERROR, error.errorCode);
3006 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.ERROR_DESC, error.errorMessage);
3007 }
3008 }
3009 }
3010 // State mismatch - unexpected/invalid state
3011 else {
3012 this.logger.verbose("State mismatch");
3013 authorityKey = stateInfo.state;
3014 acquireTokenAccountKey = stateInfo.state;
3015 var expectedState = this.cacheStorage.getItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.STATE_LOGIN, stateInfo.state), this.inCookie);
3016 this.logger.error("State Mismatch. Expected State: " + expectedState + ", Actual State: " + stateInfo.state);
3017 error = ClientAuthError_1.ClientAuthError.createInvalidStateError(stateInfo.state, expectedState);
3018 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.ERROR, error.errorCode);
3019 this.cacheStorage.setItem(Constants_1.ErrorCacheKeys.ERROR_DESC, error.errorMessage);
3020 }
3021 }
3022 // Set status to completed
3023 this.cacheStorage.removeItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.RENEW_STATUS, stateInfo.state));
3024 this.cacheStorage.resetTempCacheItems(stateInfo.state);
3025 this.logger.verbose("Status set to complete, temporary cache cleared");
3026 // this is required if navigateToLoginRequestUrl=false
3027 if (this.inCookie) {
3028 this.logger.verbose("InCookie is true, setting authorityKey in cookie");
3029 this.cacheStorage.setItemCookie(authorityKey, "", -1);
3030 this.cacheStorage.clearMsalCookie(stateInfo.state);
3031 }
3032 if (error) {
3033 // Error case, set status to cancelled
3034 throw error;
3035 }
3036 if (!response) {
3037 throw AuthError_1.AuthError.createUnexpectedError("Response is null");
3038 }
3039 return response;
3040 };
3041 /**
3042 * Set Authority when saving Token from the hash
3043 * @param state
3044 * @param inCookie
3045 * @param cacheStorage
3046 * @param idTokenObj
3047 * @param response
3048 */
3049 UserAgentApplication.prototype.populateAuthority = function (state, inCookie, cacheStorage, idTokenObj) {
3050 this.logger.verbose("PopulateAuthority has been called");
3051 var authorityKey = AuthCache_1.AuthCache.generateAuthorityKey(state);
3052 var cachedAuthority = cacheStorage.getItem(authorityKey, inCookie);
3053 // retrieve the authority from cache and replace with tenantID
3054 return StringUtils_1.StringUtils.isEmpty(cachedAuthority) ? cachedAuthority : UrlUtils_1.UrlUtils.replaceTenantPath(cachedAuthority, idTokenObj.tenantId);
3055 };
3056 /* tslint:enable:no-string-literal */
3057 // #endregion
3058 // #region Account
3059 /**
3060 * Returns the signed in account
3061 * (the account object is created at the time of successful login)
3062 * or null when no state is found
3063 * @returns {@link Account} - the account object stored in MSAL
3064 */
3065 UserAgentApplication.prototype.getAccount = function () {
3066 // if a session already exists, get the account from the session
3067 if (this.account) {
3068 return this.account;
3069 }
3070 // frame is used to get idToken and populate the account for the given session
3071 var rawIdToken = this.cacheStorage.getItem(Constants_1.PersistentCacheKeys.IDTOKEN, this.inCookie);
3072 var rawClientInfo = this.cacheStorage.getItem(Constants_1.PersistentCacheKeys.CLIENT_INFO, this.inCookie);
3073 if (!StringUtils_1.StringUtils.isEmpty(rawIdToken) && !StringUtils_1.StringUtils.isEmpty(rawClientInfo)) {
3074 var idToken = new IdToken_1.IdToken(rawIdToken);
3075 var clientInfo = new ClientInfo_1.ClientInfo(rawClientInfo, "");
3076 this.account = Account_1.Account.createAccount(idToken, clientInfo);
3077 return this.account;
3078 }
3079 // if login not yet done, return null
3080 return null;
3081 };
3082 /**
3083 * @hidden
3084 *
3085 * Extracts state value from the accountState sent with the authentication request.
3086 * @returns {string} scope.
3087 * @ignore
3088 */
3089 UserAgentApplication.prototype.getAccountState = function (state) {
3090 if (state) {
3091 var splitIndex = state.indexOf(Constants_1.Constants.resourceDelimiter);
3092 if (splitIndex > -1 && splitIndex + 1 < state.length) {
3093 return state.substring(splitIndex + 1);
3094 }
3095 }
3096 return state;
3097 };
3098 /**
3099 * Use to get a list of unique accounts in MSAL cache based on homeAccountIdentifier.
3100 *
3101 * @param {@link Array<Account>} Account - all unique accounts in MSAL cache.
3102 */
3103 UserAgentApplication.prototype.getAllAccounts = function () {
3104 var accounts = [];
3105 var accessTokenCacheItems = this.cacheStorage.getAllAccessTokens(Constants_1.Constants.clientId, Constants_1.Constants.homeAccountIdentifier);
3106 for (var i = 0; i < accessTokenCacheItems.length; i++) {
3107 var idToken = new IdToken_1.IdToken(accessTokenCacheItems[i].value.idToken);
3108 var clientInfo = new ClientInfo_1.ClientInfo(accessTokenCacheItems[i].value.homeAccountIdentifier, "");
3109 var account = Account_1.Account.createAccount(idToken, clientInfo);
3110 accounts.push(account);
3111 }
3112 return this.getUniqueAccounts(accounts);
3113 };
3114 /**
3115 * @hidden
3116 *
3117 * Used to filter accounts based on homeAccountIdentifier
3118 * @param {Array<Account>} Accounts - accounts saved in the cache
3119 * @ignore
3120 */
3121 UserAgentApplication.prototype.getUniqueAccounts = function (accounts) {
3122 if (!accounts || accounts.length <= 1) {
3123 return accounts;
3124 }
3125 var flags = [];
3126 var uniqueAccounts = [];
3127 for (var index = 0; index < accounts.length; ++index) {
3128 if (accounts[index].homeAccountIdentifier && flags.indexOf(accounts[index].homeAccountIdentifier) === -1) {
3129 flags.push(accounts[index].homeAccountIdentifier);
3130 uniqueAccounts.push(accounts[index]);
3131 }
3132 }
3133 return uniqueAccounts;
3134 };
3135 // #endregion
3136 // #region Angular
3137 /**
3138 * @hidden
3139 *
3140 * Broadcast messages - Used only for Angular? *
3141 * @param eventName
3142 * @param data
3143 */
3144 UserAgentApplication.prototype.broadcast = function (eventName, data) {
3145 var evt = new CustomEvent(eventName, { detail: data });
3146 window.dispatchEvent(evt);
3147 };
3148 /**
3149 * @hidden
3150 *
3151 * Helper function to retrieve the cached token
3152 *
3153 * @param scopes
3154 * @param {@link Account} account
3155 * @param state
3156 * @return {@link AuthResponse} AuthResponse
3157 */
3158 UserAgentApplication.prototype.getCachedTokenInternal = function (scopes, account, state, correlationId) {
3159 // Get the current session's account object
3160 var accountObject = account || this.getAccount();
3161 if (!accountObject) {
3162 return null;
3163 }
3164 // Construct AuthenticationRequest based on response type; set "redirectUri" from the "request" which makes this call from Angular - for this.getRedirectUri()
3165 var newAuthority = this.authorityInstance ? this.authorityInstance : AuthorityFactory_1.AuthorityFactory.CreateInstance(this.authority, this.config.auth.validateAuthority);
3166 var responseType = this.getTokenType(accountObject, scopes);
3167 var serverAuthenticationRequest = new ServerRequestParameters_1.ServerRequestParameters(newAuthority, this.clientId, responseType, this.getRedirectUri(), scopes, state, correlationId);
3168 // get cached token
3169 return this.getCachedToken(serverAuthenticationRequest, account);
3170 };
3171 /**
3172 * @hidden
3173 *
3174 * Get scopes for the Endpoint - Used in Angular to track protected and unprotected resources without interaction from the developer app
3175 * Note: Please check if we need to set the "redirectUri" from the "request" which makes this call from Angular - for this.getRedirectUri()
3176 *
3177 * @param endpoint
3178 */
3179 UserAgentApplication.prototype.getScopesForEndpoint = function (endpoint) {
3180 // if user specified list of unprotectedResources, no need to send token to these endpoints, return null.
3181 if (this.config.framework.unprotectedResources.length > 0) {
3182 for (var i = 0; i < this.config.framework.unprotectedResources.length; i++) {
3183 if (endpoint.indexOf(this.config.framework.unprotectedResources[i]) > -1) {
3184 return null;
3185 }
3186 }
3187 }
3188 // process all protected resources and send the matched one
3189 if (this.config.framework.protectedResourceMap.size > 0) {
3190 for (var _i = 0, _a = Array.from(this.config.framework.protectedResourceMap.keys()); _i < _a.length; _i++) {
3191 var key = _a[_i];
3192 // configEndpoint is like /api/Todo requested endpoint can be /api/Todo/1
3193 if (endpoint.indexOf(key) > -1) {
3194 return this.config.framework.protectedResourceMap.get(key);
3195 }
3196 }
3197 }
3198 /*
3199 * default resource will be clientid if nothing specified
3200 * App will use idtoken for calls to itself
3201 * check if it's staring from http or https, needs to match with app host
3202 */
3203 if (endpoint.indexOf("http://") > -1 || endpoint.indexOf("https://") > -1) {
3204 if (UrlUtils_1.UrlUtils.getHostFromUri(endpoint) === UrlUtils_1.UrlUtils.getHostFromUri(this.getRedirectUri())) {
3205 return new Array(this.clientId);
3206 }
3207 }
3208 else {
3209 /*
3210 * in angular level, the url for $http interceptor call could be relative url,
3211 * if it's relative call, we'll treat it as app backend call.
3212 */
3213 return new Array(this.clientId);
3214 }
3215 // if not the app's own backend or not a domain listed in the endpoints structure
3216 return null;
3217 };
3218 /**
3219 * Return boolean flag to developer to help inform if login is in progress
3220 * @returns {boolean} true/false
3221 */
3222 UserAgentApplication.prototype.getLoginInProgress = function () {
3223 return this.cacheStorage.isInteractionInProgress(true);
3224 };
3225 /**
3226 * @hidden
3227 * @ignore
3228 *
3229 * @param loginInProgress
3230 */
3231 UserAgentApplication.prototype.setInteractionInProgress = function (inProgress) {
3232 this.cacheStorage.setInteractionInProgress(inProgress);
3233 };
3234 /**
3235 * @hidden
3236 * @ignore
3237 *
3238 * @param loginInProgress
3239 */
3240 UserAgentApplication.prototype.setloginInProgress = function (loginInProgress) {
3241 this.setInteractionInProgress(loginInProgress);
3242 };
3243 /**
3244 * @hidden
3245 * @ignore
3246 *
3247 * returns the status of acquireTokenInProgress
3248 */
3249 UserAgentApplication.prototype.getAcquireTokenInProgress = function () {
3250 return this.cacheStorage.isInteractionInProgress(true);
3251 };
3252 /**
3253 * @hidden
3254 * @ignore
3255 *
3256 * @param acquireTokenInProgress
3257 */
3258 UserAgentApplication.prototype.setAcquireTokenInProgress = function (acquireTokenInProgress) {
3259 this.setInteractionInProgress(acquireTokenInProgress);
3260 };
3261 /**
3262 * @hidden
3263 * @ignore
3264 *
3265 * returns the logger handle
3266 */
3267 UserAgentApplication.prototype.getLogger = function () {
3268 return this.logger;
3269 };
3270 /**
3271 * Sets the logger callback.
3272 * @param logger Logger callback
3273 */
3274 UserAgentApplication.prototype.setLogger = function (logger) {
3275 this.logger = logger;
3276 };
3277 // #endregion
3278 // #region Getters and Setters
3279 /**
3280 * Use to get the redirect uri configured in MSAL or null.
3281 * Evaluates redirectUri if its a function, otherwise simply returns its value.
3282 *
3283 * @returns {string} redirect URL
3284 */
3285 UserAgentApplication.prototype.getRedirectUri = function (reqRedirectUri) {
3286 if (reqRedirectUri) {
3287 return reqRedirectUri;
3288 }
3289 else if (typeof this.config.auth.redirectUri === "function") {
3290 return this.config.auth.redirectUri();
3291 }
3292 return this.config.auth.redirectUri;
3293 };
3294 /**
3295 * Use to get the post logout redirect uri configured in MSAL or null.
3296 * Evaluates postLogoutredirectUri if its a function, otherwise simply returns its value.
3297 *
3298 * @returns {string} post logout redirect URL
3299 */
3300 UserAgentApplication.prototype.getPostLogoutRedirectUri = function () {
3301 if (typeof this.config.auth.postLogoutRedirectUri === "function") {
3302 return this.config.auth.postLogoutRedirectUri();
3303 }
3304 return this.config.auth.postLogoutRedirectUri;
3305 };
3306 /**
3307 * Use to get the current {@link Configuration} object in MSAL
3308 *
3309 * @returns {@link Configuration}
3310 */
3311 UserAgentApplication.prototype.getCurrentConfiguration = function () {
3312 if (!this.config) {
3313 throw ClientConfigurationError_1.ClientConfigurationError.createNoSetConfigurationError();
3314 }
3315 return this.config;
3316 };
3317 /**
3318 * @ignore
3319 *
3320 * Utils function to create the Authentication
3321 * @param {@link account} account object
3322 * @param scopes
3323 *
3324 * @returns {string} token type: token, id_token or id_token token
3325 *
3326 */
3327 UserAgentApplication.prototype.getTokenType = function (accountObject, scopes) {
3328 var accountsMatch = Account_1.Account.compareAccounts(accountObject, this.getAccount());
3329 return ServerRequestParameters_1.ServerRequestParameters.determineResponseType(accountsMatch, scopes);
3330 };
3331 /**
3332 * @hidden
3333 * @ignore
3334 *
3335 * Sets the cachekeys for and stores the account information in cache
3336 * @param account
3337 * @param state
3338 * @hidden
3339 */
3340 UserAgentApplication.prototype.setAccountCache = function (account, state) {
3341 // Cache acquireTokenAccountKey
3342 var accountId = account ? this.getAccountId(account) : Constants_1.Constants.no_account;
3343 var acquireTokenAccountKey = AuthCache_1.AuthCache.generateAcquireTokenAccountKey(accountId, state);
3344 this.cacheStorage.setItem(acquireTokenAccountKey, JSON.stringify(account));
3345 };
3346 /**
3347 * @hidden
3348 * @ignore
3349 *
3350 * Sets the cacheKey for and stores the authority information in cache
3351 * @param state
3352 * @param authority
3353 * @hidden
3354 */
3355 UserAgentApplication.prototype.setAuthorityCache = function (state, authority) {
3356 // Cache authorityKey
3357 var authorityKey = AuthCache_1.AuthCache.generateAuthorityKey(state);
3358 this.cacheStorage.setItem(authorityKey, UrlUtils_1.UrlUtils.CanonicalizeUri(authority), this.inCookie);
3359 };
3360 /**
3361 * Updates account, authority, and nonce in cache
3362 * @param serverAuthenticationRequest
3363 * @param account
3364 * @hidden
3365 * @ignore
3366 */
3367 UserAgentApplication.prototype.updateCacheEntries = function (serverAuthenticationRequest, account, isLoginCall, loginStartPage) {
3368 // Cache Request Originator Page
3369 if (loginStartPage) {
3370 this.cacheStorage.setItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.LOGIN_REQUEST, serverAuthenticationRequest.state), loginStartPage, this.inCookie);
3371 }
3372 // Cache account and authority
3373 if (isLoginCall) {
3374 // Cache the state
3375 this.cacheStorage.setItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.STATE_LOGIN, serverAuthenticationRequest.state), serverAuthenticationRequest.state, this.inCookie);
3376 }
3377 else {
3378 this.setAccountCache(account, serverAuthenticationRequest.state);
3379 }
3380 // Cache authorityKey
3381 this.setAuthorityCache(serverAuthenticationRequest.state, serverAuthenticationRequest.authority);
3382 // Cache nonce
3383 this.cacheStorage.setItem(AuthCache_1.AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.NONCE_IDTOKEN, serverAuthenticationRequest.state), serverAuthenticationRequest.nonce, this.inCookie);
3384 };
3385 /**
3386 * Returns the unique identifier for the logged in account
3387 * @param account
3388 * @hidden
3389 * @ignore
3390 */
3391 UserAgentApplication.prototype.getAccountId = function (account) {
3392 // return `${account.accountIdentifier}` + Constants.resourceDelimiter + `${account.homeAccountIdentifier}`;
3393 var accountId;
3394 if (!StringUtils_1.StringUtils.isEmpty(account.homeAccountIdentifier)) {
3395 accountId = account.homeAccountIdentifier;
3396 }
3397 else {
3398 accountId = Constants_1.Constants.no_account;
3399 }
3400 return accountId;
3401 };
3402 /**
3403 * @ignore
3404 * @param extraQueryParameters
3405 *
3406 * Construct 'tokenRequest' from the available data in adalIdToken
3407 */
3408 UserAgentApplication.prototype.buildIDTokenRequest = function (request) {
3409 var tokenRequest = {
3410 scopes: Constants_1.Constants.oidcScopes,
3411 authority: this.authority,
3412 account: this.getAccount(),
3413 extraQueryParameters: request.extraQueryParameters,
3414 correlationId: request.correlationId
3415 };
3416 return tokenRequest;
3417 };
3418 /**
3419 * @ignore
3420 * @param config
3421 * @param clientId
3422 *
3423 * Construct TelemetryManager from Configuration
3424 */
3425 UserAgentApplication.prototype.getTelemetryManagerFromConfig = function (config, clientId) {
3426 if (!config) { // if unset
3427 return TelemetryManager_1.default.getTelemetrymanagerStub(clientId, this.logger);
3428 }
3429 // if set then validate
3430 var applicationName = config.applicationName, applicationVersion = config.applicationVersion, telemetryEmitter = config.telemetryEmitter;
3431 if (!applicationName || !applicationVersion || !telemetryEmitter) {
3432 throw ClientConfigurationError_1.ClientConfigurationError.createTelemetryConfigError(config);
3433 }
3434 // if valid then construct
3435 var telemetryPlatform = {
3436 applicationName: applicationName,
3437 applicationVersion: applicationVersion
3438 };
3439 var telemetryManagerConfig = {
3440 platform: telemetryPlatform,
3441 clientId: clientId
3442 };
3443 return new TelemetryManager_1.default(telemetryManagerConfig, telemetryEmitter, this.logger);
3444 };
3445 return UserAgentApplication;
3446}());
3447exports.UserAgentApplication = UserAgentApplication;
3448
3449
3450/***/ }),
3451
3452/***/ 767:
3453/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
3454
3455
3456/*
3457 * Copyright (c) Microsoft Corporation. All rights reserved.
3458 * Licensed under the MIT License.
3459 */
3460Object.defineProperty(exports, "__esModule", ({ value: true }));
3461exports.XhrClient = void 0;
3462var Constants_1 = __webpack_require__(91);
3463/**
3464 * XHR client for JSON endpoints
3465 * https://www.npmjs.com/package/async-promise
3466 * @hidden
3467 */
3468var XhrClient = /** @class */ (function () {
3469 function XhrClient() {
3470 }
3471 XhrClient.prototype.sendRequestAsync = function (url, method, enableCaching) {
3472 var _this = this;
3473 return new Promise(function (resolve, reject) {
3474 var xhr = new XMLHttpRequest();
3475 xhr.open(method, url, /* async: */ true);
3476 if (enableCaching) {
3477 /*
3478 * TODO: (shivb) ensure that this can be cached
3479 * xhr.setRequestHeader("Cache-Control", "Public");
3480 */
3481 }
3482 xhr.onload = function () {
3483 if (xhr.status < 200 || xhr.status >= 300) {
3484 reject(_this.handleError(xhr.responseText));
3485 }
3486 var jsonResponse;
3487 try {
3488 jsonResponse = JSON.parse(xhr.responseText);
3489 }
3490 catch (e) {
3491 reject(_this.handleError(xhr.responseText));
3492 }
3493 var response = {
3494 statusCode: xhr.status,
3495 body: jsonResponse
3496 };
3497 resolve(response);
3498 };
3499 xhr.onerror = function () {
3500 reject(xhr.status);
3501 };
3502 if (method === Constants_1.NetworkRequestType.GET) {
3503 xhr.send();
3504 }
3505 else {
3506 throw "not implemented";
3507 }
3508 });
3509 };
3510 XhrClient.prototype.handleError = function (responseText) {
3511 var jsonResponse;
3512 try {
3513 jsonResponse = JSON.parse(responseText);
3514 if (jsonResponse["error"]) {
3515 return jsonResponse["error"];
3516 }
3517 else {
3518 throw responseText;
3519 }
3520 }
3521 catch (e) {
3522 return responseText;
3523 }
3524 };
3525 return XhrClient;
3526}());
3527exports.XhrClient = XhrClient;
3528
3529
3530/***/ }),
3531
3532/***/ 660:
3533/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
3534
3535
3536/*
3537 * Copyright (c) Microsoft Corporation. All rights reserved.
3538 * Licensed under the MIT License.
3539 */
3540Object.defineProperty(exports, "__esModule", ({ value: true }));
3541exports.Authority = exports.AuthorityType = void 0;
3542var tslib_1 = __webpack_require__(795);
3543var ClientConfigurationError_1 = __webpack_require__(550);
3544var XHRClient_1 = __webpack_require__(767);
3545var UrlUtils_1 = __webpack_require__(741);
3546var TrustedAuthority_1 = __webpack_require__(405);
3547var Constants_1 = __webpack_require__(91);
3548/**
3549 * @hidden
3550 */
3551var AuthorityType;
3552(function (AuthorityType) {
3553 AuthorityType[AuthorityType["Default"] = 0] = "Default";
3554 AuthorityType[AuthorityType["Adfs"] = 1] = "Adfs";
3555})(AuthorityType = exports.AuthorityType || (exports.AuthorityType = {}));
3556/**
3557 * @hidden
3558 */
3559var Authority = /** @class */ (function () {
3560 function Authority(authority, validateAuthority, authorityMetadata) {
3561 this.IsValidationEnabled = validateAuthority;
3562 this.CanonicalAuthority = authority;
3563 this.validateAsUri();
3564 this.tenantDiscoveryResponse = authorityMetadata;
3565 }
3566 Authority.isAdfs = function (authorityUrl) {
3567 var components = UrlUtils_1.UrlUtils.GetUrlComponents(authorityUrl);
3568 var pathSegments = components.PathSegments;
3569 return (pathSegments.length && pathSegments[0].toLowerCase() === Constants_1.Constants.ADFS);
3570 };
3571 Object.defineProperty(Authority.prototype, "AuthorityType", {
3572 get: function () {
3573 return Authority.isAdfs(this.canonicalAuthority) ? AuthorityType.Adfs : AuthorityType.Default;
3574 },
3575 enumerable: false,
3576 configurable: true
3577 });
3578 Object.defineProperty(Authority.prototype, "Tenant", {
3579 get: function () {
3580 return this.CanonicalAuthorityUrlComponents.PathSegments[0];
3581 },
3582 enumerable: false,
3583 configurable: true
3584 });
3585 Object.defineProperty(Authority.prototype, "AuthorizationEndpoint", {
3586 get: function () {
3587 this.validateResolved();
3588 return this.tenantDiscoveryResponse.AuthorizationEndpoint.replace(/{tenant}|{tenantid}/g, this.Tenant);
3589 },
3590 enumerable: false,
3591 configurable: true
3592 });
3593 Object.defineProperty(Authority.prototype, "EndSessionEndpoint", {
3594 get: function () {
3595 this.validateResolved();
3596 return this.tenantDiscoveryResponse.EndSessionEndpoint.replace(/{tenant}|{tenantid}/g, this.Tenant);
3597 },
3598 enumerable: false,
3599 configurable: true
3600 });
3601 Object.defineProperty(Authority.prototype, "SelfSignedJwtAudience", {
3602 get: function () {
3603 this.validateResolved();
3604 return this.tenantDiscoveryResponse.Issuer.replace(/{tenant}|{tenantid}/g, this.Tenant);
3605 },
3606 enumerable: false,
3607 configurable: true
3608 });
3609 Authority.prototype.validateResolved = function () {
3610 if (!this.hasCachedMetadata()) {
3611 throw "Please call ResolveEndpointsAsync first";
3612 }
3613 };
3614 Object.defineProperty(Authority.prototype, "CanonicalAuthority", {
3615 /**
3616 * A URL that is the authority set by the developer
3617 */
3618 get: function () {
3619 return this.canonicalAuthority;
3620 },
3621 set: function (url) {
3622 this.canonicalAuthority = UrlUtils_1.UrlUtils.CanonicalizeUri(url);
3623 this.canonicalAuthorityUrlComponents = null;
3624 },
3625 enumerable: false,
3626 configurable: true
3627 });
3628 Object.defineProperty(Authority.prototype, "CanonicalAuthorityUrlComponents", {
3629 get: function () {
3630 if (!this.canonicalAuthorityUrlComponents) {
3631 this.canonicalAuthorityUrlComponents = UrlUtils_1.UrlUtils.GetUrlComponents(this.CanonicalAuthority);
3632 }
3633 return this.canonicalAuthorityUrlComponents;
3634 },
3635 enumerable: false,
3636 configurable: true
3637 });
3638 Object.defineProperty(Authority.prototype, "DefaultOpenIdConfigurationEndpoint", {
3639 // http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
3640 get: function () {
3641 return (this.AuthorityType === AuthorityType.Adfs) ? "" + this.CanonicalAuthority + Constants_1.WELL_KNOWN_SUFFIX : this.CanonicalAuthority + "v2.0/" + Constants_1.WELL_KNOWN_SUFFIX;
3642 },
3643 enumerable: false,
3644 configurable: true
3645 });
3646 /**
3647 * Given a string, validate that it is of the form https://domain/path
3648 */
3649 Authority.prototype.validateAsUri = function () {
3650 var components;
3651 try {
3652 components = this.CanonicalAuthorityUrlComponents;
3653 }
3654 catch (e) {
3655 throw ClientConfigurationError_1.ClientConfigurationErrorMessage.invalidAuthorityType;
3656 }
3657 if (!components.Protocol || components.Protocol.toLowerCase() !== "https:") {
3658 throw ClientConfigurationError_1.ClientConfigurationErrorMessage.authorityUriInsecure;
3659 }
3660 if (!components.PathSegments || components.PathSegments.length < 1) {
3661 throw ClientConfigurationError_1.ClientConfigurationErrorMessage.authorityUriInvalidPath;
3662 }
3663 };
3664 /**
3665 * Calls the OIDC endpoint and returns the response
3666 */
3667 Authority.prototype.DiscoverEndpoints = function (openIdConfigurationEndpoint, telemetryManager, correlationId) {
3668 var client = new XHRClient_1.XhrClient();
3669 var httpMethod = Constants_1.NetworkRequestType.GET;
3670 var httpEvent = telemetryManager.createAndStartHttpEvent(correlationId, httpMethod, openIdConfigurationEndpoint, "openIdConfigurationEndpoint");
3671 return client.sendRequestAsync(openIdConfigurationEndpoint, httpMethod, /* enableCaching: */ true)
3672 .then(function (response) {
3673 httpEvent.httpResponseStatus = response.statusCode;
3674 telemetryManager.stopEvent(httpEvent);
3675 return {
3676 AuthorizationEndpoint: response.body["authorization_endpoint"],
3677 EndSessionEndpoint: response.body["end_session_endpoint"],
3678 Issuer: response.body["issuer"]
3679 };
3680 })
3681 .catch(function (err) {
3682 httpEvent.serverErrorCode = err;
3683 telemetryManager.stopEvent(httpEvent);
3684 throw err;
3685 });
3686 };
3687 /**
3688 * Returns a promise.
3689 * Checks to see if the authority is in the cache
3690 * Discover endpoints via openid-configuration
3691 * If successful, caches the endpoint for later use in OIDC
3692 */
3693 Authority.prototype.resolveEndpointsAsync = function (telemetryManager, correlationId) {
3694 return tslib_1.__awaiter(this, void 0, Promise, function () {
3695 var host, openIdConfigurationEndpointResponse, _a;
3696 return tslib_1.__generator(this, function (_b) {
3697 switch (_b.label) {
3698 case 0:
3699 if (!this.IsValidationEnabled) return [3 /*break*/, 3];
3700 host = this.canonicalAuthorityUrlComponents.HostNameAndPort;
3701 if (!(TrustedAuthority_1.TrustedAuthority.getTrustedHostList().length === 0)) return [3 /*break*/, 2];
3702 return [4 /*yield*/, TrustedAuthority_1.TrustedAuthority.setTrustedAuthoritiesFromNetwork(this.canonicalAuthority, telemetryManager, correlationId)];
3703 case 1:
3704 _b.sent();
3705 _b.label = 2;
3706 case 2:
3707 if (!TrustedAuthority_1.TrustedAuthority.IsInTrustedHostList(host)) {
3708 throw ClientConfigurationError_1.ClientConfigurationError.createUntrustedAuthorityError(host);
3709 }
3710 _b.label = 3;
3711 case 3:
3712 openIdConfigurationEndpointResponse = this.GetOpenIdConfigurationEndpoint();
3713 _a = this;
3714 return [4 /*yield*/, this.DiscoverEndpoints(openIdConfigurationEndpointResponse, telemetryManager, correlationId)];
3715 case 4:
3716 _a.tenantDiscoveryResponse = _b.sent();
3717 return [2 /*return*/, this.tenantDiscoveryResponse];
3718 }
3719 });
3720 });
3721 };
3722 /**
3723 * Checks if there is a cached tenant discovery response with required fields.
3724 */
3725 Authority.prototype.hasCachedMetadata = function () {
3726 return !!(this.tenantDiscoveryResponse &&
3727 this.tenantDiscoveryResponse.AuthorizationEndpoint &&
3728 this.tenantDiscoveryResponse.EndSessionEndpoint &&
3729 this.tenantDiscoveryResponse.Issuer);
3730 };
3731 /**
3732 * Returns a promise which resolves to the OIDC endpoint
3733 * Only responds with the endpoint
3734 */
3735 Authority.prototype.GetOpenIdConfigurationEndpoint = function () {
3736 return this.DefaultOpenIdConfigurationEndpoint;
3737 };
3738 return Authority;
3739}());
3740exports.Authority = Authority;
3741
3742
3743/***/ }),
3744
3745/***/ 951:
3746/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
3747
3748
3749/*
3750 * Copyright (c) Microsoft Corporation. All rights reserved.
3751 * Licensed under the MIT License.
3752 */
3753Object.defineProperty(exports, "__esModule", ({ value: true }));
3754exports.AuthorityFactory = void 0;
3755var tslib_1 = __webpack_require__(795);
3756/**
3757 * @hidden
3758 */
3759var Authority_1 = __webpack_require__(660);
3760var StringUtils_1 = __webpack_require__(454);
3761var ClientConfigurationError_1 = __webpack_require__(550);
3762var AuthorityFactory = /** @class */ (function () {
3763 function AuthorityFactory() {
3764 }
3765 AuthorityFactory.saveMetadataFromNetwork = function (authorityInstance, telemetryManager, correlationId) {
3766 return tslib_1.__awaiter(this, void 0, Promise, function () {
3767 var metadata;
3768 return tslib_1.__generator(this, function (_a) {
3769 switch (_a.label) {
3770 case 0: return [4 /*yield*/, authorityInstance.resolveEndpointsAsync(telemetryManager, correlationId)];
3771 case 1:
3772 metadata = _a.sent();
3773 this.metadataMap.set(authorityInstance.CanonicalAuthority, metadata);
3774 return [2 /*return*/, metadata];
3775 }
3776 });
3777 });
3778 };
3779 AuthorityFactory.getMetadata = function (authorityUrl) {
3780 return this.metadataMap.get(authorityUrl);
3781 };
3782 AuthorityFactory.saveMetadataFromConfig = function (authorityUrl, authorityMetadataJson) {
3783 try {
3784 if (authorityMetadataJson) {
3785 var parsedMetadata = JSON.parse(authorityMetadataJson);
3786 if (!parsedMetadata.authorization_endpoint || !parsedMetadata.end_session_endpoint || !parsedMetadata.issuer) {
3787 throw ClientConfigurationError_1.ClientConfigurationError.createInvalidAuthorityMetadataError();
3788 }
3789 this.metadataMap.set(authorityUrl, {
3790 AuthorizationEndpoint: parsedMetadata.authorization_endpoint,
3791 EndSessionEndpoint: parsedMetadata.end_session_endpoint,
3792 Issuer: parsedMetadata.issuer
3793 });
3794 }
3795 }
3796 catch (e) {
3797 throw ClientConfigurationError_1.ClientConfigurationError.createInvalidAuthorityMetadataError();
3798 }
3799 };
3800 /**
3801 * Create an authority object of the correct type based on the url
3802 * Performs basic authority validation - checks to see if the authority is of a valid type (eg aad, b2c)
3803 */
3804 AuthorityFactory.CreateInstance = function (authorityUrl, validateAuthority, authorityMetadata) {
3805 if (StringUtils_1.StringUtils.isEmpty(authorityUrl)) {
3806 return null;
3807 }
3808 if (authorityMetadata) {
3809 // todo: log statements
3810 this.saveMetadataFromConfig(authorityUrl, authorityMetadata);
3811 }
3812 return new Authority_1.Authority(authorityUrl, validateAuthority, this.metadataMap.get(authorityUrl));
3813 };
3814 AuthorityFactory.metadataMap = new Map();
3815 return AuthorityFactory;
3816}());
3817exports.AuthorityFactory = AuthorityFactory;
3818
3819
3820/***/ }),
3821
3822/***/ 405:
3823/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
3824
3825
3826/*
3827 * Copyright (c) Microsoft Corporation. All rights reserved.
3828 * Licensed under the MIT License.
3829 */
3830Object.defineProperty(exports, "__esModule", ({ value: true }));
3831exports.TrustedAuthority = void 0;
3832var tslib_1 = __webpack_require__(795);
3833var XHRClient_1 = __webpack_require__(767);
3834var Constants_1 = __webpack_require__(91);
3835var UrlUtils_1 = __webpack_require__(741);
3836var TrustedAuthority = /** @class */ (function () {
3837 function TrustedAuthority() {
3838 }
3839 /**
3840 *
3841 * @param validateAuthority
3842 * @param knownAuthorities
3843 */
3844 TrustedAuthority.setTrustedAuthoritiesFromConfig = function (validateAuthority, knownAuthorities) {
3845 if (validateAuthority && !this.getTrustedHostList().length) {
3846 knownAuthorities.forEach(function (authority) {
3847 TrustedAuthority.TrustedHostList.push(authority.toLowerCase());
3848 });
3849 }
3850 };
3851 /**
3852 *
3853 * @param telemetryManager
3854 * @param correlationId
3855 */
3856 TrustedAuthority.getAliases = function (authorityToVerify, telemetryManager, correlationId) {
3857 return tslib_1.__awaiter(this, void 0, Promise, function () {
3858 var client, httpMethod, instanceDiscoveryEndpoint, httpEvent;
3859 return tslib_1.__generator(this, function (_a) {
3860 client = new XHRClient_1.XhrClient();
3861 httpMethod = Constants_1.NetworkRequestType.GET;
3862 instanceDiscoveryEndpoint = "" + Constants_1.AAD_INSTANCE_DISCOVERY_ENDPOINT + authorityToVerify + "oauth2/v2.0/authorize";
3863 httpEvent = telemetryManager.createAndStartHttpEvent(correlationId, httpMethod, instanceDiscoveryEndpoint, "getAliases");
3864 return [2 /*return*/, client.sendRequestAsync(instanceDiscoveryEndpoint, httpMethod, true)
3865 .then(function (response) {
3866 httpEvent.httpResponseStatus = response.statusCode;
3867 telemetryManager.stopEvent(httpEvent);
3868 return response.body["metadata"];
3869 })
3870 .catch(function (err) {
3871 httpEvent.serverErrorCode = err;
3872 telemetryManager.stopEvent(httpEvent);
3873 throw err;
3874 })];
3875 });
3876 });
3877 };
3878 /**
3879 *
3880 * @param telemetryManager
3881 * @param correlationId
3882 */
3883 TrustedAuthority.setTrustedAuthoritiesFromNetwork = function (authorityToVerify, telemetryManager, correlationId) {
3884 return tslib_1.__awaiter(this, void 0, Promise, function () {
3885 var metadata, host;
3886 return tslib_1.__generator(this, function (_a) {
3887 switch (_a.label) {
3888 case 0: return [4 /*yield*/, this.getAliases(authorityToVerify, telemetryManager, correlationId)];
3889 case 1:
3890 metadata = _a.sent();
3891 metadata.forEach(function (entry) {
3892 var authorities = entry["aliases"];
3893 authorities.forEach(function (authority) {
3894 TrustedAuthority.TrustedHostList.push(authority.toLowerCase());
3895 });
3896 });
3897 host = UrlUtils_1.UrlUtils.GetUrlComponents(authorityToVerify).HostNameAndPort;
3898 if (TrustedAuthority.getTrustedHostList().length && !TrustedAuthority.IsInTrustedHostList(host)) {
3899 // Custom Domain scenario, host is trusted because Instance Discovery call succeeded
3900 TrustedAuthority.TrustedHostList.push(host.toLowerCase());
3901 }
3902 return [2 /*return*/];
3903 }
3904 });
3905 });
3906 };
3907 TrustedAuthority.getTrustedHostList = function () {
3908 return this.TrustedHostList;
3909 };
3910 /**
3911 * Checks to see if the host is in a list of trusted hosts
3912 * @param host
3913 */
3914 TrustedAuthority.IsInTrustedHostList = function (host) {
3915 return this.TrustedHostList.indexOf(host.toLowerCase()) > -1;
3916 };
3917 TrustedAuthority.TrustedHostList = [];
3918 return TrustedAuthority;
3919}());
3920exports.TrustedAuthority = TrustedAuthority;
3921
3922
3923/***/ }),
3924
3925/***/ 644:
3926/***/ (function(__unused_webpack_module, exports) {
3927
3928
3929/*
3930 * Copyright (c) Microsoft Corporation. All rights reserved.
3931 * Licensed under the MIT License.
3932 */
3933Object.defineProperty(exports, "__esModule", ({ value: true }));
3934exports.AccessTokenCacheItem = void 0;
3935/**
3936 * @hidden
3937 */
3938var AccessTokenCacheItem = /** @class */ (function () {
3939 function AccessTokenCacheItem(key, value) {
3940 this.key = key;
3941 this.value = value;
3942 }
3943 return AccessTokenCacheItem;
3944}());
3945exports.AccessTokenCacheItem = AccessTokenCacheItem;
3946
3947
3948/***/ }),
3949
3950/***/ 29:
3951/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
3952
3953
3954/*
3955 * Copyright (c) Microsoft Corporation. All rights reserved.
3956 * Licensed under the MIT License.
3957 */
3958Object.defineProperty(exports, "__esModule", ({ value: true }));
3959exports.AccessTokenKey = void 0;
3960var CryptoUtils_1 = __webpack_require__(453);
3961var UrlUtils_1 = __webpack_require__(741);
3962/**
3963 * @hidden
3964 */
3965var AccessTokenKey = /** @class */ (function () {
3966 function AccessTokenKey(authority, clientId, scopes, uid, utid) {
3967 this.authority = UrlUtils_1.UrlUtils.CanonicalizeUri(authority);
3968 this.clientId = clientId;
3969 this.scopes = scopes;
3970 this.homeAccountIdentifier = CryptoUtils_1.CryptoUtils.base64Encode(uid) + "." + CryptoUtils_1.CryptoUtils.base64Encode(utid);
3971 }
3972 return AccessTokenKey;
3973}());
3974exports.AccessTokenKey = AccessTokenKey;
3975
3976
3977/***/ }),
3978
3979/***/ 192:
3980/***/ (function(__unused_webpack_module, exports) {
3981
3982
3983/*
3984 * Copyright (c) Microsoft Corporation. All rights reserved.
3985 * Licensed under the MIT License.
3986 */
3987Object.defineProperty(exports, "__esModule", ({ value: true }));
3988exports.AccessTokenValue = void 0;
3989/**
3990 * @hidden
3991 */
3992var AccessTokenValue = /** @class */ (function () {
3993 function AccessTokenValue(accessToken, idToken, expiresIn, homeAccountIdentifier) {
3994 this.accessToken = accessToken;
3995 this.idToken = idToken;
3996 this.expiresIn = expiresIn;
3997 this.homeAccountIdentifier = homeAccountIdentifier;
3998 }
3999 return AccessTokenValue;
4000}());
4001exports.AccessTokenValue = AccessTokenValue;
4002
4003
4004/***/ }),
4005
4006/***/ 226:
4007/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
4008
4009
4010/*
4011 * Copyright (c) Microsoft Corporation. All rights reserved.
4012 * Licensed under the MIT License.
4013 */
4014Object.defineProperty(exports, "__esModule", ({ value: true }));
4015exports.AuthCache = void 0;
4016var tslib_1 = __webpack_require__(795);
4017var Constants_1 = __webpack_require__(91);
4018var AccessTokenCacheItem_1 = __webpack_require__(644);
4019var BrowserStorage_1 = __webpack_require__(96);
4020var RequestUtils_1 = __webpack_require__(52);
4021var StringUtils_1 = __webpack_require__(454);
4022var IdToken_1 = __webpack_require__(881);
4023var ClientAuthError_1 = __webpack_require__(356);
4024/**
4025 * @hidden
4026 */
4027var AuthCache = /** @class */ (function (_super) {
4028 tslib_1.__extends(AuthCache, _super);
4029 function AuthCache(clientId, cacheLocation, storeAuthStateInCookie) {
4030 var _this = _super.call(this, cacheLocation) || this;
4031 _this.temporaryCache = new BrowserStorage_1.BrowserStorage(Constants_1.SESSION_STORAGE);
4032 _this.clientId = clientId;
4033 // This is hardcoded to true for now. We may make this configurable in the future
4034 _this.rollbackEnabled = true;
4035 _this.migrateCacheEntries(storeAuthStateInCookie);
4036 return _this;
4037 }
4038 /**
4039 * Support roll back to old cache schema until the next major release: true by default now
4040 * @param storeAuthStateInCookie
4041 */
4042 AuthCache.prototype.migrateCacheEntries = function (storeAuthStateInCookie) {
4043 var _this = this;
4044 var idTokenKey = Constants_1.Constants.cachePrefix + "." + Constants_1.PersistentCacheKeys.IDTOKEN;
4045 var clientInfoKey = Constants_1.Constants.cachePrefix + "." + Constants_1.PersistentCacheKeys.CLIENT_INFO;
4046 var errorKey = Constants_1.Constants.cachePrefix + "." + Constants_1.ErrorCacheKeys.ERROR;
4047 var errorDescKey = Constants_1.Constants.cachePrefix + "." + Constants_1.ErrorCacheKeys.ERROR_DESC;
4048 var idTokenValue = _super.prototype.getItem.call(this, idTokenKey);
4049 var idToken;
4050 if (idTokenValue) {
4051 try {
4052 idToken = new IdToken_1.IdToken(idTokenValue);
4053 }
4054 catch (e) {
4055 return;
4056 }
4057 }
4058 if (idToken && idToken.claims && idToken.claims.aud === this.clientId) {
4059 var clientInfoValue = _super.prototype.getItem.call(this, clientInfoKey);
4060 var errorValue = _super.prototype.getItem.call(this, errorKey);
4061 var errorDescValue = _super.prototype.getItem.call(this, errorDescKey);
4062 var values_1 = [idTokenValue, clientInfoValue, errorValue, errorDescValue];
4063 var keysToMigrate = [Constants_1.PersistentCacheKeys.IDTOKEN, Constants_1.PersistentCacheKeys.CLIENT_INFO, Constants_1.ErrorCacheKeys.ERROR, Constants_1.ErrorCacheKeys.ERROR_DESC];
4064 keysToMigrate.forEach(function (cacheKey, index) { return _this.duplicateCacheEntry(cacheKey, values_1[index], storeAuthStateInCookie); });
4065 }
4066 };
4067 /**
4068 * Utility function to help with roll back keys
4069 * @param newKey
4070 * @param value
4071 * @param storeAuthStateInCookie
4072 */
4073 AuthCache.prototype.duplicateCacheEntry = function (newKey, value, storeAuthStateInCookie) {
4074 if (value) {
4075 this.setItem(newKey, value, storeAuthStateInCookie);
4076 }
4077 };
4078 /**
4079 * 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)
4080 * @param key
4081 * @param addInstanceId
4082 */
4083 AuthCache.prototype.generateCacheKey = function (key, addInstanceId) {
4084 try {
4085 // Defined schemas do not need the key appended
4086 JSON.parse(key);
4087 return key;
4088 }
4089 catch (e) {
4090 if (key.indexOf("" + Constants_1.Constants.cachePrefix) === 0 || key.indexOf(Constants_1.Constants.adalIdToken) === 0) {
4091 return key;
4092 }
4093 return addInstanceId ? Constants_1.Constants.cachePrefix + "." + this.clientId + "." + key : Constants_1.Constants.cachePrefix + "." + key;
4094 }
4095 };
4096 /**
4097 * Validates that the input cache key contains the account search terms (clientId and homeAccountIdentifier) and
4098 * then whether or not it contains the "scopes", depending on the token type being searched for. With matching account
4099 * search terms, Access Token search tries to match the "scopes" keyword, while Id Token search expects "scopes" to not be included.
4100 * @param key
4101 * @param clientId
4102 * @param homeAccountIdentifier
4103 * @param tokenType
4104 */
4105 AuthCache.prototype.matchKeyForType = function (key, clientId, homeAccountIdentifier, tokenType) {
4106 // All valid token cache item keys are valid JSON objects, ignore keys that aren't
4107 var parsedKey = StringUtils_1.StringUtils.validateAndParseJsonCacheKey(key);
4108 if (!parsedKey) {
4109 return null;
4110 }
4111 // Does the cache item match the request account
4112 var accountMatches = key.match(clientId) && key.match(homeAccountIdentifier);
4113 // Does the cache item match the requested token type
4114 var tokenTypeMatches = false;
4115 switch (tokenType) {
4116 case Constants_1.ServerHashParamKeys.ACCESS_TOKEN:
4117 // Cache item is an access token if scopes are included in the cache item key
4118 tokenTypeMatches = !!key.match(Constants_1.Constants.scopes);
4119 break;
4120 case Constants_1.ServerHashParamKeys.ID_TOKEN:
4121 // Cache may be an ID token if scopes are NOT included in the cache item key
4122 tokenTypeMatches = !key.match(Constants_1.Constants.scopes);
4123 break;
4124 }
4125 return (accountMatches && tokenTypeMatches) ? parsedKey : null;
4126 };
4127 /**
4128 * add value to storage
4129 * @param key
4130 * @param value
4131 * @param enableCookieStorage
4132 */
4133 AuthCache.prototype.setItem = function (key, value, enableCookieStorage) {
4134 _super.prototype.setItem.call(this, this.generateCacheKey(key, true), value, enableCookieStorage);
4135 // Values stored in cookies will have rollback disabled to minimize cookie length
4136 if (this.rollbackEnabled && !enableCookieStorage) {
4137 _super.prototype.setItem.call(this, this.generateCacheKey(key, false), value, enableCookieStorage);
4138 }
4139 };
4140 /**
4141 * get one item by key from storage
4142 * @param key
4143 * @param enableCookieStorage
4144 */
4145 AuthCache.prototype.getItem = function (key, enableCookieStorage) {
4146 return _super.prototype.getItem.call(this, this.generateCacheKey(key, true), enableCookieStorage);
4147 };
4148 /**
4149 * remove value from storage
4150 * @param key
4151 */
4152 AuthCache.prototype.removeItem = function (key) {
4153 this.temporaryCache.removeItem(this.generateCacheKey(key, true));
4154 _super.prototype.removeItem.call(this, this.generateCacheKey(key, true));
4155 if (this.rollbackEnabled) {
4156 _super.prototype.removeItem.call(this, this.generateCacheKey(key, false));
4157 }
4158 };
4159 /**
4160 * Sets temporary cache value
4161 * @param key
4162 * @param value
4163 * @param enableCookieStorage
4164 */
4165 AuthCache.prototype.setTemporaryItem = function (key, value, enableCookieStorage) {
4166 this.temporaryCache.setItem(this.generateCacheKey(key, true), value, enableCookieStorage);
4167 };
4168 /**
4169 * Gets temporary cache value
4170 * @param key
4171 * @param enableCookieStorage
4172 */
4173 AuthCache.prototype.getTemporaryItem = function (key, enableCookieStorage) {
4174 return this.temporaryCache.getItem(this.generateCacheKey(key, true), enableCookieStorage);
4175 };
4176 /**
4177 * Reset the cache items
4178 */
4179 AuthCache.prototype.resetCacheItems = function () {
4180 var storage = window[this.cacheLocation];
4181 var key;
4182 for (key in storage) {
4183 // Check if key contains msal prefix; For now, we are clearing all cache items created by MSAL.js
4184 if (storage.hasOwnProperty(key) && (key.indexOf(Constants_1.Constants.cachePrefix) !== -1)) {
4185 _super.prototype.removeItem.call(this, key);
4186 // TODO: Clear cache based on client id (clarify use cases where this is needed)
4187 }
4188 }
4189 };
4190 /**
4191 * Reset all temporary cache items
4192 */
4193 AuthCache.prototype.resetTempCacheItems = function (state) {
4194 var _this = this;
4195 var stateId = state && RequestUtils_1.RequestUtils.parseLibraryState(state).id;
4196 var isTokenRenewalInProgress = this.tokenRenewalInProgress(state);
4197 var storage = window[this.cacheLocation];
4198 // check state and remove associated cache
4199 if (stateId && !isTokenRenewalInProgress) {
4200 Object.keys(storage).forEach(function (key) {
4201 if (key.indexOf(stateId) !== -1) {
4202 _this.removeItem(key);
4203 _super.prototype.clearItemCookie.call(_this, key);
4204 }
4205 });
4206 }
4207 // delete the interaction status cache
4208 this.setInteractionInProgress(false);
4209 this.removeItem(Constants_1.TemporaryCacheKeys.REDIRECT_REQUEST);
4210 };
4211 /**
4212 * Set cookies for IE
4213 * @param cName
4214 * @param cValue
4215 * @param expires
4216 */
4217 AuthCache.prototype.setItemCookie = function (cName, cValue, expires) {
4218 _super.prototype.setItemCookie.call(this, this.generateCacheKey(cName, true), cValue, expires);
4219 if (this.rollbackEnabled) {
4220 _super.prototype.setItemCookie.call(this, this.generateCacheKey(cName, false), cValue, expires);
4221 }
4222 };
4223 AuthCache.prototype.clearItemCookie = function (cName) {
4224 _super.prototype.clearItemCookie.call(this, this.generateCacheKey(cName, true));
4225 if (this.rollbackEnabled) {
4226 _super.prototype.clearItemCookie.call(this, this.generateCacheKey(cName, false));
4227 }
4228 };
4229 /**
4230 * get one item by key from cookies
4231 * @param cName
4232 */
4233 AuthCache.prototype.getItemCookie = function (cName) {
4234 return _super.prototype.getItemCookie.call(this, this.generateCacheKey(cName, true));
4235 };
4236 /**
4237 * Get all tokens of a certain type from the cache
4238 * @param clientId
4239 * @param homeAccountIdentifier
4240 * @param tokenType
4241 */
4242 AuthCache.prototype.getAllTokensByType = function (clientId, homeAccountIdentifier, tokenType) {
4243 var _this = this;
4244 var results = Object.keys(window[this.cacheLocation]).reduce(function (tokens, key) {
4245 var matchedTokenKey = _this.matchKeyForType(key, clientId, homeAccountIdentifier, tokenType);
4246 if (matchedTokenKey) {
4247 var value = _this.getItem(key);
4248 if (value) {
4249 try {
4250 var newAccessTokenCacheItem = new AccessTokenCacheItem_1.AccessTokenCacheItem(matchedTokenKey, JSON.parse(value));
4251 return tokens.concat([newAccessTokenCacheItem]);
4252 }
4253 catch (err) {
4254 // Skip cache items with non-valid JSON values
4255 return tokens;
4256 }
4257 }
4258 }
4259 return tokens;
4260 }, []);
4261 return results;
4262 };
4263 /**
4264 * Get all access tokens in the cache
4265 * @param clientId
4266 * @param homeAccountIdentifier
4267 */
4268 AuthCache.prototype.getAllAccessTokens = function (clientId, homeAccountIdentifier) {
4269 return this.getAllTokensByType(clientId, homeAccountIdentifier, Constants_1.ServerHashParamKeys.ACCESS_TOKEN);
4270 };
4271 /**
4272 * Get all id tokens in the cache in the form of AccessTokenCacheItem objects so they are
4273 * in a normalized format and can make use of the existing cached access token validation logic
4274 */
4275 AuthCache.prototype.getAllIdTokens = function (clientId, homeAccountIdentifier) {
4276 return this.getAllTokensByType(clientId, homeAccountIdentifier, Constants_1.ServerHashParamKeys.ID_TOKEN);
4277 };
4278 /**
4279 * Get all access and ID tokens in the cache
4280 * @param clientId
4281 * @param homeAccountIdentifier
4282 */
4283 AuthCache.prototype.getAllTokens = function (clientId, homeAccountIdentifier) {
4284 var accessTokens = this.getAllAccessTokens(clientId, homeAccountIdentifier);
4285 var idTokens = this.getAllIdTokens(clientId, homeAccountIdentifier);
4286 return tslib_1.__spreadArrays(accessTokens, idTokens);
4287 };
4288 /**
4289 * Returns whether or not interaction is currently in progress. Optionally scope it to just this clientId
4290 * @param forThisClient
4291 */
4292 AuthCache.prototype.isInteractionInProgress = function (matchClientId) {
4293 var clientId = this.getInteractionInProgress();
4294 if (matchClientId) {
4295 return clientId === this.clientId;
4296 }
4297 else {
4298 return !!clientId;
4299 }
4300 };
4301 /**
4302 * Returns the clientId of the interaction currently in progress
4303 */
4304 AuthCache.prototype.getInteractionInProgress = function () {
4305 return this.getTemporaryItem(this.generateCacheKey(Constants_1.TemporaryCacheKeys.INTERACTION_STATUS, false));
4306 };
4307 /**
4308 * Sets interaction in progress state
4309 * @param isInProgress
4310 */
4311 AuthCache.prototype.setInteractionInProgress = function (newInProgressValue) {
4312 if (newInProgressValue) {
4313 if (this.isInteractionInProgress(false)) {
4314 throw ClientAuthError_1.ClientAuthError.createAcquireTokenInProgressError();
4315 }
4316 else {
4317 // Ensure we don't overwrite interaction in progress for a different clientId
4318 this.setTemporaryItem(this.generateCacheKey(Constants_1.TemporaryCacheKeys.INTERACTION_STATUS, false), this.clientId);
4319 }
4320 }
4321 else if (!newInProgressValue && this.isInteractionInProgress(true)) {
4322 // Only remove if the current in progress interaction is for this clientId
4323 this.removeItem(this.generateCacheKey(Constants_1.TemporaryCacheKeys.INTERACTION_STATUS, false));
4324 }
4325 };
4326 /**
4327 * Return if the token renewal is still in progress
4328 *
4329 * @param stateValue
4330 */
4331 AuthCache.prototype.tokenRenewalInProgress = function (stateValue) {
4332 var renewStatus = this.getItem(AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.RENEW_STATUS, stateValue));
4333 return !!(renewStatus && renewStatus === Constants_1.Constants.inProgress);
4334 };
4335 /**
4336 * Clear all cookies
4337 */
4338 AuthCache.prototype.clearMsalCookie = function (state) {
4339 var _this = this;
4340 /*
4341 * If state is truthy, remove values associated with that request.
4342 * Otherwise, remove all MSAL cookies.
4343 */
4344 if (state) {
4345 this.clearItemCookie(AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.NONCE_IDTOKEN, state));
4346 this.clearItemCookie(AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.STATE_LOGIN, state));
4347 this.clearItemCookie(AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.LOGIN_REQUEST, state));
4348 this.clearItemCookie(AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.STATE_ACQ_TOKEN, state));
4349 }
4350 else {
4351 var cookies = document.cookie.split(";");
4352 cookies.forEach(function (cookieString) {
4353 var cookieName = cookieString.trim().split("=")[0];
4354 if (cookieName.indexOf(Constants_1.Constants.cachePrefix) > -1) {
4355 _super.prototype.clearItemCookie.call(_this, cookieName);
4356 }
4357 });
4358 }
4359 };
4360 /**
4361 * Create acquireTokenAccountKey to cache account object
4362 * @param accountId
4363 * @param state
4364 */
4365 AuthCache.generateAcquireTokenAccountKey = function (accountId, state) {
4366 var stateId = RequestUtils_1.RequestUtils.parseLibraryState(state).id;
4367 return "" + Constants_1.TemporaryCacheKeys.ACQUIRE_TOKEN_ACCOUNT + Constants_1.Constants.resourceDelimiter + accountId + Constants_1.Constants.resourceDelimiter + stateId;
4368 };
4369 /**
4370 * Create authorityKey to cache authority
4371 * @param state
4372 */
4373 AuthCache.generateAuthorityKey = function (state) {
4374 return AuthCache.generateTemporaryCacheKey(Constants_1.TemporaryCacheKeys.AUTHORITY, state);
4375 };
4376 /**
4377 * Generates the cache key for temporary cache items, using request state
4378 * @param tempCacheKey Cache key prefix
4379 * @param state Request state value
4380 */
4381 AuthCache.generateTemporaryCacheKey = function (tempCacheKey, state) {
4382 // Use the state id (a guid), in the interest of shorter key names, which is important for cookies.
4383 var stateId = RequestUtils_1.RequestUtils.parseLibraryState(state).id;
4384 return "" + tempCacheKey + Constants_1.Constants.resourceDelimiter + stateId;
4385 };
4386 return AuthCache;
4387}(BrowserStorage_1.BrowserStorage));
4388exports.AuthCache = AuthCache;
4389
4390
4391/***/ }),
4392
4393/***/ 96:
4394/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
4395
4396
4397/*
4398 * Copyright (c) Microsoft Corporation. All rights reserved.
4399 * Licensed under the MIT License.
4400 */
4401Object.defineProperty(exports, "__esModule", ({ value: true }));
4402exports.BrowserStorage = void 0;
4403var ClientConfigurationError_1 = __webpack_require__(550);
4404var AuthError_1 = __webpack_require__(986);
4405/**
4406 * @hidden
4407 */
4408var BrowserStorage = /** @class */ (function () {
4409 function BrowserStorage(cacheLocation) {
4410 if (!window) {
4411 throw AuthError_1.AuthError.createNoWindowObjectError("Browser storage class could not find window object");
4412 }
4413 var storageSupported = typeof window[cacheLocation] !== "undefined" && window[cacheLocation] !== null;
4414 if (!storageSupported) {
4415 throw ClientConfigurationError_1.ClientConfigurationError.createStorageNotSupportedError(cacheLocation);
4416 }
4417 this.cacheLocation = cacheLocation;
4418 }
4419 /**
4420 * add value to storage
4421 * @param key
4422 * @param value
4423 * @param enableCookieStorage
4424 */
4425 BrowserStorage.prototype.setItem = function (key, value, enableCookieStorage) {
4426 window[this.cacheLocation].setItem(key, value);
4427 if (enableCookieStorage) {
4428 this.setItemCookie(key, value);
4429 }
4430 };
4431 /**
4432 * get one item by key from storage
4433 * @param key
4434 * @param enableCookieStorage
4435 */
4436 BrowserStorage.prototype.getItem = function (key, enableCookieStorage) {
4437 if (enableCookieStorage && this.getItemCookie(key)) {
4438 return this.getItemCookie(key);
4439 }
4440 return window[this.cacheLocation].getItem(key);
4441 };
4442 /**
4443 * remove value from storage
4444 * @param key
4445 */
4446 BrowserStorage.prototype.removeItem = function (key) {
4447 return window[this.cacheLocation].removeItem(key);
4448 };
4449 /**
4450 * clear storage (remove all items from it)
4451 */
4452 BrowserStorage.prototype.clear = function () {
4453 return window[this.cacheLocation].clear();
4454 };
4455 /**
4456 * add value to cookies
4457 * @param cName
4458 * @param cValue
4459 * @param expires
4460 */
4461 BrowserStorage.prototype.setItemCookie = function (cName, cValue, expires) {
4462 var cookieStr = encodeURIComponent(cName) + "=" + encodeURIComponent(cValue) + ";path=/;";
4463 if (expires) {
4464 var expireTime = this.getCookieExpirationTime(expires);
4465 cookieStr += "expires=" + expireTime + ";";
4466 }
4467 document.cookie = cookieStr;
4468 };
4469 /**
4470 * get one item by key from cookies
4471 * @param cName
4472 */
4473 BrowserStorage.prototype.getItemCookie = function (cName) {
4474 var name = encodeURIComponent(cName) + "=";
4475 var ca = document.cookie.split(";");
4476 for (var i = 0; i < ca.length; i++) {
4477 var c = ca[i];
4478 while (c.charAt(0) === " ") {
4479 c = c.substring(1);
4480 }
4481 if (c.indexOf(name) === 0) {
4482 return decodeURIComponent(c.substring(name.length, c.length));
4483 }
4484 }
4485 return "";
4486 };
4487 /**
4488 * Clear an item in the cookies by key
4489 * @param cName
4490 */
4491 BrowserStorage.prototype.clearItemCookie = function (cName) {
4492 this.setItemCookie(cName, "", -1);
4493 };
4494 /**
4495 * Get cookie expiration time
4496 * @param cookieLifeDays
4497 */
4498 BrowserStorage.prototype.getCookieExpirationTime = function (cookieLifeDays) {
4499 var today = new Date();
4500 var expr = new Date(today.getTime() + cookieLifeDays * 24 * 60 * 60 * 1000);
4501 return expr.toUTCString();
4502 };
4503 return BrowserStorage;
4504}());
4505exports.BrowserStorage = BrowserStorage;
4506
4507
4508/***/ }),
4509
4510/***/ 986:
4511/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
4512
4513
4514/*
4515 * Copyright (c) Microsoft Corporation. All rights reserved.
4516 * Licensed under the MIT License.
4517 */
4518Object.defineProperty(exports, "__esModule", ({ value: true }));
4519exports.AuthError = exports.AuthErrorMessage = void 0;
4520var tslib_1 = __webpack_require__(795);
4521exports.AuthErrorMessage = {
4522 unexpectedError: {
4523 code: "unexpected_error",
4524 desc: "Unexpected error in authentication."
4525 },
4526 noWindowObjectError: {
4527 code: "no_window_object",
4528 desc: "No window object available. Details:"
4529 }
4530};
4531/**
4532 * General error class thrown by the MSAL.js library.
4533 */
4534var AuthError = /** @class */ (function (_super) {
4535 tslib_1.__extends(AuthError, _super);
4536 function AuthError(errorCode, errorMessage) {
4537 var _this = _super.call(this, errorMessage) || this;
4538 Object.setPrototypeOf(_this, AuthError.prototype);
4539 _this.errorCode = errorCode;
4540 _this.errorMessage = errorMessage;
4541 _this.name = "AuthError";
4542 return _this;
4543 }
4544 AuthError.createUnexpectedError = function (errDesc) {
4545 return new AuthError(exports.AuthErrorMessage.unexpectedError.code, exports.AuthErrorMessage.unexpectedError.desc + ": " + errDesc);
4546 };
4547 AuthError.createNoWindowObjectError = function (errDesc) {
4548 return new AuthError(exports.AuthErrorMessage.noWindowObjectError.code, exports.AuthErrorMessage.noWindowObjectError.desc + " " + errDesc);
4549 };
4550 return AuthError;
4551}(Error));
4552exports.AuthError = AuthError;
4553
4554
4555/***/ }),
4556
4557/***/ 356:
4558/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
4559
4560
4561/*
4562 * Copyright (c) Microsoft Corporation. All rights reserved.
4563 * Licensed under the MIT License.
4564 */
4565Object.defineProperty(exports, "__esModule", ({ value: true }));
4566exports.ClientAuthError = exports.ClientAuthErrorMessage = void 0;
4567var tslib_1 = __webpack_require__(795);
4568var AuthError_1 = __webpack_require__(986);
4569var StringUtils_1 = __webpack_require__(454);
4570exports.ClientAuthErrorMessage = {
4571 endpointResolutionError: {
4572 code: "endpoints_resolution_error",
4573 desc: "Error: could not resolve endpoints. Please check network and try again."
4574 },
4575 popUpWindowError: {
4576 code: "popup_window_error",
4577 desc: "Error opening popup window. This can happen if you are using IE or if popups are blocked in the browser."
4578 },
4579 tokenRenewalError: {
4580 code: "token_renewal_error",
4581 desc: "Token renewal operation failed due to timeout."
4582 },
4583 invalidIdToken: {
4584 code: "invalid_id_token",
4585 desc: "Invalid ID token format."
4586 },
4587 invalidStateError: {
4588 code: "invalid_state_error",
4589 desc: "Invalid state."
4590 },
4591 nonceMismatchError: {
4592 code: "nonce_mismatch_error",
4593 desc: "Nonce is not matching, Nonce received: "
4594 },
4595 loginProgressError: {
4596 code: "login_progress_error",
4597 desc: "Login_In_Progress: Error during login call - login is already in progress."
4598 },
4599 acquireTokenProgressError: {
4600 code: "acquiretoken_progress_error",
4601 desc: "AcquireToken_In_Progress: Error during login call - login is already in progress."
4602 },
4603 userCancelledError: {
4604 code: "user_cancelled",
4605 desc: "User cancelled the flow."
4606 },
4607 callbackError: {
4608 code: "callback_error",
4609 desc: "Error occurred in token received callback function."
4610 },
4611 userLoginRequiredError: {
4612 code: "user_login_error",
4613 desc: "User login is required. For silent calls, request must contain either sid or login_hint"
4614 },
4615 userDoesNotExistError: {
4616 code: "user_non_existent",
4617 desc: "User object does not exist. Please call a login API."
4618 },
4619 clientInfoDecodingError: {
4620 code: "client_info_decoding_error",
4621 desc: "The client info could not be parsed/decoded correctly. Please review the trace to determine the root cause."
4622 },
4623 clientInfoNotPopulatedError: {
4624 code: "client_info_not_populated_error",
4625 desc: "The service did not populate client_info in the response, Please verify with the service team"
4626 },
4627 nullOrEmptyIdToken: {
4628 code: "null_or_empty_id_token",
4629 desc: "The idToken is null or empty. Please review the trace to determine the root cause."
4630 },
4631 idTokenNotParsed: {
4632 code: "id_token_parsing_error",
4633 desc: "ID token cannot be parsed. Please review stack trace to determine root cause."
4634 },
4635 tokenEncodingError: {
4636 code: "token_encoding_error",
4637 desc: "The token to be decoded is not encoded correctly."
4638 },
4639 invalidInteractionType: {
4640 code: "invalid_interaction_type",
4641 desc: "The interaction type passed to the handler was incorrect or unknown"
4642 },
4643 cacheParseError: {
4644 code: "cannot_parse_cache",
4645 desc: "The cached token key is not a valid JSON and cannot be parsed"
4646 },
4647 blockTokenRequestsInHiddenIframe: {
4648 code: "block_token_requests",
4649 desc: "Token calls are blocked in hidden iframes"
4650 }
4651};
4652/**
4653 * Error thrown when there is an error in the client code running on the browser.
4654 */
4655var ClientAuthError = /** @class */ (function (_super) {
4656 tslib_1.__extends(ClientAuthError, _super);
4657 function ClientAuthError(errorCode, errorMessage) {
4658 var _this = _super.call(this, errorCode, errorMessage) || this;
4659 _this.name = "ClientAuthError";
4660 Object.setPrototypeOf(_this, ClientAuthError.prototype);
4661 return _this;
4662 }
4663 ClientAuthError.createEndpointResolutionError = function (errDetail) {
4664 var errorMessage = exports.ClientAuthErrorMessage.endpointResolutionError.desc;
4665 if (errDetail && !StringUtils_1.StringUtils.isEmpty(errDetail)) {
4666 errorMessage += " Details: " + errDetail;
4667 }
4668 return new ClientAuthError(exports.ClientAuthErrorMessage.endpointResolutionError.code, errorMessage);
4669 };
4670 ClientAuthError.createPopupWindowError = function (errDetail) {
4671 var errorMessage = exports.ClientAuthErrorMessage.popUpWindowError.desc;
4672 if (errDetail && !StringUtils_1.StringUtils.isEmpty(errDetail)) {
4673 errorMessage += " Details: " + errDetail;
4674 }
4675 return new ClientAuthError(exports.ClientAuthErrorMessage.popUpWindowError.code, errorMessage);
4676 };
4677 ClientAuthError.createTokenRenewalTimeoutError = function () {
4678 return new ClientAuthError(exports.ClientAuthErrorMessage.tokenRenewalError.code, exports.ClientAuthErrorMessage.tokenRenewalError.desc);
4679 };
4680 ClientAuthError.createInvalidIdTokenError = function (idToken) {
4681 return new ClientAuthError(exports.ClientAuthErrorMessage.invalidIdToken.code, exports.ClientAuthErrorMessage.invalidIdToken.desc + " Given token: " + idToken);
4682 };
4683 // TODO: Is this not a security flaw to send the user the state expected??
4684 ClientAuthError.createInvalidStateError = function (invalidState, actualState) {
4685 return new ClientAuthError(exports.ClientAuthErrorMessage.invalidStateError.code, exports.ClientAuthErrorMessage.invalidStateError.desc + " " + invalidState + ", state expected : " + actualState + ".");
4686 };
4687 // TODO: Is this not a security flaw to send the user the Nonce expected??
4688 ClientAuthError.createNonceMismatchError = function (invalidNonce, actualNonce) {
4689 return new ClientAuthError(exports.ClientAuthErrorMessage.nonceMismatchError.code, exports.ClientAuthErrorMessage.nonceMismatchError.desc + " " + invalidNonce + ", nonce expected : " + actualNonce + ".");
4690 };
4691 ClientAuthError.createLoginInProgressError = function () {
4692 return new ClientAuthError(exports.ClientAuthErrorMessage.loginProgressError.code, exports.ClientAuthErrorMessage.loginProgressError.desc);
4693 };
4694 ClientAuthError.createAcquireTokenInProgressError = function () {
4695 return new ClientAuthError(exports.ClientAuthErrorMessage.acquireTokenProgressError.code, exports.ClientAuthErrorMessage.acquireTokenProgressError.desc);
4696 };
4697 ClientAuthError.createUserCancelledError = function () {
4698 return new ClientAuthError(exports.ClientAuthErrorMessage.userCancelledError.code, exports.ClientAuthErrorMessage.userCancelledError.desc);
4699 };
4700 ClientAuthError.createErrorInCallbackFunction = function (errorDesc) {
4701 return new ClientAuthError(exports.ClientAuthErrorMessage.callbackError.code, exports.ClientAuthErrorMessage.callbackError.desc + " " + errorDesc + ".");
4702 };
4703 ClientAuthError.createUserLoginRequiredError = function () {
4704 return new ClientAuthError(exports.ClientAuthErrorMessage.userLoginRequiredError.code, exports.ClientAuthErrorMessage.userLoginRequiredError.desc);
4705 };
4706 ClientAuthError.createUserDoesNotExistError = function () {
4707 return new ClientAuthError(exports.ClientAuthErrorMessage.userDoesNotExistError.code, exports.ClientAuthErrorMessage.userDoesNotExistError.desc);
4708 };
4709 ClientAuthError.createClientInfoDecodingError = function (caughtError) {
4710 return new ClientAuthError(exports.ClientAuthErrorMessage.clientInfoDecodingError.code, exports.ClientAuthErrorMessage.clientInfoDecodingError.desc + " Failed with error: " + caughtError);
4711 };
4712 ClientAuthError.createClientInfoNotPopulatedError = function (caughtError) {
4713 return new ClientAuthError(exports.ClientAuthErrorMessage.clientInfoNotPopulatedError.code, exports.ClientAuthErrorMessage.clientInfoNotPopulatedError.desc + " Failed with error: " + caughtError);
4714 };
4715 ClientAuthError.createIdTokenNullOrEmptyError = function (invalidRawTokenString) {
4716 return new ClientAuthError(exports.ClientAuthErrorMessage.nullOrEmptyIdToken.code, exports.ClientAuthErrorMessage.nullOrEmptyIdToken.desc + " Raw ID Token Value: " + invalidRawTokenString);
4717 };
4718 ClientAuthError.createIdTokenParsingError = function (caughtParsingError) {
4719 return new ClientAuthError(exports.ClientAuthErrorMessage.idTokenNotParsed.code, exports.ClientAuthErrorMessage.idTokenNotParsed.desc + " Failed with error: " + caughtParsingError);
4720 };
4721 ClientAuthError.createTokenEncodingError = function (incorrectlyEncodedToken) {
4722 return new ClientAuthError(exports.ClientAuthErrorMessage.tokenEncodingError.code, exports.ClientAuthErrorMessage.tokenEncodingError.desc + " Attempted to decode: " + incorrectlyEncodedToken);
4723 };
4724 ClientAuthError.createInvalidInteractionTypeError = function () {
4725 return new ClientAuthError(exports.ClientAuthErrorMessage.invalidInteractionType.code, exports.ClientAuthErrorMessage.invalidInteractionType.desc);
4726 };
4727 ClientAuthError.createCacheParseError = function (key) {
4728 var errorMessage = "invalid key: " + key + ", " + exports.ClientAuthErrorMessage.cacheParseError.desc;
4729 return new ClientAuthError(exports.ClientAuthErrorMessage.cacheParseError.code, errorMessage);
4730 };
4731 ClientAuthError.createBlockTokenRequestsInHiddenIframeError = function () {
4732 return new ClientAuthError(exports.ClientAuthErrorMessage.blockTokenRequestsInHiddenIframe.code, exports.ClientAuthErrorMessage.blockTokenRequestsInHiddenIframe.desc);
4733 };
4734 return ClientAuthError;
4735}(AuthError_1.AuthError));
4736exports.ClientAuthError = ClientAuthError;
4737
4738
4739/***/ }),
4740
4741/***/ 550:
4742/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
4743
4744
4745/*
4746 * Copyright (c) Microsoft Corporation. All rights reserved.
4747 * Licensed under the MIT License.
4748 */
4749Object.defineProperty(exports, "__esModule", ({ value: true }));
4750exports.ClientConfigurationError = exports.ClientConfigurationErrorMessage = void 0;
4751var tslib_1 = __webpack_require__(795);
4752var ClientAuthError_1 = __webpack_require__(356);
4753exports.ClientConfigurationErrorMessage = {
4754 configurationNotSet: {
4755 code: "no_config_set",
4756 desc: "Configuration has not been set. Please call the UserAgentApplication constructor with a valid Configuration object."
4757 },
4758 storageNotSupported: {
4759 code: "storage_not_supported",
4760 desc: "The value for the cacheLocation is not supported."
4761 },
4762 noRedirectCallbacksSet: {
4763 code: "no_redirect_callbacks",
4764 desc: "No redirect callbacks have been set. Please call handleRedirectCallback() with the appropriate function arguments before continuing. " +
4765 "More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics."
4766 },
4767 invalidCallbackObject: {
4768 code: "invalid_callback_object",
4769 desc: "The object passed for the callback was invalid. " +
4770 "More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics."
4771 },
4772 scopesRequired: {
4773 code: "scopes_required",
4774 desc: "Scopes are required to obtain an access token."
4775 },
4776 emptyScopes: {
4777 code: "empty_input_scopes_error",
4778 desc: "Scopes cannot be passed as empty array."
4779 },
4780 nonArrayScopes: {
4781 code: "nonarray_input_scopes_error",
4782 desc: "Scopes cannot be passed as non-array."
4783 },
4784 invalidPrompt: {
4785 code: "invalid_prompt_value",
4786 desc: "Supported prompt values are 'login', 'select_account', 'consent' and 'none'",
4787 },
4788 invalidAuthorityType: {
4789 code: "invalid_authority_type",
4790 desc: "The given authority is not a valid type of authority supported by MSAL. Please see here for valid authorities: <insert URL here>."
4791 },
4792 authorityUriInsecure: {
4793 code: "authority_uri_insecure",
4794 desc: "Authority URIs must use https."
4795 },
4796 authorityUriInvalidPath: {
4797 code: "authority_uri_invalid_path",
4798 desc: "Given authority URI is invalid."
4799 },
4800 unsupportedAuthorityValidation: {
4801 code: "unsupported_authority_validation",
4802 desc: "The authority validation is not supported for this authority type."
4803 },
4804 untrustedAuthority: {
4805 code: "untrusted_authority",
4806 desc: "The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter or set validateAuthority=false."
4807 },
4808 b2cAuthorityUriInvalidPath: {
4809 code: "b2c_authority_uri_invalid_path",
4810 desc: "The given URI for the B2C authority is invalid."
4811 },
4812 b2cKnownAuthoritiesNotSet: {
4813 code: "b2c_known_authorities_not_set",
4814 desc: "Must set known authorities when validateAuthority is set to True and using B2C"
4815 },
4816 claimsRequestParsingError: {
4817 code: "claims_request_parsing_error",
4818 desc: "Could not parse the given claims request object."
4819 },
4820 emptyRequestError: {
4821 code: "empty_request_error",
4822 desc: "Request object is required."
4823 },
4824 invalidCorrelationIdError: {
4825 code: "invalid_guid_sent_as_correlationId",
4826 desc: "Please set the correlationId as a valid guid"
4827 },
4828 telemetryConfigError: {
4829 code: "telemetry_config_error",
4830 desc: "Telemetry config is not configured with required values"
4831 },
4832 ssoSilentError: {
4833 code: "sso_silent_error",
4834 desc: "request must contain either sid or login_hint"
4835 },
4836 invalidAuthorityMetadataError: {
4837 code: "authority_metadata_error",
4838 desc: "Invalid authorityMetadata. Must be a JSON object containing authorization_endpoint, end_session_endpoint, and issuer fields."
4839 }
4840};
4841/**
4842 * Error thrown when there is an error in configuration of the .js library.
4843 */
4844var ClientConfigurationError = /** @class */ (function (_super) {
4845 tslib_1.__extends(ClientConfigurationError, _super);
4846 function ClientConfigurationError(errorCode, errorMessage) {
4847 var _this = _super.call(this, errorCode, errorMessage) || this;
4848 _this.name = "ClientConfigurationError";
4849 Object.setPrototypeOf(_this, ClientConfigurationError.prototype);
4850 return _this;
4851 }
4852 ClientConfigurationError.createNoSetConfigurationError = function () {
4853 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.configurationNotSet.code, "" + exports.ClientConfigurationErrorMessage.configurationNotSet.desc);
4854 };
4855 ClientConfigurationError.createStorageNotSupportedError = function (givenCacheLocation) {
4856 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.storageNotSupported.code, exports.ClientConfigurationErrorMessage.storageNotSupported.desc + " Given location: " + givenCacheLocation);
4857 };
4858 ClientConfigurationError.createRedirectCallbacksNotSetError = function () {
4859 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.noRedirectCallbacksSet.code, exports.ClientConfigurationErrorMessage.noRedirectCallbacksSet.desc);
4860 };
4861 ClientConfigurationError.createInvalidCallbackObjectError = function (callbackObject) {
4862 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.invalidCallbackObject.code, exports.ClientConfigurationErrorMessage.invalidCallbackObject.desc + " Given value for callback function: " + callbackObject);
4863 };
4864 ClientConfigurationError.createEmptyScopesArrayError = function (scopesValue) {
4865 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.emptyScopes.code, exports.ClientConfigurationErrorMessage.emptyScopes.desc + " Given value: " + scopesValue + ".");
4866 };
4867 ClientConfigurationError.createScopesNonArrayError = function (scopesValue) {
4868 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.nonArrayScopes.code, exports.ClientConfigurationErrorMessage.nonArrayScopes.desc + " Given value: " + scopesValue + ".");
4869 };
4870 ClientConfigurationError.createScopesRequiredError = function (scopesValue) {
4871 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.scopesRequired.code, exports.ClientConfigurationErrorMessage.scopesRequired.desc + " Given value: " + scopesValue);
4872 };
4873 ClientConfigurationError.createInvalidPromptError = function (promptValue) {
4874 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.invalidPrompt.code, exports.ClientConfigurationErrorMessage.invalidPrompt.desc + " Given value: " + promptValue);
4875 };
4876 ClientConfigurationError.createClaimsRequestParsingError = function (claimsRequestParseError) {
4877 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.claimsRequestParsingError.code, exports.ClientConfigurationErrorMessage.claimsRequestParsingError.desc + " Given value: " + claimsRequestParseError);
4878 };
4879 ClientConfigurationError.createEmptyRequestError = function () {
4880 var _a = exports.ClientConfigurationErrorMessage.emptyRequestError, code = _a.code, desc = _a.desc;
4881 return new ClientConfigurationError(code, desc);
4882 };
4883 ClientConfigurationError.createInvalidCorrelationIdError = function () {
4884 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.invalidCorrelationIdError.code, exports.ClientConfigurationErrorMessage.invalidCorrelationIdError.desc);
4885 };
4886 ClientConfigurationError.createKnownAuthoritiesNotSetError = function () {
4887 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.b2cKnownAuthoritiesNotSet.code, exports.ClientConfigurationErrorMessage.b2cKnownAuthoritiesNotSet.desc);
4888 };
4889 ClientConfigurationError.createInvalidAuthorityTypeError = function () {
4890 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.invalidAuthorityType.code, exports.ClientConfigurationErrorMessage.invalidAuthorityType.desc);
4891 };
4892 ClientConfigurationError.createUntrustedAuthorityError = function (host) {
4893 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.untrustedAuthority.code, exports.ClientConfigurationErrorMessage.untrustedAuthority.desc + " Provided Authority: " + host);
4894 };
4895 ClientConfigurationError.createTelemetryConfigError = function (config) {
4896 var _a = exports.ClientConfigurationErrorMessage.telemetryConfigError, code = _a.code, desc = _a.desc;
4897 var requiredKeys = {
4898 applicationName: "string",
4899 applicationVersion: "string",
4900 telemetryEmitter: "function"
4901 };
4902 var missingKeys = Object.keys(requiredKeys)
4903 .reduce(function (keys, key) {
4904 return config[key] ? keys : keys.concat([key + " (" + requiredKeys[key] + ")"]);
4905 }, []);
4906 return new ClientConfigurationError(code, desc + " mising values: " + missingKeys.join(","));
4907 };
4908 ClientConfigurationError.createSsoSilentError = function () {
4909 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.ssoSilentError.code, exports.ClientConfigurationErrorMessage.ssoSilentError.desc);
4910 };
4911 ClientConfigurationError.createInvalidAuthorityMetadataError = function () {
4912 return new ClientConfigurationError(exports.ClientConfigurationErrorMessage.invalidAuthorityMetadataError.code, exports.ClientConfigurationErrorMessage.invalidAuthorityMetadataError.desc);
4913 };
4914 return ClientConfigurationError;
4915}(ClientAuthError_1.ClientAuthError));
4916exports.ClientConfigurationError = ClientConfigurationError;
4917
4918
4919/***/ }),
4920
4921/***/ 961:
4922/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
4923
4924
4925/*
4926 * Copyright (c) Microsoft Corporation. All rights reserved.
4927 * Licensed under the MIT License.
4928 */
4929Object.defineProperty(exports, "__esModule", ({ value: true }));
4930exports.InteractionRequiredAuthError = exports.InteractionRequiredAuthErrorMessage = void 0;
4931var tslib_1 = __webpack_require__(795);
4932var ServerError_1 = __webpack_require__(447);
4933exports.InteractionRequiredAuthErrorMessage = {
4934 interactionRequired: {
4935 code: "interaction_required"
4936 },
4937 consentRequired: {
4938 code: "consent_required"
4939 },
4940 loginRequired: {
4941 code: "login_required"
4942 },
4943};
4944/**
4945 * Error thrown when the user is required to perform an interactive token request.
4946 */
4947var InteractionRequiredAuthError = /** @class */ (function (_super) {
4948 tslib_1.__extends(InteractionRequiredAuthError, _super);
4949 function InteractionRequiredAuthError(errorCode, errorMessage) {
4950 var _this = _super.call(this, errorCode, errorMessage) || this;
4951 _this.name = "InteractionRequiredAuthError";
4952 Object.setPrototypeOf(_this, InteractionRequiredAuthError.prototype);
4953 return _this;
4954 }
4955 InteractionRequiredAuthError.isInteractionRequiredError = function (errorString) {
4956 var interactionRequiredCodes = [
4957 exports.InteractionRequiredAuthErrorMessage.interactionRequired.code,
4958 exports.InteractionRequiredAuthErrorMessage.consentRequired.code,
4959 exports.InteractionRequiredAuthErrorMessage.loginRequired.code
4960 ];
4961 return errorString && interactionRequiredCodes.indexOf(errorString) > -1;
4962 };
4963 InteractionRequiredAuthError.createLoginRequiredAuthError = function (errorDesc) {
4964 return new InteractionRequiredAuthError(exports.InteractionRequiredAuthErrorMessage.loginRequired.code, errorDesc);
4965 };
4966 InteractionRequiredAuthError.createInteractionRequiredAuthError = function (errorDesc) {
4967 return new InteractionRequiredAuthError(exports.InteractionRequiredAuthErrorMessage.interactionRequired.code, errorDesc);
4968 };
4969 InteractionRequiredAuthError.createConsentRequiredAuthError = function (errorDesc) {
4970 return new InteractionRequiredAuthError(exports.InteractionRequiredAuthErrorMessage.consentRequired.code, errorDesc);
4971 };
4972 return InteractionRequiredAuthError;
4973}(ServerError_1.ServerError));
4974exports.InteractionRequiredAuthError = InteractionRequiredAuthError;
4975
4976
4977/***/ }),
4978
4979/***/ 447:
4980/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
4981
4982
4983/*
4984 * Copyright (c) Microsoft Corporation. All rights reserved.
4985 * Licensed under the MIT License.
4986 */
4987Object.defineProperty(exports, "__esModule", ({ value: true }));
4988exports.ServerError = exports.ServerErrorMessage = void 0;
4989var tslib_1 = __webpack_require__(795);
4990var AuthError_1 = __webpack_require__(986);
4991exports.ServerErrorMessage = {
4992 serverUnavailable: {
4993 code: "server_unavailable",
4994 desc: "Server is temporarily unavailable."
4995 },
4996 unknownServerError: {
4997 code: "unknown_server_error"
4998 },
4999};
5000/**
5001 * Error thrown when there is an error with the server code, for example, unavailability.
5002 */
5003var ServerError = /** @class */ (function (_super) {
5004 tslib_1.__extends(ServerError, _super);
5005 function ServerError(errorCode, errorMessage) {
5006 var _this = _super.call(this, errorCode, errorMessage) || this;
5007 _this.name = "ServerError";
5008 Object.setPrototypeOf(_this, ServerError.prototype);
5009 return _this;
5010 }
5011 ServerError.createServerUnavailableError = function () {
5012 return new ServerError(exports.ServerErrorMessage.serverUnavailable.code, exports.ServerErrorMessage.serverUnavailable.desc);
5013 };
5014 ServerError.createUnknownServerError = function (errorDesc) {
5015 return new ServerError(exports.ServerErrorMessage.unknownServerError.code, errorDesc);
5016 };
5017 return ServerError;
5018}(AuthError_1.AuthError));
5019exports.ServerError = ServerError;
5020
5021
5022/***/ }),
5023
5024/***/ 700:
5025/***/ (function(__unused_webpack_module, exports) {
5026
5027
5028Object.defineProperty(exports, "__esModule", ({ value: true }));
5029exports.version = exports.name = void 0;
5030/* eslint-disable header/header */
5031exports.name = "msal";
5032exports.version = "1.4.18";
5033
5034
5035/***/ }),
5036
5037/***/ 663:
5038/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5039
5040
5041/*
5042 * Copyright (c) Microsoft Corporation. All rights reserved.
5043 * Licensed under the MIT License.
5044 */
5045var _a;
5046Object.defineProperty(exports, "__esModule", ({ value: true }));
5047exports.API_EVENT_IDENTIFIER = exports.API_CODE = exports.EVENT_KEYS = void 0;
5048var tslib_1 = __webpack_require__(795);
5049var TelemetryEvent_1 = tslib_1.__importDefault(__webpack_require__(336));
5050var TelemetryConstants_1 = __webpack_require__(810);
5051var TelemetryUtils_1 = __webpack_require__(847);
5052exports.EVENT_KEYS = {
5053 AUTHORITY: TelemetryUtils_1.prependEventNamePrefix("authority"),
5054 AUTHORITY_TYPE: TelemetryUtils_1.prependEventNamePrefix("authority_type"),
5055 PROMPT: TelemetryUtils_1.prependEventNamePrefix("ui_behavior"),
5056 TENANT_ID: TelemetryUtils_1.prependEventNamePrefix("tenant_id"),
5057 USER_ID: TelemetryUtils_1.prependEventNamePrefix("user_id"),
5058 WAS_SUCESSFUL: TelemetryUtils_1.prependEventNamePrefix("was_successful"),
5059 API_ERROR_CODE: TelemetryUtils_1.prependEventNamePrefix("api_error_code"),
5060 LOGIN_HINT: TelemetryUtils_1.prependEventNamePrefix("login_hint")
5061};
5062var API_CODE;
5063(function (API_CODE) {
5064 API_CODE[API_CODE["AcquireTokenRedirect"] = 2001] = "AcquireTokenRedirect";
5065 API_CODE[API_CODE["AcquireTokenSilent"] = 2002] = "AcquireTokenSilent";
5066 API_CODE[API_CODE["AcquireTokenPopup"] = 2003] = "AcquireTokenPopup";
5067 API_CODE[API_CODE["LoginRedirect"] = 2004] = "LoginRedirect";
5068 API_CODE[API_CODE["LoginPopup"] = 2005] = "LoginPopup";
5069 API_CODE[API_CODE["Logout"] = 2006] = "Logout";
5070})(API_CODE = exports.API_CODE || (exports.API_CODE = {}));
5071var API_EVENT_IDENTIFIER;
5072(function (API_EVENT_IDENTIFIER) {
5073 API_EVENT_IDENTIFIER["AcquireTokenRedirect"] = "AcquireTokenRedirect";
5074 API_EVENT_IDENTIFIER["AcquireTokenSilent"] = "AcquireTokenSilent";
5075 API_EVENT_IDENTIFIER["AcquireTokenPopup"] = "AcquireTokenPopup";
5076 API_EVENT_IDENTIFIER["LoginRedirect"] = "LoginRedirect";
5077 API_EVENT_IDENTIFIER["LoginPopup"] = "LoginPopup";
5078 API_EVENT_IDENTIFIER["Logout"] = "Logout";
5079})(API_EVENT_IDENTIFIER = exports.API_EVENT_IDENTIFIER || (exports.API_EVENT_IDENTIFIER = {}));
5080var mapEventIdentiferToCode = (_a = {},
5081 _a[API_EVENT_IDENTIFIER.AcquireTokenSilent] = API_CODE.AcquireTokenSilent,
5082 _a[API_EVENT_IDENTIFIER.AcquireTokenPopup] = API_CODE.AcquireTokenPopup,
5083 _a[API_EVENT_IDENTIFIER.AcquireTokenRedirect] = API_CODE.AcquireTokenRedirect,
5084 _a[API_EVENT_IDENTIFIER.LoginPopup] = API_CODE.LoginPopup,
5085 _a[API_EVENT_IDENTIFIER.LoginRedirect] = API_CODE.LoginRedirect,
5086 _a[API_EVENT_IDENTIFIER.Logout] = API_CODE.Logout,
5087 _a);
5088var ApiEvent = /** @class */ (function (_super) {
5089 tslib_1.__extends(ApiEvent, _super);
5090 function ApiEvent(correlationId, piiEnabled, apiEventIdentifier) {
5091 var _this = _super.call(this, TelemetryUtils_1.prependEventNamePrefix("api_event"), correlationId, apiEventIdentifier) || this;
5092 if (apiEventIdentifier) {
5093 _this.apiCode = mapEventIdentiferToCode[apiEventIdentifier];
5094 _this.apiEventIdentifier = apiEventIdentifier;
5095 }
5096 _this.piiEnabled = piiEnabled;
5097 return _this;
5098 }
5099 Object.defineProperty(ApiEvent.prototype, "apiEventIdentifier", {
5100 set: function (apiEventIdentifier) {
5101 this.event[TelemetryConstants_1.TELEMETRY_BLOB_EVENT_NAMES.ApiTelemIdConstStrKey] = apiEventIdentifier;
5102 },
5103 enumerable: false,
5104 configurable: true
5105 });
5106 Object.defineProperty(ApiEvent.prototype, "apiCode", {
5107 set: function (apiCode) {
5108 this.event[TelemetryConstants_1.TELEMETRY_BLOB_EVENT_NAMES.ApiIdConstStrKey] = apiCode;
5109 },
5110 enumerable: false,
5111 configurable: true
5112 });
5113 Object.defineProperty(ApiEvent.prototype, "authority", {
5114 set: function (uri) {
5115 this.event[exports.EVENT_KEYS.AUTHORITY] = TelemetryUtils_1.scrubTenantFromUri(uri).toLowerCase();
5116 },
5117 enumerable: false,
5118 configurable: true
5119 });
5120 Object.defineProperty(ApiEvent.prototype, "apiErrorCode", {
5121 set: function (errorCode) {
5122 this.event[exports.EVENT_KEYS.API_ERROR_CODE] = errorCode;
5123 },
5124 enumerable: false,
5125 configurable: true
5126 });
5127 Object.defineProperty(ApiEvent.prototype, "tenantId", {
5128 set: function (tenantId) {
5129 this.event[exports.EVENT_KEYS.TENANT_ID] = this.piiEnabled && tenantId ?
5130 TelemetryUtils_1.hashPersonalIdentifier(tenantId)
5131 : null;
5132 },
5133 enumerable: false,
5134 configurable: true
5135 });
5136 Object.defineProperty(ApiEvent.prototype, "accountId", {
5137 set: function (accountId) {
5138 this.event[exports.EVENT_KEYS.USER_ID] = this.piiEnabled && accountId ?
5139 TelemetryUtils_1.hashPersonalIdentifier(accountId)
5140 : null;
5141 },
5142 enumerable: false,
5143 configurable: true
5144 });
5145 Object.defineProperty(ApiEvent.prototype, "wasSuccessful", {
5146 get: function () {
5147 return this.event[exports.EVENT_KEYS.WAS_SUCESSFUL] === true;
5148 },
5149 set: function (wasSuccessful) {
5150 this.event[exports.EVENT_KEYS.WAS_SUCESSFUL] = wasSuccessful;
5151 },
5152 enumerable: false,
5153 configurable: true
5154 });
5155 Object.defineProperty(ApiEvent.prototype, "loginHint", {
5156 set: function (loginHint) {
5157 this.event[exports.EVENT_KEYS.LOGIN_HINT] = this.piiEnabled && loginHint ?
5158 TelemetryUtils_1.hashPersonalIdentifier(loginHint)
5159 : null;
5160 },
5161 enumerable: false,
5162 configurable: true
5163 });
5164 Object.defineProperty(ApiEvent.prototype, "authorityType", {
5165 set: function (authorityType) {
5166 this.event[exports.EVENT_KEYS.AUTHORITY_TYPE] = authorityType.toLowerCase();
5167 },
5168 enumerable: false,
5169 configurable: true
5170 });
5171 Object.defineProperty(ApiEvent.prototype, "promptType", {
5172 set: function (promptType) {
5173 this.event[exports.EVENT_KEYS.PROMPT] = promptType.toLowerCase();
5174 },
5175 enumerable: false,
5176 configurable: true
5177 });
5178 return ApiEvent;
5179}(TelemetryEvent_1.default));
5180exports["default"] = ApiEvent;
5181
5182
5183/***/ }),
5184
5185/***/ 868:
5186/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5187
5188
5189/*
5190 * Copyright (c) Microsoft Corporation. All rights reserved.
5191 * Licensed under the MIT License.
5192 */
5193Object.defineProperty(exports, "__esModule", ({ value: true }));
5194var tslib_1 = __webpack_require__(795);
5195var TelemetryConstants_1 = __webpack_require__(810);
5196var TelemetryEvent_1 = tslib_1.__importDefault(__webpack_require__(336));
5197var TelemetryUtils_1 = __webpack_require__(847);
5198var DefaultEvent = /** @class */ (function (_super) {
5199 tslib_1.__extends(DefaultEvent, _super);
5200 // TODO Platform Type
5201 function DefaultEvent(platform, correlationId, clientId, eventCount) {
5202 var _this = _super.call(this, TelemetryUtils_1.prependEventNamePrefix("default_event"), correlationId, "DefaultEvent") || this;
5203 _this.event[TelemetryUtils_1.prependEventNamePrefix("client_id")] = clientId;
5204 _this.event[TelemetryUtils_1.prependEventNamePrefix("sdk_plaform")] = platform.sdk;
5205 _this.event[TelemetryUtils_1.prependEventNamePrefix("sdk_version")] = platform.sdkVersion;
5206 _this.event[TelemetryUtils_1.prependEventNamePrefix("application_name")] = platform.applicationName;
5207 _this.event[TelemetryUtils_1.prependEventNamePrefix("application_version")] = platform.applicationVersion;
5208 _this.event[TelemetryUtils_1.prependEventNamePrefix("effective_connection_speed")] = platform.networkInformation && platform.networkInformation.connectionSpeed;
5209 _this.event["" + TelemetryConstants_1.TELEMETRY_BLOB_EVENT_NAMES.UiEventCountTelemetryBatchKey] = _this.getEventCount(TelemetryUtils_1.prependEventNamePrefix("ui_event"), eventCount);
5210 _this.event["" + TelemetryConstants_1.TELEMETRY_BLOB_EVENT_NAMES.HttpEventCountTelemetryBatchKey] = _this.getEventCount(TelemetryUtils_1.prependEventNamePrefix("http_event"), eventCount);
5211 _this.event["" + TelemetryConstants_1.TELEMETRY_BLOB_EVENT_NAMES.CacheEventCountConstStrKey] = _this.getEventCount(TelemetryUtils_1.prependEventNamePrefix("cache_event"), eventCount);
5212 return _this;
5213 // / Device id?
5214 }
5215 DefaultEvent.prototype.getEventCount = function (eventName, eventCount) {
5216 if (!eventCount[eventName]) {
5217 return 0;
5218 }
5219 return eventCount[eventName];
5220 };
5221 return DefaultEvent;
5222}(TelemetryEvent_1.default));
5223exports["default"] = DefaultEvent;
5224
5225
5226/***/ }),
5227
5228/***/ 140:
5229/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5230
5231
5232/*
5233 * Copyright (c) Microsoft Corporation. All rights reserved.
5234 * Licensed under the MIT License.
5235 */
5236Object.defineProperty(exports, "__esModule", ({ value: true }));
5237exports.EVENT_KEYS = void 0;
5238var tslib_1 = __webpack_require__(795);
5239var TelemetryEvent_1 = tslib_1.__importDefault(__webpack_require__(336));
5240var TelemetryUtils_1 = __webpack_require__(847);
5241var ServerRequestParameters_1 = __webpack_require__(436);
5242exports.EVENT_KEYS = {
5243 HTTP_PATH: TelemetryUtils_1.prependEventNamePrefix("http_path"),
5244 USER_AGENT: TelemetryUtils_1.prependEventNamePrefix("user_agent"),
5245 QUERY_PARAMETERS: TelemetryUtils_1.prependEventNamePrefix("query_parameters"),
5246 API_VERSION: TelemetryUtils_1.prependEventNamePrefix("api_version"),
5247 RESPONSE_CODE: TelemetryUtils_1.prependEventNamePrefix("response_code"),
5248 O_AUTH_ERROR_CODE: TelemetryUtils_1.prependEventNamePrefix("oauth_error_code"),
5249 HTTP_METHOD: TelemetryUtils_1.prependEventNamePrefix("http_method"),
5250 REQUEST_ID_HEADER: TelemetryUtils_1.prependEventNamePrefix("request_id_header"),
5251 SPE_INFO: TelemetryUtils_1.prependEventNamePrefix("spe_info"),
5252 SERVER_ERROR_CODE: TelemetryUtils_1.prependEventNamePrefix("server_error_code"),
5253 SERVER_SUB_ERROR_CODE: TelemetryUtils_1.prependEventNamePrefix("server_sub_error_code"),
5254 URL: TelemetryUtils_1.prependEventNamePrefix("url")
5255};
5256var HttpEvent = /** @class */ (function (_super) {
5257 tslib_1.__extends(HttpEvent, _super);
5258 function HttpEvent(correlationId, eventLabel) {
5259 return _super.call(this, TelemetryUtils_1.prependEventNamePrefix("http_event"), correlationId, eventLabel) || this;
5260 }
5261 Object.defineProperty(HttpEvent.prototype, "url", {
5262 set: function (url) {
5263 var scrubbedUri = TelemetryUtils_1.scrubTenantFromUri(url);
5264 this.event[exports.EVENT_KEYS.URL] = scrubbedUri && scrubbedUri.toLowerCase();
5265 },
5266 enumerable: false,
5267 configurable: true
5268 });
5269 Object.defineProperty(HttpEvent.prototype, "httpPath", {
5270 set: function (httpPath) {
5271 this.event[exports.EVENT_KEYS.HTTP_PATH] = TelemetryUtils_1.scrubTenantFromUri(httpPath).toLowerCase();
5272 },
5273 enumerable: false,
5274 configurable: true
5275 });
5276 Object.defineProperty(HttpEvent.prototype, "userAgent", {
5277 set: function (userAgent) {
5278 this.event[exports.EVENT_KEYS.USER_AGENT] = userAgent;
5279 },
5280 enumerable: false,
5281 configurable: true
5282 });
5283 Object.defineProperty(HttpEvent.prototype, "queryParams", {
5284 set: function (queryParams) {
5285 this.event[exports.EVENT_KEYS.QUERY_PARAMETERS] = ServerRequestParameters_1.ServerRequestParameters.generateQueryParametersString(queryParams);
5286 },
5287 enumerable: false,
5288 configurable: true
5289 });
5290 Object.defineProperty(HttpEvent.prototype, "apiVersion", {
5291 set: function (apiVersion) {
5292 this.event[exports.EVENT_KEYS.API_VERSION] = apiVersion.toLowerCase();
5293 },
5294 enumerable: false,
5295 configurable: true
5296 });
5297 Object.defineProperty(HttpEvent.prototype, "httpResponseStatus", {
5298 set: function (statusCode) {
5299 this.event[exports.EVENT_KEYS.RESPONSE_CODE] = statusCode;
5300 },
5301 enumerable: false,
5302 configurable: true
5303 });
5304 Object.defineProperty(HttpEvent.prototype, "oAuthErrorCode", {
5305 set: function (errorCode) {
5306 this.event[exports.EVENT_KEYS.O_AUTH_ERROR_CODE] = errorCode;
5307 },
5308 enumerable: false,
5309 configurable: true
5310 });
5311 Object.defineProperty(HttpEvent.prototype, "httpMethod", {
5312 set: function (httpMethod) {
5313 this.event[exports.EVENT_KEYS.HTTP_METHOD] = httpMethod;
5314 },
5315 enumerable: false,
5316 configurable: true
5317 });
5318 Object.defineProperty(HttpEvent.prototype, "requestIdHeader", {
5319 set: function (requestIdHeader) {
5320 this.event[exports.EVENT_KEYS.REQUEST_ID_HEADER] = requestIdHeader;
5321 },
5322 enumerable: false,
5323 configurable: true
5324 });
5325 Object.defineProperty(HttpEvent.prototype, "speInfo", {
5326 /**
5327 * Indicates whether the request was executed on a ring serving SPE traffic.
5328 * An empty string indicates this occurred on an outer ring, and the string "I"
5329 * indicates the request occurred on the inner ring
5330 */
5331 set: function (speInfo) {
5332 this.event[exports.EVENT_KEYS.SPE_INFO] = speInfo;
5333 },
5334 enumerable: false,
5335 configurable: true
5336 });
5337 Object.defineProperty(HttpEvent.prototype, "serverErrorCode", {
5338 set: function (errorCode) {
5339 this.event[exports.EVENT_KEYS.SERVER_ERROR_CODE] = errorCode;
5340 },
5341 enumerable: false,
5342 configurable: true
5343 });
5344 Object.defineProperty(HttpEvent.prototype, "serverSubErrorCode", {
5345 set: function (subErrorCode) {
5346 this.event[exports.EVENT_KEYS.SERVER_SUB_ERROR_CODE] = subErrorCode;
5347 },
5348 enumerable: false,
5349 configurable: true
5350 });
5351 return HttpEvent;
5352}(TelemetryEvent_1.default));
5353exports["default"] = HttpEvent;
5354
5355
5356/***/ }),
5357
5358/***/ 810:
5359/***/ (function(__unused_webpack_module, exports) {
5360
5361
5362/*
5363 * Copyright (c) Microsoft Corporation. All rights reserved.
5364 * Licensed under the MIT License.
5365 */
5366Object.defineProperty(exports, "__esModule", ({ value: true }));
5367exports.TENANT_PLACEHOLDER = exports.TELEMETRY_BLOB_EVENT_NAMES = exports.ELAPSED_TIME_KEY = exports.START_TIME_KEY = exports.EVENT_NAME_KEY = exports.EVENT_NAME_PREFIX = void 0;
5368exports.EVENT_NAME_PREFIX = "msal.";
5369exports.EVENT_NAME_KEY = "event_name";
5370exports.START_TIME_KEY = "start_time";
5371exports.ELAPSED_TIME_KEY = "elapsed_time";
5372exports.TELEMETRY_BLOB_EVENT_NAMES = {
5373 MsalCorrelationIdConstStrKey: "Microsoft.MSAL.correlation_id",
5374 ApiTelemIdConstStrKey: "msal.api_telem_id",
5375 ApiIdConstStrKey: "msal.api_id",
5376 BrokerAppConstStrKey: "Microsoft_MSAL_broker_app",
5377 CacheEventCountConstStrKey: "Microsoft_MSAL_cache_event_count",
5378 HttpEventCountTelemetryBatchKey: "Microsoft_MSAL_http_event_count",
5379 IdpConstStrKey: "Microsoft_MSAL_idp",
5380 IsSilentTelemetryBatchKey: "",
5381 IsSuccessfulConstStrKey: "Microsoft_MSAL_is_successful",
5382 ResponseTimeConstStrKey: "Microsoft_MSAL_response_time",
5383 TenantIdConstStrKey: "Microsoft_MSAL_tenant_id",
5384 UiEventCountTelemetryBatchKey: "Microsoft_MSAL_ui_event_count"
5385};
5386// This is used to replace the real tenant in telemetry info
5387exports.TENANT_PLACEHOLDER = "<tenant>";
5388
5389
5390/***/ }),
5391
5392/***/ 336:
5393/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5394
5395
5396/*
5397 * Copyright (c) Microsoft Corporation. All rights reserved.
5398 * Licensed under the MIT License.
5399 */
5400Object.defineProperty(exports, "__esModule", ({ value: true }));
5401var tslib_1 = __webpack_require__(795);
5402var TelemetryConstants_1 = __webpack_require__(810);
5403var TelemetryUtils_1 = __webpack_require__(847);
5404var CryptoUtils_1 = __webpack_require__(453);
5405var TelemetryEvent = /** @class */ (function () {
5406 function TelemetryEvent(eventName, correlationId, eventLabel) {
5407 var _a;
5408 this.eventId = CryptoUtils_1.CryptoUtils.createNewGuid();
5409 this.label = eventLabel;
5410 this.event = (_a = {},
5411 _a[TelemetryUtils_1.prependEventNamePrefix(TelemetryConstants_1.EVENT_NAME_KEY)] = eventName,
5412 _a[TelemetryUtils_1.prependEventNamePrefix(TelemetryConstants_1.ELAPSED_TIME_KEY)] = -1,
5413 _a["" + TelemetryConstants_1.TELEMETRY_BLOB_EVENT_NAMES.MsalCorrelationIdConstStrKey] = correlationId,
5414 _a);
5415 }
5416 TelemetryEvent.prototype.setElapsedTime = function (time) {
5417 this.event[TelemetryUtils_1.prependEventNamePrefix(TelemetryConstants_1.ELAPSED_TIME_KEY)] = time;
5418 };
5419 TelemetryEvent.prototype.stop = function () {
5420 // Set duration of event
5421 this.setElapsedTime(+Date.now() - +this.startTimestamp);
5422 TelemetryUtils_1.endBrowserPerformanceMeasurement(this.displayName, this.perfStartMark, this.perfEndMark);
5423 };
5424 TelemetryEvent.prototype.start = function () {
5425 this.startTimestamp = Date.now();
5426 this.event[TelemetryUtils_1.prependEventNamePrefix(TelemetryConstants_1.START_TIME_KEY)] = this.startTimestamp;
5427 TelemetryUtils_1.startBrowserPerformanceMeasurement(this.perfStartMark);
5428 };
5429 Object.defineProperty(TelemetryEvent.prototype, "telemetryCorrelationId", {
5430 get: function () {
5431 return this.event["" + TelemetryConstants_1.TELEMETRY_BLOB_EVENT_NAMES.MsalCorrelationIdConstStrKey];
5432 },
5433 set: function (value) {
5434 this.event["" + TelemetryConstants_1.TELEMETRY_BLOB_EVENT_NAMES.MsalCorrelationIdConstStrKey] = value;
5435 },
5436 enumerable: false,
5437 configurable: true
5438 });
5439 Object.defineProperty(TelemetryEvent.prototype, "eventName", {
5440 get: function () {
5441 return this.event[TelemetryUtils_1.prependEventNamePrefix(TelemetryConstants_1.EVENT_NAME_KEY)];
5442 },
5443 enumerable: false,
5444 configurable: true
5445 });
5446 TelemetryEvent.prototype.get = function () {
5447 return tslib_1.__assign(tslib_1.__assign({}, this.event), { eventId: this.eventId });
5448 };
5449 Object.defineProperty(TelemetryEvent.prototype, "key", {
5450 get: function () {
5451 return this.telemetryCorrelationId + "_" + this.eventId + "-" + this.eventName;
5452 },
5453 enumerable: false,
5454 configurable: true
5455 });
5456 Object.defineProperty(TelemetryEvent.prototype, "displayName", {
5457 get: function () {
5458 return "Msal-" + this.label + "-" + this.telemetryCorrelationId;
5459 },
5460 enumerable: false,
5461 configurable: true
5462 });
5463 Object.defineProperty(TelemetryEvent.prototype, "perfStartMark", {
5464 get: function () {
5465 return "start-" + this.key;
5466 },
5467 enumerable: false,
5468 configurable: true
5469 });
5470 Object.defineProperty(TelemetryEvent.prototype, "perfEndMark", {
5471 get: function () {
5472 return "end-" + this.key;
5473 },
5474 enumerable: false,
5475 configurable: true
5476 });
5477 return TelemetryEvent;
5478}());
5479exports["default"] = TelemetryEvent;
5480
5481
5482/***/ }),
5483
5484/***/ 478:
5485/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5486
5487
5488/*
5489 * Copyright (c) Microsoft Corporation. All rights reserved.
5490 * Licensed under the MIT License.
5491 */
5492Object.defineProperty(exports, "__esModule", ({ value: true }));
5493var tslib_1 = __webpack_require__(795);
5494var DefaultEvent_1 = tslib_1.__importDefault(__webpack_require__(868));
5495var Constants_1 = __webpack_require__(91);
5496var ApiEvent_1 = tslib_1.__importDefault(__webpack_require__(663));
5497var HttpEvent_1 = tslib_1.__importDefault(__webpack_require__(140));
5498var packageMetadata_1 = __webpack_require__(700);
5499var TelemetryManager = /** @class */ (function () {
5500 function TelemetryManager(config, telemetryEmitter, logger) {
5501 // correlation Id to list of events
5502 this.completedEvents = {};
5503 // event key to event
5504 this.inProgressEvents = {};
5505 // correlation id to map of eventname to count
5506 this.eventCountByCorrelationId = {};
5507 // Implement after API EVENT
5508 this.onlySendFailureTelemetry = false;
5509 // TODO THROW if bad options
5510 this.telemetryPlatform = tslib_1.__assign({ sdk: Constants_1.Constants.libraryName, sdkVersion: packageMetadata_1.version, networkInformation: {
5511 // @ts-ignore
5512 connectionSpeed: typeof navigator !== "undefined" && navigator.connection && navigator.connection.effectiveType
5513 } }, config.platform);
5514 this.clientId = config.clientId;
5515 this.onlySendFailureTelemetry = config.onlySendFailureTelemetry;
5516 /*
5517 * TODO, when i get to wiring this through, think about what it means if
5518 * a developer does not implement telem at all, we still instrument, but telemetryEmitter can be
5519 * optional?
5520 */
5521 this.telemetryEmitter = telemetryEmitter;
5522 this.logger = logger;
5523 }
5524 TelemetryManager.getTelemetrymanagerStub = function (clientId, logger) {
5525 var applicationName = "UnSetStub";
5526 var applicationVersion = "0.0";
5527 var telemetryEmitter = function () { };
5528 var telemetryPlatform = {
5529 applicationName: applicationName,
5530 applicationVersion: applicationVersion
5531 };
5532 var telemetryManagerConfig = {
5533 platform: telemetryPlatform,
5534 clientId: clientId
5535 };
5536 return new this(telemetryManagerConfig, telemetryEmitter, logger);
5537 };
5538 TelemetryManager.prototype.startEvent = function (event) {
5539 this.logger.verbose("Telemetry Event started: " + event.key);
5540 if (!this.telemetryEmitter) {
5541 return;
5542 }
5543 event.start();
5544 this.inProgressEvents[event.key] = event;
5545 };
5546 TelemetryManager.prototype.stopEvent = function (event) {
5547 this.logger.verbose("Telemetry Event stopped: " + event.key);
5548 if (!this.telemetryEmitter || !this.inProgressEvents[event.key]) {
5549 return;
5550 }
5551 event.stop();
5552 this.incrementEventCount(event);
5553 var completedEvents = this.completedEvents[event.telemetryCorrelationId];
5554 this.completedEvents[event.telemetryCorrelationId] = tslib_1.__spreadArrays((completedEvents || []), [event]);
5555 delete this.inProgressEvents[event.key];
5556 };
5557 TelemetryManager.prototype.flush = function (correlationId) {
5558 var _this = this;
5559 this.logger.verbose("Flushing telemetry events: " + correlationId);
5560 // If there is only unfinished events should this still return them?
5561 if (!this.telemetryEmitter || !this.completedEvents[correlationId]) {
5562 return;
5563 }
5564 var orphanedEvents = this.getOrphanedEvents(correlationId);
5565 orphanedEvents.forEach(function (event) { return _this.incrementEventCount(event); });
5566 var eventsToFlush = tslib_1.__spreadArrays(this.completedEvents[correlationId], orphanedEvents);
5567 delete this.completedEvents[correlationId];
5568 var eventCountsToFlush = this.eventCountByCorrelationId[correlationId];
5569 delete this.eventCountByCorrelationId[correlationId];
5570 // TODO add funcitonality for onlyFlushFailures after implementing api event? ??
5571 if (!eventsToFlush || !eventsToFlush.length) {
5572 return;
5573 }
5574 var defaultEvent = new DefaultEvent_1.default(this.telemetryPlatform, correlationId, this.clientId, eventCountsToFlush);
5575 var eventsWithDefaultEvent = tslib_1.__spreadArrays(eventsToFlush, [defaultEvent]);
5576 this.telemetryEmitter(eventsWithDefaultEvent.map(function (e) { return e.get(); }));
5577 };
5578 TelemetryManager.prototype.createAndStartApiEvent = function (correlationId, apiEventIdentifier) {
5579 var apiEvent = new ApiEvent_1.default(correlationId, this.logger.isPiiLoggingEnabled(), apiEventIdentifier);
5580 this.startEvent(apiEvent);
5581 return apiEvent;
5582 };
5583 TelemetryManager.prototype.stopAndFlushApiEvent = function (correlationId, apiEvent, wasSuccessful, errorCode) {
5584 apiEvent.wasSuccessful = wasSuccessful;
5585 if (errorCode) {
5586 apiEvent.apiErrorCode = errorCode;
5587 }
5588 this.stopEvent(apiEvent);
5589 this.flush(correlationId);
5590 };
5591 TelemetryManager.prototype.createAndStartHttpEvent = function (correlation, httpMethod, url, eventLabel) {
5592 var httpEvent = new HttpEvent_1.default(correlation, eventLabel);
5593 httpEvent.url = url;
5594 httpEvent.httpMethod = httpMethod;
5595 this.startEvent(httpEvent);
5596 return httpEvent;
5597 };
5598 TelemetryManager.prototype.incrementEventCount = function (event) {
5599 var _a;
5600 /*
5601 * TODO, name cache event different?
5602 * if type is cache event, change name
5603 */
5604 var eventName = event.eventName;
5605 var eventCount = this.eventCountByCorrelationId[event.telemetryCorrelationId];
5606 if (!eventCount) {
5607 this.eventCountByCorrelationId[event.telemetryCorrelationId] = (_a = {},
5608 _a[eventName] = 1,
5609 _a);
5610 }
5611 else {
5612 eventCount[eventName] = eventCount[eventName] ? eventCount[eventName] + 1 : 1;
5613 }
5614 };
5615 TelemetryManager.prototype.getOrphanedEvents = function (correlationId) {
5616 var _this = this;
5617 return Object.keys(this.inProgressEvents)
5618 .reduce(function (memo, eventKey) {
5619 if (eventKey.indexOf(correlationId) !== -1) {
5620 var event = _this.inProgressEvents[eventKey];
5621 delete _this.inProgressEvents[eventKey];
5622 return tslib_1.__spreadArrays(memo, [event]);
5623 }
5624 return memo;
5625 }, []);
5626 };
5627 return TelemetryManager;
5628}());
5629exports["default"] = TelemetryManager;
5630
5631
5632/***/ }),
5633
5634/***/ 847:
5635/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5636
5637
5638/*
5639 * Copyright (c) Microsoft Corporation. All rights reserved.
5640 * Licensed under the MIT License.
5641 */
5642Object.defineProperty(exports, "__esModule", ({ value: true }));
5643exports.startBrowserPerformanceMeasurement = exports.endBrowserPerformanceMeasurement = exports.supportsBrowserPerformance = exports.prependEventNamePrefix = exports.hashPersonalIdentifier = exports.scrubTenantFromUri = void 0;
5644var TelemetryConstants_1 = __webpack_require__(810);
5645var CryptoUtils_1 = __webpack_require__(453);
5646var UrlUtils_1 = __webpack_require__(741);
5647var Authority_1 = __webpack_require__(660);
5648exports.scrubTenantFromUri = function (uri) {
5649 var url = UrlUtils_1.UrlUtils.GetUrlComponents(uri);
5650 // validate trusted host
5651 if (Authority_1.Authority.isAdfs(uri)) {
5652 /**
5653 * returning what was passed because the library needs to work with uris that are non
5654 * AAD trusted but passed by users such as B2C or others.
5655 * HTTP Events for instance can take a url to the open id config endpoint
5656 */
5657 return uri;
5658 }
5659 var pathParams = url.PathSegments;
5660 if (pathParams && pathParams.length >= 2) {
5661 var tenantPosition = pathParams[1] === "tfp" ? 2 : 1;
5662 if (tenantPosition < pathParams.length) {
5663 pathParams[tenantPosition] = TelemetryConstants_1.TENANT_PLACEHOLDER;
5664 }
5665 }
5666 return url.Protocol + "//" + url.HostNameAndPort + "/" + pathParams.join("/");
5667};
5668exports.hashPersonalIdentifier = function (valueToHash) {
5669 /*
5670 * TODO sha256 this
5671 * Current test runner is being funny with node libs that are webpacked anyway
5672 * need a different solution
5673 */
5674 return CryptoUtils_1.CryptoUtils.base64Encode(valueToHash);
5675};
5676exports.prependEventNamePrefix = function (suffix) { return "" + TelemetryConstants_1.EVENT_NAME_PREFIX + (suffix || ""); };
5677exports.supportsBrowserPerformance = function () { return !!(typeof window !== "undefined" &&
5678 "performance" in window &&
5679 window.performance.mark &&
5680 window.performance.measure); };
5681exports.endBrowserPerformanceMeasurement = function (measureName, startMark, endMark) {
5682 if (exports.supportsBrowserPerformance()) {
5683 window.performance.mark(endMark);
5684 window.performance.measure(measureName, startMark, endMark);
5685 window.performance.clearMeasures(measureName);
5686 window.performance.clearMarks(startMark);
5687 window.performance.clearMarks(endMark);
5688 }
5689};
5690exports.startBrowserPerformanceMeasurement = function (startMark) {
5691 if (exports.supportsBrowserPerformance()) {
5692 window.performance.mark(startMark);
5693 }
5694};
5695
5696
5697/***/ }),
5698
5699/***/ 49:
5700/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5701
5702
5703/*
5704 * Copyright (c) Microsoft Corporation. All rights reserved.
5705 * Licensed under the MIT License.
5706 */
5707Object.defineProperty(exports, "__esModule", ({ value: true }));
5708exports.AuthCacheUtils = void 0;
5709var ScopeSet_1 = __webpack_require__(55);
5710var UrlUtils_1 = __webpack_require__(741);
5711/**
5712 * @hidden
5713 */
5714var AuthCacheUtils = /** @class */ (function () {
5715 function AuthCacheUtils() {
5716 }
5717 AuthCacheUtils.filterTokenCacheItemsByScope = function (tokenCacheItems, requestScopes) {
5718 return tokenCacheItems.filter(function (cacheItem) {
5719 var cachedScopes = cacheItem.key.scopes.split(" ");
5720 var searchScopes = ScopeSet_1.ScopeSet.removeDefaultScopes(requestScopes);
5721 // If requestScopes contain only default scopes search for default scopes otherwise search for everything but default scopes
5722 return searchScopes.length === 0 ? ScopeSet_1.ScopeSet.containsScope(cachedScopes, requestScopes) : ScopeSet_1.ScopeSet.containsScope(cachedScopes, searchScopes);
5723 });
5724 };
5725 AuthCacheUtils.filterTokenCacheItemsByAuthority = function (tokenCacheItems, authority) {
5726 return tokenCacheItems.filter(function (cacheItem) { return UrlUtils_1.UrlUtils.CanonicalizeUri(cacheItem.key.authority) === authority; });
5727 };
5728 AuthCacheUtils.filterTokenCacheItemsByDomain = function (tokenCacheItems, requestDomain) {
5729 return tokenCacheItems.filter(function (cacheItem) {
5730 var cacheItemDomain = UrlUtils_1.UrlUtils.GetUrlComponents(cacheItem.key.authority).HostNameAndPort;
5731 return cacheItemDomain === requestDomain;
5732 });
5733 };
5734 return AuthCacheUtils;
5735}());
5736exports.AuthCacheUtils = AuthCacheUtils;
5737
5738
5739/***/ }),
5740
5741/***/ 91:
5742/***/ (function(__unused_webpack_module, exports) {
5743
5744
5745/*
5746 * Copyright (c) Microsoft Corporation. All rights reserved.
5747 * Licensed under the MIT License.
5748 */
5749Object.defineProperty(exports, "__esModule", ({ value: true }));
5750exports.FramePrefix = exports.PromptState = exports.NetworkRequestType = exports.DisallowedEQParams = exports.SSOTypes = exports.WELL_KNOWN_SUFFIX = exports.AAD_INSTANCE_DISCOVERY_ENDPOINT = exports.DEFAULT_AUTHORITY = exports.ErrorCacheKeys = exports.PersistentCacheKeys = exports.TemporaryCacheKeys = exports.ResponseTypes = exports.ServerHashParamKeys = exports.SESSION_STORAGE = exports.Constants = void 0;
5751/**
5752 * @hidden
5753 * Constants
5754 */
5755var Constants = /** @class */ (function () {
5756 function Constants() {
5757 }
5758 Object.defineProperty(Constants, "libraryName", {
5759 get: function () { return "Msal.js"; } // used in telemetry sdkName
5760 ,
5761 enumerable: false,
5762 configurable: true
5763 });
5764 Object.defineProperty(Constants, "claims", {
5765 get: function () { return "claims"; },
5766 enumerable: false,
5767 configurable: true
5768 });
5769 Object.defineProperty(Constants, "clientId", {
5770 get: function () { return "clientId"; },
5771 enumerable: false,
5772 configurable: true
5773 });
5774 Object.defineProperty(Constants, "adalIdToken", {
5775 get: function () { return "adal.idtoken"; },
5776 enumerable: false,
5777 configurable: true
5778 });
5779 Object.defineProperty(Constants, "cachePrefix", {
5780 get: function () { return "msal"; },
5781 enumerable: false,
5782 configurable: true
5783 });
5784 Object.defineProperty(Constants, "scopes", {
5785 get: function () { return "scopes"; },
5786 enumerable: false,
5787 configurable: true
5788 });
5789 Object.defineProperty(Constants, "no_account", {
5790 get: function () { return "NO_ACCOUNT"; },
5791 enumerable: false,
5792 configurable: true
5793 });
5794 Object.defineProperty(Constants, "upn", {
5795 get: function () { return "upn"; },
5796 enumerable: false,
5797 configurable: true
5798 });
5799 Object.defineProperty(Constants, "domain_hint", {
5800 get: function () { return "domain_hint"; },
5801 enumerable: false,
5802 configurable: true
5803 });
5804 Object.defineProperty(Constants, "prompt_select_account", {
5805 get: function () { return "&prompt=select_account"; },
5806 enumerable: false,
5807 configurable: true
5808 });
5809 Object.defineProperty(Constants, "prompt_none", {
5810 get: function () { return "&prompt=none"; },
5811 enumerable: false,
5812 configurable: true
5813 });
5814 Object.defineProperty(Constants, "prompt", {
5815 get: function () { return "prompt"; },
5816 enumerable: false,
5817 configurable: true
5818 });
5819 Object.defineProperty(Constants, "response_mode_fragment", {
5820 get: function () { return "&response_mode=fragment"; },
5821 enumerable: false,
5822 configurable: true
5823 });
5824 Object.defineProperty(Constants, "resourceDelimiter", {
5825 get: function () { return "|"; },
5826 enumerable: false,
5827 configurable: true
5828 });
5829 Object.defineProperty(Constants, "cacheDelimiter", {
5830 get: function () { return "."; },
5831 enumerable: false,
5832 configurable: true
5833 });
5834 Object.defineProperty(Constants, "popUpWidth", {
5835 get: function () { return this._popUpWidth; },
5836 set: function (width) {
5837 this._popUpWidth = width;
5838 },
5839 enumerable: false,
5840 configurable: true
5841 });
5842 Object.defineProperty(Constants, "popUpHeight", {
5843 get: function () { return this._popUpHeight; },
5844 set: function (height) {
5845 this._popUpHeight = height;
5846 },
5847 enumerable: false,
5848 configurable: true
5849 });
5850 Object.defineProperty(Constants, "login", {
5851 get: function () { return "LOGIN"; },
5852 enumerable: false,
5853 configurable: true
5854 });
5855 Object.defineProperty(Constants, "renewToken", {
5856 get: function () { return "RENEW_TOKEN"; },
5857 enumerable: false,
5858 configurable: true
5859 });
5860 Object.defineProperty(Constants, "unknown", {
5861 get: function () { return "UNKNOWN"; },
5862 enumerable: false,
5863 configurable: true
5864 });
5865 Object.defineProperty(Constants, "ADFS", {
5866 get: function () { return "adfs"; },
5867 enumerable: false,
5868 configurable: true
5869 });
5870 Object.defineProperty(Constants, "homeAccountIdentifier", {
5871 get: function () { return "homeAccountIdentifier"; },
5872 enumerable: false,
5873 configurable: true
5874 });
5875 Object.defineProperty(Constants, "common", {
5876 get: function () { return "common"; },
5877 enumerable: false,
5878 configurable: true
5879 });
5880 Object.defineProperty(Constants, "openidScope", {
5881 get: function () { return "openid"; },
5882 enumerable: false,
5883 configurable: true
5884 });
5885 Object.defineProperty(Constants, "profileScope", {
5886 get: function () { return "profile"; },
5887 enumerable: false,
5888 configurable: true
5889 });
5890 Object.defineProperty(Constants, "oidcScopes", {
5891 get: function () { return [this.openidScope, this.profileScope]; },
5892 enumerable: false,
5893 configurable: true
5894 });
5895 Object.defineProperty(Constants, "interactionTypeRedirect", {
5896 get: function () { return "redirectInteraction"; },
5897 enumerable: false,
5898 configurable: true
5899 });
5900 Object.defineProperty(Constants, "interactionTypePopup", {
5901 get: function () { return "popupInteraction"; },
5902 enumerable: false,
5903 configurable: true
5904 });
5905 Object.defineProperty(Constants, "interactionTypeSilent", {
5906 get: function () { return "silentInteraction"; },
5907 enumerable: false,
5908 configurable: true
5909 });
5910 Object.defineProperty(Constants, "inProgress", {
5911 get: function () { return "inProgress"; },
5912 enumerable: false,
5913 configurable: true
5914 });
5915 Constants._popUpWidth = 483;
5916 Constants._popUpHeight = 600;
5917 return Constants;
5918}());
5919exports.Constants = Constants;
5920exports.SESSION_STORAGE = "sessionStorage";
5921/**
5922 * Keys in the hashParams
5923 */
5924var ServerHashParamKeys;
5925(function (ServerHashParamKeys) {
5926 ServerHashParamKeys["SCOPE"] = "scope";
5927 ServerHashParamKeys["STATE"] = "state";
5928 ServerHashParamKeys["ERROR"] = "error";
5929 ServerHashParamKeys["ERROR_DESCRIPTION"] = "error_description";
5930 ServerHashParamKeys["ACCESS_TOKEN"] = "access_token";
5931 ServerHashParamKeys["ID_TOKEN"] = "id_token";
5932 ServerHashParamKeys["EXPIRES_IN"] = "expires_in";
5933 ServerHashParamKeys["SESSION_STATE"] = "session_state";
5934 ServerHashParamKeys["CLIENT_INFO"] = "client_info";
5935})(ServerHashParamKeys = exports.ServerHashParamKeys || (exports.ServerHashParamKeys = {}));
5936/**
5937 * @hidden
5938 * @ignore
5939 * response_type from OpenIDConnect
5940 * References: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html & https://tools.ietf.org/html/rfc6749#section-4.2.1
5941 *
5942 */
5943exports.ResponseTypes = {
5944 id_token: "id_token",
5945 token: "token",
5946 id_token_token: "id_token token"
5947};
5948/**
5949 * @hidden
5950 * CacheKeys for MSAL
5951 */
5952var TemporaryCacheKeys;
5953(function (TemporaryCacheKeys) {
5954 TemporaryCacheKeys["AUTHORITY"] = "authority";
5955 TemporaryCacheKeys["ACQUIRE_TOKEN_ACCOUNT"] = "acquireTokenAccount";
5956 TemporaryCacheKeys["SESSION_STATE"] = "session.state";
5957 TemporaryCacheKeys["STATE_LOGIN"] = "state.login";
5958 TemporaryCacheKeys["STATE_ACQ_TOKEN"] = "state.acquireToken";
5959 TemporaryCacheKeys["STATE_RENEW"] = "state.renew";
5960 TemporaryCacheKeys["NONCE_IDTOKEN"] = "nonce.idtoken";
5961 TemporaryCacheKeys["LOGIN_REQUEST"] = "login.request";
5962 TemporaryCacheKeys["RENEW_STATUS"] = "token.renew.status";
5963 TemporaryCacheKeys["URL_HASH"] = "urlHash";
5964 TemporaryCacheKeys["INTERACTION_STATUS"] = "interaction.status";
5965 TemporaryCacheKeys["REDIRECT_REQUEST"] = "redirect_request";
5966})(TemporaryCacheKeys = exports.TemporaryCacheKeys || (exports.TemporaryCacheKeys = {}));
5967var PersistentCacheKeys;
5968(function (PersistentCacheKeys) {
5969 PersistentCacheKeys["IDTOKEN"] = "idtoken";
5970 PersistentCacheKeys["CLIENT_INFO"] = "client.info";
5971})(PersistentCacheKeys = exports.PersistentCacheKeys || (exports.PersistentCacheKeys = {}));
5972var ErrorCacheKeys;
5973(function (ErrorCacheKeys) {
5974 ErrorCacheKeys["LOGIN_ERROR"] = "login.error";
5975 ErrorCacheKeys["ERROR"] = "error";
5976 ErrorCacheKeys["ERROR_DESC"] = "error.description";
5977})(ErrorCacheKeys = exports.ErrorCacheKeys || (exports.ErrorCacheKeys = {}));
5978exports.DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common/";
5979exports.AAD_INSTANCE_DISCOVERY_ENDPOINT = exports.DEFAULT_AUTHORITY + "/discovery/instance?api-version=1.1&authorization_endpoint=";
5980exports.WELL_KNOWN_SUFFIX = ".well-known/openid-configuration";
5981/**
5982 * @hidden
5983 * SSO Types - generated to populate hints
5984 */
5985var SSOTypes;
5986(function (SSOTypes) {
5987 SSOTypes["ACCOUNT"] = "account";
5988 SSOTypes["SID"] = "sid";
5989 SSOTypes["LOGIN_HINT"] = "login_hint";
5990 SSOTypes["ORGANIZATIONS"] = "organizations";
5991 SSOTypes["CONSUMERS"] = "consumers";
5992 SSOTypes["ID_TOKEN"] = "id_token";
5993 SSOTypes["ACCOUNT_ID"] = "accountIdentifier";
5994 SSOTypes["HOMEACCOUNT_ID"] = "homeAccountIdentifier";
5995})(SSOTypes = exports.SSOTypes || (exports.SSOTypes = {}));
5996/**
5997 * @hidden
5998 */
5999exports.DisallowedEQParams = [
6000 SSOTypes.SID,
6001 SSOTypes.LOGIN_HINT
6002];
6003exports.NetworkRequestType = {
6004 GET: "GET",
6005 POST: "POST"
6006};
6007/**
6008 * we considered making this "enum" in the request instead of string, however it looks like the allowed list of
6009 * prompt values kept changing over past couple of years. There are some undocumented prompt values for some
6010 * internal partners too, hence the choice of generic "string" type instead of the "enum"
6011 * @hidden
6012 */
6013exports.PromptState = {
6014 LOGIN: "login",
6015 SELECT_ACCOUNT: "select_account",
6016 CONSENT: "consent",
6017 NONE: "none"
6018};
6019/**
6020 * Frame name prefixes for the hidden iframe created in silent frames
6021 */
6022exports.FramePrefix = {
6023 ID_TOKEN_FRAME: "msalIdTokenFrame",
6024 TOKEN_FRAME: "msalRenewFrame"
6025};
6026
6027
6028/***/ }),
6029
6030/***/ 453:
6031/***/ (function(__unused_webpack_module, exports) {
6032
6033
6034/*
6035 * Copyright (c) Microsoft Corporation. All rights reserved.
6036 * Licensed under the MIT License.
6037 */
6038Object.defineProperty(exports, "__esModule", ({ value: true }));
6039exports.CryptoUtils = void 0;
6040/**
6041 * @hidden
6042 */
6043var CryptoUtils = /** @class */ (function () {
6044 function CryptoUtils() {
6045 }
6046 /**
6047 * Creates a new random GUID
6048 * @returns string (GUID)
6049 */
6050 CryptoUtils.createNewGuid = function () {
6051 /*
6052 * RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or
6053 * pseudo-random numbers.
6054 * The algorithm is as follows:
6055 * Set the two most significant bits (bits 6 and 7) of the
6056 * clock_seq_hi_and_reserved to zero and one, respectively.
6057 * Set the four most significant bits (bits 12 through 15) of the
6058 * time_hi_and_version field to the 4-bit version number from
6059 * Section 4.1.3. Version4
6060 * Set all the other bits to randomly (or pseudo-randomly) chosen
6061 * values.
6062 * UUID = time-low "-" time-mid "-"time-high-and-version "-"clock-seq-reserved and low(2hexOctet)"-" node
6063 * time-low = 4hexOctet
6064 * time-mid = 2hexOctet
6065 * time-high-and-version = 2hexOctet
6066 * clock-seq-and-reserved = hexOctet:
6067 * clock-seq-low = hexOctet
6068 * node = 6hexOctet
6069 * Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
6070 * y could be 1000, 1001, 1010, 1011 since most significant two bits needs to be 10
6071 * y values are 8, 9, A, B
6072 */
6073 var cryptoObj = window.crypto; // for IE 11
6074 if (cryptoObj && cryptoObj.getRandomValues) {
6075 var buffer = new Uint8Array(16);
6076 cryptoObj.getRandomValues(buffer);
6077 // buffer[6] and buffer[7] represents the time_hi_and_version field. We will set the four most significant bits (4 through 7) of buffer[6] to represent decimal number 4 (UUID version number).
6078 buffer[6] |= 0x40; // buffer[6] | 01000000 will set the 6 bit to 1.
6079 buffer[6] &= 0x4f; // buffer[6] & 01001111 will set the 4, 5, and 7 bit to 0 such that bits 4-7 == 0100 = "4".
6080 // buffer[8] represents the clock_seq_hi_and_reserved field. We will set the two most significant bits (6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively.
6081 buffer[8] |= 0x80; // buffer[8] | 10000000 will set the 7 bit to 1.
6082 buffer[8] &= 0xbf; // buffer[8] & 10111111 will set the 6 bit to 0.
6083 return CryptoUtils.decimalToHex(buffer[0]) + CryptoUtils.decimalToHex(buffer[1])
6084 + CryptoUtils.decimalToHex(buffer[2]) + CryptoUtils.decimalToHex(buffer[3])
6085 + "-" + CryptoUtils.decimalToHex(buffer[4]) + CryptoUtils.decimalToHex(buffer[5])
6086 + "-" + CryptoUtils.decimalToHex(buffer[6]) + CryptoUtils.decimalToHex(buffer[7])
6087 + "-" + CryptoUtils.decimalToHex(buffer[8]) + CryptoUtils.decimalToHex(buffer[9])
6088 + "-" + CryptoUtils.decimalToHex(buffer[10]) + CryptoUtils.decimalToHex(buffer[11])
6089 + CryptoUtils.decimalToHex(buffer[12]) + CryptoUtils.decimalToHex(buffer[13])
6090 + CryptoUtils.decimalToHex(buffer[14]) + CryptoUtils.decimalToHex(buffer[15]);
6091 }
6092 else {
6093 var guidHolder = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
6094 var hex = "0123456789abcdef";
6095 var r = 0;
6096 var guidResponse = "";
6097 for (var i = 0; i < 36; i++) {
6098 if (guidHolder[i] !== "-" && guidHolder[i] !== "4") {
6099 // each x and y needs to be random
6100 r = Math.random() * 16 | 0;
6101 }
6102 if (guidHolder[i] === "x") {
6103 guidResponse += hex[r];
6104 }
6105 else if (guidHolder[i] === "y") {
6106 // clock-seq-and-reserved first hex is filtered and remaining hex values are random
6107 r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0??
6108 r |= 0x8; // set pos 3 to 1 as 1???
6109 guidResponse += hex[r];
6110 }
6111 else {
6112 guidResponse += guidHolder[i];
6113 }
6114 }
6115 return guidResponse;
6116 }
6117 };
6118 /**
6119 * verifies if a string is GUID
6120 * @param guid
6121 */
6122 CryptoUtils.isGuid = function (guid) {
6123 var regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6124 return regexGuid.test(guid);
6125 };
6126 /**
6127 * Decimal to Hex
6128 *
6129 * @param num
6130 */
6131 CryptoUtils.decimalToHex = function (num) {
6132 var hex = num.toString(16);
6133 while (hex.length < 2) {
6134 hex = "0" + hex;
6135 }
6136 return hex;
6137 };
6138 // See: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_4_%E2%80%93_escaping_the_string_before_encoding_it
6139 /**
6140 * encoding string to base64 - platform specific check
6141 *
6142 * @param input
6143 */
6144 CryptoUtils.base64Encode = function (input) {
6145 return btoa(encodeURIComponent(input).replace(/%([0-9A-F]{2})/g, function toSolidBytes(match, p1) {
6146 return String.fromCharCode(Number("0x" + p1));
6147 }));
6148 };
6149 /**
6150 * Decodes a base64 encoded string.
6151 *
6152 * @param input
6153 */
6154 CryptoUtils.base64Decode = function (input) {
6155 var encodedString = input.replace(/-/g, "+").replace(/_/g, "/");
6156 switch (encodedString.length % 4) {
6157 case 0:
6158 break;
6159 case 2:
6160 encodedString += "==";
6161 break;
6162 case 3:
6163 encodedString += "=";
6164 break;
6165 default:
6166 throw new Error("Invalid base64 string");
6167 }
6168 return decodeURIComponent(atob(encodedString).split("").map(function (c) {
6169 return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
6170 }).join(""));
6171 };
6172 /**
6173 * deserialize a string
6174 *
6175 * @param query
6176 */
6177 CryptoUtils.deserialize = function (query) {
6178 var match; // Regex for replacing addition symbol with a space
6179 var pl = /\+/g;
6180 var search = /([^&=]+)=([^&]*)/g;
6181 var decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); };
6182 var obj = {};
6183 match = search.exec(query);
6184 while (match) {
6185 obj[decode(match[1])] = decode(match[2]);
6186 match = search.exec(query);
6187 }
6188 return obj;
6189 };
6190 return CryptoUtils;
6191}());
6192exports.CryptoUtils = CryptoUtils;
6193
6194
6195/***/ }),
6196
6197/***/ 52:
6198/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6199
6200
6201/*
6202 * Copyright (c) Microsoft Corporation. All rights reserved.
6203 * Licensed under the MIT License.
6204 */
6205Object.defineProperty(exports, "__esModule", ({ value: true }));
6206exports.RequestUtils = void 0;
6207var tslib_1 = __webpack_require__(795);
6208var Constants_1 = __webpack_require__(91);
6209var ClientConfigurationError_1 = __webpack_require__(550);
6210var ScopeSet_1 = __webpack_require__(55);
6211var StringUtils_1 = __webpack_require__(454);
6212var CryptoUtils_1 = __webpack_require__(453);
6213var TimeUtils_1 = __webpack_require__(78);
6214var ClientAuthError_1 = __webpack_require__(356);
6215/**
6216 * @hidden
6217 */
6218var RequestUtils = /** @class */ (function () {
6219 function RequestUtils() {
6220 }
6221 /**
6222 * @ignore
6223 *
6224 * @param request
6225 * @param isLoginCall
6226 * @param cacheStorage
6227 * @param clientId
6228 *
6229 * validates all request parameters and generates a consumable request object
6230 */
6231 RequestUtils.validateRequest = function (request, isLoginCall, clientId, interactionType) {
6232 // Throw error if request is empty for acquire * calls
6233 if (!isLoginCall && !request) {
6234 throw ClientConfigurationError_1.ClientConfigurationError.createEmptyRequestError();
6235 }
6236 var scopes;
6237 var extraQueryParameters;
6238 if (request) {
6239 // if extraScopesToConsent is passed in loginCall, append them to the login request; Validate and filter scopes (the validate function will throw if validation fails)
6240 scopes = isLoginCall ? ScopeSet_1.ScopeSet.appendScopes(request.scopes, request.extraScopesToConsent) : request.scopes;
6241 ScopeSet_1.ScopeSet.validateInputScope(scopes, !isLoginCall);
6242 scopes = ScopeSet_1.ScopeSet.translateClientIdIfSingleScope(scopes, clientId);
6243 // validate prompt parameter
6244 this.validatePromptParameter(request.prompt);
6245 // validate extraQueryParameters
6246 extraQueryParameters = this.validateEQParameters(request.extraQueryParameters, request.claimsRequest);
6247 // validate claimsRequest
6248 this.validateClaimsRequest(request.claimsRequest);
6249 }
6250 // validate and generate state and correlationId
6251 var state = this.validateAndGenerateState(request && request.state, interactionType);
6252 var correlationId = this.validateAndGenerateCorrelationId(request && request.correlationId);
6253 var validatedRequest = tslib_1.__assign(tslib_1.__assign({}, request), { extraQueryParameters: extraQueryParameters,
6254 scopes: scopes,
6255 state: state,
6256 correlationId: correlationId });
6257 return validatedRequest;
6258 };
6259 /**
6260 * @ignore
6261 *
6262 * Utility to test if valid prompt value is passed in the request
6263 * @param request
6264 */
6265 RequestUtils.validatePromptParameter = function (prompt) {
6266 if (prompt) {
6267 if ([Constants_1.PromptState.LOGIN, Constants_1.PromptState.SELECT_ACCOUNT, Constants_1.PromptState.CONSENT, Constants_1.PromptState.NONE].indexOf(prompt) < 0) {
6268 throw ClientConfigurationError_1.ClientConfigurationError.createInvalidPromptError(prompt);
6269 }
6270 }
6271 };
6272 /**
6273 * @ignore
6274 *
6275 * Removes unnecessary or duplicate query parameters from extraQueryParameters
6276 * @param request
6277 */
6278 RequestUtils.validateEQParameters = function (extraQueryParameters, claimsRequest) {
6279 var eQParams = tslib_1.__assign({}, extraQueryParameters);
6280 if (!eQParams) {
6281 return null;
6282 }
6283 if (claimsRequest) {
6284 // this.logger.warning("Removed duplicate claims from extraQueryParameters. Please use either the claimsRequest field OR pass as extraQueryParameter - not both.");
6285 delete eQParams[Constants_1.Constants.claims];
6286 }
6287 Constants_1.DisallowedEQParams.forEach(function (param) {
6288 if (eQParams[param]) {
6289 // this.logger.warning("Removed duplicate " + param + " from extraQueryParameters. Please use the " + param + " field in request object.");
6290 delete eQParams[param];
6291 }
6292 });
6293 return eQParams;
6294 };
6295 /**
6296 * @ignore
6297 *
6298 * Validates the claims passed in request is a JSON
6299 * TODO: More validation will be added when the server team tells us how they have actually implemented claims
6300 * @param claimsRequest
6301 */
6302 RequestUtils.validateClaimsRequest = function (claimsRequest) {
6303 if (!claimsRequest) {
6304 return;
6305 }
6306 try {
6307 JSON.parse(claimsRequest);
6308 }
6309 catch (e) {
6310 throw ClientConfigurationError_1.ClientConfigurationError.createClaimsRequestParsingError(e);
6311 }
6312 };
6313 /**
6314 * @ignore
6315 *
6316 * generate unique state per request
6317 * @param userState User-provided state value
6318 * @returns State string include library state and user state
6319 */
6320 RequestUtils.validateAndGenerateState = function (userState, interactionType) {
6321 return !StringUtils_1.StringUtils.isEmpty(userState) ? "" + RequestUtils.generateLibraryState(interactionType) + Constants_1.Constants.resourceDelimiter + userState : RequestUtils.generateLibraryState(interactionType);
6322 };
6323 /**
6324 * Generates the state value used by the library.
6325 *
6326 * @returns Base64 encoded string representing the state
6327 */
6328 RequestUtils.generateLibraryState = function (interactionType) {
6329 var stateObject = {
6330 id: CryptoUtils_1.CryptoUtils.createNewGuid(),
6331 ts: TimeUtils_1.TimeUtils.now(),
6332 method: interactionType
6333 };
6334 var stateString = JSON.stringify(stateObject);
6335 return CryptoUtils_1.CryptoUtils.base64Encode(stateString);
6336 };
6337 /**
6338 * Decodes the state value into a StateObject
6339 *
6340 * @param state State value returned in the request
6341 * @returns Parsed values from the encoded state value
6342 */
6343 RequestUtils.parseLibraryState = function (state) {
6344 var libraryState = decodeURIComponent(state).split(Constants_1.Constants.resourceDelimiter)[0];
6345 if (CryptoUtils_1.CryptoUtils.isGuid(libraryState)) {
6346 // If state is guid, assume timestamp is now and is redirect, as redirect should be only method where this can happen.
6347 return {
6348 id: libraryState,
6349 ts: TimeUtils_1.TimeUtils.now(),
6350 method: Constants_1.Constants.interactionTypeRedirect
6351 };
6352 }
6353 try {
6354 var stateString = CryptoUtils_1.CryptoUtils.base64Decode(libraryState);
6355 var stateObject = JSON.parse(stateString);
6356 return stateObject;
6357 }
6358 catch (e) {
6359 throw ClientAuthError_1.ClientAuthError.createInvalidStateError(state, null);
6360 }
6361 };
6362 /**
6363 * @ignore
6364 *
6365 * validate correlationId and generate if not valid or not set by the user
6366 * @param correlationId
6367 */
6368 RequestUtils.validateAndGenerateCorrelationId = function (correlationId) {
6369 // validate user set correlationId or set one for the user if null
6370 if (correlationId && !CryptoUtils_1.CryptoUtils.isGuid(correlationId)) {
6371 throw ClientConfigurationError_1.ClientConfigurationError.createInvalidCorrelationIdError();
6372 }
6373 return CryptoUtils_1.CryptoUtils.isGuid(correlationId) ? correlationId : CryptoUtils_1.CryptoUtils.createNewGuid();
6374 };
6375 /**
6376 * Create a request signature
6377 * @param request
6378 */
6379 RequestUtils.createRequestSignature = function (request) {
6380 return "" + request.scopes.join(" ").toLowerCase() + Constants_1.Constants.resourceDelimiter + request.authority;
6381 };
6382 return RequestUtils;
6383}());
6384exports.RequestUtils = RequestUtils;
6385
6386
6387/***/ }),
6388
6389/***/ 756:
6390/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6391
6392
6393/*
6394 * Copyright (c) Microsoft Corporation. All rights reserved.
6395 * Licensed under the MIT License.
6396 */
6397Object.defineProperty(exports, "__esModule", ({ value: true }));
6398exports.ResponseUtils = void 0;
6399var tslib_1 = __webpack_require__(795);
6400var Constants_1 = __webpack_require__(91);
6401/*
6402 * Copyright (c) Microsoft Corporation. All rights reserved.
6403 * Licensed under the MIT License.
6404 */
6405/**
6406 * @hidden
6407 */
6408var ResponseUtils = /** @class */ (function () {
6409 function ResponseUtils() {
6410 }
6411 ResponseUtils.setResponseIdToken = function (originalResponse, idTokenObj) {
6412 if (!originalResponse) {
6413 return null;
6414 }
6415 else if (!idTokenObj) {
6416 return originalResponse;
6417 }
6418 var exp = Number(idTokenObj.expiration);
6419 if (exp && !originalResponse.expiresOn) {
6420 originalResponse.expiresOn = new Date(exp * 1000);
6421 }
6422 return tslib_1.__assign(tslib_1.__assign({}, originalResponse), { idToken: idTokenObj, idTokenClaims: idTokenObj.claims, uniqueId: idTokenObj.objectId || idTokenObj.subject, tenantId: idTokenObj.tenantId });
6423 };
6424 ResponseUtils.buildAuthResponse = function (idToken, authResponse, serverAuthenticationRequest, account, scopes, accountState) {
6425 switch (serverAuthenticationRequest.responseType) {
6426 case Constants_1.ResponseTypes.id_token:
6427 var idTokenResponse = tslib_1.__assign(tslib_1.__assign({}, authResponse), { tokenType: Constants_1.ServerHashParamKeys.ID_TOKEN, account: account, scopes: scopes, accountState: accountState });
6428 idTokenResponse = ResponseUtils.setResponseIdToken(idTokenResponse, idToken);
6429 return (idTokenResponse.idToken) ? idTokenResponse : null;
6430 case Constants_1.ResponseTypes.id_token_token:
6431 var idTokeTokenResponse = ResponseUtils.setResponseIdToken(authResponse, idToken);
6432 return (idTokeTokenResponse && idTokeTokenResponse.accessToken && idTokeTokenResponse.idToken) ? idTokeTokenResponse : null;
6433 case Constants_1.ResponseTypes.token:
6434 var tokenResponse = ResponseUtils.setResponseIdToken(authResponse, idToken);
6435 return tokenResponse;
6436 default:
6437 return null;
6438 }
6439 };
6440 return ResponseUtils;
6441}());
6442exports.ResponseUtils = ResponseUtils;
6443
6444
6445/***/ }),
6446
6447/***/ 454:
6448/***/ (function(__unused_webpack_module, exports) {
6449
6450
6451/*
6452 * Copyright (c) Microsoft Corporation. All rights reserved.
6453 * Licensed under the MIT License.
6454 */
6455Object.defineProperty(exports, "__esModule", ({ value: true }));
6456exports.StringUtils = void 0;
6457/**
6458 * @hidden
6459 */
6460var StringUtils = /** @class */ (function () {
6461 function StringUtils() {
6462 }
6463 /**
6464 * Check if a string is empty
6465 *
6466 * @param str
6467 */
6468 StringUtils.isEmpty = function (str) {
6469 return (typeof str === "undefined" || !str || 0 === str.length);
6470 };
6471 /**
6472 * Check if a string's value is a valid JSON object
6473 *
6474 * @param str
6475 */
6476 StringUtils.validateAndParseJsonCacheKey = function (str) {
6477 try {
6478 var parsedKey = JSON.parse(str);
6479 /**
6480 * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
6481 * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
6482 * of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
6483 *
6484 */
6485 return (parsedKey && typeof parsedKey === "object") ? parsedKey : null;
6486 }
6487 catch (error) {
6488 return null;
6489 }
6490 };
6491 return StringUtils;
6492}());
6493exports.StringUtils = StringUtils;
6494
6495
6496/***/ }),
6497
6498/***/ 78:
6499/***/ (function(__unused_webpack_module, exports) {
6500
6501
6502/*
6503 * Copyright (c) Microsoft Corporation. All rights reserved.
6504 * Licensed under the MIT License.
6505 */
6506Object.defineProperty(exports, "__esModule", ({ value: true }));
6507exports.TimeUtils = void 0;
6508/**
6509 * @hidden
6510 */
6511var TimeUtils = /** @class */ (function () {
6512 function TimeUtils() {
6513 }
6514 /**
6515 * Returns time in seconds for expiration based on string value passed in.
6516 *
6517 * @param expiresIn
6518 */
6519 TimeUtils.parseExpiresIn = function (expiresIn) {
6520 // if AAD did not send "expires_in" property, use default expiration of 3599 seconds, for some reason AAD sends 3599 as "expires_in" value instead of 3600
6521 var expires = expiresIn || "3599";
6522 return parseInt(expires, 10);
6523 };
6524 /**
6525 * Return the current time in Unix time (seconds). Date.getTime() returns in milliseconds.
6526 */
6527 TimeUtils.now = function () {
6528 return Math.round(new Date().getTime() / 1000.0);
6529 };
6530 /**
6531 * Returns the amount of time in milliseconds since the page loaded.
6532 */
6533 TimeUtils.relativeNowMs = function () {
6534 return window.performance.now();
6535 };
6536 return TimeUtils;
6537}());
6538exports.TimeUtils = TimeUtils;
6539
6540
6541/***/ }),
6542
6543/***/ 94:
6544/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6545
6546
6547/*
6548 * Copyright (c) Microsoft Corporation. All rights reserved.
6549 * Licensed under the MIT License.
6550 */
6551Object.defineProperty(exports, "__esModule", ({ value: true }));
6552exports.TokenUtils = void 0;
6553var CryptoUtils_1 = __webpack_require__(453);
6554var StringUtils_1 = __webpack_require__(454);
6555var TimeUtils_1 = __webpack_require__(78);
6556/**
6557 * @hidden
6558 */
6559var TokenUtils = /** @class */ (function () {
6560 function TokenUtils() {
6561 }
6562 /**
6563 * decode a JWT
6564 *
6565 * @param jwtToken
6566 */
6567 TokenUtils.decodeJwt = function (jwtToken) {
6568 if (StringUtils_1.StringUtils.isEmpty(jwtToken)) {
6569 return null;
6570 }
6571 var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;
6572 var matches = idTokenPartsRegex.exec(jwtToken);
6573 if (!matches || matches.length < 4) {
6574 // this._requestContext.logger.warn("The returned id_token is not parseable.");
6575 return null;
6576 }
6577 var crackedToken = {
6578 header: matches[1],
6579 JWSPayload: matches[2],
6580 JWSSig: matches[3]
6581 };
6582 return crackedToken;
6583 };
6584 /**
6585 * Evaluates whether token cache item expiration is within expiration offset range
6586 * @param tokenCacheItem
6587 */
6588 TokenUtils.validateExpirationIsWithinOffset = function (expiration, tokenRenewalOffsetSeconds) {
6589 var offset = tokenRenewalOffsetSeconds || 300;
6590 return expiration && (expiration > TimeUtils_1.TimeUtils.now() + offset);
6591 };
6592 /**
6593 * Extract IdToken by decoding the RAWIdToken
6594 *
6595 * @param encodedIdToken
6596 */
6597 TokenUtils.extractIdToken = function (encodedIdToken) {
6598 // id token will be decoded to get the username
6599 var decodedToken = this.decodeJwt(encodedIdToken);
6600 if (!decodedToken) {
6601 return null;
6602 }
6603 try {
6604 var base64IdToken = decodedToken["JWSPayload"];
6605 var base64Decoded = CryptoUtils_1.CryptoUtils.base64Decode(base64IdToken);
6606 if (!base64Decoded) {
6607 // this._requestContext.logger.info("The returned id_token could not be base64 url safe decoded.");
6608 return null;
6609 }
6610 // ECMA script has JSON built-in support
6611 return JSON.parse(base64Decoded);
6612 }
6613 catch (err) {
6614 // this._requestContext.logger.error("The returned id_token could not be decoded" + err);
6615 }
6616 return null;
6617 };
6618 return TokenUtils;
6619}());
6620exports.TokenUtils = TokenUtils;
6621
6622
6623/***/ }),
6624
6625/***/ 741:
6626/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6627
6628
6629/*
6630 * Copyright (c) Microsoft Corporation. All rights reserved.
6631 * Licensed under the MIT License.
6632 */
6633Object.defineProperty(exports, "__esModule", ({ value: true }));
6634exports.UrlUtils = void 0;
6635var Constants_1 = __webpack_require__(91);
6636var ScopeSet_1 = __webpack_require__(55);
6637var StringUtils_1 = __webpack_require__(454);
6638var CryptoUtils_1 = __webpack_require__(453);
6639/**
6640 * @hidden
6641 */
6642var UrlUtils = /** @class */ (function () {
6643 function UrlUtils() {
6644 }
6645 /**
6646 * generates the URL with QueryString Parameters
6647 * @param scopes
6648 */
6649 UrlUtils.createNavigateUrl = function (serverRequestParams) {
6650 var str = this.createNavigationUrlString(serverRequestParams);
6651 var authEndpoint = serverRequestParams.authorityInstance.AuthorizationEndpoint;
6652 // if the endpoint already has queryparams, lets add to it, otherwise add the first one
6653 if (authEndpoint.indexOf("?") < 0) {
6654 authEndpoint += "?";
6655 }
6656 else {
6657 authEndpoint += "&";
6658 }
6659 var requestUrl = "" + authEndpoint + str.join("&");
6660 return requestUrl;
6661 };
6662 /**
6663 * Generate the array of all QueryStringParams to be sent to the server
6664 * @param scopes
6665 */
6666 UrlUtils.createNavigationUrlString = function (serverRequestParams) {
6667 var scopes = ScopeSet_1.ScopeSet.appendDefaultScopes(serverRequestParams.scopes);
6668 var str = [];
6669 str.push("response_type=" + serverRequestParams.responseType);
6670 str.push("scope=" + encodeURIComponent(ScopeSet_1.ScopeSet.parseScope(scopes)));
6671 str.push("client_id=" + encodeURIComponent(serverRequestParams.clientId));
6672 str.push("redirect_uri=" + encodeURIComponent(serverRequestParams.redirectUri));
6673 str.push("state=" + encodeURIComponent(serverRequestParams.state));
6674 str.push("nonce=" + encodeURIComponent(serverRequestParams.nonce));
6675 str.push("client_info=1");
6676 str.push("x-client-SKU=" + serverRequestParams.xClientSku);
6677 str.push("x-client-Ver=" + serverRequestParams.xClientVer);
6678 if (serverRequestParams.promptValue) {
6679 str.push("prompt=" + encodeURIComponent(serverRequestParams.promptValue));
6680 }
6681 if (serverRequestParams.claimsValue) {
6682 str.push("claims=" + encodeURIComponent(serverRequestParams.claimsValue));
6683 }
6684 if (serverRequestParams.queryParameters) {
6685 str.push(serverRequestParams.queryParameters);
6686 }
6687 if (serverRequestParams.extraQueryParameters) {
6688 str.push(serverRequestParams.extraQueryParameters);
6689 }
6690 str.push("client-request-id=" + encodeURIComponent(serverRequestParams.correlationId));
6691 return str;
6692 };
6693 /**
6694 * Returns current window URL as redirect uri
6695 */
6696 UrlUtils.getCurrentUrl = function () {
6697 return window.location.href.split("?")[0].split("#")[0];
6698 };
6699 /**
6700 * Returns given URL with query string removed
6701 */
6702 UrlUtils.removeHashFromUrl = function (url) {
6703 return url.split("#")[0];
6704 };
6705 /**
6706 * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d
6707 * @param href The url
6708 * @param tenantId The tenant id to replace
6709 */
6710 UrlUtils.replaceTenantPath = function (url, tenantId) {
6711 var lowerCaseUrl = url.toLowerCase();
6712 var urlObject = this.GetUrlComponents(lowerCaseUrl);
6713 var pathArray = urlObject.PathSegments;
6714 if (tenantId && (pathArray.length !== 0 && (pathArray[0] === Constants_1.Constants.common || pathArray[0] === Constants_1.SSOTypes.ORGANIZATIONS || pathArray[0] === Constants_1.SSOTypes.CONSUMERS))) {
6715 pathArray[0] = tenantId;
6716 }
6717 return this.constructAuthorityUriFromObject(urlObject, pathArray);
6718 };
6719 UrlUtils.constructAuthorityUriFromObject = function (urlObject, pathArray) {
6720 return this.CanonicalizeUri(urlObject.Protocol + "//" + urlObject.HostNameAndPort + "/" + pathArray.join("/"));
6721 };
6722 /**
6723 * Checks if an authority is common (ex. https://a:b/common/)
6724 * @param url The url
6725 * @returns true if authority is common and false otherwise
6726 */
6727 UrlUtils.isCommonAuthority = function (url) {
6728 var authority = this.CanonicalizeUri(url);
6729 var pathArray = this.GetUrlComponents(authority).PathSegments;
6730 return (pathArray.length !== 0 && pathArray[0] === Constants_1.Constants.common);
6731 };
6732 /**
6733 * Checks if an authority is for organizations (ex. https://a:b/organizations/)
6734 * @param url The url
6735 * @returns true if authority is for and false otherwise
6736 */
6737 UrlUtils.isOrganizationsAuthority = function (url) {
6738 var authority = this.CanonicalizeUri(url);
6739 var pathArray = this.GetUrlComponents(authority).PathSegments;
6740 return (pathArray.length !== 0 && pathArray[0] === Constants_1.SSOTypes.ORGANIZATIONS);
6741 };
6742 /**
6743 * Checks if an authority is for consumers (ex. https://a:b/consumers/)
6744 * @param url The url
6745 * @returns true if authority is for and false otherwise
6746 */
6747 UrlUtils.isConsumersAuthority = function (url) {
6748 var authority = this.CanonicalizeUri(url);
6749 var pathArray = this.GetUrlComponents(authority).PathSegments;
6750 return (pathArray.length !== 0 && pathArray[0] === Constants_1.SSOTypes.CONSUMERS);
6751 };
6752 /**
6753 * Parses out the components from a url string.
6754 * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url.
6755 */
6756 UrlUtils.GetUrlComponents = function (url) {
6757 if (!url) {
6758 throw "Url required";
6759 }
6760 // https://gist.github.com/curtisz/11139b2cfcaef4a261e0
6761 var regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
6762 var match = url.match(regEx);
6763 if (!match || match.length < 6) {
6764 throw "Valid url required";
6765 }
6766 var urlComponents = {
6767 Protocol: match[1],
6768 HostNameAndPort: match[4],
6769 AbsolutePath: match[5]
6770 };
6771 var pathSegments = urlComponents.AbsolutePath.split("/");
6772 pathSegments = pathSegments.filter(function (val) { return val && val.length > 0; }); // remove empty elements
6773 urlComponents.PathSegments = pathSegments;
6774 if (match[6]) {
6775 urlComponents.Search = match[6];
6776 }
6777 if (match[8]) {
6778 urlComponents.Hash = match[8];
6779 }
6780 return urlComponents;
6781 };
6782 /**
6783 * Given a url or path, append a trailing slash if one doesnt exist
6784 *
6785 * @param url
6786 */
6787 UrlUtils.CanonicalizeUri = function (url) {
6788 if (url) {
6789 var lowerCaseUrl = url.toLowerCase();
6790 if (!UrlUtils.endsWith(lowerCaseUrl, "/")) {
6791 lowerCaseUrl += "/";
6792 }
6793 return lowerCaseUrl;
6794 }
6795 return url;
6796 };
6797 /**
6798 * Checks to see if the url ends with the suffix
6799 * Required because we are compiling for es5 instead of es6
6800 * @param url
6801 * @param str
6802 */
6803 // TODO: Rename this, not clear what it is supposed to do
6804 UrlUtils.endsWith = function (url, suffix) {
6805 if (!url || !suffix) {
6806 return false;
6807 }
6808 return url.indexOf(suffix, url.length - suffix.length) !== -1;
6809 };
6810 /**
6811 * Utils function to remove the login_hint and domain_hint from the i/p extraQueryParameters
6812 * @param url
6813 * @param name
6814 */
6815 UrlUtils.urlRemoveQueryStringParameter = function (url, name) {
6816 if (StringUtils_1.StringUtils.isEmpty(url)) {
6817 return url;
6818 }
6819 var updatedUrl = url;
6820 var regex = new RegExp("(\\&" + name + "=)[^\&]+");
6821 updatedUrl = url.replace(regex, "");
6822 // name=value&
6823 regex = new RegExp("(" + name + "=)[^\&]+&");
6824 updatedUrl = url.replace(regex, "");
6825 // name=value
6826 regex = new RegExp("(" + name + "=)[^\&]+");
6827 updatedUrl = url.replace(regex, "");
6828 return updatedUrl;
6829 };
6830 /**
6831 * @hidden
6832 * @ignore
6833 *
6834 * Returns the anchor part(#) of the URL
6835 */
6836 UrlUtils.getHashFromUrl = function (urlStringOrFragment) {
6837 var hashIndex1 = urlStringOrFragment.indexOf("#");
6838 var hashIndex2 = urlStringOrFragment.indexOf("#/");
6839 if (hashIndex2 > -1) {
6840 return urlStringOrFragment.substring(hashIndex2 + 2);
6841 }
6842 else if (hashIndex1 > -1) {
6843 return urlStringOrFragment.substring(hashIndex1 + 1);
6844 }
6845 return urlStringOrFragment;
6846 };
6847 /**
6848 * @hidden
6849 * Check if the url contains a hash with known properties
6850 * @ignore
6851 */
6852 UrlUtils.urlContainsHash = function (urlString) {
6853 var parameters = UrlUtils.deserializeHash(urlString);
6854 return (parameters.hasOwnProperty(Constants_1.ServerHashParamKeys.ERROR_DESCRIPTION) ||
6855 parameters.hasOwnProperty(Constants_1.ServerHashParamKeys.ERROR) ||
6856 parameters.hasOwnProperty(Constants_1.ServerHashParamKeys.ACCESS_TOKEN) ||
6857 parameters.hasOwnProperty(Constants_1.ServerHashParamKeys.ID_TOKEN));
6858 };
6859 /**
6860 * @hidden
6861 * Returns deserialized portion of URL hash
6862 * @ignore
6863 */
6864 UrlUtils.deserializeHash = function (urlFragment) {
6865 var hash = UrlUtils.getHashFromUrl(urlFragment);
6866 return CryptoUtils_1.CryptoUtils.deserialize(hash);
6867 };
6868 /**
6869 * @ignore
6870 * @param {string} URI
6871 * @returns {string} host from the URI
6872 *
6873 * extract URI from the host
6874 */
6875 UrlUtils.getHostFromUri = function (uri) {
6876 // remove http:// or https:// from uri
6877 var extractedUri = String(uri).replace(/^(https?:)\/\//, "");
6878 extractedUri = extractedUri.split("/")[0];
6879 return extractedUri;
6880 };
6881 return UrlUtils;
6882}());
6883exports.UrlUtils = UrlUtils;
6884
6885
6886/***/ }),
6887
6888/***/ 758:
6889/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6890
6891
6892/*
6893 * Copyright (c) Microsoft Corporation. All rights reserved.
6894 * Licensed under the MIT License.
6895 */
6896Object.defineProperty(exports, "__esModule", ({ value: true }));
6897exports.WindowUtils = void 0;
6898var ClientAuthError_1 = __webpack_require__(356);
6899var UrlUtils_1 = __webpack_require__(741);
6900var Constants_1 = __webpack_require__(91);
6901var TimeUtils_1 = __webpack_require__(78);
6902var WindowUtils = /** @class */ (function () {
6903 function WindowUtils() {
6904 }
6905 /**
6906 * @hidden
6907 * Checks if the current page is running in an iframe.
6908 * @ignore
6909 */
6910 WindowUtils.isInIframe = function () {
6911 return window.parent !== window;
6912 };
6913 /**
6914 * @hidden
6915 * Check if the current page is running in a popup.
6916 * @ignore
6917 */
6918 WindowUtils.isInPopup = function () {
6919 return !!(window.opener && window.opener !== window);
6920 };
6921 /**
6922 * @hidden
6923 * @param prefix
6924 * @param scopes
6925 * @param authority
6926 */
6927 WindowUtils.generateFrameName = function (prefix, requestSignature) {
6928 return "" + prefix + Constants_1.Constants.resourceDelimiter + requestSignature;
6929 };
6930 /**
6931 * @hidden
6932 * Polls an iframe until it loads a url with a hash
6933 * @ignore
6934 */
6935 WindowUtils.monitorIframeForHash = function (contentWindow, timeout, urlNavigate, logger) {
6936 return new Promise(function (resolve, reject) {
6937 /*
6938 * Polling for iframes can be purely timing based,
6939 * since we don't need to account for interaction.
6940 */
6941 var nowMark = TimeUtils_1.TimeUtils.relativeNowMs();
6942 var timeoutMark = nowMark + timeout;
6943 logger.verbose("monitorWindowForIframe polling started");
6944 var intervalId = setInterval(function () {
6945 if (TimeUtils_1.TimeUtils.relativeNowMs() > timeoutMark) {
6946 logger.error("monitorIframeForHash unable to find hash in url, timing out");
6947 logger.errorPii("monitorIframeForHash polling timed out for url: " + urlNavigate);
6948 clearInterval(intervalId);
6949 reject(ClientAuthError_1.ClientAuthError.createTokenRenewalTimeoutError());
6950 return;
6951 }
6952 var href;
6953 try {
6954 /*
6955 * Will throw if cross origin,
6956 * which should be caught and ignored
6957 * since we need the interval to keep running while on STS UI.
6958 */
6959 href = contentWindow.location.href;
6960 }
6961 catch (e) { }
6962 if (href && UrlUtils_1.UrlUtils.urlContainsHash(href)) {
6963 logger.verbose("monitorIframeForHash found url in hash");
6964 clearInterval(intervalId);
6965 resolve(contentWindow.location.hash);
6966 }
6967 }, WindowUtils.POLLING_INTERVAL_MS);
6968 });
6969 };
6970 /**
6971 * @hidden
6972 * Polls a popup until it loads a url with a hash
6973 * @ignore
6974 */
6975 WindowUtils.monitorPopupForHash = function (contentWindow, timeout, urlNavigate, logger) {
6976 return new Promise(function (resolve, reject) {
6977 /*
6978 * Polling for popups needs to be tick-based,
6979 * since a non-trivial amount of time can be spent on interaction (which should not count against the timeout).
6980 */
6981 var maxTicks = timeout / WindowUtils.POLLING_INTERVAL_MS;
6982 var ticks = 0;
6983 logger.verbose("monitorWindowForHash polling started");
6984 var intervalId = setInterval(function () {
6985 if (contentWindow.closed) {
6986 logger.error("monitorWindowForHash window closed");
6987 clearInterval(intervalId);
6988 reject(ClientAuthError_1.ClientAuthError.createUserCancelledError());
6989 return;
6990 }
6991 var href;
6992 try {
6993 /*
6994 * Will throw if cross origin,
6995 * which should be caught and ignored
6996 * since we need the interval to keep running while on STS UI.
6997 */
6998 href = contentWindow.location.href;
6999 }
7000 catch (e) { }
7001 // Don't process blank pages or cross domain
7002 if (!href || href === "about:blank") {
7003 return;
7004 }
7005 /*
7006 * Only run clock when we are on same domain for popups
7007 * as popup operations can take a long time.
7008 */
7009 ticks++;
7010 if (href && UrlUtils_1.UrlUtils.urlContainsHash(href)) {
7011 logger.verbose("monitorPopupForHash found url in hash");
7012 clearInterval(intervalId);
7013 var hash = contentWindow.location.hash;
7014 WindowUtils.clearUrlFragment(contentWindow);
7015 resolve(hash);
7016 }
7017 else if (ticks > maxTicks) {
7018 logger.error("monitorPopupForHash unable to find hash in url, timing out");
7019 logger.errorPii("monitorPopupForHash polling timed out for url: " + urlNavigate);
7020 clearInterval(intervalId);
7021 reject(ClientAuthError_1.ClientAuthError.createTokenRenewalTimeoutError());
7022 }
7023 }, WindowUtils.POLLING_INTERVAL_MS);
7024 });
7025 };
7026 /**
7027 * @hidden
7028 * Loads iframe with authorization endpoint URL
7029 * @ignore
7030 */
7031 WindowUtils.loadFrame = function (urlNavigate, frameName, timeoutMs, logger) {
7032 var _this = this;
7033 /*
7034 * This trick overcomes iframe navigation in IE
7035 * IE does not load the page consistently in iframe
7036 */
7037 logger.infoPii("LoadFrame: " + frameName);
7038 return new Promise(function (resolve, reject) {
7039 setTimeout(function () {
7040 var frameHandle = _this.loadFrameSync(urlNavigate, frameName, logger);
7041 if (!frameHandle) {
7042 reject("Unable to load iframe with name: " + frameName);
7043 return;
7044 }
7045 resolve(frameHandle);
7046 }, timeoutMs);
7047 });
7048 };
7049 /**
7050 * @hidden
7051 * Loads the iframe synchronously when the navigateTimeFrame is set to `0`
7052 * @param urlNavigate
7053 * @param frameName
7054 * @param logger
7055 */
7056 WindowUtils.loadFrameSync = function (urlNavigate, frameName, logger) {
7057 var frameHandle = WindowUtils.addHiddenIFrame(frameName, logger);
7058 // returning to handle null in loadFrame, also to avoid null object access errors
7059 if (!frameHandle) {
7060 return null;
7061 }
7062 else if (frameHandle.src === "" || frameHandle.src === "about:blank") {
7063 frameHandle.src = urlNavigate;
7064 logger.infoPii("Frame Name : " + frameName + " Navigated to: " + urlNavigate);
7065 }
7066 return frameHandle;
7067 };
7068 /**
7069 * @hidden
7070 * Adds the hidden iframe for silent token renewal.
7071 * @ignore
7072 */
7073 WindowUtils.addHiddenIFrame = function (iframeId, logger) {
7074 if (typeof iframeId === "undefined") {
7075 return null;
7076 }
7077 logger.info("Add msal iframe to document");
7078 logger.infoPii("Add msal frame to document:" + iframeId);
7079 var adalFrame = document.getElementById(iframeId);
7080 if (!adalFrame) {
7081 logger.verbose("Add msal iframe does not exist");
7082 var ifr = document.createElement("iframe");
7083 ifr.setAttribute("id", iframeId);
7084 ifr.setAttribute("aria-hidden", "true");
7085 ifr.style.visibility = "hidden";
7086 ifr.style.position = "absolute";
7087 ifr.style.width = ifr.style.height = "0";
7088 ifr.style.border = "0";
7089 ifr.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
7090 adalFrame = document.getElementsByTagName("body")[0].appendChild(ifr);
7091 }
7092 else {
7093 logger.verbose("Add msal iframe already exists");
7094 }
7095 return adalFrame;
7096 };
7097 /**
7098 * @hidden
7099 * Removes a hidden iframe from the page.
7100 * @ignore
7101 */
7102 WindowUtils.removeHiddenIframe = function (iframe) {
7103 if (document.body === iframe.parentNode) {
7104 document.body.removeChild(iframe);
7105 }
7106 };
7107 /**
7108 * @hidden
7109 * Find and return the iframe element with the given hash
7110 * @ignore
7111 */
7112 WindowUtils.getIframeWithHash = function (hash) {
7113 var iframes = document.getElementsByTagName("iframe");
7114 var iframeArray = Array.apply(null, Array(iframes.length)).map(function (iframe, index) { return iframes.item(index); }); // eslint-disable-line prefer-spread
7115 return iframeArray.filter(function (iframe) {
7116 try {
7117 return iframe.contentWindow.location.hash === hash;
7118 }
7119 catch (e) {
7120 return false;
7121 }
7122 })[0];
7123 };
7124 /**
7125 * @hidden
7126 * Returns an array of all the popups opened by MSAL
7127 * @ignore
7128 */
7129 WindowUtils.getPopups = function () {
7130 if (!window.openedWindows) {
7131 window.openedWindows = [];
7132 }
7133 return window.openedWindows;
7134 };
7135 /**
7136 * @hidden
7137 * Find and return the popup with the given hash
7138 * @ignore
7139 */
7140 WindowUtils.getPopUpWithHash = function (hash) {
7141 return WindowUtils.getPopups().filter(function (popup) {
7142 try {
7143 return popup.location.hash === hash;
7144 }
7145 catch (e) {
7146 return false;
7147 }
7148 })[0];
7149 };
7150 /**
7151 * @hidden
7152 * Add the popup to the known list of popups
7153 * @ignore
7154 */
7155 WindowUtils.trackPopup = function (popup) {
7156 WindowUtils.getPopups().push(popup);
7157 };
7158 /**
7159 * @hidden
7160 * Close all popups
7161 * @ignore
7162 */
7163 WindowUtils.closePopups = function () {
7164 WindowUtils.getPopups().forEach(function (popup) { return popup.close(); });
7165 };
7166 /**
7167 * @ignore
7168 *
7169 * blocks any login/acquireToken calls to reload from within a hidden iframe (generated for silent calls)
7170 */
7171 WindowUtils.blockReloadInHiddenIframes = function () {
7172 // return an error if called from the hidden iframe created by the msal js silent calls
7173 if (UrlUtils_1.UrlUtils.urlContainsHash(window.location.hash) && WindowUtils.isInIframe()) {
7174 throw ClientAuthError_1.ClientAuthError.createBlockTokenRequestsInHiddenIframeError();
7175 }
7176 };
7177 /**
7178 *
7179 * @param cacheStorage
7180 */
7181 WindowUtils.checkIfBackButtonIsPressed = function (cacheStorage) {
7182 var redirectCache = cacheStorage.getItem(Constants_1.TemporaryCacheKeys.REDIRECT_REQUEST);
7183 // if redirect request is set and there is no hash
7184 if (redirectCache && !UrlUtils_1.UrlUtils.urlContainsHash(window.location.hash)) {
7185 var splitCache = redirectCache.split(Constants_1.Constants.resourceDelimiter);
7186 splitCache.shift();
7187 var state = splitCache.length > 0 ? splitCache.join(Constants_1.Constants.resourceDelimiter) : null;
7188 cacheStorage.resetTempCacheItems(state);
7189 }
7190 };
7191 /**
7192 * Removes url fragment from browser url
7193 */
7194 WindowUtils.clearUrlFragment = function (contentWindow) {
7195 contentWindow.location.hash = "";
7196 // Office.js sets history.replaceState to null
7197 if (typeof contentWindow.history.replaceState === "function") {
7198 // Full removes "#" from url
7199 contentWindow.history.replaceState(null, null, "" + contentWindow.location.pathname + contentWindow.location.search);
7200 }
7201 };
7202 /**
7203 * @hidden
7204 * Interval in milliseconds that we poll a window
7205 * @ignore
7206 */
7207 WindowUtils.POLLING_INTERVAL_MS = 50;
7208 return WindowUtils;
7209}());
7210exports.WindowUtils = WindowUtils;
7211
7212
7213/***/ })
7214
7215/******/ });
7216/************************************************************************/
7217/******/ // The module cache
7218/******/ var __webpack_module_cache__ = {};
7219/******/
7220/******/ // The require function
7221/******/ function __webpack_require__(moduleId) {
7222/******/ // Check if module is in cache
7223/******/ var cachedModule = __webpack_module_cache__[moduleId];
7224/******/ if (cachedModule !== undefined) {
7225/******/ return cachedModule.exports;
7226/******/ }
7227/******/ // Create a new module (and put it into the cache)
7228/******/ var module = __webpack_module_cache__[moduleId] = {
7229/******/ // no module.id needed
7230/******/ // no module.loaded needed
7231/******/ exports: {}
7232/******/ };
7233/******/
7234/******/ // Execute the module function
7235/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
7236/******/
7237/******/ // Return the exports of the module
7238/******/ return module.exports;
7239/******/ }
7240/******/
7241/************************************************************************/
7242var __webpack_exports__ = {};
7243// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
7244!function() {
7245var exports = __webpack_exports__;
7246
7247/*
7248 * Copyright (c) Microsoft Corporation. All rights reserved.
7249 * Licensed under the MIT License.
7250 */
7251Object.defineProperty(exports, "__esModule", ({ value: true }));
7252/**
7253 * @packageDocumentation
7254 * @module @azure/msal
7255 */
7256var UserAgentApplication_1 = __webpack_require__(463);
7257Object.defineProperty(exports, "UserAgentApplication", ({ enumerable: true, get: function () { return UserAgentApplication_1.UserAgentApplication; } }));
7258Object.defineProperty(exports, "authResponseCallback", ({ enumerable: true, get: function () { return UserAgentApplication_1.authResponseCallback; } }));
7259Object.defineProperty(exports, "errorReceivedCallback", ({ enumerable: true, get: function () { return UserAgentApplication_1.errorReceivedCallback; } }));
7260Object.defineProperty(exports, "tokenReceivedCallback", ({ enumerable: true, get: function () { return UserAgentApplication_1.tokenReceivedCallback; } }));
7261var Logger_1 = __webpack_require__(89);
7262Object.defineProperty(exports, "Logger", ({ enumerable: true, get: function () { return Logger_1.Logger; } }));
7263var Logger_2 = __webpack_require__(89);
7264Object.defineProperty(exports, "LogLevel", ({ enumerable: true, get: function () { return Logger_2.LogLevel; } }));
7265var Account_1 = __webpack_require__(630);
7266Object.defineProperty(exports, "Account", ({ enumerable: true, get: function () { return Account_1.Account; } }));
7267var Constants_1 = __webpack_require__(91);
7268Object.defineProperty(exports, "Constants", ({ enumerable: true, get: function () { return Constants_1.Constants; } }));
7269Object.defineProperty(exports, "ServerHashParamKeys", ({ enumerable: true, get: function () { return Constants_1.ServerHashParamKeys; } }));
7270var Authority_1 = __webpack_require__(660);
7271Object.defineProperty(exports, "Authority", ({ enumerable: true, get: function () { return Authority_1.Authority; } }));
7272var UserAgentApplication_2 = __webpack_require__(463);
7273Object.defineProperty(exports, "CacheResult", ({ enumerable: true, get: function () { return UserAgentApplication_2.CacheResult; } }));
7274var Configuration_1 = __webpack_require__(875);
7275Object.defineProperty(exports, "CacheLocation", ({ enumerable: true, get: function () { return Configuration_1.CacheLocation; } }));
7276Object.defineProperty(exports, "Configuration", ({ enumerable: true, get: function () { return Configuration_1.Configuration; } }));
7277var AuthenticationParameters_1 = __webpack_require__(733);
7278Object.defineProperty(exports, "AuthenticationParameters", ({ enumerable: true, get: function () { return AuthenticationParameters_1.AuthenticationParameters; } }));
7279var AuthResponse_1 = __webpack_require__(681);
7280Object.defineProperty(exports, "AuthResponse", ({ enumerable: true, get: function () { return AuthResponse_1.AuthResponse; } }));
7281var CryptoUtils_1 = __webpack_require__(453);
7282Object.defineProperty(exports, "CryptoUtils", ({ enumerable: true, get: function () { return CryptoUtils_1.CryptoUtils; } }));
7283var UrlUtils_1 = __webpack_require__(741);
7284Object.defineProperty(exports, "UrlUtils", ({ enumerable: true, get: function () { return UrlUtils_1.UrlUtils; } }));
7285var WindowUtils_1 = __webpack_require__(758);
7286Object.defineProperty(exports, "WindowUtils", ({ enumerable: true, get: function () { return WindowUtils_1.WindowUtils; } }));
7287// Errors
7288var AuthError_1 = __webpack_require__(986);
7289Object.defineProperty(exports, "AuthError", ({ enumerable: true, get: function () { return AuthError_1.AuthError; } }));
7290var ClientAuthError_1 = __webpack_require__(356);
7291Object.defineProperty(exports, "ClientAuthError", ({ enumerable: true, get: function () { return ClientAuthError_1.ClientAuthError; } }));
7292var ServerError_1 = __webpack_require__(447);
7293Object.defineProperty(exports, "ServerError", ({ enumerable: true, get: function () { return ServerError_1.ServerError; } }));
7294var ClientConfigurationError_1 = __webpack_require__(550);
7295Object.defineProperty(exports, "ClientConfigurationError", ({ enumerable: true, get: function () { return ClientConfigurationError_1.ClientConfigurationError; } }));
7296var InteractionRequiredAuthError_1 = __webpack_require__(961);
7297Object.defineProperty(exports, "InteractionRequiredAuthError", ({ enumerable: true, get: function () { return InteractionRequiredAuthError_1.InteractionRequiredAuthError; } }));
7298var packageMetadata_1 = __webpack_require__(700);
7299Object.defineProperty(exports, "version", ({ enumerable: true, get: function () { return packageMetadata_1.version; } }));
7300
7301}();
7302/******/ return __webpack_exports__;
7303/******/ })()
7304;
7305});
7306//# sourceMappingURL=msal.js.map
\No newline at end of file