@microsoft/teamsfx 0.6.3-alpha.ffd3f8bc7.0 → 0.7.0-beta.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';
@@ -95,6 +95,8 @@ ErrorMessage.BasicCredentialAlreadyExists = "Basic credential already exists!";
95
95
  // InvalidParameter Error
96
96
  ErrorMessage.EmptyParameter = "Parameter {0} is empty";
97
97
  ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
98
+ ErrorMessage.DuplicateApiKeyInHeader = "The request already defined api key in request header with name {0}.";
99
+ ErrorMessage.DuplicateApiKeyInQueryParam = "The request already defined api key in query parameter with name {0}.";
98
100
  /**
99
101
  * Error class with code and message thrown by the SDK.
100
102
  *
@@ -546,51 +548,48 @@ class TeamsUserCredential {
546
548
  if (!this.initialized) {
547
549
  await this.init();
548
550
  }
549
- return new Promise((resolve, reject) => {
550
- microsoftTeams.initialize(() => {
551
- microsoftTeams.authentication.authenticate({
552
- url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,
553
- width: loginPageWidth,
554
- height: loginPageHeight,
555
- successCallback: async (result) => {
556
- if (!result) {
557
- const errorMsg = "Get empty authentication result from MSAL";
558
- internalLogger.error(errorMsg);
559
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
560
- return;
561
- }
562
- let resultJson = {};
563
- try {
564
- resultJson = JSON.parse(result);
565
- }
566
- catch (error) {
567
- // If can not parse result as Json, will throw error.
568
- const failedToParseResult = "Failed to parse response to Json.";
569
- internalLogger.error(failedToParseResult);
570
- reject(new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse));
571
- }
572
- // If code exists in result, user may using previous auth-start and auth-end page.
573
- if (resultJson.code) {
574
- const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
575
- const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
576
- `Please refer to the help link for how to fix the issue: ${helpLink}.`;
577
- internalLogger.error(usingPreviousAuthPage);
578
- reject(new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse));
579
- }
580
- // If sessionStorage exists in result, set the values in current session storage.
581
- if (resultJson.sessionStorage) {
582
- this.setSessionStorage(resultJson.sessionStorage);
583
- }
584
- resolve();
585
- },
586
- failureCallback: (reason) => {
587
- const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${reason}`;
588
- internalLogger.error(errorMsg);
589
- reject(new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed));
590
- },
591
- });
592
- });
593
- });
551
+ await app.initialize();
552
+ let result;
553
+ try {
554
+ const params = {
555
+ url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,
556
+ width: loginPageWidth,
557
+ height: loginPageHeight,
558
+ };
559
+ result = await authentication.authenticate(params);
560
+ if (!result) {
561
+ const errorMsg = "Get empty authentication result from MSAL";
562
+ internalLogger.error(errorMsg);
563
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
564
+ }
565
+ }
566
+ catch (err) {
567
+ const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${err.message}`;
568
+ internalLogger.error(errorMsg);
569
+ throw new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed);
570
+ }
571
+ let resultJson = {};
572
+ try {
573
+ resultJson = JSON.parse(result);
574
+ }
575
+ catch (error) {
576
+ // If can not parse result as Json, will throw error.
577
+ const failedToParseResult = "Failed to parse response to Json.";
578
+ internalLogger.error(failedToParseResult);
579
+ throw new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse);
580
+ }
581
+ // If code exists in result, user may using previous auth-start and auth-end page.
582
+ if (resultJson.code) {
583
+ const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
584
+ const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
585
+ `Please refer to the help link for how to fix the issue: ${helpLink}.`;
586
+ internalLogger.error(usingPreviousAuthPage);
587
+ throw new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse);
588
+ }
589
+ // If sessionStorage exists in result, set the values in current session storage.
590
+ if (resultJson.sessionStorage) {
591
+ this.setSessionStorage(resultJson.sessionStorage);
592
+ }
594
593
  }
595
594
  /**
596
595
  * Get access token from credential.
@@ -723,54 +722,41 @@ class TeamsUserCredential {
723
722
  * 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
724
723
  * @returns SSO token
725
724
  */
