@microsoft/teamsfx 0.4.1-rc.0 → 0.4.2-alpha.29989668.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- import { __extends, __awaiter, __generator } from 'tslib';
2
1
  import jwt_decode from 'jwt-decode';
2
+ import { __awaiter } from 'tslib';
3
3
  import * as microsoftTeams from '@microsoft/teams-js';
4
- import axios from 'axios';
4
+ import { PublicClientApplication } from '@azure/msal-browser';
5
5
  import { Client } from '@microsoft/microsoft-graph-client';
6
- import { ManagedIdentityCredential } from '@azure/identity';
7
6
 
8
7
  // Copyright (c) Microsoft Corporation.
8
+ // Licensed under the MIT license.
9
9
  /**
10
10
  * Error code to trace the error types.
11
11
  * @beta
@@ -56,35 +56,35 @@ var ErrorCode;
56
56
  * Operation failed.
57
57
  */
58
58
  ErrorCode["FailedOperation"] = "FailedOperation";
59
+ /**
60
+ * Invalid response error.
61
+ */
62
+ ErrorCode["InvalidResponse"] = "InvalidResponse";
59
63
  })(ErrorCode || (ErrorCode = {}));
60
64
  /**
61
65
  * @internal
62
66
  */
63
- var ErrorMessage = /** @class */ (function () {
64
- function ErrorMessage() {
65
- }
66
- // InvalidConfiguration Error
67
- ErrorMessage.InvalidConfiguration = "{0} in configuration is invalid: {1}.";
68
- ErrorMessage.ConfigurationNotExists = "Configuration does not exist. {0}";
69
- ErrorMessage.ResourceConfigurationNotExists = "{0} resource configuration does not exist.";
70
- ErrorMessage.MissingResourceConfiguration = "Missing resource configuration with type: {0}, name: {1}.";
71
- ErrorMessage.AuthenticationConfigurationNotExists = "Authentication configuration does not exist.";
72
- // RuntimeNotSupported Error
73
- ErrorMessage.BrowserRuntimeNotSupported = "{0} is not supported in browser.";
74
- ErrorMessage.NodejsRuntimeNotSupported = "{0} is not supported in Node.";
75
- // Internal Error
76
- ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token on behalf of user: {0}";
77
- // ChannelNotSupported Error
78
- ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
79
- return ErrorMessage;
80
- }());
67
+ class ErrorMessage {
68
+ }
69
+ // InvalidConfiguration Error
70
+ ErrorMessage.InvalidConfiguration = "{0} in configuration is invalid: {1}.";
71
+ ErrorMessage.ConfigurationNotExists = "Configuration does not exist. {0}";
72
+ ErrorMessage.ResourceConfigurationNotExists = "{0} resource configuration does not exist.";
73
+ ErrorMessage.MissingResourceConfiguration = "Missing resource configuration with type: {0}, name: {1}.";
74
+ ErrorMessage.AuthenticationConfigurationNotExists = "Authentication configuration does not exist.";
75
+ // RuntimeNotSupported Error
76
+ ErrorMessage.BrowserRuntimeNotSupported = "{0} is not supported in browser.";
77
+ ErrorMessage.NodejsRuntimeNotSupported = "{0} is not supported in Node.";
78
+ // Internal Error
79
+ ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token on behalf of user: {0}";
80
+ // ChannelNotSupported Error
81
+ ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
81
82
  /**
82
83
  * Error class with code and message thrown by the SDK.
83
84
  *
84
85
  * @beta
85
86
  */
