@microsoft/teamsfx 1.2.1 → 2.0.0-alpha.28543dcd0.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,6 +1,6 @@
1
1
  import { __awaiter } from 'tslib';
2
2
  import jwt_decode from 'jwt-decode';
3
- import * as microsoftTeams from '@microsoft/teams-js';
3
+ import { app, authentication } from '@microsoft/teams-js';
4
4
  import { PublicClientApplication } from '@azure/msal-browser';
5
5
  import { Client } from '@microsoft/microsoft-graph-client';
6
6
  import axios from 'axios';
@@ -433,12 +433,6 @@ function validateScopesType(value) {
433
433
  * Only works in in server side.
434
434
  */
435
435
  class AppCredential {
436
- /**
437
- * Constructor of AppCredential.
438
- *
439
- * @remarks
440
- * Only works in in server side.
441
- */
442
436
  constructor(authConfig) {
443
437
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported);
444
438
  }
@@ -463,12 +457,6 @@ class AppCredential {
463
457
  * Can only be used in server side.
464
458
  */
465
459
  class OnBehalfOfUserCredential {
466
- /**
467
- * Constructor of OnBehalfOfUserCredential
468
- *
469
- * @remarks
470
- * Can Only works in in server side.
471
- */
472
460
  constructor(ssoToken, config) {
473
461
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
474
462
  }
@@ -503,28 +491,6 @@ const loginPageHeight = 535;
503
491
  * Can only be used within Teams.
504
492
  */
505
493
  class TeamsUserCredential {
506
- /**
507
- * Constructor of TeamsUserCredential.
508
- *
509
- * @example
510
- * ```typescript
511
- * const config = {
512
- * authentication: {
513
- * initiateLoginEndpoint: "https://localhost:3000/auth-start.html",
514
- * clientId: "xxx"
515
- * }
516
- * }
517
- * // Use default configuration provided by Teams Toolkit
518
- * const credential = new TeamsUserCredential();
519
- * // Use a customized configuration
520
- * const anotherCredential = new TeamsUserCredential(config);
521
- * ```
522
- *
523
- * @param {AuthenticationConfiguration} authConfig - The authentication configuration. Use environment variables if not provided.
524
- *
525
- * @throws {@link ErrorCode|InvalidConfiguration} when client id, initiate login endpoint or simple auth endpoint is not found in config.
526
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
527
- */
528
494
  constructor(authConfig) {
529
495
  internalLogger.info("Create teams user credential");
530
496
  this.config = this.loadAndValidateConfig(authConfig);
@@ -560,51 +526,48 @@ class TeamsUserCredential {
560
526
  if (!this.initialized) {
561
527
  yield this.init(resources);
562
528
  }
563
- return new Promise((resolve, reject) => {
564
- microsoftTeams.initialize(() => {
565
- microsoftTeams.authentication.authenticate({
566
- url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,
567
- width: loginPageWidth,
568
- height: loginPageHeight,
569
- successCallback: (result) => __awaiter(this, void 0, void 0, function* () {
570
- if (!result) {
571
- const errorMsg = "Get empty authentication result from MSAL";
572
- internalLogger.error(errorMsg);
573
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
574
- return;
575
- }
576
- let resultJson = {};
577
- try {
578
- resultJson = typeof result == "string" ? JSON.parse(result) : result;
579
- }
580
- catch (error) {
581
- // If can not parse result as Json, will throw error.
582
- const failedToParseResult = "Failed to parse response to Json.";
583
- internalLogger.error(failedToParseResult);
584
- reject(new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse));
585
- }
586
- // If code exists in result, user may using previous auth-start and auth-end page.
587
- if (resultJson.code) {
588
- const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
589
- const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
590
- `Please refer to the help link for how to fix the issue: ${helpLink}.`;
591
- internalLogger.error(usingPreviousAuthPage);
592
- reject(new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse));
593
- }
594
- // If sessionStorage exists in result, set the values in current session storage.
595
- if (resultJson.sessionStorage) {
596
- this.setSessionStorage(resultJson.sessionStorage);
597
- }
598
- resolve();
599
- }),
600
- failureCallback: (reason) => {
601
- const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${reason}`;
602
- internalLogger.error(errorMsg);
603
- reject(new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed));
604
- },
605
- });
606
- });
607
- });
529
+ yield app.initialize();
530
+ let result;
531
+ try {
532
+ const params = {
533
+ url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,
534
+ width: loginPageWidth,
535
+ height: loginPageHeight,
536
+ };
537
+ result = yield authentication.authenticate(params);
538
+ if (!result) {
539
+ const errorMsg = "Get empty authentication result from MSAL";
540
+ internalLogger.error(errorMsg);
541
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
542
+ }
543
+ }
544
+ catch (err) {
545
+ const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${err.message}`;
546
+ internalLogger.error(errorMsg);
547
+ throw new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed);
548
+ }
549
+ let resultJson = {};
550
+ try {
551
+ resultJson = typeof result == "string" ? JSON.parse(result) : result;
552
+ }
553
+ catch (error) {
554
+ // If can not parse result as Json, will throw error.
555
+ const failedToParseResult = "Failed to parse response to Json.";
556
+ internalLogger.error(failedToParseResult);
557
+ throw new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse);
558
+ }
559
+ // If code exists in result, user may using previous auth-start and auth-end page.
560
+ if (resultJson.code) {
561
+ const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
562
+ const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
563
+ `Please refer to the help link for how to fix the issue: ${helpLink}.`;
564
+ internalLogger.error(usingPreviousAuthPage);
565
+ throw new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse);
566
+ }
567
+ // If sessionStorage exists in result, set the values in current session storage.
568
+ if (resultJson.sessionStorage) {
569
+ this.setSessionStorage(resultJson.sessionStorage);
570
+ }
608
571
  });
609
572
  }
610
573
  /**
@@ -754,52 +717,48 @@ class TeamsUserCredential {
754
717
  * @returns SSO token
755
718
  */
756
719
  getSSOToken(resources) {
757
- return new Promise((resolve, reject) => {
720
+ return __awaiter(this, void 0, void 0, function* () {
758
721
  if (this.ssoToken) {
759
722
  if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
760
723
  internalLogger.verbose("Get SSO token from memory cache");
761
- resolve(this.ssoToken);
762
- return;
724
+ return this.ssoToken;
763
725
  }
764
726
  }
765
- if (this.checkInTeams()) {
766
- microsoftTeams.initialize(() => {
767
- microsoftTeams.authentication.getAuthToken({
768
- successCallback: (token) => {
769
- if (!token) {
770
- const errorMsg = "Get empty SSO token from Teams";
771
- internalLogger.error(errorMsg);
772
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
773
- return;
774
- }
775
- const tokenObject = parseJwt(token);
776
- if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
777
- const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
778
- internalLogger.error(errorMsg);
779
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
780
- return;
781
- }
782
- const ssoToken = {
783
- token,
784
- expiresOnTimestamp: tokenObject.exp * 1000,
785
- };
786
- this.ssoToken = ssoToken;
787
- resolve(ssoToken);
788
- },
789
- failureCallback: (errMessage) => {
790
- const errorMsg = "Get SSO token failed with error: " + errMessage;
791
- internalLogger.error(errorMsg);
792
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
793
- },
794
- resources: resources !== null && resources !== void 0 ? resources : [],
795
- });
796
- });
727
+ const params = { resources: resources !== null && resources !== void 0 ? resources : [] };
728
+ let token;
729
+ try {
730
+ yield app.initialize();
797
731
  }
798
- else {
799
- const errorMsg = "Initialize teams sdk failed due to not running inside Teams";
732
+ catch (err) {
733
+ const errorMsg = "Initialize teams sdk failed due to not running inside Teams environment";
734
+ internalLogger.error(errorMsg);
735
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
736
+ }
737
+ try {
738
+ token = yield authentication.getAuthToken(params);
739
+ }
740
+ catch (err) {
741
+ const errorMsg = "Get SSO token failed with error: " + err.message;
800
742
  internalLogger.error(errorMsg);
801
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
743
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
802
744
  }
745
+ if (!token) {
746
+ const errorMsg = "Get empty SSO token from Teams";
747
+ internalLogger.error(errorMsg);
748
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
749
+ }
750
+ const tokenObject = parseJwt(token);
751
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
752
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
753
+ internalLogger.error(errorMsg);
754
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
755
+ }
756
+ const ssoToken = {
757
+ token,
758
+ expiresOnTimestamp: tokenObject.exp * 1000,
759
+ };
760
+ this.ssoToken = ssoToken;
761
+ return ssoToken;
803
762
  });
804
763
  }
805
764
  /**
@@ -840,16 +799,6 @@ class TeamsUserCredential {
840
799
  throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
841
800
  }
842
801
  }
843
- // Come from here: https://github.com/wictorwilen/msteams-react-base-component/blob/master/src/useTeams.ts
844
- checkInTeams() {
845
- if ((window.parent === window.self && window.nativeInterface) ||
846
- window.navigator.userAgent.includes("Teams/") ||
847
- window.name === "embedded-page-container" ||
848
- window.name === "extension-tab-frame") {
849
- return true;
850
- }
851
- return false;
852
- }
853
802
  }
854
803
 
855
804
  // Copyright (c) Microsoft Corporation.
@@ -858,18 +807,8 @@ const defaultScope = "https://graph.microsoft.com/.default";
858
807
  * Microsoft Graph auth provider for Teams Framework
859
808
  */
860
809
  class MsGraphAuthProvider {
861
- /**
862
- * Constructor of MsGraphAuthProvider.
863
- *
864
- * @param {TeamsFx} teamsfx - Used to provide configuration and auth.
865
- * @param {string | string[]} scopes - The list of scopes for which the token will have access.
866
- *
867
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
868
- *
869
- * @returns An instance of MsGraphAuthProvider.
870
- */
871
- constructor(teamsfx, scopes) {
872
- this.teamsfx = teamsfx;
810
+ constructor(credentialOrTeamsFx, scopes) {
811
+ this.credentialOrTeamsFx = credentialOrTeamsFx;
873
812
  let scopesStr = defaultScope;
874
813
  if (scopes) {
875
814
  validateScopesType(scopes);
@@ -896,7 +835,15 @@ class MsGraphAuthProvider {
896
835
  getAccessToken() {
897
836
  return __awaiter(this, void 0, void 0, function* () {
898
837
  internalLogger.info(`Get Graph Access token with scopes: '${this.scopes}'`);
899
- const accessToken = yield this.teamsfx.getCredential().getToken(this.scopes);
838
+ let accessToken;
839
+ if (this.credentialOrTeamsFx.getCredential) {
840
+ accessToken = yield this.credentialOrTeamsFx
841
+ .getCredential()
842
+ .getToken(this.scopes);
843
+ }
844
+ else {
845
+ accessToken = yield this.credentialOrTeamsFx.getToken(this.scopes);
846
+ }
900
847
  return new Promise((resolve, reject) => {
901
848
  if (accessToken) {
902
849
  resolve(accessToken.token);
@@ -914,7 +861,6 @@ class MsGraphAuthProvider {
914
861
  // Copyright (c) Microsoft Corporation.
915
862
  /**
916
863
  * Get Microsoft graph client.
917
- *
918
864
  * @example
919
865
  * Get Microsoft graph client by TokenCredential
920
866
  * ```typescript
@@ -968,11 +914,74 @@ function createMicrosoftGraphClient(teamsfx, scopes) {
968
914
  authProvider,
969
915
  });
970
916
  return graphClient;
917
+ }
918
+ // eslint-disable-next-line no-secrets/no-secrets
919
+ /**
920
+ * Get Microsoft graph client.
921
+ * @example
922
+ * Get Microsoft graph client by TokenCredential
923
+ * ```typescript
924
+ * // In browser: TeamsUserCredential
925
+ * const authConfig: TeamsUserCredentialAuthConfig = {
926
+ * clientId: "xxx",
927
+ initiateLoginEndpoint: "https://xxx/auth-start.html",
928
+ * };
929
+
930
+ * const credential = new TeamsUserCredential(authConfig);
931
+
932
+ * const scope = "User.Read";
933
+ * await credential.login(scope);
934
+
935
+ * const client = createMicrosoftGraphClientWithCredential(credential, scope);
936
+
937
+ * // In node: OnBehalfOfUserCredential
938
+ * const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {
939
+ * authorityHost: "xxx",
940
+ * clientId: "xxx",
941
+ * tenantId: "xxx",
942
+ * clientSecret: "xxx",
943
+ * };
944
+
945
+ * const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);
946
+ * const scope = "User.Read";
947
+ * const client = createMicrosoftGraphClientWithCredential(oboCredential, scope);
948
+
949
+ * // In node: AppCredential
950
+ * const appAuthConfig: AppCredentialAuthConfig = {
951
+ * authorityHost: "xxx",
952
+ * clientId: "xxx",
953
+ * tenantId: "xxx",
954
+ * clientSecret: "xxx",
955
+ * };
956
+ * const appCredential = new AppCredential(appAuthConfig);
957
+ * const scope = "User.Read";
958
+ * const client = createMicrosoftGraphClientWithCredential(appCredential, scope);
959
+ *
960
+ * const profile = await client.api("/me").get();
961
+ * ```
962
+ *
963
+ * @param {TokenCredential} credential - Used to provide configuration and auth.
964
+ * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.
965
+ *
966
+ * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
967
+ *
968
+ * @returns Graph client with specified scopes.
969
+ */
970
+ function createMicrosoftGraphClientWithCredential(credential, scopes) {
971
+ internalLogger.info("Create Microsoft Graph Client");
972
+ const authProvider = new MsGraphAuthProvider(credential, scopes);
973
+ const graphClient = Client.initWithMiddleware({
974
+ authProvider,
975
+ });
976
+ return graphClient;
971
977
  }
972
978
 
973
979
  // Copyright (c) Microsoft Corporation.
974
980
  /**
975
981
  * Generate connection configuration consumed by tedious.
982
+ *
983
+ * @deprecated we recommend you compose your own Tedious configuration for better flexibility.
984
+ *
976
985
  * @remarks
977
986
  * Only works in in server side.
978
987
  */
@@ -1514,13 +1523,7 @@ class ConversationBot {
1514
1523
  * Sso execution dialog, use to handle sso command
1515
1524
  */
1516
1525
  class BotSsoExecutionDialog {
1517
- /**
1518
- * Creates a new instance of the BotSsoExecutionDialog.
1519
- * @param dedupStorage Helper storage to remove duplicated messages
1520
- * @param requiredScopes The list of scopes for which the token will have access
1521
- * @param teamsfx {@link TeamsFx} instance for authentication
1522
- */
1523
- constructor(dedupStorage, requiredScopes, teamsfx) {
1526
+ constructor(dedupStorage, ssoPromptSettings, authConfig, ...args) {
1524
1527
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1525
1528
  }
1526
1529
  /**
@@ -2041,7 +2044,17 @@ function handleMessageExtensionQueryWithToken(context, config, scopes, logic) {
2041
2044
  return __awaiter(this, void 0, void 0, function* () {
2042
2045
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
2043
2046
  });
2047
+ }
2048
+ /**
2049
+ * Users execute query with SSO or Access Token.
2050
+ * @remarks
2051
+ * Only works in in server side.
2052
+ */
2053
+ function handleMessageExtensionQueryWithSSO(context, config, initiateLoginEndpoint, scopes, logic) {
2054
+ return __awaiter(this, void 0, void 0, function* () {
2055
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
2056
+ });
2044
2057
  }
2045
2058
 
2046
- export { AdaptiveCardResponse, ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, BotSsoExecutionDialog, CardActionBot, CertificateAuthProvider, Channel, CommandBot, ConversationBot, ErrorCode, ErrorWithCode, IdentityType, InvokeResponseErrorCode, LogLevel, Member, MsGraphAuthProvider, NotificationBot, NotificationTargetType, OnBehalfOfUserCredential, TeamsBotInstallation, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createApiClient, createMicrosoftGraphClient, createPemCertOption, createPfxCertOption, getLogLevel, getTediousConnectionConfig, handleMessageExtensionQueryWithToken, sendAdaptiveCard, sendMessage, setLogFunction, setLogLevel, setLogger };
2059
+ export { AdaptiveCardResponse, ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, BotSsoExecutionDialog, CardActionBot, CertificateAuthProvider, Channel, CommandBot, ConversationBot, ErrorCode, ErrorWithCode, IdentityType, InvokeResponseErrorCode, LogLevel, Member, MsGraphAuthProvider, NotificationBot, NotificationTargetType, OnBehalfOfUserCredential, TeamsBotInstallation, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createApiClient, createMicrosoftGraphClient, createMicrosoftGraphClientWithCredential, createPemCertOption, createPfxCertOption, getLogLevel, getTediousConnectionConfig, handleMessageExtensionQueryWithSSO, handleMessageExtensionQueryWithToken, sendAdaptiveCard, sendMessage, setLogFunction, setLogLevel, setLogger };
2047
2060
  //# sourceMappingURL=index.esm5.js.map