726
- getSSOToken() {
727
- return new Promise((resolve, reject) => {
728
- if (this.ssoToken) {
729
- if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
730
- internalLogger.verbose("Get SSO token from memory cache");
731
- resolve(this.ssoToken);
732
- return;
733
- }
734
- }
735
- if (this.checkInTeams()) {
736
- microsoftTeams.initialize(() => {
737
- microsoftTeams.authentication.getAuthToken({
738
- successCallback: (token) => {
739
- if (!token) {
740
- const errorMsg = "Get empty SSO token from Teams";
741
- internalLogger.error(errorMsg);
742
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
743
- return;
744
- }
745
- const tokenObject = parseJwt(token);
746
- if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
747
- const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
748
- internalLogger.error(errorMsg);
749
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
750
- return;
751
- }
752
- const ssoToken = {
753
- token,
754
- expiresOnTimestamp: tokenObject.exp * 1000,
755
- };
756
- this.ssoToken = ssoToken;
757
- resolve(ssoToken);
758
- },
759
- failureCallback: (errMessage) => {
760
- const errorMsg = "Get SSO token failed with error: " + errMessage;
761
- internalLogger.error(errorMsg);
762
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
763
- },
764
- resources: [],
765
- });
766
- });
767
- }
768
- else {
769
- const errorMsg = "Initialize teams sdk failed due to not running inside Teams";
770
- internalLogger.error(errorMsg);
771
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
725
+ async getSSOToken() {
726
+ if (this.ssoToken) {
727
+ if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
728
+ internalLogger.verbose("Get SSO token from memory cache");
729
+ return this.ssoToken;
772
730
  }
773
- });
731
+ }
732
+ const params = {};
733
+ let token;
734
+ try {
735
+ await app.initialize();
736
+ token = await authentication.getAuthToken(params);
737
+ }
738
+ catch (err) {
739
+ const errorMsg = "Get SSO token failed with error: " + err.message;
740
+ internalLogger.error(errorMsg);
741
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
742
+ }
743
+ if (!token) {
744
+ const errorMsg = "Get empty SSO token from Teams";
745
+ internalLogger.error(errorMsg);
746
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
747
+ }
748
+ const tokenObject = parseJwt(token);
749
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
750
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
751
+ internalLogger.error(errorMsg);
752
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
753
+ }
754
+ const ssoToken = {
755
+ token,
756
+ expiresOnTimestamp: tokenObject.exp * 1000,
757
+ };
758
+ this.ssoToken = ssoToken;
759
+ return ssoToken;
774
760
  }
775
761
  /**
776
762
  * Load and validate authentication configuration
@@ -1099,7 +1085,7 @@ function createApiClient(apiEndpoint, authProvider) {
1099
1085
  */
1100
1086
  class BearerTokenAuthProvider {
1101
1087
  /**
1102
- * @param getToken Function that returns the content of bearer token used in http request
1088
+ * @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request
1103
1089
  *
1104
1090
  * @beta
1105
1091
  */
@@ -1109,7 +1095,7 @@ class BearerTokenAuthProvider {
1109
1095
  /**
1110
1096
  * Adds authentication info to http requests
1111
1097
  *
1112
- * @param config - Contains all the request information and can be updated to include extra authentication info.
1098
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1113
1099
  * Refer https://axios-http.com/docs/req_config for detailed document.
1114
1100
  *
1115
1101
  * @returns Updated axios request config.
@@ -1140,48 +1126,90 @@ class BearerTokenAuthProvider {
1140
1126
  class BasicAuthProvider {
1141
1127
  /**
1142
1128
  *
1143
- * @param userName - Username used in basic auth
1144
- * @param password - Password used in basic auth
1129
+ * @param { string } userName - Username used in basic auth
1130
+ * @param { string } password - Password used in basic auth
1131
+ *
1132
+ * @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.
1133
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1145
1134
  *
1146
1135
  * @beta
1147
1136
  */
1148
1137
  constructor(userName, password) {
1149
- if (!userName) {
1150
- throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "username"), ErrorCode.InvalidParameter);
1151
- }
1152
- if (!password) {
1153
- throw new ErrorWithCode(formatString(ErrorMessage.EmptyParameter, "password"), ErrorCode.InvalidParameter);
1154
- }
1155
- this.userName = userName;
1156
- this.password = password;
1138
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported);
1157
1139
  }
1158
1140
  /**
1159
1141
  * Adds authentication info to http requests
1160
1142
  *
1161
- * @param config - Contains all the request information and can be updated to include extra authentication info.
1143
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1162
1144
  * Refer https://axios-http.com/docs/req_config for detailed document.
1163
1145
  *
1164
1146
  * @returns Updated axios request config.
1165
1147
  *
1166
1148
  * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.
1149
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1167
1150
  *
1168
1151
  * @beta
1169
1152
  */
1170
1153
  async AddAuthenticationInfo(config) {
1171
- if (config.headers && config.headers["Authorization"]) {
1172
- throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
1173
- }
1174
- if (config.auth) {
1175
- throw new ErrorWithCode(ErrorMessage.BasicCredentialAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
1176
- }
1177
- config.auth = {
1178
- username: this.userName,
1179
- password: this.password,
1180
- };
1181
- return config;
1154
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported);
1182
1155
  }
1183
1156
  }
1184
1157
 