86
- var ErrorWithCode = /** @class */ (function (_super) {
87
- __extends(ErrorWithCode, _super);
87
+ class ErrorWithCode extends Error {
88
88
  /**
89
89
  * Constructor of ErrorWithCode.
90
90
  *
@@ -93,21 +93,17 @@ var ErrorWithCode = /** @class */ (function (_super) {
93
93
  *
94
94
  * @beta
95
95
  */
96
- function ErrorWithCode(message, code) {
97
- var _newTarget = this.constructor;
98
- var _this = this;
96
+ constructor(message, code) {
99
97
  if (!code) {
100
- _this = _super.call(this, message) || this;
101
- return _this;
98
+ super(message);
99
+ return this;
102
100
  }
103
- _this = _super.call(this, message) || this;
104
- Object.setPrototypeOf(_this, ErrorWithCode.prototype);
105
- _this.name = _newTarget.name + "." + code;
106
- _this.code = code;
107
- return _this;
101
+ super(message);
102
+ Object.setPrototypeOf(this, ErrorWithCode.prototype);
103
+ this.name = `${new.target.name}.${code}`;
104
+ this.code = code;
108
105
  }
109
- return ErrorWithCode;
110
- }(Error));
106
+ }
111
107
 
112
108
  // Copyright (c) Microsoft Corporation.
113
109
  // Licensed under the MIT license.
@@ -175,8 +171,8 @@ function setLogLevel(level) {
175
171
  function getLogLevel() {
176
172
  return internalLogger.level;
177
173
  }
178
- var InternalLogger = /** @class */ (function () {
179
- function InternalLogger() {
174
+ class InternalLogger {
175
+ constructor(name, logLevel) {
180
176
  this.level = undefined;
181
177
  this.defaultLogger = {
182
178
  verbose: console.debug,
@@ -184,26 +180,34 @@ var InternalLogger = /** @class */ (function () {
184
180
  warn: console.warn,
185
181
  error: console.error,
186
182
  };
183
+ this.name = name;
184
+ this.level = logLevel;
187
185
  }
188
- InternalLogger.prototype.error = function (message) {
189
- this.log(LogLevel.Error, function (x) { return x.error; }, message);
190
- };
191
- InternalLogger.prototype.warn = function (message) {
192
- this.log(LogLevel.Warn, function (x) { return x.warn; }, message);
193
- };
194
- InternalLogger.prototype.info = function (message) {
195
- this.log(LogLevel.Info, function (x) { return x.info; }, message);
196
- };
197
- InternalLogger.prototype.verbose = function (message) {
198
- this.log(LogLevel.Verbose, function (x) { return x.verbose; }, message);
199
- };
200
- InternalLogger.prototype.log = function (logLevel, logFunction, message) {
186
+ error(message) {
187
+ this.log(LogLevel.Error, (x) => x.error, message);
188
+ }
189
+ warn(message) {
190
+ this.log(LogLevel.Warn, (x) => x.warn, message);
191
+ }
192
+ info(message) {
193
+ this.log(LogLevel.Info, (x) => x.info, message);
194
+ }
195
+ verbose(message) {
196
+ this.log(LogLevel.Verbose, (x) => x.verbose, message);
197
+ }
198
+ log(logLevel, logFunction, message) {
201
199
  if (message.trim() === "") {
202
200
  return;
203
201
  }
204
- var timestamp = new Date().toUTCString();
205
- var logHeader = "[" + timestamp + "] : @microsoft/teamsfx : " + LogLevel[logLevel] + " - ";
206
- var logMessage = "" + logHeader + message;
202
+ const timestamp = new Date().toUTCString();
203
+ let logHeader;
204
+ if (this.name) {
205
+ logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;
206
+ }
207
+ else {
208
+ logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
209
+ }
210
+ const logMessage = `${logHeader}${message}`;
207
211
  if (this.level !== undefined && this.level <= logLevel) {
208
212
  if (this.customLogger) {
209
213
  logFunction(this.customLogger)(logMessage);
@@ -215,15 +219,14 @@ var InternalLogger = /** @class */ (function () {
215
219
  logFunction(this.defaultLogger)(logMessage);
216
220
  }
217
221
  }
218
- };
219
- return InternalLogger;
220
- }());
222
+ }
223
+ }
221
224
  /**
222
225
  * Logger instance used internally
223
226
  *
224
227
  * @internal
225
228
  */
226
- var internalLogger = new InternalLogger();
229
+ const internalLogger = new InternalLogger();
227
230
  /**
228
231
  * Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.
229
232
  *
@@ -276,14 +279,14 @@ function setLogFunction(logFunction) {
276
279
  */
277
280
  function parseJwt(token) {
278
281
  try {
279
- var tokenObj = jwt_decode(token);
282
+ const tokenObj = jwt_decode(token);
280
283
  if (!tokenObj || !tokenObj.exp) {
281
284
  throw new ErrorWithCode("Decoded token is null or exp claim does not exists.", ErrorCode.InternalError);
282
285
  }
283
286
  return tokenObj;
284
287
  }
285
288
  catch (err) {
286
- var errorMsg = "Parse jwt token failed in node env with error: " + err.message;
289
+ const errorMsg = "Parse jwt token failed in node env with error: " + err.message;
287
290
  internalLogger.error(errorMsg);
288
291
  throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
289
292
  }
@@ -293,12 +296,12 @@ function parseJwt(token) {
293
296
  */
294
297
  function getUserInfoFromSsoToken(ssoToken) {
295
298
  if (!ssoToken) {
296
- var errorMsg = "SSO token is undefined.";
299
+ const errorMsg = "SSO token is undefined.";
297
300
  internalLogger.error(errorMsg);
298
301
  throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
299
302
  }
300
- var tokenObject = parseJwt(ssoToken);
301
- var userInfo = {
303
+ const tokenObject = parseJwt(ssoToken);
304
+ const userInfo = {
302
305
  displayName: tokenObject.name,
303
306
  objectId: tokenObject.oid,
304
307
  preferredUserName: "",
@@ -311,6 +314,57 @@ function getUserInfoFromSsoToken(ssoToken) {
311
314
  }
312
315
  return userInfo;
313
316
  }
317
+ /**
318
+ * @internal
319
+ */
320
+ function getTenantIdAndLoginHintFromSsoToken(ssoToken) {
321
+ if (!ssoToken) {
322
+ const errorMsg = "SSO token is undefined.";
323
+ internalLogger.error(errorMsg);
324
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
325
+ }
326
+ const tokenObject = parseJwt(ssoToken);
327
+ const userInfo = {
328
+ tid: tokenObject.tid,
329
+ loginHint: tokenObject.ver === "2.0"
330
+ ? tokenObject.preferred_username
331
+ : tokenObject.upn,
332
+ };
333
+ return userInfo;
334
+ }
335
+ /**
336
+ * @internal
337
+ */
338
+ function parseAccessTokenFromAuthCodeTokenResponse(tokenResponse) {
339
+ try {
340
+ const tokenResponseObject = typeof tokenResponse == "string"
341
+ ? JSON.parse(tokenResponse)
342
+ : tokenResponse;
343
+ if (!tokenResponseObject || !tokenResponseObject.accessToken) {
344
+ const errorMsg = "Get empty access token from Auth Code token response.";
345
+ internalLogger.error(errorMsg);
346
+ throw new Error(errorMsg);
347
+ }
348
+ const token = tokenResponseObject.accessToken;
349
+ const tokenObject = parseJwt(token);
350
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
351
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
352
+ internalLogger.error(errorMsg);
353
+ throw new Error(errorMsg);
354
+ }
355
+ const accessToken = {
356
+ token: token,
357
+ expiresOnTimestamp: tokenObject.exp * 1000,
358
+ };
359
+ return accessToken;
360
+ }
361
+ catch (error) {
362
+ const errorMsg = "Parse access token failed from Auth Code token response in node env with error: " +
363
+ error.message;
364
+ internalLogger.error(errorMsg);
365
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
366
+ }
367
+ }
314
368
  /**
315
369
  * Format string template with replacements
316
370
  *
@@ -325,12 +379,8 @@ function getUserInfoFromSsoToken(ssoToken) {
325
379
  *
326
380
  * @internal
327
381
  */
328
- function formatString(str) {
329
- var replacements = [];
330
- for (var _i = 1; _i < arguments.length; _i++) {
331
- replacements[_i - 1] = arguments[_i];
332
- }
333
- var args = replacements;
382
+ function formatString(str, ...replacements) {
383
+ const args = replacements;
334
384
  return str.replace(/{(\d+)}/g, function (match, number) {
335
385
  return typeof args[number] != "undefined" ? args[number] : match;
336
386
  });
@@ -348,17 +398,17 @@ function validateScopesType(value) {
348
398
  return;
349
399
  }
350
400
  // string array
351
- if (Array.isArray(value) && value.length > 0 && value.every(function (item) { return typeof item === "string"; })) {
401
+ if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string")) {
352
402
  return;
353
403
  }
354
- var errorMsg = "The type of scopes is not valid, it must be string or string array";
404
+ const errorMsg = "The type of scopes is not valid, it must be string or string array";
355
405
  internalLogger.error(errorMsg);
356
406
  throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
357
407
  }
358
408
  /**
359
409
  * @internal
360
410
  */
361
- var isNode = typeof process !== "undefined" &&
411
+ const isNode = typeof process !== "undefined" &&
362
412
  !!process.version &&
363
413
  !!process.versions &&
364
414
  !!process.versions.node;
@@ -368,7 +418,7 @@ var isNode = typeof process !== "undefined" &&
368
418
  * Global configuration instance
369
419
  *
370
420
  */
371
- var config;
421
+ let config;
372
422
  /**
373
423
  * Initialize configuration from environment variables or configuration object and set the global instance
374
424
  *
@@ -383,7 +433,7 @@ function loadConfiguration(configuration) {
383
433
  // browser environment
384
434
  if (!isNode) {
385
435
  if (!configuration) {
386
- var errorMsg = "You are running the code in browser. Configuration must be passed in.";
436
+ const errorMsg = "You are running the code in browser. Configuration must be passed in.";
387
437
  internalLogger.error(errorMsg);
388
438
  throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
389
439
  }
@@ -391,9 +441,9 @@ function loadConfiguration(configuration) {
391
441
  return;
392
442
  }
393
443
  // node environment
394
- var newAuthentication;
395
- var newResources = [];
396
- var defaultResourceName = "default";
444
+ let newAuthentication;
445
+ let newResources = [];
446
+ const defaultResourceName = "default";
397
447
  if (configuration === null || configuration === void 0 ? void 0 : configuration.authentication) {
398
448
  newAuthentication = configuration.authentication;
399
449
  }
@@ -451,15 +501,14 @@ function loadConfiguration(configuration) {
451
501
  *
452
502
  * @beta
453
503
  */
454
- function getResourceConfiguration(resourceType, resourceName) {
504
+ function getResourceConfiguration(resourceType, resourceName = "default") {
455
505
  var _a;
456
- if (resourceName === void 0) { resourceName = "default"; }
457
- internalLogger.info("Get resource configuration of " + ResourceType[resourceType] + " from " + resourceName);
458
- var result = (_a = config.resources) === null || _a === void 0 ? void 0 : _a.find(function (item) { return item.type === resourceType && item.name === resourceName; });
506
+ internalLogger.info(`Get resource configuration of ${ResourceType[resourceType]} from ${resourceName}`);
507
+ const result = (_a = config.resources) === null || _a === void 0 ? void 0 : _a.find((item) => item.type === resourceType && item.name === resourceName);
459
508
  if (result) {
460
509
  return result.properties;
461
510
  }
462
- var errorMsg = formatString(ErrorMessage.MissingResourceConfiguration, ResourceType[resourceType], resourceName);
511
+ const errorMsg = formatString(ErrorMessage.MissingResourceConfiguration, ResourceType[resourceType], resourceName);
463
512
  internalLogger.error(errorMsg);
464
513
  throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
465
514
  }
@@ -477,7 +526,7 @@ function getAuthenticationConfiguration() {
477
526
  if (config) {
478
527
  return config.authentication;
479
528
  }
480
- var errorMsg = "Please call loadConfiguration() first before calling getAuthenticationConfiguration().";
529
+ const errorMsg = "Please call loadConfiguration() first before calling getAuthenticationConfiguration().";
481
530
  internalLogger.error(errorMsg);
482
531
  throw new ErrorWithCode(formatString(ErrorMessage.ConfigurationNotExists, errorMsg), ErrorCode.InvalidConfiguration);
483
532
  }
@@ -491,7 +540,7 @@ function getAuthenticationConfiguration() {
491
540
  *
492
541
  * @beta
493
542
  */
494
- var M365TenantCredential = /** @class */ (function () {
543
+ class M365TenantCredential {
495
544
  /**
496
545
  * Constructor of M365TenantCredential.
497
546
  *
@@ -499,7 +548,7 @@ var M365TenantCredential = /** @class */ (function () {
499
548
  * Only works in in server side.
500
549
  * @beta
501
550
  */
502
- function M365TenantCredential() {
551
+ constructor() {
503
552
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "M365TenantCredential"), ErrorCode.RuntimeNotSupported);
504
553
  }
505
554
  /**
@@ -509,15 +558,12 @@ var M365TenantCredential = /** @class */ (function () {
509
558
  * Only works in in server side.
510
559
  * @beta
511
560
  */
512
- M365TenantCredential.prototype.getToken = function (scopes, options) {
513
- return __awaiter(this, void 0, void 0, function () {
514
- return __generator(this, function (_a) {
515
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "M365TenantCredential"), ErrorCode.RuntimeNotSupported);
516
- });
561
+ getToken(scopes, options) {
562
+ return __awaiter(this, void 0, void 0, function* () {
563
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "M365TenantCredential"), ErrorCode.RuntimeNotSupported);
517
564
  });
518
- };
519
- return M365TenantCredential;
520
- }());
565
+ }
566
+ }
521
567
 
522
568
  // Copyright (c) Microsoft Corporation.
523
569
  /**
@@ -528,7 +574,7 @@ var M365TenantCredential = /** @class */ (function () {
528
574
  *
529
575
  * @beta
530
576
  */
531
- var OnBehalfOfUserCredential = /** @class */ (function () {
577
+ class OnBehalfOfUserCredential {
532
578
  /**
533
579
  * Constructor of OnBehalfOfUserCredential
534
580
  *
@@ -536,7 +582,7 @@ var OnBehalfOfUserCredential = /** @class */ (function () {
536
582
  * Can Only works in in server side.
537
583
  * @beta
538
584
  */
539
- function OnBehalfOfUserCredential(ssoToken) {
585
+ constructor(ssoToken) {
540
586
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
541
587
  }
542
588
  /**
@@ -545,66 +591,27 @@ var OnBehalfOfUserCredential = /** @class */ (function () {
545
591
  * Can only be used in server side.
546
592
  * @beta
547
593
  */
548
- OnBehalfOfUserCredential.prototype.getToken = function (scopes, options) {
549
- return __awaiter(this, void 0, void 0, function () {
550
- return __generator(this, function (_a) {
551
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
552
- });
594
+ getToken(scopes, options) {
595
+ return __awaiter(this, void 0, void 0, function* () {
596
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
553
597
  });
554
- };
598
+ }
555
599
  /**
556
600
  * Get basic user info from SSO token.
557
601
  * @remarks
558
602
  * Can only be used in server side.
559
603
  * @beta
560
604
  */
561
- OnBehalfOfUserCredential.prototype.getUserInfo = function () {
605
+ getUserInfo() {
562
606
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
563
- };
564
- return OnBehalfOfUserCredential;
565
- }());
566
-
567
- // Copyright (c) Microsoft Corporation.
568
- // Licensed under the MIT license.
569
- /**
570
- * Configuration used in initialization.
571
- * @internal
572
- */
573
- var Cache = /** @class */ (function () {
574
- function Cache() {
575
607
  }
576
- Cache.get = function (key) {
577
- return sessionStorage.getItem(key);
578
- };
579
- Cache.set = function (key, value) {
580
- sessionStorage.setItem(key, value);
581
- };
582
- Cache.remove = function (key) {
583
- sessionStorage.removeItem(key);
584
- };
585
- return Cache;
586
- }());
587
-
588
- // Copyright (c) Microsoft Corporation.
589
- // Licensed under the MIT license.
590
- /**
591
- * @internal
592
- */
593
- var GrantType;
594
- (function (GrantType) {
595
- GrantType["authCode"] = "authorization_code";
596
- GrantType["ssoToken"] = "sso_token";
597
- })(GrantType || (GrantType = {}));
608
+ }
598
609
 
599
610
  // Copyright (c) Microsoft Corporation.
600
- var accessTokenCacheKeyPrefix = "accessToken";
601
- var separator = "-";
602
- var tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
603
- var initializeTeamsSdkTimeoutInMillisecond = 5000;
604
- var loginPageWidth = 600;
605
- var loginPageHeight = 535;
606
- var maxRetryCount = 3;
607
- var retryTimeSpanInMillisecond = 3000;
611
+ const tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
612
+ const initializeTeamsSdkTimeoutInMillisecond = 5000;
613
+ const loginPageWidth = 600;
614
+ const loginPageHeight = 535;
608
615
  /**
609
616
  * Represent Teams current user's identity, and it is used within Teams tab application.
610
617
  *
@@ -613,7 +620,7 @@ var retryTimeSpanInMillisecond = 3000;
613
620
  *
614
621
  * @beta
615
622
  */
616
- var TeamsUserCredential = /** @class */ (function () {
623
+ class TeamsUserCredential {
617
624
  /**
618
625
  * Constructor of TeamsUserCredential.
619
626
  * Developer need to call loadConfiguration(config) before using this class.
@@ -622,7 +629,6 @@ var TeamsUserCredential = /** @class */ (function () {
622
629
  * ```typescript
623
630
  * const config = {
624
631
  * authentication: {
625
- * runtimeConnectorEndpoint: "https://xxx.xxx.com",
626
632
  * initiateLoginEndpoint: "https://localhost:3000/auth-start.html",
627
633
  * clientId: "xxx"
628
634
  * }
@@ -636,10 +642,11 @@ var TeamsUserCredential = /** @class */ (function () {
636
642
  *
637
643
  * @beta
638
644
  */
639
- function TeamsUserCredential() {
645
+ constructor() {
640
646
  internalLogger.info("Create teams user credential");
641
647
  this.config = this.loadAndValidateConfig();
642
648
  this.ssoToken = null;
649
+ this.initialized = false;
643
650
  }
644
651
  /**
645
652
  * Popup login page to get user's access token with specific scopes.
@@ -657,66 +664,67 @@ var TeamsUserCredential = /** @class */ (function () {
657
664
  * @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.
658
665
  *
659
666
  * @throws {@link ErrorCode|InternalError} when failed to login with unknown error.
660
- * @throws {@link ErrorCode|ServiceError} when simple auth server failed to exchange access token.
661
667
  * @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.
662
668
  * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
663
669
  * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
664
670
  *
665
671
  * @beta
666
672
  */
667
- TeamsUserCredential.prototype.login = function (scopes) {
668
- return __awaiter(this, void 0, void 0, function () {
669
- var scopesStr;
670
- var _this = this;
671
- return __generator(this, function (_a) {
672
- validateScopesType(scopes);
673
- scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
674
- internalLogger.info("Popup login page to get user's access token with scopes: " + scopesStr);
675
- return [2 /*return*/, new Promise(function (resolve, reject) {
676
- microsoftTeams.initialize(function () {
677
- microsoftTeams.authentication.authenticate({
678
- url: _this.config.initiateLoginEndpoint + "?clientId=" + _this.config.clientId + "&scope=" + encodeURI(scopesStr),
679
- width: loginPageWidth,
680
- height: loginPageHeight,
681
- successCallback: function (result) { return __awaiter(_this, void 0, void 0, function () {
682
- var errorMsg, authCodeResult, err_1;
683
- return __generator(this, function (_a) {
684
- switch (_a.label) {
685
- case 0:
686
- if (!result) {
687
- errorMsg = "Get empty authentication result from Teams";
688
- internalLogger.error(errorMsg);
689
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
690
- return [2 /*return*/];
691
- }
692
- authCodeResult = JSON.parse(result);
693
- _a.label = 1;
694
- case 1:
695
- _a.trys.push([1, 3, , 4]);
696
- return [4 /*yield*/, this.exchangeAccessTokenFromSimpleAuthServer(scopesStr, authCodeResult)];
697
- case 2:
698
- _a.sent();
699
- resolve();
700
- return [3 /*break*/, 4];
701
- case 3:
702
- err_1 = _a.sent();
703
- reject(this.generateAuthServerError(err_1));
704
- return [3 /*break*/, 4];
705
- case 4: return [2 /*return*/];
706
- }
707
- });
708
- }); },
709
- failureCallback: function (reason) {
710
- var errorMsg = "Consent failed for the scope " + scopesStr + " with error: " + reason;
711
- internalLogger.error(errorMsg);
712
- reject(new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed));
713
- },
714
- });
715
- });
716
- })];
673
+ login(scopes) {
674
+ return __awaiter(this, void 0, void 0, function* () {
675
+ validateScopesType(scopes);
676
+ const scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
677
+ internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);
678
+ if (!this.initialized) {
679
+ yield this.init();
680
+ }
681
+ return new Promise((resolve, reject) => {
682
+ microsoftTeams.initialize(() => {
683
+ microsoftTeams.authentication.authenticate({
684
+ url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,
685
+ width: loginPageWidth,
686
+ height: loginPageHeight,
687
+ successCallback: (result) => __awaiter(this, void 0, void 0, function* () {
688
+ if (!result) {
689
+ const errorMsg = "Get empty authentication result from MSAL";
690
+ internalLogger.error(errorMsg);
691
+ reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
692
+ return;
693
+ }
694
+ let resultJson = {};
695
+ try {
696
+ resultJson = JSON.parse(result);
697
+ }
698
+ catch (error) {
699
+ // If can not parse result as Json, will throw error.
700
+ const failedToParseResult = "Failed to parse response to Json.";
701
+ internalLogger.error(failedToParseResult);
702
+ reject(new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse));
703
+ }
704
+ // If code exists in result, user may using previous auth-start and auth-end page.
705
+ if (resultJson.code) {
706
+ const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
707
+ const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
708
+ `Please refer to the help link for how to fix the issue: ${helpLink}.`;
709
+ internalLogger.error(usingPreviousAuthPage);
710
+ reject(new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse));
711
+ }
712
+ // If sessionStorage exists in result, set the values in current session storage.
713
+ if (resultJson.sessionStorage) {
714
+ this.setSessionStorage(resultJson.sessionStorage);
715
+ }
716
+ resolve();
717
+ }),
718
+ failureCallback: (reason) => {
719
+ const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${reason}`;
720
+ internalLogger.error(errorMsg);
721
+ reject(new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed));
722
+ },
723
+ });
724
+ });
717
725
  });
718
726
  });
719
- };
727
+ }
720
728
  /**
721
729
  * Get access token from credential.
722
730
  *
@@ -741,7 +749,6 @@ var TeamsUserCredential = /** @class */ (function () {
741
749
  *
742
750
  * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
743
751
  * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
744
- * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.
745
752
  * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
746
753
  * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
747
754
  *
@@ -752,46 +759,62 @@ var TeamsUserCredential = /** @class */ (function () {
752
759
  *
753
760
  * @beta
754
761
  */
755
- TeamsUserCredential.prototype.getToken = function (scopes, options) {
756
- return __awaiter(this, void 0, void 0, function () {
757
- var ssoToken, scopeStr, cachedKey, cachedToken, accessToken;
758
- return __generator(this, function (_a) {
759
- switch (_a.label) {
760
- case 0:
761
- validateScopesType(scopes);
762
- return [4 /*yield*/, this.getSSOToken()];
763
- case 1:
764
- ssoToken = _a.sent();
765
- scopeStr = typeof scopes === "string" ? scopes : scopes.join(" ");
766
- if (!(scopeStr === "")) return [3 /*break*/, 2];
767
- internalLogger.info("Get SSO token");
768
- return [2 /*return*/, ssoToken];
769
- case 2:
770
- internalLogger.info("Get access token with scopes: " + scopeStr);
771
- return [4 /*yield*/, this.getAccessTokenCacheKey(scopeStr)];
772
- case 3:
773
- cachedKey = _a.sent();
774
- cachedToken = this.getTokenCache(cachedKey);
775
- if (cachedToken) {
776
- if (!this.isAccessTokenNearExpired(cachedToken)) {
777
- internalLogger.verbose("Get access token from cache");
778
- return [2 /*return*/, cachedToken];
779
- }
780
- else {
781
- internalLogger.verbose("Cached access token is expired");
782
- }
783
- }
784
- else {
785
- internalLogger.verbose("No cached access token");
786
- }
787
- return [4 /*yield*/, this.getAndCacheAccessTokenFromSimpleAuthServer(scopeStr)];
788
- case 4:
789
- accessToken = _a.sent();
790
- return [2 /*return*/, accessToken];
762
+ getToken(scopes, options) {
763
+ return __awaiter(this, void 0, void 0, function* () {
764
+ validateScopesType(scopes);
765
+ const ssoToken = yield this.getSSOToken();
766
+ const scopeStr = typeof scopes === "string" ? scopes : scopes.join(" ");
767
+ if (scopeStr === "") {
768
+ internalLogger.info("Get SSO token");
769
+ return ssoToken;
770
+ }
771
+ else {
772
+ internalLogger.info("Get access token with scopes: " + scopeStr);
773
+ if (!this.initialized) {
774
+ yield this.init();
791
775
  }
792
- });
776
+ let tokenResponse;
777
+ const scopesArray = typeof scopes === "string" ? scopes.split(" ") : scopes;
778
+ const domain = window.location.origin;
779
+ // First try to get Access Token from cache.
780
+ try {
781
+ const account = this.msalInstance.getAccountByUsername(this.loginHint);
782
+ const scopesRequestForAcquireTokenSilent = {
783
+ scopes: scopesArray,
784
+ account: account !== null && account !== void 0 ? account : undefined,
785
+ redirectUri: `${domain}/blank-auth-end.html`,
786
+ };
787
+ tokenResponse = yield this.msalInstance.acquireTokenSilent(scopesRequestForAcquireTokenSilent);
788
+ }
789
+ catch (error) {
790
+ const acquireTokenSilentFailedMessage = `Failed to call acquireTokenSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
791
+ internalLogger.verbose(acquireTokenSilentFailedMessage);
792
+ }
793
+ if (!tokenResponse) {
794
+ // If fail to get Access Token from cache, try to get Access token by silent login.
795
+ try {
796
+ const scopesRequestForSsoSilent = {
797
+ scopes: scopesArray,
798
+ loginHint: this.loginHint,
799
+ redirectUri: `${domain}/blank-auth-end.html`,
800
+ };
801
+ tokenResponse = yield this.msalInstance.ssoSilent(scopesRequestForSsoSilent);
802
+ }
803
+ catch (error) {
804
+ const ssoSilentFailedMessage = `Failed to call ssoSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
805
+ internalLogger.verbose(ssoSilentFailedMessage);
806
+ }
807
+ }
808
+ if (!tokenResponse) {
809
+ const errorMsg = `Failed to get access token cache silently, please login first: you need login first before get access token.`;
810
+ internalLogger.error(errorMsg);
811
+ throw new ErrorWithCode(errorMsg, ErrorCode.UiRequiredError);
812
+ }
813
+ const accessToken = parseAccessTokenFromAuthCodeTokenResponse(tokenResponse);
814
+ return accessToken;
815
+ }
793
816
  });
794
- };
817
+ }
795
818
  /**
796
819
  * Get basic user info from SSO token
797
820
  *
@@ -808,153 +831,73 @@ var TeamsUserCredential = /** @class */ (function () {
808
831
  *
809
832
  * @beta
810
833
  */
811
- TeamsUserCredential.prototype.getUserInfo = function () {
812
- return __awaiter(this, void 0, void 0, function () {
813
- var ssoToken;
814
- return __generator(this, function (_a) {
815
- switch (_a.label) {
816
- case 0:
817
- internalLogger.info("Get basic user info from SSO token");
818
- return [4 /*yield*/, this.getSSOToken()];
819
- case 1:
820
- ssoToken = _a.sent();
821
- return [2 /*return*/, getUserInfoFromSsoToken(ssoToken.token)];
822
- }
823
- });
824
- });
825
- };
826
- TeamsUserCredential.prototype.exchangeAccessTokenFromSimpleAuthServer = function (scopesStr, authCodeResult) {
827
- var _a, _b;
828
- return __awaiter(this, void 0, void 0, function () {
829
- var axiosInstance, retryCount, response, tokenResult, key, err_2;
830
- return __generator(this, function (_c) {
831
- switch (_c.label) {
832
- case 0: return [4 /*yield*/, this.getAxiosInstance()];
833
- case 1:
834
- axiosInstance = _c.sent();
835
- retryCount = 0;
836
- _c.label = 2;
837
- case 2:
838
- _c.label = 3;
839
- case 3:
840
- _c.trys.push([3, 6, , 9]);
841
- return [4 /*yield*/, axiosInstance.post("/auth/token", {
842
- scope: scopesStr,
843
- code: authCodeResult.code,
844
- code_verifier: authCodeResult.codeVerifier,
845
- redirect_uri: authCodeResult.redirectUri,
846
- grant_type: GrantType.authCode,
847
- })];
848
- case 4:
849
- response = _c.sent();
850
- tokenResult = response.data;
851
- return [4 /*yield*/, this.getAccessTokenCacheKey(scopesStr)];
852
- case 5:
853
- key = _c.sent();
854
- // Important: tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice
855
- this.setTokenCache(key, {
856
- token: tokenResult.access_token,
857
- expiresOnTimestamp: tokenResult.expires_on,
858
- });
859
- return [2 /*return*/];
860
- case 6:
861
- err_2 = _c.sent();
862
- if (!(((_b = (_a = err_2.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.type) && err_2.response.data.type === "AadUiRequiredException")) return [3 /*break*/, 8];
863
- internalLogger.warn("Exchange access token failed, retry...");
864
- if (!(retryCount < maxRetryCount)) return [3 /*break*/, 8];
865
- return [4 /*yield*/, this.sleep(retryTimeSpanInMillisecond)];
866
- case 7:
867
- _c.sent();
868
- retryCount++;
869
- return [3 /*break*/, 2];
870
- case 8: throw err_2;
871
- case 9: return [3 /*break*/, 2];
872
- case 10: return [2 /*return*/];
873
- }
874
- });
834
+ getUserInfo() {
835
+ return __awaiter(this, void 0, void 0, function* () {
836
+ internalLogger.info("Get basic user info from SSO token");
837
+ const ssoToken = yield this.getSSOToken();
838
+ return getUserInfoFromSsoToken(ssoToken.token);
875
839
  });
876
- };
877
- /**
878
- * Get access token cache from authentication server
879
- * @returns Access token
880
- */
881
- TeamsUserCredential.prototype.getAndCacheAccessTokenFromSimpleAuthServer = function (scopesStr) {
882
- return __awaiter(this, void 0, void 0, function () {
883
- var axiosInstance, response, accessTokenResult, accessToken, cacheKey, err_3;
884
- return __generator(this, function (_a) {
885
- switch (_a.label) {
886
- case 0:
887
- _a.trys.push([0, 4, , 5]);
888
- internalLogger.verbose("Get access token from authentication server with scopes: " + scopesStr);
889
- return [4 /*yield*/, this.getAxiosInstance()];
890
- case 1:
891
- axiosInstance = _a.sent();
892
- return [4 /*yield*/, axiosInstance.post("/auth/token", {
893
- scope: scopesStr,
894
- grant_type: GrantType.ssoToken,
895
- })];
896
- case 2:
897
- response = _a.sent();
898
- accessTokenResult = response.data;
899
- accessToken = {
900
- token: accessTokenResult.access_token,
901
- expiresOnTimestamp: accessTokenResult.expires_on,
902
- };
903
- return [4 /*yield*/, this.getAccessTokenCacheKey(scopesStr)];
904
- case 3:
905
- cacheKey = _a.sent();
906
- this.setTokenCache(cacheKey, accessToken);
907
- return [2 /*return*/, accessToken];
908
- case 4:
909
- err_3 = _a.sent();
910
- throw this.generateAuthServerError(err_3);
911
- case 5: return [2 /*return*/];
912
- }
913
- });
840
+ }
841
+ init() {
842
+ return __awaiter(this, void 0, void 0, function* () {
843
+ const ssoToken = yield this.getSSOToken();
844
+ const info = getTenantIdAndLoginHintFromSsoToken(ssoToken.token);
845
+ this.loginHint = info.loginHint;
846
+ this.tid = info.tid;
847
+ const msalConfig = {
848
+ auth: {
849
+ clientId: this.config.clientId,
850
+ authority: `https://login.microsoftonline.com/${this.tid}`,
851
+ },
852
+ cache: {
853
+ cacheLocation: "sessionStorage",
854
+ },
855
+ };
856
+ this.msalInstance = new PublicClientApplication(msalConfig);
857
+ this.initialized = true;
914
858
  });
915
- };
859
+ }
916
860
  /**
917
861
  * Get SSO token using teams SDK
918
862
  * It will try to get SSO token from memory first, if SSO token doesn't exist or about to expired, then it will using teams SDK to get SSO token
919
863
  * @returns SSO token
920
864
  */
921
- TeamsUserCredential.prototype.getSSOToken = function () {
922
- var _this = this;
923
- return new Promise(function (resolve, reject) {
924
- if (_this.ssoToken) {
925
- if (_this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
865
+ getSSOToken() {
866
+ return new Promise((resolve, reject) => {
867
+ if (this.ssoToken) {
868
+ if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
926
869
  internalLogger.verbose("Get SSO token from memory cache");
927
- resolve(_this.ssoToken);
870
+ resolve(this.ssoToken);
928
871
  return;
929
872
  }
930
873
  }
931
- var initialized = false;
932
- microsoftTeams.initialize(function () {
874
+ let initialized = false;
875
+ microsoftTeams.initialize(() => {
933
876
  initialized = true;
934
877
  microsoftTeams.authentication.getAuthToken({
935
- successCallback: function (token) {
878
+ successCallback: (token) => {
936
879
  if (!token) {
937
- var errorMsg = "Get empty SSO token from Teams";
880
+ const errorMsg = "Get empty SSO token from Teams";
938
881
  internalLogger.error(errorMsg);
939
882
  reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
940
883
  return;
941
884
  }
942
- var tokenObject = parseJwt(token);
885
+ const tokenObject = parseJwt(token);
943
886
  if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
944
- var errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
887
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
945
888
  internalLogger.error(errorMsg);
946
889
  reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
947
890
  return;
948
891
  }
949
- var ssoToken = {
950
- token: token,
892
+ const ssoToken = {
893
+ token,
951
894
  expiresOnTimestamp: tokenObject.exp * 1000,
952
895
  };
953
- _this.ssoToken = ssoToken;
896
+ this.ssoToken = ssoToken;
954
897
  resolve(ssoToken);
955
898
  },
956
- failureCallback: function (errMessage) {
957
- var errorMsg = "Get SSO token failed with error: " + errMessage;
899
+ failureCallback: (errMessage) => {
900
+ const errorMsg = "Get SSO token failed with error: " + errMessage;
958
901
  internalLogger.error(errorMsg);
959
902
  reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
960
903
  },
@@ -962,178 +905,65 @@ var TeamsUserCredential = /** @class */ (function () {
962
905
  });
963
906
  });
964
907
  // If the code not running in Teams, the initialize callback function would never trigger
965
- setTimeout(function () {
908
+ setTimeout(() => {
966
909
  if (!initialized) {
967
- var errorMsg = "Initialize teams sdk timeout, maybe the code is not running inside Teams";
910
+ const errorMsg = "Initialize teams sdk timeout, maybe the code is not running inside Teams";
968
911
  internalLogger.error(errorMsg);
969
912
  reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
970
913
  }
971
914
  }, initializeTeamsSdkTimeoutInMillisecond);
972
915
  });
973
- };
916
+ }
974
917
  /**
975
918
  * Load and validate authentication configuration
976
919
  * @returns Authentication configuration
977
920
  */
978
- TeamsUserCredential.prototype.loadAndValidateConfig = function () {
921
+ loadAndValidateConfig() {
979
922
  internalLogger.verbose("Validate authentication configuration");
980
- var config = getAuthenticationConfiguration();
923
+ const config = getAuthenticationConfiguration();
981
924
  if (!config) {
982
925
  internalLogger.error(ErrorMessage.AuthenticationConfigurationNotExists);
983
926
  throw new ErrorWithCode(ErrorMessage.AuthenticationConfigurationNotExists, ErrorCode.InvalidConfiguration);
984
927
  }
985
- if (config.initiateLoginEndpoint && config.simpleAuthEndpoint && config.clientId) {
928
+ if (config.initiateLoginEndpoint && config.clientId) {
986
929
  return config;
987
930
  }
988
- var missingValues = [];
931
+ const missingValues = [];
989
932
  if (!config.initiateLoginEndpoint) {
990
933
  missingValues.push("initiateLoginEndpoint");
991
934
  }
992
- if (!config.simpleAuthEndpoint) {
993
- missingValues.push("simpleAuthEndpoint");
994
- }
995
935
  if (!config.clientId) {
996
936
  missingValues.push("clientId");
997
937
  }
998
- var errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingValues.join(", "), "undefined");
938
+ const errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingValues.join(", "), "undefined");
999
939
  internalLogger.error(errorMsg);
1000
940
  throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
1001
- };
1002
- /**
1003
- * Get axios instance with sso token bearer header
1004
- * @returns AxiosInstance
1005
- */
1006
- TeamsUserCredential.prototype.getAxiosInstance = function () {
1007
- return __awaiter(this, void 0, void 0, function () {
1008
- var ssoToken, axiosInstance;
1009
- return __generator(this, function (_a) {
1010
- switch (_a.label) {
1011
- case 0: return [4 /*yield*/, this.getSSOToken()];
1012
- case 1:
1013
- ssoToken = _a.sent();
1014
- axiosInstance = axios.create({
1015
- baseURL: this.config.simpleAuthEndpoint,
1016
- });
1017
- axiosInstance.interceptors.request.use(function (config) {
1018
- config.headers.Authorization = "Bearer " + ssoToken.token;
1019
- return config;
1020
- });
1021
- return [2 /*return*/, axiosInstance];
1022
- }
1023
- });
1024
- });
1025
- };
1026
- /**
1027
- * Set access token to cache
1028
- * @param key
1029
- * @param token
1030
- */
1031
- TeamsUserCredential.prototype.setTokenCache = function (key, token) {
1032
- Cache.set(key, JSON.stringify(token));
1033
- };
1034
- /**
1035
- * Get access token from cache.
1036
- * If there is no cache or cannot be parsed, then it will return null
1037
- * @param key
1038
- * @returns Access token or null
1039
- */
1040
- TeamsUserCredential.prototype.getTokenCache = function (key) {
1041
- var value = Cache.get(key);
1042
- if (value === null) {
1043
- return null;
1044
- }
1045
- var accessToken = this.validateAndParseJson(value);
1046
- return accessToken;
1047
- };
1048
- /**
1049
- * Parses passed value as JSON access token, if value is not a valid json string JSON.parse() will throw an error.
1050
- * @param jsonValue
1051
- */
1052
- TeamsUserCredential.prototype.validateAndParseJson = function (jsonValue) {
941
+ }
942
+ setSessionStorage(sessonStorageValues) {
1053
943
  try {
1054
- var parsedJson = JSON.parse(jsonValue);
1055
- /**
1056
- * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
1057
- * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
1058
- * of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
1059
- *
1060
- */
1061
- return parsedJson && typeof parsedJson === "object" ? parsedJson : null;
1062
- }
1063
- catch (error) {
1064
- return null;
1065
- }
1066
- };
1067
- /**
1068
- * Generate cache key
1069
- * @param scopesStr
1070
- * @returns Access token cache key, a key example: accessToken-userId-clientId-tenantId-scopes
1071
- */
1072
- TeamsUserCredential.prototype.getAccessTokenCacheKey = function (scopesStr) {
1073
- return __awaiter(this, void 0, void 0, function () {
1074
- var ssoToken, ssoTokenObj, clientId, userObjectId, tenantId, key;
1075
- return __generator(this, function (_a) {
1076
- switch (_a.label) {
1077
- case 0: return [4 /*yield*/, this.getSSOToken()];
1078
- case 1:
1079
- ssoToken = _a.sent();
1080
- ssoTokenObj = parseJwt(ssoToken.token);
1081
- clientId = this.config.clientId;
1082
- userObjectId = ssoTokenObj.oid;
1083
- tenantId = ssoTokenObj.tid;
1084
- key = [accessTokenCacheKeyPrefix, userObjectId, clientId, tenantId, scopesStr]
1085
- .join(separator)
1086
- .replace(/" "/g, "_");
1087
- return [2 /*return*/, key];
1088
- }
944
+ const sessionStorageKeys = Object.keys(sessonStorageValues);
945
+ sessionStorageKeys.forEach((key) => {
946
+ sessionStorage.setItem(key, sessonStorageValues[key]);
1089
947
  });
1090
- });
1091
- };
1092
- /**
1093
- * Check whether the token is about to expire (within 5 minutes)
1094
- * @returns Boolean value indicate whether the token is about to expire
1095
- */
1096
- TeamsUserCredential.prototype.isAccessTokenNearExpired = function (token) {
1097
- var expireDate = new Date(token.expiresOnTimestamp);
1098
- if (expireDate.getTime() - Date.now() > tokenRefreshTimeSpanInMillisecond) {
1099
- return false;
1100
948
  }
1101
- return true;
1102
- };
1103
- TeamsUserCredential.prototype.generateAuthServerError = function (err) {
1104
- var _a, _b;
1105
- var errorMessage = err.message;
1106
- if ((_b = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.type) {
1107
- errorMessage = err.response.data.detail;
1108
- if (err.response.data.type === "AadUiRequiredException") {
1109
- var fullErrorMsg_1 = "Failed to get access token from authentication server, please login first: " +
1110
- errorMessage;
1111
- internalLogger.warn(fullErrorMsg_1);
1112
- return new ErrorWithCode(fullErrorMsg_1, ErrorCode.UiRequiredError);
1113
- }
1114
- else {
1115
- var fullErrorMsg_2 = "Failed to get access token from authentication server: " + errorMessage;
1116
- internalLogger.error(fullErrorMsg_2);
1117
- return new ErrorWithCode(fullErrorMsg_2, ErrorCode.ServiceError);
1118
- }
949
+ catch (error) {
950
+ // Values in result.sessionStorage can not be set into session storage.
951
+ // Throw error since this may block user.
952
+ const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;
953
+ internalLogger.error(errorMessage);
954
+ throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
1119
955
  }
1120
- var fullErrorMsg = "Failed to get access token with error: " + errorMessage;
1121
- return new ErrorWithCode(fullErrorMsg, ErrorCode.InternalError);
1122
- };
1123
- TeamsUserCredential.prototype.sleep = function (ms) {
1124
- return new Promise(function (resolve) { return setTimeout(resolve, ms); });
1125
- };
1126
- return TeamsUserCredential;
1127
- }());
956
+ }
957
+ }
1128
958
 
1129
959
  // Copyright (c) Microsoft Corporation.
1130
- var defaultScope = "https://graph.microsoft.com/.default";
960
+ const defaultScope = "https://graph.microsoft.com/.default";
1131
961
  /**
1132
962
  * Microsoft Graph auth provider for Teams Framework
1133
963
  *
1134
964
  * @beta
1135
965
  */
1136
- var MsGraphAuthProvider = /** @class */ (function () {
966
+ class MsGraphAuthProvider {
1137
967
  /**
1138
968
  * Constructor of MsGraphAuthProvider.
1139
969
  *
@@ -1146,9 +976,9 @@ var MsGraphAuthProvider = /** @class */ (function () {
1146
976
  *
1147
977
  * @beta
1148
978
  */
1149
- function MsGraphAuthProvider(credential, scopes) {
979
+ constructor(credential, scopes) {
1150
980
  this.credential = credential;
1151
- var scopesStr = defaultScope;
981
+ let scopesStr = defaultScope;
1152
982
  if (scopes) {
1153
983
  validateScopesType(scopes);
1154
984
  scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
@@ -1156,7 +986,7 @@ var MsGraphAuthProvider = /** @class */ (function () {
1156
986
  scopesStr = defaultScope;
1157
987
  }
1158
988
  }
1159
- internalLogger.info("Create Microsoft Graph Authentication Provider with scopes: '" + scopesStr + "'");
989
+ internalLogger.info(`Create Microsoft Graph Authentication Provider with scopes: '${scopesStr}'`);
1160
990
  this.scopes = scopesStr;
1161
991
  }
1162
992
  /**
@@ -1171,32 +1001,23 @@ var MsGraphAuthProvider = /** @class */ (function () {
1171
1001
  * @returns Access token from the credential.
1172
1002
  *
1173
1003
  */
1174
- MsGraphAuthProvider.prototype.getAccessToken = function () {
1175
- return __awaiter(this, void 0, void 0, function () {
1176
- var accessToken;
1177
- return __generator(this, function (_a) {
1178
- switch (_a.label) {
1179
- case 0:
1180
- internalLogger.info("Get Graph Access token with scopes: '" + this.scopes + "'");
1181
- return [4 /*yield*/, this.credential.getToken(this.scopes)];
1182
- case 1:
1183
- accessToken = _a.sent();
1184
- return [2 /*return*/, new Promise(function (resolve, reject) {
1185
- if (accessToken) {
1186
- resolve(accessToken.token);
1187
- }
1188
- else {
1189
- var errorMsg = "Graph access token is undefined or empty";
1190
- internalLogger.error(errorMsg);
1191
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
1192
- }
1193
- })];
1004
+ getAccessToken() {
1005
+ return __awaiter(this, void 0, void 0, function* () {
1006
+ internalLogger.info(`Get Graph Access token with scopes: '${this.scopes}'`);
1007
+ const accessToken = yield this.credential.getToken(this.scopes);
1008
+ return new Promise((resolve, reject) => {
1009
+ if (accessToken) {
1010
+ resolve(accessToken.token);
1011
+ }
1012
+ else {
1013
+ const errorMsg = "Graph access token is undefined or empty";
1014
+ internalLogger.error(errorMsg);
1015
+ reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
1194
1016
  }
1195
1017
  });
1196
1018
  });
1197
- };
1198
- return MsGraphAuthProvider;
1199
- }());
1019
+ }
1020
+ }
1200
1021
 
1201
1022
  // Copyright (c) Microsoft Corporation.
1202
1023
  /**
@@ -1252,208 +1073,35 @@ var MsGraphAuthProvider = /** @class */ (function () {
1252
1073
  */
1253
1074
  function createMicrosoftGraphClient(credential, scopes) {
1254
1075
  internalLogger.info("Create Microsoft Graph Client");
1255
- var authProvider = new MsGraphAuthProvider(credential, scopes);
1256
- var graphClient = Client.initWithMiddleware({
1257
- authProvider: authProvider,
1076
+ const authProvider = new MsGraphAuthProvider(credential, scopes);
1077
+ const graphClient = Client.initWithMiddleware({
1078
+ authProvider,
1258
1079
  });
1259
1080
  return graphClient;
1260
1081
  }
1261
1082
 
1262
- // Copyright (c) Microsoft Corporation.
1263
1083
  /**
1264
- * SQL connection configuration instance.
1084
+ * Generate connection configuration consumed by tedious.
1265
1085
  * @remarks
1266
1086
  * Only works in in server side.
1267
- *
1268
1087
  * @beta
1269
- *
1270
1088
  */
1271
- var DefaultTediousConnectionConfiguration = /** @class */ (function () {
1272
- function DefaultTediousConnectionConfiguration() {
1273
- /**
1274
- * MSSQL default scope
1275
- * https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi
1276
- */
1277
- this.defaultSQLScope = "https://database.windows.net/";
1089
+ class DefaultTediousConnectionConfiguration {
1090
+ constructor() {
1091
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "DefaultTediousConnectionConfiguration"), ErrorCode.RuntimeNotSupported);
1278
1092
  }
1279
1093
  /**
1280
1094
  * Generate connection configuration consumed by tedious.
1281
- *
1282
- * @returns Connection configuration of tedious for the SQL.
1283
- *
1284
- * @throws {@link ErrorCode|InvalidConfiguration} when SQL config resource configuration is invalid.
1285
- * @throws {@link ErrorCode|InternalError} when get user MSI token failed or MSI token is invalid.
1286
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1287
- *
1095
+ * @remarks
1096
+ * Only works in in server side.
1288
1097
  * @beta
1289
1098
  */
1290
- DefaultTediousConnectionConfiguration.prototype.getConfig = function () {
1291
- return __awaiter(this, void 0, void 0, function () {
1292
- var configuration, errMsg, configWithUPS, configWithToken, error_1;
1293
- return __generator(this, function (_a) {
1294
- switch (_a.label) {
1295
- case 0:
1296
- internalLogger.info("Get SQL configuration");
1297
- configuration = getResourceConfiguration(ResourceType.SQL);
1298
- if (!configuration) {
1299
- errMsg = "SQL resource configuration not exist";
1300
- internalLogger.error(errMsg);
1301
- throw new ErrorWithCode(errMsg, ErrorCode.InvalidConfiguration);
1302
- }
1303
- try {
1304
- this.isSQLConfigurationValid(configuration);
1305
- }
1306
- catch (err) {
1307
- throw err;
1308
- }
1309
- if (!this.isMsiAuthentication()) {
1310
- configWithUPS = this.generateDefaultConfig(configuration);
1311
- internalLogger.verbose("SQL configuration with username and password generated");
1312
- return [2 /*return*/, configWithUPS];
1313
- }
1314
- _a.label = 1;
1315
- case 1:
1316
- _a.trys.push([1, 3, , 4]);
1317
- return [4 /*yield*/, this.generateTokenConfig(configuration)];
1318
- case 2:
1319
- configWithToken = _a.sent();
1320
- internalLogger.verbose("SQL configuration with MSI token generated");
1321
- return [2 /*return*/, configWithToken];
1322
- case 3:
1323
- error_1 = _a.sent();
1324
- throw error_1;
1325
- case 4: return [2 /*return*/];
1326
- }
1327
- });
1328
- });
1329
- };
1330
- /**
1331
- * Check SQL use MSI identity or username and password.
1332
- *
1333
- * @returns false - login with SQL MSI identity, true - login with username and password.
1334
- * @internal
1335
- */
1336
- DefaultTediousConnectionConfiguration.prototype.isMsiAuthentication = function () {
1337
- internalLogger.verbose("Check connection config using MSI access token or username and password");
1338
- var configuration = getResourceConfiguration(ResourceType.SQL);
1339
- if ((configuration === null || configuration === void 0 ? void 0 : configuration.sqlUsername) != null && (configuration === null || configuration === void 0 ? void 0 : configuration.sqlPassword) != null) {
1340
- internalLogger.verbose("Login with username and password");
1341
- return false;
1342
- }
1343
- internalLogger.verbose("Login with MSI identity");
1344
- return true;
1345
- };
1346
- /**
1347
- * check configuration is an available configurations.
1348
- * @param { SqlConfiguration } sqlConfig
1349
- *
1350
- * @returns true - SQL configuration has a valid SQL endpoints, SQL username with password or identity ID.
1351
- * false - configuration is not valid.
1352
- * @internal
1353
- */
1354
- DefaultTediousConnectionConfiguration.prototype.isSQLConfigurationValid = function (sqlConfig) {
1355
- internalLogger.verbose("Check SQL configuration if valid");
1356
- if (!sqlConfig.sqlServerEndpoint) {
1357
- internalLogger.error("SQL configuration is not valid without SQL server endpoint exist");
1358
- throw new ErrorWithCode("SQL configuration error without SQL server endpoint exist", ErrorCode.InvalidConfiguration);
1359
- }
1360
- if (!(sqlConfig.sqlUsername && sqlConfig.sqlPassword) && !sqlConfig.sqlIdentityId) {
1361
- var errMsg = "SQL configuration is not valid without " + (sqlConfig.sqlIdentityId ? "" : "identity id ") + " " + (sqlConfig.sqlUsername ? "" : "SQL username ") + " " + (sqlConfig.sqlPassword ? "" : "SQL password") + " exist";
1362
- internalLogger.error(errMsg);
1363
- throw new ErrorWithCode(errMsg, ErrorCode.InvalidConfiguration);
1364
- }
1365
- internalLogger.verbose("SQL configuration is valid");
1366
- };
1367
- /**
1368
- * Generate tedious connection configuration with default authentication type.
1369
- *
1370
- * @param { SqlConfiguration } SQL configuration with username and password.
1371
- *
1372
- * @returns Tedious connection configuration with username and password.
1373
- * @internal
1374
- */
1375
- DefaultTediousConnectionConfiguration.prototype.generateDefaultConfig = function (sqlConfig) {
1376
- internalLogger.verbose("SQL server " + sqlConfig.sqlServerEndpoint + ", user name " + sqlConfig.sqlUsername + ", database name " + sqlConfig.sqlDatabaseName);
1377
- var config = {
1378
- server: sqlConfig.sqlServerEndpoint,
1379
- authentication: {
1380
- type: TediousAuthenticationType.default,
1381
- options: {
1382
- userName: sqlConfig.sqlUsername,
1383
- password: sqlConfig.sqlPassword,
1384
- },
1385
- },
1386
- options: {
1387
- database: sqlConfig.sqlDatabaseName,
1388
- encrypt: true,
1389
- },
1390
- };
1391
- return config;
1392
- };
1393
- /**
1394
- * Generate tedious connection configuration with azure-active-directory-access-token authentication type.
1395
- *
1396
- * @param { SqlConfiguration } SQL configuration with AAD access token.
1397
- *
1398
- * @returns Tedious connection configuration with access token.
1399
- * @internal
1400
- */
1401
- DefaultTediousConnectionConfiguration.prototype.generateTokenConfig = function (sqlConfig) {
1402
- return __awaiter(this, void 0, void 0, function () {
1403
- var token, credential, errMsg, config;
1404
- return __generator(this, function (_a) {
1405
- switch (_a.label) {
1406
- case 0:
1407
- internalLogger.verbose("Generate tedious config with MSI token");
1408
- _a.label = 1;
1409
- case 1:
1410
- _a.trys.push([1, 3, , 4]);
1411
- credential = new ManagedIdentityCredential(sqlConfig.sqlIdentityId);
1412
- return [4 /*yield*/, credential.getToken(this.defaultSQLScope)];
1413
- case 2:
1414
- token = _a.sent();
1415
- return [3 /*break*/, 4];
1416
- case 3:
1417
- _a.sent();
1418
- errMsg = "Get user MSI token failed";
1419
- internalLogger.error(errMsg);
1420
- throw new ErrorWithCode(errMsg, ErrorCode.InternalError);
1421
- case 4:
1422
- if (token) {
1423
- config = {
1424
- server: sqlConfig.sqlServerEndpoint,
1425
- authentication: {
1426
- type: TediousAuthenticationType.MSI,
1427
- options: {
1428
- token: token.token,
1429
- },
1430
- },
1431
- options: {
1432
- database: sqlConfig.sqlDatabaseName,
1433
- encrypt: true,
1434
- },
1435
- };
1436
- internalLogger.verbose("Generate token configuration success, server endpoint is " + sqlConfig.sqlServerEndpoint + ", database name is " + sqlConfig.sqlDatabaseName);
1437
- return [2 /*return*/, config];
1438
- }
1439
- internalLogger.error("Generate token configuration, server endpoint is " + sqlConfig.sqlServerEndpoint + ", MSI token is not valid");
1440
- throw new ErrorWithCode("MSI token is not valid", ErrorCode.InternalError);
1441
- }
1442
- });
1099
+ getConfig(databaseName) {
1100
+ return __awaiter(this, void 0, void 0, function* () {
1101
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "DefaultTediousConnectionConfiguration"), ErrorCode.RuntimeNotSupported);
1443
1102
  });
1444
- };
1445
- return DefaultTediousConnectionConfiguration;
1446
- }());
1447
- /**
1448
- * tedious connection config authentication type.
1449
- * https://tediousjs.github.io/tedious/api-connection.html
1450
- * @internal
1451
- */
1452
- var TediousAuthenticationType;
1453
- (function (TediousAuthenticationType) {
1454
- TediousAuthenticationType["default"] = "default";
1455
- TediousAuthenticationType["MSI"] = "azure-active-directory-access-token";
1456
- })(TediousAuthenticationType || (TediousAuthenticationType = {}));
1103
+ }
1104
+ }
1457
1105
 
1458
1106
  // Copyright (c) Microsoft Corporation.
1459
1107
  /**
@@ -1507,7 +1155,7 @@ var TediousAuthenticationType;
1507
1155
  *
1508
1156
  * @beta
1509
1157
  */
1510
- var TeamsBotSsoPrompt = /** @class */ (function () {
1158
+ class TeamsBotSsoPrompt {
1511
1159
  /**
1512
1160
  * Constructor of TeamsBotSsoPrompt.
1513
1161
  *
@@ -1519,7 +1167,7 @@ var TeamsBotSsoPrompt = /** @class */ (function () {
1519
1167
  *
1520
1168
  * @beta
1521
1169
  */
1522
- function TeamsBotSsoPrompt(dialogId, settings) {
1170
+ constructor(dialogId, settings) {
1523
1171
  this.settings = settings;
1524
1172
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
1525
1173
  }
@@ -1539,13 +1187,11 @@ var TeamsBotSsoPrompt = /** @class */ (function () {
1539
1187
  *
1540
1188
  * @beta
1541
1189
  */
1542
- TeamsBotSsoPrompt.prototype.beginDialog = function (dc) {
1543
- return __awaiter(this, void 0, void 0, function () {
1544
- return __generator(this, function (_a) {
1545
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
1546
- });
1190
+ beginDialog(dc) {
1191
+ return __awaiter(this, void 0, void 0, function* () {
1192
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
1547
1193
  });
1548
- };
1194
+ }
1549
1195
  /**
1550
1196
  * Called when a prompt dialog is the active dialog and the user replied with a new activity.
1551
1197
  *
@@ -1564,15 +1210,12 @@ var TeamsBotSsoPrompt = /** @class */ (function () {
1564
1210
  *
1565
1211
  * @beta
1566
1212
  */
1567
- TeamsBotSsoPrompt.prototype.continueDialog = function (dc) {
1568
- return __awaiter(this, void 0, void 0, function () {
1569
- return __generator(this, function (_a) {
1570
- throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
1571
- });
1213
+ continueDialog(dc) {
1214
+ return __awaiter(this, void 0, void 0, function* () {
1215
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
1572
1216
  });
1573
- };
1574
- return TeamsBotSsoPrompt;
1575
- }());
1217
+ }
1218
+ }
1576
1219
 
1577
1220
  export { DefaultTediousConnectionConfiguration, ErrorCode, ErrorWithCode, LogLevel, M365TenantCredential, MsGraphAuthProvider, OnBehalfOfUserCredential, ResourceType, TeamsBotSsoPrompt, TeamsUserCredential, createMicrosoftGraphClient, getAuthenticationConfiguration, getLogLevel, getResourceConfiguration, loadConfiguration, setLogFunction, setLogLevel, setLogger };
1578
1221
  //# sourceMappingURL=index.esm5.js.map