@microsoft/teamsfx 1.2.1-rc.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,5 +1,5 @@
1
1
  import jwt_decode from 'jwt-decode';
2
- import * as microsoftTeams from '@microsoft/teams-js';
2
+ import { app, authentication } from '@microsoft/teams-js';
3
3
  import { PublicClientApplication } from '@azure/msal-browser';
4
4
  import { Client } from '@microsoft/microsoft-graph-client';
5
5
  import axios from 'axios';
@@ -432,12 +432,6 @@ function validateScopesType(value) {
432
432
  * Only works in in server side.
433
433
  */
434
434
  class AppCredential {
435
- /**
436
- * Constructor of AppCredential.
437
- *
438
- * @remarks
439
- * Only works in in server side.
440
- */
441
435
  constructor(authConfig) {
442
436
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported);
443
437
  }
@@ -460,12 +454,6 @@ class AppCredential {
460
454
  * Can only be used in server side.
461
455
  */
462
456
  class OnBehalfOfUserCredential {
463
- /**
464
- * Constructor of OnBehalfOfUserCredential
465
- *
466
- * @remarks
467
- * Can Only works in in server side.
468
- */
469
457
  constructor(ssoToken, config) {
470
458
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
471
459
  }
@@ -498,28 +486,6 @@ const loginPageHeight = 535;
498
486
  * Can only be used within Teams.
499
487
  */
500
488
  class TeamsUserCredential {
501
- /**
502
- * Constructor of TeamsUserCredential.
503
- *
504
- * @example
505
- * ```typescript
506
- * const config = {
507
- * authentication: {
508
- * initiateLoginEndpoint: "https://localhost:3000/auth-start.html",
509
- * clientId: "xxx"
510
- * }
511
- * }
512
- * // Use default configuration provided by Teams Toolkit
513
- * const credential = new TeamsUserCredential();
514
- * // Use a customized configuration
515
- * const anotherCredential = new TeamsUserCredential(config);
516
- * ```
517
- *
518
- * @param {AuthenticationConfiguration} authConfig - The authentication configuration. Use environment variables if not provided.
519
- *
520
- * @throws {@link ErrorCode|InvalidConfiguration} when client id, initiate login endpoint or simple auth endpoint is not found in config.
521
- * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
522
- */
523
489
  constructor(authConfig) {
524
490
  internalLogger.info("Create teams user credential");
525
491
  this.config = this.loadAndValidateConfig(authConfig);
@@ -554,51 +520,48 @@ class TeamsUserCredential {
554
520
  if (!this.initialized) {
555
521
  await this.init(resources);
556
522
  }
557
- return new Promise((resolve, reject) => {
558
- microsoftTeams.initialize(() => {
559
- microsoftTeams.authentication.authenticate({
560
- url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,
561
- width: loginPageWidth,
562
- height: loginPageHeight,
563
- successCallback: async (result) => {
564
- if (!result) {
565
- const errorMsg = "Get empty authentication result from MSAL";
566
- internalLogger.error(errorMsg);
567
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
568
- return;
569
- }
570
- let resultJson = {};
571
- try {
572
- resultJson = typeof result == "string" ? JSON.parse(result) : result;
573
- }
574
- catch (error) {
575
- // If can not parse result as Json, will throw error.
576
- const failedToParseResult = "Failed to parse response to Json.";
577
- internalLogger.error(failedToParseResult);
578
- reject(new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse));
579
- }
580
- // If code exists in result, user may using previous auth-start and auth-end page.
581
- if (resultJson.code) {
582
- const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
583
- const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
584
- `Please refer to the help link for how to fix the issue: ${helpLink}.`;
585
- internalLogger.error(usingPreviousAuthPage);
586
- reject(new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse));
587
- }
588
- // If sessionStorage exists in result, set the values in current session storage.
589
- if (resultJson.sessionStorage) {
590
- this.setSessionStorage(resultJson.sessionStorage);
591
- }
592
- resolve();
593
- },
594
- failureCallback: (reason) => {
595
- const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${reason}`;
596
- internalLogger.error(errorMsg);
597
- reject(new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed));
598
- },
599
- });
600
- });
601
- });
523
+ await app.initialize();
524
+ let result;
525
+ try {
526
+ const params = {
527
+ url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,
528
+ width: loginPageWidth,
529
+ height: loginPageHeight,
530
+ };
531
+ result = await authentication.authenticate(params);
532
+ if (!result) {
533
+ const errorMsg = "Get empty authentication result from MSAL";
534
+ internalLogger.error(errorMsg);
535
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
536
+ }
537
+ }
538
+ catch (err) {
539
+ const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${err.message}`;
540
+ internalLogger.error(errorMsg);
541
+ throw new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed);
542
+ }
543
+ let resultJson = {};
544
+ try {
545
+ resultJson = typeof result == "string" ? JSON.parse(result) : result;
546
+ }
547
+ catch (error) {
548
+ // If can not parse result as Json, will throw error.
549
+ const failedToParseResult = "Failed to parse response to Json.";
550
+ internalLogger.error(failedToParseResult);
551
+ throw new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse);
552
+ }
553
+ // If code exists in result, user may using previous auth-start and auth-end page.
554
+ if (resultJson.code) {
555
+ const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
556
+ const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
557
+ `Please refer to the help link for how to fix the issue: ${helpLink}.`;
558
+ internalLogger.error(usingPreviousAuthPage);
559
+ throw new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse);
560
+ }
561
+ // If sessionStorage exists in result, set the values in current session storage.
562
+ if (resultJson.sessionStorage) {
563
+ this.setSessionStorage(resultJson.sessionStorage);
564
+ }
602
565
  }
603
566
  /**
604
567
  * Get access token from credential.
@@ -740,54 +703,48 @@ class TeamsUserCredential {
740
703
  *
741
704
  * @returns SSO token
742
705
  */
743
- getSSOToken(resources) {
744
- return new Promise((resolve, reject) => {
745
- if (this.ssoToken) {
746
- if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
747
- internalLogger.verbose("Get SSO token from memory cache");
748
- resolve(this.ssoToken);
749
- return;
750
- }
751
- }
752
- if (this.checkInTeams()) {
753
- microsoftTeams.initialize(() => {
754
- microsoftTeams.authentication.getAuthToken({
755
- successCallback: (token) => {
756
- if (!token) {
757
- const errorMsg = "Get empty SSO token from Teams";
758
- internalLogger.error(errorMsg);
759
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
760
- return;
761
- }
762
- const tokenObject = parseJwt(token);
763
- if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
764
- const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
765
- internalLogger.error(errorMsg);
766
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
767
- return;
768
- }
769
- const ssoToken = {
770
- token,
771
- expiresOnTimestamp: tokenObject.exp * 1000,
772
- };
773
- this.ssoToken = ssoToken;
774
- resolve(ssoToken);
775
- },
776
- failureCallback: (errMessage) => {
777
- const errorMsg = "Get SSO token failed with error: " + errMessage;
778
- internalLogger.error(errorMsg);
779
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
780
- },
781
- resources: resources !== null && resources !== void 0 ? resources : [],
782
- });
783
- });
706
+ async getSSOToken(resources) {
707
+ if (this.ssoToken) {
708
+ if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
709
+ internalLogger.verbose("Get SSO token from memory cache");
710
+ return this.ssoToken;
784
711
  }
785
- else {
786
- const errorMsg = "Initialize teams sdk failed due to not running inside Teams";
787
- internalLogger.error(errorMsg);
788
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
789
- }
790
- });
712
+ }
713
+ const params = { resources: resources !== null && resources !== void 0 ? resources : [] };
714
+ let token;
715
+ try {
716
+ await app.initialize();
717
+ }
718
+ catch (err) {
719
+ const errorMsg = "Initialize teams sdk failed due to not running inside Teams environment";
720
+ internalLogger.error(errorMsg);
721
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
722
+ }
723
+ try {
724
+ token = await authentication.getAuthToken(params);
725
+ }
726
+ catch (err) {
727
+ const errorMsg = "Get SSO token failed with error: " + err.message;
728
+ internalLogger.error(errorMsg);
729
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
730
+ }
731
+ if (!token) {
732
+ const errorMsg = "Get empty SSO token from Teams";
733
+ internalLogger.error(errorMsg);
734
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
735
+ }
736
+ const tokenObject = parseJwt(token);
737
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
738
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
739
+ internalLogger.error(errorMsg);
740
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
741
+ }
742
+ const ssoToken = {
743
+ token,
744
+ expiresOnTimestamp: tokenObject.exp * 1000,
745
+ };
746
+ this.ssoToken = ssoToken;
747
+ return ssoToken;
791
748
  }
792
749
  /**
793
750
  * Load and validate authentication configuration
@@ -827,16 +784,6 @@ class TeamsUserCredential {
827
784
  throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
828
785
  }
829
786
  }
830
- // Come from here: https://github.com/wictorwilen/msteams-react-base-component/blob/master/src/useTeams.ts
831
- checkInTeams() {
832
- if ((window.parent === window.self && window.nativeInterface) ||
833
- window.navigator.userAgent.includes("Teams/") ||
834
- window.name === "embedded-page-container" ||
835
- window.name === "extension-tab-frame") {
836
- return true;
837
- }
838
- return false;
839
- }
840
787
  }
841
788
 
842
789
  // Copyright (c) Microsoft Corporation.
@@ -845,18 +792,8 @@ const defaultScope = "https://graph.microsoft.com/.default";
845
792
  * Microsoft Graph auth provider for Teams Framework
846
793
  */
847
794
  class MsGraphAuthProvider {
848
- /**
849
- * Constructor of MsGraphAuthProvider.
850
- *
851
- * @param {TeamsFx} teamsfx - Used to provide configuration and auth.
852
- * @param {string | string[]} scopes - The list of scopes for which the token will have access.
853
- *
854
- * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
855
- *
856
- * @returns An instance of MsGraphAuthProvider.
857
- */
858
- constructor(teamsfx, scopes) {
859
- this.teamsfx = teamsfx;
795
+ constructor(credentialOrTeamsFx, scopes) {
796
+ this.credentialOrTeamsFx = credentialOrTeamsFx;
860
797
  let scopesStr = defaultScope;
861
798
  if (scopes) {
862
799
  validateScopesType(scopes);
@@ -882,7 +819,15 @@ class MsGraphAuthProvider {
882
819
  */
883
820
  async getAccessToken() {
884
821
  internalLogger.info(`Get Graph Access token with scopes: '${this.scopes}'`);
885
- const accessToken = await this.teamsfx.getCredential().getToken(this.scopes);
822
+ let accessToken;
823
+ if (this.credentialOrTeamsFx.getCredential) {
824
+ accessToken = await this.credentialOrTeamsFx
825
+ .getCredential()
826
+ .getToken(this.scopes);
827
+ }
828
+ else {
829
+ accessToken = await this.credentialOrTeamsFx.getToken(this.scopes);
830
+ }
886
831
  return new Promise((resolve, reject) => {
887
832
  if (accessToken) {
888
833
  resolve(accessToken.token);
@@ -899,7 +844,6 @@ class MsGraphAuthProvider {
899
844
  // Copyright (c) Microsoft Corporation.
900
845
  /**
901
846
  * Get Microsoft graph client.
902
- *
903
847
  * @example
904
848
  * Get Microsoft graph client by TokenCredential
905
849
  * ```typescript
@@ -953,11 +897,74 @@ function createMicrosoftGraphClient(teamsfx, scopes) {
953
897
  authProvider,
954
898
  });
955
899
  return graphClient;
900
+ }
901
+ // eslint-disable-next-line no-secrets/no-secrets
902
+ /**
903
+ * Get Microsoft graph client.
904
+ * @example
905
+ * Get Microsoft graph client by TokenCredential
906
+ * ```typescript
907
+ * // In browser: TeamsUserCredential
908
+ * const authConfig: TeamsUserCredentialAuthConfig = {
909
+ * clientId: "xxx",
910
+ initiateLoginEndpoint: "https://xxx/auth-start.html",
911
+ * };
912
+
913
+ * const credential = new TeamsUserCredential(authConfig);
914
+
915
+ * const scope = "User.Read";
916
+ * await credential.login(scope);
917
+
918
+ * const client = createMicrosoftGraphClientWithCredential(credential, scope);
919
+
920
+ * // In node: OnBehalfOfUserCredential
921
+ * const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {
922
+ * authorityHost: "xxx",
923
+ * clientId: "xxx",
924
+ * tenantId: "xxx",
925
+ * clientSecret: "xxx",
926
+ * };
927
+
928
+ * const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);
929
+ * const scope = "User.Read";
930
+ * const client = createMicrosoftGraphClientWithCredential(oboCredential, scope);
931
+
932
+ * // In node: AppCredential
933
+ * const appAuthConfig: AppCredentialAuthConfig = {
934
+ * authorityHost: "xxx",
935
+ * clientId: "xxx",
936
+ * tenantId: "xxx",
937
+ * clientSecret: "xxx",
938
+ * };
939
+ * const appCredential = new AppCredential(appAuthConfig);
940
+ * const scope = "User.Read";
941
+ * const client = createMicrosoftGraphClientWithCredential(appCredential, scope);
942
+ *
943
+ * const profile = await client.api("/me").get();
944
+ * ```
945
+ *
946
+ * @param {TokenCredential} credential - Used to provide configuration and auth.
947
+ * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.
948
+ *
949
+ * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
950
+ *
951
+ * @returns Graph client with specified scopes.
952
+ */
953
+ function createMicrosoftGraphClientWithCredential(credential, scopes) {
954
+ internalLogger.info("Create Microsoft Graph Client");
955
+ const authProvider = new MsGraphAuthProvider(credential, scopes);
956
+ const graphClient = Client.initWithMiddleware({
957
+ authProvider,
958
+ });
959
+ return graphClient;
956
960
  }
957
961
 
958
962
  // Copyright (c) Microsoft Corporation.
959
963
  /**
960
964
  * Generate connection configuration consumed by tedious.
965
+ *
966
+ * @deprecated we recommend you compose your own Tedious configuration for better flexibility.
967
+ *
961
968
  * @remarks
962
969
  * Only works in in server side.
963
970
  */
@@ -1477,13 +1484,7 @@ class ConversationBot {
1477
1484
  * Sso execution dialog, use to handle sso command
1478
1485
  */
1479
1486
  class BotSsoExecutionDialog {
1480
- /**
1481
- * Creates a new instance of the BotSsoExecutionDialog.
1482
- * @param dedupStorage Helper storage to remove duplicated messages
1483
- * @param requiredScopes The list of scopes for which the token will have access
1484
- * @param teamsfx {@link TeamsFx} instance for authentication
1485
- */
1486
- constructor(dedupStorage, requiredScopes, teamsfx) {
1487
+ constructor(dedupStorage, ssoPromptSettings, authConfig, ...args) {
1487
1488
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
1488
1489
  }
1489
1490
  /**
@@ -1978,7 +1979,15 @@ class CardActionBot {
1978
1979
  */
1979
1980
  async function handleMessageExtensionQueryWithToken(context, config, scopes, logic) {
1980
1981
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
1982
+ }
1983
+ /**
1984
+ * Users execute query with SSO or Access Token.
1985
+ * @remarks
1986
+ * Only works in in server side.
1987
+ */
1988
+ async function handleMessageExtensionQueryWithSSO(context, config, initiateLoginEndpoint, scopes, logic) {
1989
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
1981
1990
  }
1982
1991
 
1983
- 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 };
1992
+ 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 };
1984
1993
  //# sourceMappingURL=index.esm2017.js.map