1158
+ // Copyright (c) Microsoft Corporation.
1159
+ /**
1160
+ * Provider that handles API Key authentication
1161
+ *
1162
+ * @beta
1163
+ */
1164
+ class ApiKeyProvider {
1165
+ /**
1166
+ *
1167
+ * @param { string } keyName - The name of request header or query parameter that specifies API Key
1168
+ * @param { string } keyValue - The value of API Key
1169
+ * @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.
1170
+ *
1171
+ * @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.
1172
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1173
+ *
1174
+ * @beta
1175
+ */
1176
+ constructor(keyName, keyValue, keyLocation) {
1177
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported);
1178
+ }
1179
+ /**
1180
+ * Adds authentication info to http requests
1181
+ *
1182
+ * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
1183
+ * Refer https://axios-http.com/docs/req_config for detailed document.
1184
+ *
1185
+ * @returns Updated axios request config.
1186
+ *
1187
+ * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.
1188
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1189
+ *
1190
+ * @beta
1191
+ */
1192
+ async AddAuthenticationInfo(config) {
1193
+ throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported);
1194
+ }
1195
+ }
1196
+ /**
1197
+ * Define available location for API Key location
1198
+ *
1199
+ * @beta
1200
+ */
1201
+ var ApiKeyLocation;
1202
+ (function (ApiKeyLocation) {
1203
+ /**
1204
+ * The API Key is placed in request header
1205
+ */
1206
+ ApiKeyLocation[ApiKeyLocation["Header"] = 0] = "Header";
1207
+ /**
1208
+ * The API Key is placed in query parameter
1209
+ */
1210
+ ApiKeyLocation[ApiKeyLocation["QueryParams"] = 1] = "QueryParams";
1211
+ })(ApiKeyLocation || (ApiKeyLocation = {}));
1212
+
1185
1213
  // Copyright (c) Microsoft Corporation.
1186
1214
  /**
1187
1215
  * Provider that handles Certificate authentication
@@ -1207,6 +1235,7 @@ class CertificateAuthProvider {
1207
1235
  * @returns Updated axios request config.
1208
1236
  *
1209
1237
  * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
1238
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1210
1239
  *
1211
1240
  * @beta
1212
1241
  */
@@ -1219,29 +1248,30 @@ class CertificateAuthProvider {
1219
1248
  *
1220
1249
  * @param { string | Buffer } cert - The cert chain in PEM format
1221
1250
  * @param { string | Buffer } key - The private key for the cert chain
1222
- * @param { string? } passphrase - The passphrase for private key
1223
- * @param { string? | Buffer? } ca - Overrides the trusted CA certificates
1251
+ * @param { {passphrase?: string; ca?: string | Buffer} } options - Optional settings when create the cert options.
1224
1252
  *
1225
1253
  * @returns Instance of SecureContextOptions
1226
1254
  *
1227
1255
  * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1256
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1228
1257
  *
1229
1258
  */
1230
- function createPemCertOption(cert, key, passphrase, ca) {
1259
+ function createPemCertOption(cert, key, options) {
1231
1260
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPemCertOption"), ErrorCode.RuntimeNotSupported);
1232
1261
  }
1233
1262
  /**
1234
1263
  * Helper to create SecureContextOptions from PFX format cert
1235
1264
  *
1236
1265
  * @param { string | Buffer } pfx - The content of .pfx file
1237
- * @param { string? } passphrase - Optional. The passphrase of .pfx file
1266
+ * @param { {passphrase?: string} } options - Optional settings when create the cert options.
1238
1267
  *
1239
1268
  * @returns Instance of SecureContextOptions
1240
1269
  *
1241
1270
  * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
1271
+ * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
1242
1272
  *
1243
1273
  */
1244
- function createPfxCertOption(pfx, passphrase) {
1274
+ function createPfxCertOption(pfx, options) {
1245
1275
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPfxCertOption"), ErrorCode.RuntimeNotSupported);
1246
1276
  }
1247
1277
 
@@ -1759,5 +1789,5 @@ class CommandBot {
1759
1789
  }
1760
1790
  }
1761
1791
 
1762
- export { AppCredential, BasicAuthProvider, BearerTokenAuthProvider, CertificateAuthProvider, Channel, CommandBot, ConversationBot, ErrorCode, ErrorWithCode, IdentityType, LogLevel, Member, MsGraphAuthProvider, NotificationBot, OnBehalfOfUserCredential, TeamsBotInstallation, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createApiClient, createMicrosoftGraphClient, createPemCertOption, createPfxCertOption, getLogLevel, getTediousConnectionConfig, sendAdaptiveCard, sendMessage, setLogFunction, setLogLevel, setLogger };
1792
+ export { ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, CertificateAuthProvider, Channel, CommandBot, ConversationBot, ErrorCode, ErrorWithCode, IdentityType, LogLevel, Member, MsGraphAuthProvider, NotificationBot, OnBehalfOfUserCredential, TeamsBotInstallation, TeamsBotSsoPrompt, TeamsFx, TeamsUserCredential, createApiClient, createMicrosoftGraphClient, createPemCertOption, createPfxCertOption, getLogLevel, getTediousConnectionConfig, sendAdaptiveCard, sendMessage, setLogFunction, setLogLevel, setLogger };
1763
1793
  //# sourceMappingURL=index.esm2017.js.map