@microsoft/teamsfx 3.0.0-alpha.e84e1682b.0 → 3.0.0-alpha.eb9d0eaa6.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.
- package/dist/index.esm2017.js +1 -1734
- package/dist/index.esm2017.js.map +1 -1
- package/dist/index.esm2017.mjs +16 -3577
- package/dist/index.esm2017.mjs.map +1 -1
- package/dist/index.esm5.js +15 -1778
- package/dist/index.esm5.js.map +1 -1
- package/dist/index.node.cjs.js +15 -3735
- package/dist/index.node.cjs.js.map +1 -1
- package/package.json +8 -8
- package/types/teamsfx.d.ts +0 -2181
package/dist/index.esm2017.js
CHANGED
@@ -1,1735 +1,2 @@
|
|
1
|
-
import { jwtDecode } from 'jwt-decode';
|
2
|
-
import { app, authentication } from '@microsoft/teams-js';
|
3
|
-
import { PublicClientApplication } from '@azure/msal-browser';
|
4
|
-
import axios from 'axios';
|
5
|
-
|
6
|
-
// Copyright (c) Microsoft Corporation.
|
7
|
-
// Licensed under the MIT license.
|
8
|
-
/**
|
9
|
-
* Error code to trace the error types.
|
10
|
-
*/
|
11
|
-
var ErrorCode;
|
12
|
-
(function (ErrorCode) {
|
13
|
-
/**
|
14
|
-
* Invalid parameter error.
|
15
|
-
*/
|
16
|
-
ErrorCode["InvalidParameter"] = "InvalidParameter";
|
17
|
-
/**
|
18
|
-
* Invalid configuration error.
|
19
|
-
*/
|
20
|
-
ErrorCode["InvalidConfiguration"] = "InvalidConfiguration";
|
21
|
-
/**
|
22
|
-
* Invalid certificate error.
|
23
|
-
*/
|
24
|
-
ErrorCode["InvalidCertificate"] = "InvalidCertificate";
|
25
|
-
/**
|
26
|
-
* Internal error.
|
27
|
-
*/
|
28
|
-
ErrorCode["InternalError"] = "InternalError";
|
29
|
-
/**
|
30
|
-
* Channel is not supported error.
|
31
|
-
*/
|
32
|
-
ErrorCode["ChannelNotSupported"] = "ChannelNotSupported";
|
33
|
-
/**
|
34
|
-
* Failed to retrieve sso token
|
35
|
-
*/
|
36
|
-
ErrorCode["FailedToRetrieveSsoToken"] = "FailedToRetrieveSsoToken";
|
37
|
-
/**
|
38
|
-
* Failed to process sso handler
|
39
|
-
*/
|
40
|
-
ErrorCode["FailedToProcessSsoHandler"] = "FailedToProcessSsoHandler";
|
41
|
-
/**
|
42
|
-
* Cannot find command
|
43
|
-
*/
|
44
|
-
ErrorCode["CannotFindCommand"] = "CannotFindCommand";
|
45
|
-
/**
|
46
|
-
* Failed to run sso step
|
47
|
-
*/
|
48
|
-
ErrorCode["FailedToRunSsoStep"] = "FailedToRunSsoStep";
|
49
|
-
/**
|
50
|
-
* Failed to run dedup step
|
51
|
-
*/
|
52
|
-
ErrorCode["FailedToRunDedupStep"] = "FailedToRunDedupStep";
|
53
|
-
/**
|
54
|
-
* Sso activity handler is undefined
|
55
|
-
*/
|
56
|
-
ErrorCode["SsoActivityHandlerIsUndefined"] = "SsoActivityHandlerIsUndefined";
|
57
|
-
/**
|
58
|
-
* Runtime is not supported error.
|
59
|
-
*/
|
60
|
-
ErrorCode["RuntimeNotSupported"] = "RuntimeNotSupported";
|
61
|
-
/**
|
62
|
-
* User failed to finish the AAD consent flow failed.
|
63
|
-
*/
|
64
|
-
ErrorCode["ConsentFailed"] = "ConsentFailed";
|
65
|
-
/**
|
66
|
-
* The user or administrator has not consented to use the application error.
|
67
|
-
*/
|
68
|
-
ErrorCode["UiRequiredError"] = "UiRequiredError";
|
69
|
-
/**
|
70
|
-
* Token is not within its valid time range error.
|
71
|
-
*/
|
72
|
-
ErrorCode["TokenExpiredError"] = "TokenExpiredError";
|
73
|
-
/**
|
74
|
-
* Call service (AAD or simple authentication server) failed.
|
75
|
-
*/
|
76
|
-
ErrorCode["ServiceError"] = "ServiceError";
|
77
|
-
/**
|
78
|
-
* Operation failed.
|
79
|
-
*/
|
80
|
-
ErrorCode["FailedOperation"] = "FailedOperation";
|
81
|
-
/**
|
82
|
-
* Invalid response error.
|
83
|
-
*/
|
84
|
-
ErrorCode["InvalidResponse"] = "InvalidResponse";
|
85
|
-
/**
|
86
|
-
* Authentication info already exists error.
|
87
|
-
*/
|
88
|
-
ErrorCode["AuthorizationInfoAlreadyExists"] = "AuthorizationInfoAlreadyExists";
|
89
|
-
})(ErrorCode || (ErrorCode = {}));
|
90
|
-
/**
|
91
|
-
* @internal
|
92
|
-
*/
|
93
|
-
class ErrorMessage {
|
94
|
-
}
|
95
|
-
// InvalidConfiguration Error
|
96
|
-
ErrorMessage.InvalidConfiguration = "{0} in configuration is invalid: {1}.";
|
97
|
-
ErrorMessage.ConfigurationNotExists = "Configuration does not exist. {0}";
|
98
|
-
ErrorMessage.ResourceConfigurationNotExists = "{0} resource configuration does not exist.";
|
99
|
-
ErrorMessage.MissingResourceConfiguration = "Missing resource configuration with type: {0}, name: {1}.";
|
100
|
-
ErrorMessage.AuthenticationConfigurationNotExists = "Authentication configuration does not exist.";
|
101
|
-
// RuntimeNotSupported Error
|
102
|
-
ErrorMessage.BrowserRuntimeNotSupported = "{0} is not supported in browser.";
|
103
|
-
ErrorMessage.NodejsRuntimeNotSupported = "{0} is not supported in Node.";
|
104
|
-
// Internal Error
|
105
|
-
ErrorMessage.FailToAcquireTokenOnBehalfOfUser = "Failed to acquire access token on behalf of user: {0}";
|
106
|
-
// ChannelNotSupported Error
|
107
|
-
ErrorMessage.OnlyMSTeamsChannelSupported = "{0} is only supported in MS Teams Channel";
|
108
|
-
ErrorMessage.FailedToProcessSsoHandler = "Failed to process sso handler: {0}";
|
109
|
-
// FailedToRetrieveSsoToken Error
|
110
|
-
ErrorMessage.FailedToRetrieveSsoToken = "Failed to retrieve sso token, user failed to finish the AAD consent flow.";
|
111
|
-
// CannotFindCommand Error
|
112
|
-
ErrorMessage.CannotFindCommand = "Cannot find command: {0}";
|
113
|
-
ErrorMessage.FailedToRunSsoStep = "Failed to run dialog to retrieve sso token: {0}";
|
114
|
-
ErrorMessage.FailedToRunDedupStep = "Failed to run dialog to remove duplicated messages: {0}";
|
115
|
-
// SsoActivityHandlerIsUndefined Error
|
116
|
-
ErrorMessage.SsoActivityHandlerIsNull = "Sso command can only be used or added when sso activity handler is not undefined";
|
117
|
-
// AuthorizationInfoError
|
118
|
-
ErrorMessage.AuthorizationHeaderAlreadyExists = "Authorization header already exists!";
|
119
|
-
ErrorMessage.BasicCredentialAlreadyExists = "Basic credential already exists!";
|
120
|
-
// InvalidParameter Error
|
121
|
-
ErrorMessage.EmptyParameter = "Parameter {0} is empty";
|
122
|
-
ErrorMessage.DuplicateHttpsOptionProperty = "Axios HTTPS agent already defined value for property {0}";
|
123
|
-
ErrorMessage.DuplicateApiKeyInHeader = "The request already defined api key in request header with name {0}.";
|
124
|
-
ErrorMessage.DuplicateApiKeyInQueryParam = "The request already defined api key in query parameter with name {0}.";
|
125
|
-
ErrorMessage.OnlySupportInQueryActivity = "The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.";
|
126
|
-
ErrorMessage.OnlySupportInLinkQueryActivity = "The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";
|
127
|
-
/**
|
128
|
-
* Error class with code and message thrown by the SDK.
|
129
|
-
*/
|
130
|
-
class ErrorWithCode extends Error {
|
131
|
-
/**
|
132
|
-
* Constructor of ErrorWithCode.
|
133
|
-
*
|
134
|
-
* @param {string} message - error message.
|
135
|
-
* @param {ErrorCode} code - error code.
|
136
|
-
*/
|
137
|
-
constructor(message, code) {
|
138
|
-
if (!code) {
|
139
|
-
super(message);
|
140
|
-
return this;
|
141
|
-
}
|
142
|
-
super(message);
|
143
|
-
Object.setPrototypeOf(this, ErrorWithCode.prototype);
|
144
|
-
this.name = `${new.target.name}.${code}`;
|
145
|
-
this.code = code;
|
146
|
-
}
|
147
|
-
}
|
148
|
-
|
149
|
-
// Copyright (c) Microsoft Corporation.
|
150
|
-
// Licensed under the MIT license.
|
151
|
-
/**
|
152
|
-
* Log level.
|
153
|
-
*/
|
154
|
-
var LogLevel;
|
155
|
-
(function (LogLevel) {
|
156
|
-
/**
|
157
|
-
* Show verbose, information, warning and error message.
|
158
|
-
*/
|
159
|
-
LogLevel[LogLevel["Verbose"] = 0] = "Verbose";
|
160
|
-
/**
|
161
|
-
* Show information, warning and error message.
|
162
|
-
*/
|
163
|
-
LogLevel[LogLevel["Info"] = 1] = "Info";
|
164
|
-
/**
|
165
|
-
* Show warning and error message.
|
166
|
-
*/
|
167
|
-
LogLevel[LogLevel["Warn"] = 2] = "Warn";
|
168
|
-
/**
|
169
|
-
* Show error message.
|
170
|
-
*/
|
171
|
-
LogLevel[LogLevel["Error"] = 3] = "Error";
|
172
|
-
})(LogLevel || (LogLevel = {}));
|
173
|
-
/**
|
174
|
-
* Update log level helper.
|
175
|
-
*
|
176
|
-
* @param { LogLevel } level - log level in configuration
|
177
|
-
*/
|
178
|
-
function setLogLevel(level) {
|
179
|
-
internalLogger.level = level;
|
180
|
-
}
|
181
|
-
/**
|
182
|
-
* Get log level.
|
183
|
-
*
|
184
|
-
* @returns Log level
|
185
|
-
*/
|
186
|
-
function getLogLevel() {
|
187
|
-
return internalLogger.level;
|
188
|
-
}
|
189
|
-
class InternalLogger {
|
190
|
-
constructor(name, logLevel) {
|
191
|
-
this.level = undefined;
|
192
|
-
this.defaultLogger = {
|
193
|
-
verbose: console.debug,
|
194
|
-
info: console.info,
|
195
|
-
warn: console.warn,
|
196
|
-
error: console.error,
|
197
|
-
};
|
198
|
-
this.name = name;
|
199
|
-
this.level = logLevel;
|
200
|
-
}
|
201
|
-
error(message) {
|
202
|
-
this.log(LogLevel.Error, (x) => x.error, message);
|
203
|
-
}
|
204
|
-
warn(message) {
|
205
|
-
this.log(LogLevel.Warn, (x) => x.warn, message);
|
206
|
-
}
|
207
|
-
info(message) {
|
208
|
-
this.log(LogLevel.Info, (x) => x.info, message);
|
209
|
-
}
|
210
|
-
verbose(message) {
|
211
|
-
this.log(LogLevel.Verbose, (x) => x.verbose, message);
|
212
|
-
}
|
213
|
-
log(logLevel, logFunction, message) {
|
214
|
-
if (message.trim() === "") {
|
215
|
-
return;
|
216
|
-
}
|
217
|
-
const timestamp = new Date().toUTCString();
|
218
|
-
let logHeader;
|
219
|
-
if (this.name) {
|
220
|
-
logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;
|
221
|
-
}
|
222
|
-
else {
|
223
|
-
logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
|
224
|
-
}
|
225
|
-
const logMessage = `${logHeader}${message}`;
|
226
|
-
if (this.level !== undefined && this.level <= logLevel) {
|
227
|
-
if (this.customLogger) {
|
228
|
-
logFunction(this.customLogger)(logMessage);
|
229
|
-
}
|
230
|
-
else if (this.customLogFunction) {
|
231
|
-
this.customLogFunction(logLevel, logMessage);
|
232
|
-
}
|
233
|
-
else {
|
234
|
-
logFunction(this.defaultLogger)(logMessage);
|
235
|
-
}
|
236
|
-
}
|
237
|
-
}
|
238
|
-
}
|
239
|
-
/**
|
240
|
-
* Logger instance used internally
|
241
|
-
*
|
242
|
-
* @internal
|
243
|
-
*/
|
244
|
-
const internalLogger = new InternalLogger();
|
245
|
-
/**
|
246
|
-
* Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.
|
247
|
-
*
|
248
|
-
* @param {Logger} logger - custom logger. If it's undefined, custom logger will be cleared.
|
249
|
-
*
|
250
|
-
* @example
|
251
|
-
* ```typescript
|
252
|
-
* setLogger({
|
253
|
-
* verbose: console.debug,
|
254
|
-
* info: console.info,
|
255
|
-
* warn: console.warn,
|
256
|
-
* error: console.error,
|
257
|
-
* });
|
258
|
-
* ```
|
259
|
-
*/
|
260
|
-
function setLogger(logger) {
|
261
|
-
internalLogger.customLogger = logger;
|
262
|
-
}
|
263
|
-
/**
|
264
|
-
* Set custom log function. Use the function if it's set. Priority is lower than setLogger.
|
265
|
-
*
|
266
|
-
* @param {LogFunction} logFunction - custom log function. If it's undefined, custom log function will be cleared.
|
267
|
-
*
|
268
|
-
* @example
|
269
|
-
* ```typescript
|
270
|
-
* setLogFunction((level: LogLevel, message: string) => {
|
271
|
-
* if (level === LogLevel.Error) {
|
272
|
-
* console.log(message);
|
273
|
-
* }
|
274
|
-
* });
|
275
|
-
* ```
|
276
|
-
*/
|
277
|
-
function setLogFunction(logFunction) {
|
278
|
-
internalLogger.customLogFunction = logFunction;
|
279
|
-
}
|
280
|
-
|
281
|
-
// Copyright (c) Microsoft Corporation.
|
282
|
-
/**
|
283
|
-
* Parse jwt token payload
|
284
|
-
*
|
285
|
-
* @param token
|
286
|
-
*
|
287
|
-
* @returns Payload object
|
288
|
-
*
|
289
|
-
* @internal
|
290
|
-
*/
|
291
|
-
function parseJwt(token) {
|
292
|
-
try {
|
293
|
-
const tokenObj = jwtDecode(token);
|
294
|
-
if (!tokenObj || !tokenObj.exp) {
|
295
|
-
throw new ErrorWithCode("Decoded token is null or exp claim does not exists.", ErrorCode.InternalError);
|
296
|
-
}
|
297
|
-
return tokenObj;
|
298
|
-
}
|
299
|
-
catch (err) {
|
300
|
-
const errorMsg = "Parse jwt token failed in node env with error: " + err.message;
|
301
|
-
internalLogger.error(errorMsg);
|
302
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
303
|
-
}
|
304
|
-
}
|
305
|
-
/**
|
306
|
-
* @internal
|
307
|
-
*/
|
308
|
-
function getUserInfoFromSsoToken(ssoToken) {
|
309
|
-
if (!ssoToken) {
|
310
|
-
const errorMsg = "SSO token is undefined.";
|
311
|
-
internalLogger.error(errorMsg);
|
312
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
|
313
|
-
}
|
314
|
-
const tokenObject = parseJwt(ssoToken);
|
315
|
-
const userInfo = {
|
316
|
-
displayName: tokenObject.name,
|
317
|
-
objectId: tokenObject.oid,
|
318
|
-
tenantId: tokenObject.tid,
|
319
|
-
preferredUserName: "",
|
320
|
-
};
|
321
|
-
if (tokenObject.ver === "2.0") {
|
322
|
-
userInfo.preferredUserName = tokenObject.preferred_username;
|
323
|
-
}
|
324
|
-
else if (tokenObject.ver === "1.0") {
|
325
|
-
userInfo.preferredUserName = tokenObject.upn;
|
326
|
-
}
|
327
|
-
return userInfo;
|
328
|
-
}
|
329
|
-
/**
|
330
|
-
* @internal
|
331
|
-
*/
|
332
|
-
function getTenantIdAndLoginHintFromSsoToken(ssoToken) {
|
333
|
-
if (!ssoToken) {
|
334
|
-
const errorMsg = "SSO token is undefined.";
|
335
|
-
internalLogger.error(errorMsg);
|
336
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
|
337
|
-
}
|
338
|
-
const tokenObject = parseJwt(ssoToken);
|
339
|
-
const userInfo = {
|
340
|
-
tid: tokenObject.tid,
|
341
|
-
loginHint: tokenObject.ver === "2.0"
|
342
|
-
? tokenObject.preferred_username
|
343
|
-
: tokenObject.upn,
|
344
|
-
};
|
345
|
-
return userInfo;
|
346
|
-
}
|
347
|
-
/**
|
348
|
-
* @internal
|
349
|
-
*/
|
350
|
-
function parseAccessTokenFromAuthCodeTokenResponse(tokenResponse) {
|
351
|
-
try {
|
352
|
-
const tokenResponseObject = typeof tokenResponse == "string"
|
353
|
-
? JSON.parse(tokenResponse)
|
354
|
-
: tokenResponse;
|
355
|
-
if (!tokenResponseObject || !tokenResponseObject.accessToken) {
|
356
|
-
const errorMsg = "Get empty access token from Auth Code token response.";
|
357
|
-
internalLogger.error(errorMsg);
|
358
|
-
throw new Error(errorMsg);
|
359
|
-
}
|
360
|
-
const token = tokenResponseObject.accessToken;
|
361
|
-
const tokenObject = parseJwt(token);
|
362
|
-
if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
|
363
|
-
const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
|
364
|
-
internalLogger.error(errorMsg);
|
365
|
-
throw new Error(errorMsg);
|
366
|
-
}
|
367
|
-
const accessToken = {
|
368
|
-
token: token,
|
369
|
-
expiresOnTimestamp: tokenObject.exp * 1000,
|
370
|
-
};
|
371
|
-
return accessToken;
|
372
|
-
}
|
373
|
-
catch (error) {
|
374
|
-
const errorMsg = "Parse access token failed from Auth Code token response in node env with error: " +
|
375
|
-
error.message;
|
376
|
-
internalLogger.error(errorMsg);
|
377
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
378
|
-
}
|
379
|
-
}
|
380
|
-
/**
|
381
|
-
* Format string template with replacements
|
382
|
-
*
|
383
|
-
* ```typescript
|
384
|
-
* const template = "{0} and {1} are fruit. {0} is my favorite one."
|
385
|
-
* const formattedStr = formatString(template, "apple", "pear"); // formattedStr: "apple and pear are fruit. apple is my favorite one."
|
386
|
-
* ```
|
387
|
-
*
|
388
|
-
* @param str string template
|
389
|
-
* @param replacements replacement string array
|
390
|
-
* @returns Formatted string
|
391
|
-
*
|
392
|
-
* @internal
|
393
|
-
*/
|
394
|
-
function formatString(str, ...replacements) {
|
395
|
-
const args = replacements;
|
396
|
-
return str.replace(/{(\d+)}/g, function (match, number) {
|
397
|
-
return typeof args[number] != "undefined" ? args[number] : match;
|
398
|
-
});
|
399
|
-
}
|
400
|
-
/**
|
401
|
-
* @internal
|
402
|
-
*/
|
403
|
-
function validateScopesType(value) {
|
404
|
-
// string
|
405
|
-
if (typeof value === "string" || value instanceof String) {
|
406
|
-
return;
|
407
|
-
}
|
408
|
-
// empty array
|
409
|
-
if (Array.isArray(value) && value.length === 0) {
|
410
|
-
return;
|
411
|
-
}
|
412
|
-
// string array
|
413
|
-
if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string")) {
|
414
|
-
return;
|
415
|
-
}
|
416
|
-
const errorMsg = "The type of scopes is not valid, it must be string or string array";
|
417
|
-
internalLogger.error(errorMsg);
|
418
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
|
419
|
-
}
|
420
|
-
|
421
|
-
// Copyright (c) Microsoft Corporation.
|
422
|
-
/**
|
423
|
-
* Represent Microsoft 365 tenant identity, and it is usually used when user is not involved.
|
424
|
-
*
|
425
|
-
* @remarks
|
426
|
-
* Only works in in server side.
|
427
|
-
*/
|
428
|
-
class AppCredential {
|
429
|
-
/**
|
430
|
-
* Constructor of AppCredential.
|
431
|
-
*
|
432
|
-
* @remarks
|
433
|
-
* Only works in in server side.
|
434
|
-
*/
|
435
|
-
constructor(authConfig) {
|
436
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported);
|
437
|
-
}
|
438
|
-
/**
|
439
|
-
* Get access token for credential.
|
440
|
-
*
|
441
|
-
* @remarks
|
442
|
-
* Only works in in server side.
|
443
|
-
*/
|
444
|
-
getToken(scopes, options) {
|
445
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "AppCredential"), ErrorCode.RuntimeNotSupported));
|
446
|
-
}
|
447
|
-
}
|
448
|
-
|
449
|
-
// Copyright (c) Microsoft Corporation.
|
450
|
-
/**
|
451
|
-
* Represent on-behalf-of flow to get user identity, and it is designed to be used in Azure Function or Bot scenarios.
|
452
|
-
*
|
453
|
-
* @remarks
|
454
|
-
* Can only be used in server side.
|
455
|
-
*/
|
456
|
-
class OnBehalfOfUserCredential {
|
457
|
-
/**
|
458
|
-
* Constructor of OnBehalfOfUserCredential
|
459
|
-
*
|
460
|
-
* @remarks
|
461
|
-
* Can Only works in in server side.
|
462
|
-
*/
|
463
|
-
constructor(ssoToken, config) {
|
464
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported);
|
465
|
-
}
|
466
|
-
/**
|
467
|
-
* Get access token from credential.
|
468
|
-
* @remarks
|
469
|
-
* Can only be used in server side.
|
470
|
-
*/
|
471
|
-
getToken(scopes, options) {
|
472
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
|
473
|
-
}
|
474
|
-
/**
|
475
|
-
* Get basic user info from SSO token.
|
476
|
-
* @remarks
|
477
|
-
* Can only be used in server side.
|
478
|
-
*/
|
479
|
-
getUserInfo() {
|
480
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "OnBehalfOfUserCredential"), ErrorCode.RuntimeNotSupported));
|
481
|
-
}
|
482
|
-
}
|
483
|
-
|
484
|
-
// Copyright (c) Microsoft Corporation.
|
485
|
-
const tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
|
486
|
-
const loginPageWidth = 600;
|
487
|
-
const loginPageHeight = 535;
|
488
|
-
/**
|
489
|
-
* Represent Teams current user's identity, and it is used within Teams tab application.
|
490
|
-
*
|
491
|
-
* @remarks
|
492
|
-
* Can only be used within Teams.
|
493
|
-
*/
|
494
|
-
class TeamsUserCredential {
|
495
|
-
// eslint-disable-next-line no-secrets/no-secrets
|
496
|
-
/**
|
497
|
-
* Constructor of TeamsUserCredential.
|
498
|
-
*
|
499
|
-
* @example
|
500
|
-
* ```typescript
|
501
|
-
* const config: TeamsUserCredentialAuthConfig = {
|
502
|
-
* initiateLoginEndpoint: "https://localhost:3000/auth-start.html",
|
503
|
-
* clientId: "xxx"
|
504
|
-
* }
|
505
|
-
* const credential = new TeamsUserCredential(config);
|
506
|
-
* ```
|
507
|
-
*
|
508
|
-
* @param {TeamsUserCredentialAuthConfig} authConfig - The authentication configuration.
|
509
|
-
*
|
510
|
-
* @throws {@link ErrorCode|InvalidConfiguration} when client id, initiate login endpoint or simple auth endpoint is not found in config.
|
511
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
512
|
-
*/
|
513
|
-
constructor(authConfig) {
|
514
|
-
internalLogger.info("Create teams user credential");
|
515
|
-
this.config = this.loadAndValidateConfig(authConfig);
|
516
|
-
this.ssoToken = null;
|
517
|
-
this.initialized = false;
|
518
|
-
}
|
519
|
-
/**
|
520
|
-
* Popup login page to get user's access token with specific scopes.
|
521
|
-
*
|
522
|
-
* @remarks
|
523
|
-
* Only works in Teams client APP. User will be redirected to the authorization page to login and consent.
|
524
|
-
*
|
525
|
-
* @example
|
526
|
-
* ```typescript
|
527
|
-
* await credential.login(["https://graph.microsoft.com/User.Read"]); // single scope using string array
|
528
|
-
* await credential.login("https://graph.microsoft.com/User.Read"); // single scopes using string
|
529
|
-
* await credential.login(["https://graph.microsoft.com/User.Read", "Calendars.Read"]); // multiple scopes using string array
|
530
|
-
* await credential.login("https://graph.microsoft.com/User.Read Calendars.Read"); // multiple scopes using string
|
531
|
-
* ```
|
532
|
-
* @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.
|
533
|
-
* @param { string[] } resources - The optional list of resources for full trust Teams apps.
|
534
|
-
*
|
535
|
-
* @throws {@link ErrorCode|InternalError} when failed to login with unknown error.
|
536
|
-
* @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.
|
537
|
-
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
538
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
539
|
-
*/
|
540
|
-
async login(scopes, resources) {
|
541
|
-
validateScopesType(scopes);
|
542
|
-
const scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
|
543
|
-
internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);
|
544
|
-
if (!this.initialized) {
|
545
|
-
await this.init(resources);
|
546
|
-
}
|
547
|
-
await app.initialize();
|
548
|
-
let result;
|
549
|
-
try {
|
550
|
-
const params = {
|
551
|
-
url: `${this.config.initiateLoginEndpoint ? this.config.initiateLoginEndpoint : ""}?clientId=${this.config.clientId ? this.config.clientId : ""}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint ? this.loginHint : ""}`,
|
552
|
-
width: loginPageWidth,
|
553
|
-
height: loginPageHeight,
|
554
|
-
};
|
555
|
-
result = await authentication.authenticate(params);
|
556
|
-
if (!result) {
|
557
|
-
const errorMsg = "Get empty authentication result from MSAL";
|
558
|
-
internalLogger.error(errorMsg);
|
559
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
560
|
-
}
|
561
|
-
}
|
562
|
-
catch (err) {
|
563
|
-
const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${err.message}`;
|
564
|
-
internalLogger.error(errorMsg);
|
565
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed);
|
566
|
-
}
|
567
|
-
let resultJson = {};
|
568
|
-
try {
|
569
|
-
resultJson = typeof result == "string" ? JSON.parse(result) : result;
|
570
|
-
}
|
571
|
-
catch (error) {
|
572
|
-
// If can not parse result as Json, will throw error.
|
573
|
-
const failedToParseResult = "Failed to parse response to Json.";
|
574
|
-
internalLogger.error(failedToParseResult);
|
575
|
-
throw new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse);
|
576
|
-
}
|
577
|
-
// If code exists in result, user may using previous auth-start and auth-end page.
|
578
|
-
if (resultJson.code) {
|
579
|
-
const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
|
580
|
-
const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
|
581
|
-
`Please refer to the help link for how to fix the issue: ${helpLink}.`;
|
582
|
-
internalLogger.error(usingPreviousAuthPage);
|
583
|
-
throw new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse);
|
584
|
-
}
|
585
|
-
// If sessionStorage exists in result, set the values in current session storage.
|
586
|
-
if (resultJson.sessionStorage) {
|
587
|
-
this.setSessionStorage(resultJson.sessionStorage);
|
588
|
-
}
|
589
|
-
}
|
590
|
-
/**
|
591
|
-
* Get access token from credential.
|
592
|
-
*
|
593
|
-
* Important: Access tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice
|
594
|
-
* Important: Full trust applications do not read the resource information from the webApplicationInfo section of the app
|
595
|
-
* manifest. Instead, this resource (along with any additional resources from which to request tokens) must be provided
|
596
|
-
* as a list of resources to the getToken() method through a GetTeamsUserTokenOptions object.
|
597
|
-
*
|
598
|
-
* @example
|
599
|
-
* ```typescript
|
600
|
-
* await credential.getToken([]) // Get SSO token using empty string array
|
601
|
-
* await credential.getToken("") // Get SSO token using empty string
|
602
|
-
* await credential.getToken([".default"]) // Get Graph access token with default scope using string array
|
603
|
-
* await credential.getToken(".default") // Get Graph access token with default scope using string
|
604
|
-
* await credential.getToken(["User.Read"]) // Get Graph access token for single scope using string array
|
605
|
-
* await credential.getToken("User.Read") // Get Graph access token for single scope using string
|
606
|
-
* await credential.getToken(["User.Read", "Application.Read.All"]) // Get Graph access token for multiple scopes using string array
|
607
|
-
* await credential.getToken("User.Read Application.Read.All") // Get Graph access token for multiple scopes using space-separated string
|
608
|
-
* await credential.getToken("https://graph.microsoft.com/User.Read") // Get Graph access token with full resource URI
|
609
|
-
* await credential.getToken(["https://outlook.office.com/Mail.Read"]) // Get Outlook access token
|
610
|
-
*
|
611
|
-
* const options: GetTeamsUserTokenOptions = { resources: ["https://domain.example.com"] }; // set up resources for full trust apps.
|
612
|
-
* await credential.getToken([], options) // Get sso token from teams client - only use this approach for full trust apps.
|
613
|
-
* ```
|
614
|
-
*
|
615
|
-
* @param {string | string[]} scopes - The list of scopes for which the token will have access.
|
616
|
-
* @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.
|
617
|
-
*
|
618
|
-
* @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
|
619
|
-
* @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
|
620
|
-
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
621
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
622
|
-
*
|
623
|
-
* @returns User access token of defined scopes.
|
624
|
-
* If scopes is empty string or array, it returns SSO token.
|
625
|
-
* If scopes is non-empty, it returns access token for target scope.
|
626
|
-
* Throw error if get access token failed.
|
627
|
-
*/
|
628
|
-
async getToken(scopes, options) {
|
629
|
-
validateScopesType(scopes);
|
630
|
-
const resources = options === null || options === void 0 ? void 0 : options.resources;
|
631
|
-
const ssoToken = await this.getSSOToken(resources);
|
632
|
-
const scopeStr = typeof scopes === "string" ? scopes : scopes.join(" ");
|
633
|
-
if (scopeStr === "") {
|
634
|
-
internalLogger.info("Get SSO token");
|
635
|
-
return ssoToken;
|
636
|
-
}
|
637
|
-
else {
|
638
|
-
internalLogger.info("Get access token with scopes: " + scopeStr);
|
639
|
-
if (!this.initialized) {
|
640
|
-
await this.init(resources);
|
641
|
-
}
|
642
|
-
let tokenResponse;
|
643
|
-
const scopesArray = typeof scopes === "string" ? scopes.split(" ") : scopes;
|
644
|
-
const domain = window.location.origin;
|
645
|
-
// First try to get Access Token from cache.
|
646
|
-
try {
|
647
|
-
const account = this.msalInstance.getAccountByUsername(this.loginHint);
|
648
|
-
const scopesRequestForAcquireTokenSilent = {
|
649
|
-
scopes: scopesArray,
|
650
|
-
account: account !== null && account !== void 0 ? account : undefined,
|
651
|
-
redirectUri: `${domain}/blank-auth-end.html`,
|
652
|
-
};
|
653
|
-
tokenResponse = await this.msalInstance.acquireTokenSilent(scopesRequestForAcquireTokenSilent);
|
654
|
-
}
|
655
|
-
catch (error) {
|
656
|
-
const acquireTokenSilentFailedMessage = `Failed to call acquireTokenSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
|
657
|
-
internalLogger.verbose(acquireTokenSilentFailedMessage);
|
658
|
-
}
|
659
|
-
if (!tokenResponse) {
|
660
|
-
// If fail to get Access Token from cache, try to get Access token by silent login.
|
661
|
-
try {
|
662
|
-
const scopesRequestForSsoSilent = {
|
663
|
-
scopes: scopesArray,
|
664
|
-
loginHint: this.loginHint,
|
665
|
-
redirectUri: `${domain}/blank-auth-end.html`,
|
666
|
-
};
|
667
|
-
tokenResponse = await this.msalInstance.ssoSilent(scopesRequestForSsoSilent);
|
668
|
-
}
|
669
|
-
catch (error) {
|
670
|
-
const ssoSilentFailedMessage = `Failed to call ssoSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
|
671
|
-
internalLogger.verbose(ssoSilentFailedMessage);
|
672
|
-
}
|
673
|
-
}
|
674
|
-
if (!tokenResponse) {
|
675
|
-
const errorMsg = `Failed to get access token cache silently, please login first: you need login first before get access token.`;
|
676
|
-
internalLogger.error(errorMsg);
|
677
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.UiRequiredError);
|
678
|
-
}
|
679
|
-
const accessToken = parseAccessTokenFromAuthCodeTokenResponse(tokenResponse);
|
680
|
-
return accessToken;
|
681
|
-
}
|
682
|
-
}
|
683
|
-
/**
|
684
|
-
* Get basic user info from SSO token
|
685
|
-
*
|
686
|
-
* @param {string[]} resources - The optional list of resources for full trust Teams apps.
|
687
|
-
*
|
688
|
-
* @example
|
689
|
-
* ```typescript
|
690
|
-
* const currentUser = await credential.getUserInfo();
|
691
|
-
* ```
|
692
|
-
*
|
693
|
-
* @throws {@link ErrorCode|InternalError} when SSO token from Teams client is not valid.
|
694
|
-
* @throws {@link ErrorCode|InvalidParameter} when SSO token from Teams client is empty.
|
695
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
|
696
|
-
*
|
697
|
-
* @returns Basic user info with user displayName, objectId and preferredUserName.
|
698
|
-
*/
|
699
|
-
async getUserInfo(resources) {
|
700
|
-
internalLogger.info("Get basic user info from SSO token");
|
701
|
-
const ssoToken = await this.getSSOToken(resources);
|
702
|
-
return getUserInfoFromSsoToken(ssoToken.token);
|
703
|
-
}
|
704
|
-
async init(resources) {
|
705
|
-
const ssoToken = await this.getSSOToken(resources);
|
706
|
-
const info = getTenantIdAndLoginHintFromSsoToken(ssoToken.token);
|
707
|
-
this.loginHint = info.loginHint;
|
708
|
-
this.tid = info.tid;
|
709
|
-
const msalConfig = {
|
710
|
-
auth: {
|
711
|
-
clientId: this.config.clientId,
|
712
|
-
authority: `https://login.microsoftonline.com/${this.tid}`,
|
713
|
-
},
|
714
|
-
cache: {
|
715
|
-
cacheLocation: "sessionStorage",
|
716
|
-
},
|
717
|
-
};
|
718
|
-
this.msalInstance = new PublicClientApplication(msalConfig);
|
719
|
-
await this.msalInstance.initialize();
|
720
|
-
this.initialized = true;
|
721
|
-
}
|
722
|
-
/**
|
723
|
-
* Get SSO token using teams SDK
|
724
|
-
* 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
|
725
|
-
*
|
726
|
-
* @param {string[]} resources - The optional list of resources for full trust Teams apps.
|
727
|
-
*
|
728
|
-
* @returns SSO token
|
729
|
-
*/
|
730
|
-
async getSSOToken(resources) {
|
731
|
-
if (this.ssoToken) {
|
732
|
-
if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {
|
733
|
-
internalLogger.verbose("Get SSO token from memory cache");
|
734
|
-
return this.ssoToken;
|
735
|
-
}
|
736
|
-
}
|
737
|
-
const params = { resources: resources !== null && resources !== void 0 ? resources : [] };
|
738
|
-
let token;
|
739
|
-
try {
|
740
|
-
await app.initialize();
|
741
|
-
}
|
742
|
-
catch (err) {
|
743
|
-
const errorMsg = "Initialize teams sdk failed due to not running inside Teams environment";
|
744
|
-
internalLogger.error(errorMsg);
|
745
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
746
|
-
}
|
747
|
-
try {
|
748
|
-
token = await authentication.getAuthToken(params);
|
749
|
-
}
|
750
|
-
catch (err) {
|
751
|
-
const errorMsg = "Get SSO token failed with error: " + err.message;
|
752
|
-
internalLogger.error(errorMsg);
|
753
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
754
|
-
}
|
755
|
-
if (!token) {
|
756
|
-
const errorMsg = "Get empty SSO token from Teams";
|
757
|
-
internalLogger.error(errorMsg);
|
758
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
759
|
-
}
|
760
|
-
const tokenObject = parseJwt(token);
|
761
|
-
if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
|
762
|
-
const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
|
763
|
-
internalLogger.error(errorMsg);
|
764
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
|
765
|
-
}
|
766
|
-
const ssoToken = {
|
767
|
-
token,
|
768
|
-
expiresOnTimestamp: tokenObject.exp * 1000,
|
769
|
-
};
|
770
|
-
this.ssoToken = ssoToken;
|
771
|
-
return ssoToken;
|
772
|
-
}
|
773
|
-
/**
|
774
|
-
* Load and validate authentication configuration
|
775
|
-
*
|
776
|
-
* @param {AuthenticationConfiguration?} config - The authentication configuration. Use environment variables if not provided.
|
777
|
-
*
|
778
|
-
* @returns Authentication configuration
|
779
|
-
*/
|
780
|
-
loadAndValidateConfig(config) {
|
781
|
-
internalLogger.verbose("Validate authentication configuration");
|
782
|
-
if (config.initiateLoginEndpoint && config.clientId) {
|
783
|
-
return config;
|
784
|
-
}
|
785
|
-
const missingValues = [];
|
786
|
-
if (!config.initiateLoginEndpoint) {
|
787
|
-
missingValues.push("initiateLoginEndpoint");
|
788
|
-
}
|
789
|
-
if (!config.clientId) {
|
790
|
-
missingValues.push("clientId");
|
791
|
-
}
|
792
|
-
const errorMsg = formatString(ErrorMessage.InvalidConfiguration, missingValues.join(", "), "undefined");
|
793
|
-
internalLogger.error(errorMsg);
|
794
|
-
throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
|
795
|
-
}
|
796
|
-
setSessionStorage(sessionStorageValues) {
|
797
|
-
try {
|
798
|
-
const sessionStorageKeys = Object.keys(sessionStorageValues);
|
799
|
-
sessionStorageKeys.forEach((key) => {
|
800
|
-
sessionStorage.setItem(key, sessionStorageValues[key]);
|
801
|
-
});
|
802
|
-
}
|
803
|
-
catch (error) {
|
804
|
-
// Values in result.sessionStorage can not be set into session storage.
|
805
|
-
// Throw error since this may block user.
|
806
|
-
const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;
|
807
|
-
internalLogger.error(errorMessage);
|
808
|
-
throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
|
809
|
-
}
|
810
|
-
}
|
811
|
-
}
|
812
|
-
|
813
|
-
// Copyright (c) Microsoft Corporation.
|
814
|
-
/**
|
815
|
-
* Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and
|
816
|
-
* help receive oauth token, asks the user to consent if needed.
|
817
|
-
*
|
818
|
-
* @remarks
|
819
|
-
* The prompt will attempt to retrieve the users current token of the desired scopes and store it in
|
820
|
-
* the token store.
|
821
|
-
*
|
822
|
-
* User will be automatically signed in leveraging Teams support of Bot Single Sign On(SSO):
|
823
|
-
* https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots
|
824
|
-
*
|
825
|
-
* @example
|
826
|
-
* When used with your bots `DialogSet` you can simply add a new instance of the prompt as a named
|
827
|
-
* dialog using `DialogSet.add()`. You can then start the prompt from a waterfall step using either
|
828
|
-
* `DialogContext.beginDialog()` or `DialogContext.prompt()`. The user will be prompted to sign in as
|
829
|
-
* needed and their access token will be passed as an argument to the callers next waterfall step:
|
830
|
-
*
|
831
|
-
* ```JavaScript
|
832
|
-
* const { ConversationState, MemoryStorage } = require('botbuilder');
|
833
|
-
* const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');
|
834
|
-
* const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx');
|
835
|
-
*
|
836
|
-
* const convoState = new ConversationState(new MemoryStorage());
|
837
|
-
* const dialogState = convoState.createProperty('dialogState');
|
838
|
-
* const dialogs = new DialogSet(dialogState);
|
839
|
-
*
|
840
|
-
* dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {
|
841
|
-
* scopes: ["User.Read"],
|
842
|
-
* }));
|
843
|
-
*
|
844
|
-
* dialogs.add(new WaterfallDialog('taskNeedingLogin', [
|
845
|
-
* async (step) => {
|
846
|
-
* return await step.beginDialog('TeamsBotSsoPrompt');
|
847
|
-
* },
|
848
|
-
* async (step) => {
|
849
|
-
* const token = step.result;
|
850
|
-
* if (token) {
|
851
|
-
*
|
852
|
-
* // ... continue with task needing access token ...
|
853
|
-
*
|
854
|
-
* } else {
|
855
|
-
* await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);
|
856
|
-
* return await step.endDialog();
|
857
|
-
* }
|
858
|
-
* }
|
859
|
-
* ]));
|
860
|
-
* ```
|
861
|
-
*/
|
862
|
-
class TeamsBotSsoPrompt {
|
863
|
-
/**
|
864
|
-
* Constructor of TeamsBotSsoPrompt.
|
865
|
-
*
|
866
|
-
* @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.
|
867
|
-
* @param settings Settings used to configure the prompt.
|
868
|
-
*
|
869
|
-
* @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
|
870
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
871
|
-
*/
|
872
|
-
constructor(authConfig, initiateLoginEndpoint, dialogId, settings) {
|
873
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported);
|
874
|
-
}
|
875
|
-
/**
|
876
|
-
* Called when a prompt dialog is pushed onto the dialog stack and is being activated.
|
877
|
-
* @remarks
|
878
|
-
* If the task is successful, the result indicates whether the prompt is still
|
879
|
-
* active after the turn has been processed by the prompt.
|
880
|
-
*
|
881
|
-
* @param dc The DialogContext for the current turn of the conversation.
|
882
|
-
*
|
883
|
-
* @throws {@link ErrorCode|InvalidParameter} when timeout property in teams bot sso prompt settings is not number or is not positive.
|
884
|
-
* @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
|
885
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
886
|
-
*
|
887
|
-
* @returns A `Promise` representing the asynchronous operation.
|
888
|
-
*/
|
889
|
-
beginDialog(dc) {
|
890
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
|
891
|
-
}
|
892
|
-
/**
|
893
|
-
* Called when a prompt dialog is the active dialog and the user replied with a new activity.
|
894
|
-
*
|
895
|
-
* @remarks
|
896
|
-
* If the task is successful, the result indicates whether the dialog is still
|
897
|
-
* active after the turn has been processed by the dialog.
|
898
|
-
* The prompt generally continues to receive the user's replies until it accepts the
|
899
|
-
* user's reply as valid input for the prompt.
|
900
|
-
*
|
901
|
-
* @param dc The DialogContext for the current turn of the conversation.
|
902
|
-
*
|
903
|
-
* @returns A `Promise` representing the asynchronous operation.
|
904
|
-
*
|
905
|
-
* @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.
|
906
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
907
|
-
*/
|
908
|
-
continueDialog(dc) {
|
909
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotSsoPrompt"), ErrorCode.RuntimeNotSupported));
|
910
|
-
}
|
911
|
-
}
|
912
|
-
|
913
|
-
// Copyright (c) Microsoft Corporation.
|
914
|
-
/**
|
915
|
-
* Initializes new Axios instance with specific auth provider
|
916
|
-
*
|
917
|
-
* @param apiEndpoint - Base url of the API
|
918
|
-
* @param authProvider - Auth provider that injects authentication info to each request
|
919
|
-
* @returns axios instance configured with specfic auth provider
|
920
|
-
*
|
921
|
-
* @example
|
922
|
-
* ```typescript
|
923
|
-
* const client = createApiClient("https://my-api-endpoint-base-url", new BasicAuthProvider("xxx","xxx"));
|
924
|
-
* ```
|
925
|
-
*/
|
926
|
-
function createApiClient(apiEndpoint, authProvider) {
|
927
|
-
// Add a request interceptor
|
928
|
-
const instance = axios.create({
|
929
|
-
baseURL: apiEndpoint,
|
930
|
-
});
|
931
|
-
instance.interceptors.request.use(async function (config) {
|
932
|
-
return (await authProvider.AddAuthenticationInfo(config));
|
933
|
-
});
|
934
|
-
return instance;
|
935
|
-
}
|
936
|
-
|
937
|
-
// Copyright (c) Microsoft Corporation.
|
938
|
-
/**
|
939
|
-
* Provider that handles Bearer Token authentication
|
940
|
-
*/
|
941
|
-
class BearerTokenAuthProvider {
|
942
|
-
/**
|
943
|
-
* @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request
|
944
|
-
*/
|
945
|
-
constructor(getToken) {
|
946
|
-
this.getToken = getToken;
|
947
|
-
}
|
948
|
-
/**
|
949
|
-
* Adds authentication info to http requests
|
950
|
-
*
|
951
|
-
* @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
|
952
|
-
* Refer https://axios-http.com/docs/req_config for detailed document.
|
953
|
-
*
|
954
|
-
* @returns Updated axios request config.
|
955
|
-
*
|
956
|
-
* @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.
|
957
|
-
*/
|
958
|
-
async AddAuthenticationInfo(config) {
|
959
|
-
const token = await this.getToken();
|
960
|
-
if (!config.headers) {
|
961
|
-
config.headers = {};
|
962
|
-
}
|
963
|
-
if (config.headers["Authorization"]) {
|
964
|
-
throw new ErrorWithCode(ErrorMessage.AuthorizationHeaderAlreadyExists, ErrorCode.AuthorizationInfoAlreadyExists);
|
965
|
-
}
|
966
|
-
config.headers["Authorization"] = `Bearer ${token}`;
|
967
|
-
return config;
|
968
|
-
}
|
969
|
-
}
|
970
|
-
|
971
|
-
// Copyright (c) Microsoft Corporation.
|
972
|
-
/**
|
973
|
-
* Provider that handles Basic authentication
|
974
|
-
*/
|
975
|
-
class BasicAuthProvider {
|
976
|
-
/**
|
977
|
-
*
|
978
|
-
* @param { string } userName - Username used in basic auth
|
979
|
-
* @param { string } password - Password used in basic auth
|
980
|
-
*
|
981
|
-
* @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.
|
982
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
983
|
-
*/
|
984
|
-
constructor(userName, password) {
|
985
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported);
|
986
|
-
}
|
987
|
-
/**
|
988
|
-
* Adds authentication info to http requests
|
989
|
-
*
|
990
|
-
* @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
|
991
|
-
* Refer https://axios-http.com/docs/req_config for detailed document.
|
992
|
-
*
|
993
|
-
* @returns Updated axios request config.
|
994
|
-
*
|
995
|
-
* @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.
|
996
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
997
|
-
*/
|
998
|
-
AddAuthenticationInfo(config) {
|
999
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BasicAuthProvider"), ErrorCode.RuntimeNotSupported));
|
1000
|
-
}
|
1001
|
-
}
|
1002
|
-
|
1003
|
-
// Copyright (c) Microsoft Corporation.
|
1004
|
-
/**
|
1005
|
-
* Provider that handles API Key authentication
|
1006
|
-
*/
|
1007
|
-
class ApiKeyProvider {
|
1008
|
-
/**
|
1009
|
-
*
|
1010
|
-
* @param { string } keyName - The name of request header or query parameter that specifies API Key
|
1011
|
-
* @param { string } keyValue - The value of API Key
|
1012
|
-
* @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.
|
1013
|
-
*
|
1014
|
-
* @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.
|
1015
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
1016
|
-
*/
|
1017
|
-
constructor(keyName, keyValue, keyLocation) {
|
1018
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported);
|
1019
|
-
}
|
1020
|
-
/**
|
1021
|
-
* Adds authentication info to http requests
|
1022
|
-
*
|
1023
|
-
* @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
|
1024
|
-
* Refer https://axios-http.com/docs/req_config for detailed document.
|
1025
|
-
*
|
1026
|
-
* @returns Updated axios request config.
|
1027
|
-
*
|
1028
|
-
* @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.
|
1029
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
1030
|
-
*/
|
1031
|
-
AddAuthenticationInfo(config) {
|
1032
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ApiKeyProvider"), ErrorCode.RuntimeNotSupported));
|
1033
|
-
}
|
1034
|
-
}
|
1035
|
-
/**
|
1036
|
-
* Define available location for API Key location
|
1037
|
-
*/
|
1038
|
-
var ApiKeyLocation;
|
1039
|
-
(function (ApiKeyLocation) {
|
1040
|
-
/**
|
1041
|
-
* The API Key is placed in request header
|
1042
|
-
*/
|
1043
|
-
ApiKeyLocation[ApiKeyLocation["Header"] = 0] = "Header";
|
1044
|
-
/**
|
1045
|
-
* The API Key is placed in query parameter
|
1046
|
-
*/
|
1047
|
-
ApiKeyLocation[ApiKeyLocation["QueryParams"] = 1] = "QueryParams";
|
1048
|
-
})(ApiKeyLocation || (ApiKeyLocation = {}));
|
1049
|
-
|
1050
|
-
// Copyright (c) Microsoft Corporation.
|
1051
|
-
/**
|
1052
|
-
* Provider that handles Certificate authentication
|
1053
|
-
*/
|
1054
|
-
class CertificateAuthProvider {
|
1055
|
-
/**
|
1056
|
-
*
|
1057
|
-
* @param { SecureContextOptions } certOption - information about the cert used in http requests
|
1058
|
-
*/
|
1059
|
-
constructor(certOption) {
|
1060
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported);
|
1061
|
-
}
|
1062
|
-
/**
|
1063
|
-
* Adds authentication info to http requests.
|
1064
|
-
*
|
1065
|
-
* @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.
|
1066
|
-
* Refer https://axios-http.com/docs/req_config for detailed document.
|
1067
|
-
*
|
1068
|
-
* @returns Updated axios request config.
|
1069
|
-
*
|
1070
|
-
* @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.
|
1071
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
1072
|
-
*/
|
1073
|
-
AddAuthenticationInfo(config) {
|
1074
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CertificateAuthProvider"), ErrorCode.RuntimeNotSupported));
|
1075
|
-
}
|
1076
|
-
}
|
1077
|
-
/**
|
1078
|
-
* Helper to create SecureContextOptions from PEM format cert
|
1079
|
-
*
|
1080
|
-
* @param { string | Buffer } cert - The cert chain in PEM format
|
1081
|
-
* @param { string | Buffer } key - The private key for the cert chain
|
1082
|
-
* @param { {passphrase?: string; ca?: string | Buffer} } options - Optional settings when create the cert options.
|
1083
|
-
*
|
1084
|
-
* @returns Instance of SecureContextOptions
|
1085
|
-
*
|
1086
|
-
* @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
|
1087
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
1088
|
-
*
|
1089
|
-
*/
|
1090
|
-
function createPemCertOption(cert, key, options) {
|
1091
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPemCertOption"), ErrorCode.RuntimeNotSupported);
|
1092
|
-
}
|
1093
|
-
/**
|
1094
|
-
* Helper to create SecureContextOptions from PFX format cert
|
1095
|
-
*
|
1096
|
-
* @param { string | Buffer } pfx - The content of .pfx file
|
1097
|
-
* @param { {passphrase?: string} } options - Optional settings when create the cert options.
|
1098
|
-
*
|
1099
|
-
* @returns Instance of SecureContextOptions
|
1100
|
-
*
|
1101
|
-
* @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty
|
1102
|
-
* @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.
|
1103
|
-
*
|
1104
|
-
*/
|
1105
|
-
function createPfxCertOption(pfx, options) {
|
1106
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "createPfxCertOption"), ErrorCode.RuntimeNotSupported);
|
1107
|
-
}
|
1108
|
-
|
1109
|
-
// Copyright (c) Microsoft Corporation.
|
1110
|
-
// Licensed under the MIT license.
|
1111
|
-
/**
|
1112
|
-
* The target type where the notification will be sent to.
|
1113
|
-
*
|
1114
|
-
* @remarks
|
1115
|
-
* - "Channel" means to a team channel. (By default, notification to a team will be sent to its "General" channel.)
|
1116
|
-
* - "Group" means to a group chat.
|
1117
|
-
* - "Person" means to a personal chat.
|
1118
|
-
*/
|
1119
|
-
var NotificationTargetType;
|
1120
|
-
(function (NotificationTargetType) {
|
1121
|
-
/**
|
1122
|
-
* The notification will be sent to a team channel.
|
1123
|
-
* (By default, notification to a team will be sent to its "General" channel.)
|
1124
|
-
*/
|
1125
|
-
NotificationTargetType["Channel"] = "Channel";
|
1126
|
-
/**
|
1127
|
-
* The notification will be sent to a group chat.
|
1128
|
-
*/
|
1129
|
-
NotificationTargetType["Group"] = "Group";
|
1130
|
-
/**
|
1131
|
-
* The notification will be sent to a personal chat.
|
1132
|
-
*/
|
1133
|
-
NotificationTargetType["Person"] = "Person";
|
1134
|
-
})(NotificationTargetType || (NotificationTargetType = {}));
|
1135
|
-
/**
|
1136
|
-
* Options used to control how the response card will be sent to users.
|
1137
|
-
*/
|
1138
|
-
var AdaptiveCardResponse;
|
1139
|
-
(function (AdaptiveCardResponse) {
|
1140
|
-
/**
|
1141
|
-
* The response card will be replaced the current one for the interactor who trigger the action.
|
1142
|
-
*/
|
1143
|
-
AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForInteractor"] = 0] = "ReplaceForInteractor";
|
1144
|
-
/**
|
1145
|
-
* The response card will be replaced the current one for all users in the chat.
|
1146
|
-
*/
|
1147
|
-
AdaptiveCardResponse[AdaptiveCardResponse["ReplaceForAll"] = 1] = "ReplaceForAll";
|
1148
|
-
/**
|
1149
|
-
* The response card will be sent as a new message for all users in the chat.
|
1150
|
-
*/
|
1151
|
-
AdaptiveCardResponse[AdaptiveCardResponse["NewForAll"] = 2] = "NewForAll";
|
1152
|
-
})(AdaptiveCardResponse || (AdaptiveCardResponse = {}));
|
1153
|
-
/**
|
1154
|
-
* Status code for an `application/vnd.microsoft.error` invoke response.
|
1155
|
-
*/
|
1156
|
-
var InvokeResponseErrorCode;
|
1157
|
-
(function (InvokeResponseErrorCode) {
|
1158
|
-
/**
|
1159
|
-
* Invalid request.
|
1160
|
-
*/
|
1161
|
-
InvokeResponseErrorCode[InvokeResponseErrorCode["BadRequest"] = 400] = "BadRequest";
|
1162
|
-
/**
|
1163
|
-
* Internal server error.
|
1164
|
-
*/
|
1165
|
-
InvokeResponseErrorCode[InvokeResponseErrorCode["InternalServerError"] = 500] = "InternalServerError";
|
1166
|
-
})(InvokeResponseErrorCode || (InvokeResponseErrorCode = {}));
|
1167
|
-
|
1168
|
-
// Copyright (c) Microsoft Corporation.
|
1169
|
-
/*
|
1170
|
-
* Sso execution dialog, use to handle sso command
|
1171
|
-
*/
|
1172
|
-
class BotSsoExecutionDialog {
|
1173
|
-
constructor(dedupStorage, ssoPromptSettings, authConfig, ...args) {
|
1174
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
|
1175
|
-
}
|
1176
|
-
// eslint-disable-next-line no-secrets/no-secrets
|
1177
|
-
/**
|
1178
|
-
* Add TeamsFxBotSsoCommandHandler instance
|
1179
|
-
* @param handler {@link BotSsoExecutionDialogHandler} callback function
|
1180
|
-
* @param triggerPatterns The trigger pattern
|
1181
|
-
*/
|
1182
|
-
addCommand(handler, triggerPatterns) {
|
1183
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
|
1184
|
-
}
|
1185
|
-
/**
|
1186
|
-
* The run method handles the incoming activity (in the form of a DialogContext) and passes it through the dialog system.
|
1187
|
-
*
|
1188
|
-
* @param context The context object for the current turn.
|
1189
|
-
* @param accessor The instance of StatePropertyAccessor for dialog system.
|
1190
|
-
*/
|
1191
|
-
run(context, accessor) {
|
1192
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
|
1193
|
-
}
|
1194
|
-
/**
|
1195
|
-
* Called when the component is ending.
|
1196
|
-
*
|
1197
|
-
* @param context Context for the current turn of conversation.
|
1198
|
-
*/
|
1199
|
-
onEndDialog(context) {
|
1200
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "BotSsoExecutionDialog"), ErrorCode.RuntimeNotSupported);
|
1201
|
-
}
|
1202
|
-
}
|
1203
|
-
|
1204
|
-
/**
|
1205
|
-
* Users execute query with SSO or Access Token.
|
1206
|
-
* @remarks
|
1207
|
-
* Only works in in server side.
|
1208
|
-
*/
|
1209
|
-
function handleMessageExtensionQueryWithSSO(context, config, initiateLoginEndpoint, scopes, logic) {
|
1210
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "queryWithToken in message extension"), ErrorCode.RuntimeNotSupported);
|
1211
|
-
}
|
1212
|
-
|
1213
|
-
// Copyright (c) Microsoft Corporation.
|
1214
|
-
/**
|
1215
|
-
* Provide utilities for bot conversation, including:
|
1216
|
-
* - handle command and response.
|
1217
|
-
* - send notification to varies targets (e.g., member, group, channel).
|
1218
|
-
*
|
1219
|
-
* @remarks
|
1220
|
-
* Only work on server side.
|
1221
|
-
*/
|
1222
|
-
class ConversationBot {
|
1223
|
-
/**
|
1224
|
-
* Create new instance of the `ConversationBot`.
|
1225
|
-
*
|
1226
|
-
* @param options - The initialize options.
|
1227
|
-
*
|
1228
|
-
* @remarks
|
1229
|
-
* Only work on server side.
|
1230
|
-
*/
|
1231
|
-
constructor(options) {
|
1232
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported);
|
1233
|
-
}
|
1234
|
-
/**
|
1235
|
-
* The request handler to integrate with web request.
|
1236
|
-
*
|
1237
|
-
* @param req - An incoming HTTP [Request](xref:botbuilder.Request).
|
1238
|
-
* @param res - The corresponding HTTP [Response](xref:botbuilder.Response).
|
1239
|
-
* @param logic - The additional function to handle bot context.
|
1240
|
-
*
|
1241
|
-
* @remarks
|
1242
|
-
* Only work on server side.
|
1243
|
-
*/
|
1244
|
-
requestHandler(req, res, logic) {
|
1245
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "ConversationBot"), ErrorCode.RuntimeNotSupported));
|
1246
|
-
}
|
1247
|
-
}
|
1248
|
-
|
1249
|
-
// Copyright (c) Microsoft Corporation.
|
1250
|
-
/**
|
1251
|
-
* Send a plain text message to a notification target.
|
1252
|
-
*
|
1253
|
-
* @remarks
|
1254
|
-
* Only work on server side.
|
1255
|
-
*
|
1256
|
-
* @param target - The notification target.
|
1257
|
-
* @param text - The plain text message.
|
1258
|
-
* @param onError - An optional error handler that can catch exceptions during message sending.
|
1259
|
-
*
|
1260
|
-
* @returns A `Promise` representing the asynchronous operation.
|
1261
|
-
*/
|
1262
|
-
function sendMessage(target, text, onError) {
|
1263
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendMessage"), ErrorCode.RuntimeNotSupported));
|
1264
|
-
}
|
1265
|
-
/**
|
1266
|
-
* Send an adaptive card message to a notification target.
|
1267
|
-
*
|
1268
|
-
* @remarks
|
1269
|
-
* Only work on server side.
|
1270
|
-
*
|
1271
|
-
* @param target - The notification target.
|
1272
|
-
* @param card - The adaptive card raw JSON.
|
1273
|
-
* @param onError - An optional error handler that can catch exceptions during adaptive card sending.
|
1274
|
-
*
|
1275
|
-
* @returns A `Promise` representing the asynchronous operation.
|
1276
|
-
*/
|
1277
|
-
function sendAdaptiveCard(target, card, onError) {
|
1278
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "sendAdaptiveCard"), ErrorCode.RuntimeNotSupported));
|
1279
|
-
}
|
1280
|
-
/**
|
1281
|
-
* A {@link NotificationTarget} that represents a team channel.
|
1282
|
-
*
|
1283
|
-
* @remarks
|
1284
|
-
* Only work on server side.
|
1285
|
-
*
|
1286
|
-
* It's recommended to get channels from {@link TeamsBotInstallation.channels()}.
|
1287
|
-
*/
|
1288
|
-
class Channel {
|
1289
|
-
/**
|
1290
|
-
* Constructor.
|
1291
|
-
*
|
1292
|
-
* @remarks
|
1293
|
-
* Only work on server side.
|
1294
|
-
*
|
1295
|
-
* It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.
|
1296
|
-
*
|
1297
|
-
* @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.
|
1298
|
-
* @param info - Detailed channel information.
|
1299
|
-
*/
|
1300
|
-
constructor(parent, info) {
|
1301
|
-
/**
|
1302
|
-
* Notification target type. For channel it's always "Channel".
|
1303
|
-
*
|
1304
|
-
* @remarks
|
1305
|
-
* Only work on server side.
|
1306
|
-
*/
|
1307
|
-
this.type = NotificationTargetType.Channel;
|
1308
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported);
|
1309
|
-
}
|
1310
|
-
/**
|
1311
|
-
* Send a plain text message.
|
1312
|
-
*
|
1313
|
-
* @remarks
|
1314
|
-
* Only work on server side.
|
1315
|
-
*
|
1316
|
-
* @param text - The plain text message.
|
1317
|
-
* @param onError - An optional error handler that can catch exceptions during message sending.
|
1318
|
-
*
|
1319
|
-
* @returns The response of sending message.
|
1320
|
-
*/
|
1321
|
-
sendMessage(text, onError) {
|
1322
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
|
1323
|
-
}
|
1324
|
-
/**
|
1325
|
-
* Send an adaptive card message.
|
1326
|
-
*
|
1327
|
-
* @remarks
|
1328
|
-
* Only work on server side.
|
1329
|
-
*
|
1330
|
-
* @param card - The adaptive card raw JSON.
|
1331
|
-
* @param onError - An optional error handler that can catch exceptions during adaptive card sending.
|
1332
|
-
*
|
1333
|
-
* @returns The response of sending adaptive card message.
|
1334
|
-
*/
|
1335
|
-
sendAdaptiveCard(card, onError) {
|
1336
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Channel"), ErrorCode.RuntimeNotSupported));
|
1337
|
-
}
|
1338
|
-
}
|
1339
|
-
/**
|
1340
|
-
* A {@link NotificationTarget} that represents a team member.
|
1341
|
-
*
|
1342
|
-
* @remarks
|
1343
|
-
* Only work on server side.
|
1344
|
-
*
|
1345
|
-
* It's recommended to get members from {@link TeamsBotInstallation.members()}.
|
1346
|
-
*/
|
1347
|
-
class Member {
|
1348
|
-
/**
|
1349
|
-
* Constructor.
|
1350
|
-
*
|
1351
|
-
* @remarks
|
1352
|
-
* Only work on server side.
|
1353
|
-
*
|
1354
|
-
* It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.
|
1355
|
-
*
|
1356
|
-
* @param parent - The parent {@link TeamsBotInstallation} where this member is created from.
|
1357
|
-
* @param account - Detailed member account information.
|
1358
|
-
*/
|
1359
|
-
constructor(parent, account) {
|
1360
|
-
/**
|
1361
|
-
* Notification target type. For member it's always "Person".
|
1362
|
-
*
|
1363
|
-
* @remarks
|
1364
|
-
* Only work on server side.
|
1365
|
-
*/
|
1366
|
-
this.type = NotificationTargetType.Person;
|
1367
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported);
|
1368
|
-
}
|
1369
|
-
/**
|
1370
|
-
* Send a plain text message.
|
1371
|
-
*
|
1372
|
-
* @remarks
|
1373
|
-
* Only work on server side.
|
1374
|
-
*
|
1375
|
-
* @param text - The plain text message.
|
1376
|
-
* @param onError - An optional error handler that can catch exceptions during message sending.
|
1377
|
-
*
|
1378
|
-
* @returns The response of sending message.
|
1379
|
-
*/
|
1380
|
-
sendMessage(text, onError) {
|
1381
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported));
|
1382
|
-
}
|
1383
|
-
/**
|
1384
|
-
* Send an adaptive card message.
|
1385
|
-
*
|
1386
|
-
* @remarks
|
1387
|
-
* Only work on server side.
|
1388
|
-
*
|
1389
|
-
* @param card - The adaptive card raw JSON.
|
1390
|
-
* @param onError - An optional error handler that can catch exceptions during adaptive card sending.
|
1391
|
-
*
|
1392
|
-
* @returns The response of sending adaptive card message.
|
1393
|
-
*/
|
1394
|
-
sendAdaptiveCard(card, onError) {
|
1395
|
-
return Promise.reject(Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "Member"), ErrorCode.RuntimeNotSupported)));
|
1396
|
-
}
|
1397
|
-
}
|
1398
|
-
/**
|
1399
|
-
* A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into
|
1400
|
-
* - Personal chat
|
1401
|
-
* - Group chat
|
1402
|
-
* - Team (by default the `General` channel)
|
1403
|
-
*
|
1404
|
-
* @remarks
|
1405
|
-
* Only work on server side.
|
1406
|
-
*
|
1407
|
-
* It's recommended to get bot installations from {@link ConversationBot.installations()}.
|
1408
|
-
*/
|
1409
|
-
class TeamsBotInstallation {
|
1410
|
-
/**
|
1411
|
-
* Constructor
|
1412
|
-
*
|
1413
|
-
* @remarks
|
1414
|
-
* Only work on server side.
|
1415
|
-
*
|
1416
|
-
* It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.
|
1417
|
-
*
|
1418
|
-
* @param adapter - The bound `CloudAdapter`.
|
1419
|
-
* @param conversationReference - The bound `ConversationReference`.
|
1420
|
-
*/
|
1421
|
-
constructor(adapter, conversationReference) {
|
1422
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported);
|
1423
|
-
}
|
1424
|
-
/**
|
1425
|
-
* Send a plain text message.
|
1426
|
-
*
|
1427
|
-
* @remarks
|
1428
|
-
* Only work on server side.
|
1429
|
-
*
|
1430
|
-
* @param text - The plain text message.
|
1431
|
-
* @param onError - An optional error handler that can catch exceptions during message sending.
|
1432
|
-
*
|
1433
|
-
* @returns The response of sending message.
|
1434
|
-
*/
|
1435
|
-
sendMessage(text, onError) {
|
1436
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
|
1437
|
-
}
|
1438
|
-
/**
|
1439
|
-
* Send an adaptive card message.
|
1440
|
-
*
|
1441
|
-
* @remarks
|
1442
|
-
* Only work on server side.
|
1443
|
-
*
|
1444
|
-
* @param card - The adaptive card raw JSON.
|
1445
|
-
* @param onError - An optional error handler that can catch exceptions during adaptive card sending.
|
1446
|
-
*
|
1447
|
-
* @returns The response of sending adaptive card message.
|
1448
|
-
*/
|
1449
|
-
sendAdaptiveCard(card, onError) {
|
1450
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
|
1451
|
-
}
|
1452
|
-
/**
|
1453
|
-
* Get channels from this bot installation.
|
1454
|
-
*
|
1455
|
-
* @remarks
|
1456
|
-
* Only work on server side.
|
1457
|
-
*
|
1458
|
-
* @returns An array of channels if bot is installed into a team, otherwise returns an empty array.
|
1459
|
-
*/
|
1460
|
-
channels() {
|
1461
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
|
1462
|
-
}
|
1463
|
-
/**
|
1464
|
-
* Get members from this bot installation.
|
1465
|
-
*
|
1466
|
-
* @remarks
|
1467
|
-
* Only work on server side.
|
1468
|
-
*
|
1469
|
-
* @returns An array of members from where the bot is installed.
|
1470
|
-
*/
|
1471
|
-
members() {
|
1472
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
|
1473
|
-
}
|
1474
|
-
/**
|
1475
|
-
* Get team details from this bot installation
|
1476
|
-
*
|
1477
|
-
* @returns The team details if bot is installed into a team, otherwise returns undefined.
|
1478
|
-
*/
|
1479
|
-
getTeamDetails() {
|
1480
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "TeamsBotInstallation"), ErrorCode.RuntimeNotSupported));
|
1481
|
-
}
|
1482
|
-
}
|
1483
|
-
/**
|
1484
|
-
* Provide static utilities for bot notification.
|
1485
|
-
*
|
1486
|
-
* @remarks
|
1487
|
-
* Only work on server side.
|
1488
|
-
*
|
1489
|
-
* @example
|
1490
|
-
* Here's an example on how to send notification via Teams Bot.
|
1491
|
-
* ```typescript
|
1492
|
-
* // initialize (it's recommended to be called before handling any bot message)
|
1493
|
-
* const notificationBot = new NotificationBot(adapter);
|
1494
|
-
*
|
1495
|
-
* // get all bot installations and send message
|
1496
|
-
* for (const target of await notificationBot.installations()) {
|
1497
|
-
* await target.sendMessage("Hello Notification");
|
1498
|
-
* }
|
1499
|
-
*
|
1500
|
-
* // alternative - send message to all members
|
1501
|
-
* for (const target of await notificationBot.installations()) {
|
1502
|
-
* for (const member of await target.members()) {
|
1503
|
-
* await member.sendMessage("Hello Notification");
|
1504
|
-
* }
|
1505
|
-
* }
|
1506
|
-
* ```
|
1507
|
-
*/
|
1508
|
-
class NotificationBot {
|
1509
|
-
/**
|
1510
|
-
* Constructor of the notification bot.
|
1511
|
-
*
|
1512
|
-
* @remarks
|
1513
|
-
* Only work on server side.
|
1514
|
-
*
|
1515
|
-
* To ensure accuracy, it's recommended to initialize before handling any message.
|
1516
|
-
*
|
1517
|
-
* @param adapter - The bound `CloudAdapter`
|
1518
|
-
* @param options - The initialize options
|
1519
|
-
*/
|
1520
|
-
constructor(adapter, options) {
|
1521
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported);
|
1522
|
-
}
|
1523
|
-
/**
|
1524
|
-
* Get all targets where the bot is installed.
|
1525
|
-
*
|
1526
|
-
* @remarks
|
1527
|
-
* Only work on server side.
|
1528
|
-
*
|
1529
|
-
* The result is retrieving from the persisted storage.
|
1530
|
-
*
|
1531
|
-
* @returns An array of {@link TeamsBotInstallation}.
|
1532
|
-
*/
|
1533
|
-
static installations() {
|
1534
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
|
1535
|
-
}
|
1536
|
-
/**
|
1537
|
-
* Return the first {@link Member} where predicate is true, and undefined otherwise.
|
1538
|
-
*
|
1539
|
-
* @remarks
|
1540
|
-
* Only work on server side.
|
1541
|
-
*
|
1542
|
-
* @param predicate find calls predicate once for each member of the installation,
|
1543
|
-
* until it finds one where predicate returns true. If such a member is found,
|
1544
|
-
* find immediately returns that member. Otherwise, find returns undefined.
|
1545
|
-
* @param scope the scope to find members from the installations (personal chat, group chat, Teams channel).
|
1546
|
-
*
|
1547
|
-
* @returns The first {@link Member} where predicate is true, and undefined otherwise.
|
1548
|
-
*/
|
1549
|
-
findMember(predicate, scope) {
|
1550
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
|
1551
|
-
}
|
1552
|
-
/**
|
1553
|
-
* Return the first {@link Channel} where predicate is true, and undefined otherwise.
|
1554
|
-
* (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)
|
1555
|
-
*
|
1556
|
-
* @remarks
|
1557
|
-
* Only work on server side.
|
1558
|
-
*
|
1559
|
-
* @param predicate - Find calls predicate once for each channel of the installation,
|
1560
|
-
* until it finds one where predicate returns true. If such a channel is found, find
|
1561
|
-
* immediately returns that channel. Otherwise, find returns undefined.
|
1562
|
-
*
|
1563
|
-
* @returns The first {@link Channel} where predicate is true, and `undefined` otherwise.
|
1564
|
-
*/
|
1565
|
-
findChannel(predicate) {
|
1566
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
|
1567
|
-
}
|
1568
|
-
/**
|
1569
|
-
* Return all {@link Member} where predicate is true, and empty array otherwise.
|
1570
|
-
*
|
1571
|
-
* @remarks
|
1572
|
-
* Only work on server side.
|
1573
|
-
*
|
1574
|
-
* @param predicate - Find calls predicate for each member of the installation.
|
1575
|
-
* @param scope - The scope to find members from the installations.
|
1576
|
-
* (personal chat, group chat, Teams channel).
|
1577
|
-
*
|
1578
|
-
* @returns An array of {@link Member} where predicate is true, and empty array otherwise.
|
1579
|
-
*/
|
1580
|
-
findAllMembers(predicate, scope) {
|
1581
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
|
1582
|
-
}
|
1583
|
-
/**
|
1584
|
-
* Return all {@link Channel} where predicate is true, and empty array otherwise.
|
1585
|
-
* (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)
|
1586
|
-
*
|
1587
|
-
* @remarks
|
1588
|
-
* Only work on server side.
|
1589
|
-
*
|
1590
|
-
* @param predicate - Find calls predicate for each channel of the installation.
|
1591
|
-
*
|
1592
|
-
* @returns An array of {@link Channel} where predicate is true, and empty array otherwise.
|
1593
|
-
*/
|
1594
|
-
findAllChannels(predicate) {
|
1595
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "NotificationBot"), ErrorCode.RuntimeNotSupported));
|
1596
|
-
}
|
1597
|
-
}
|
1598
|
-
/**
|
1599
|
-
* The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.
|
1600
|
-
* The search scope is a flagged enum and it can be combined with `|`.
|
1601
|
-
* For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.
|
1602
|
-
*/
|
1603
|
-
var SearchScope;
|
1604
|
-
(function (SearchScope) {
|
1605
|
-
/**
|
1606
|
-
* Search members from the installations in personal chat only.
|
1607
|
-
*/
|
1608
|
-
SearchScope[SearchScope["Person"] = 1] = "Person";
|
1609
|
-
/**
|
1610
|
-
* Search members from the installations in group chat only.
|
1611
|
-
*/
|
1612
|
-
SearchScope[SearchScope["Group"] = 2] = "Group";
|
1613
|
-
/**
|
1614
|
-
* Search members from the installations in Teams channel only.
|
1615
|
-
*/
|
1616
|
-
SearchScope[SearchScope["Channel"] = 4] = "Channel";
|
1617
|
-
/**
|
1618
|
-
* Search members from all installations including personal chat, group chat and Teams channel.
|
1619
|
-
*/
|
1620
|
-
SearchScope[SearchScope["All"] = 7] = "All";
|
1621
|
-
})(SearchScope || (SearchScope = {}));
|
1622
|
-
|
1623
|
-
// Copyright (c) Microsoft Corporation.
|
1624
|
-
/**
|
1625
|
-
* A command bot for receiving commands and sending responses in Teams.
|
1626
|
-
*
|
1627
|
-
* @remarks
|
1628
|
-
* Only work on server side.
|
1629
|
-
*/
|
1630
|
-
class CommandBot {
|
1631
|
-
/**
|
1632
|
-
* Create a new instance of the `CommandBot`.
|
1633
|
-
*
|
1634
|
-
* @param adapter - The bound `CloudAdapter`.
|
1635
|
-
* @param commands - The commands to be registered with the command bot. Each command should implement the interface {@link TeamsFxBotCommandHandler} so that it can be correctly handled by this command bot.
|
1636
|
-
*/
|
1637
|
-
constructor(adapter, commands) {
|
1638
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
|
1639
|
-
}
|
1640
|
-
/**
|
1641
|
-
* Register a command into the command bot.
|
1642
|
-
*
|
1643
|
-
* @param command - The command to be registered.
|
1644
|
-
*
|
1645
|
-
* @remarks
|
1646
|
-
* Only work on server side.
|
1647
|
-
*/
|
1648
|
-
registerCommand(command) {
|
1649
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
|
1650
|
-
}
|
1651
|
-
/**
|
1652
|
-
* Register commands into the command bot.
|
1653
|
-
*
|
1654
|
-
* @param commands - The commands to be registered.
|
1655
|
-
*
|
1656
|
-
* @remarks
|
1657
|
-
* Only work on server side.
|
1658
|
-
*/
|
1659
|
-
registerCommands(commands) {
|
1660
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
|
1661
|
-
}
|
1662
|
-
/**
|
1663
|
-
* Register a sso command into the command bot.
|
1664
|
-
*
|
1665
|
-
* @param ssoCommand - The sso command to be registered.
|
1666
|
-
*/
|
1667
|
-
registerSsoCommand(ssoCommand) {
|
1668
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
|
1669
|
-
}
|
1670
|
-
/**
|
1671
|
-
* Register sso commands into the command bot.
|
1672
|
-
*
|
1673
|
-
* @param ssoCommands - The sso commands to be registered.
|
1674
|
-
*/
|
1675
|
-
registerSsoCommands(ssoCommands) {
|
1676
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CommandBot"), ErrorCode.RuntimeNotSupported);
|
1677
|
-
}
|
1678
|
-
}
|
1679
|
-
|
1680
|
-
/**
|
1681
|
-
* A card action bot to respond to adaptive card universal actions.
|
1682
|
-
*
|
1683
|
-
* @remarks
|
1684
|
-
* Only work on server side.
|
1685
|
-
*/
|
1686
|
-
class CardActionBot {
|
1687
|
-
/**
|
1688
|
-
* Create a new instance of the `CardActionBot`.
|
1689
|
-
*
|
1690
|
-
* @param adapter - The bound `CloudAdapter`.
|
1691
|
-
* @param options - The initialize options.
|
1692
|
-
*/
|
1693
|
-
constructor(adapter, options) {
|
1694
|
-
throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported);
|
1695
|
-
}
|
1696
|
-
/**
|
1697
|
-
* Register a card action handler to the bot.
|
1698
|
-
*
|
1699
|
-
* @param actionHandler - A card action handler to be registered.
|
1700
|
-
*
|
1701
|
-
* @remarks
|
1702
|
-
* Only work on server side.
|
1703
|
-
*/
|
1704
|
-
registerHandler(actionHandler) {
|
1705
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
|
1706
|
-
}
|
1707
|
-
/**
|
1708
|
-
* Register card action handlers to the bot.
|
1709
|
-
*
|
1710
|
-
* @param actionHandlers - A set of card action handlers to be registered.
|
1711
|
-
*
|
1712
|
-
* @remarks
|
1713
|
-
* Only work on server side.
|
1714
|
-
*/
|
1715
|
-
registerHandlers(actionHandlers) {
|
1716
|
-
return Promise.reject(new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "CardActionBot"), ErrorCode.RuntimeNotSupported));
|
1717
|
-
}
|
1718
|
-
}
|
1719
|
-
|
1720
|
-
var conversationWithCloudAdapter_browser = /*#__PURE__*/Object.freeze({
|
1721
|
-
__proto__: null,
|
1722
|
-
ConversationBot: ConversationBot,
|
1723
|
-
BotSsoExecutionDialog: BotSsoExecutionDialog,
|
1724
|
-
Channel: Channel,
|
1725
|
-
Member: Member,
|
1726
|
-
NotificationBot: NotificationBot,
|
1727
|
-
sendAdaptiveCard: sendAdaptiveCard,
|
1728
|
-
sendMessage: sendMessage,
|
1729
|
-
TeamsBotInstallation: TeamsBotInstallation,
|
1730
|
-
CommandBot: CommandBot,
|
1731
|
-
CardActionBot: CardActionBot
|
1732
|
-
});
|
1733
|
-
|
1734
|
-
export { AdaptiveCardResponse, ApiKeyLocation, ApiKeyProvider, AppCredential, BasicAuthProvider, BearerTokenAuthProvider, conversationWithCloudAdapter_browser as BotBuilderCloudAdapter, BotSsoExecutionDialog, CertificateAuthProvider, ErrorCode, ErrorWithCode, InvokeResponseErrorCode, LogLevel, NotificationTargetType, OnBehalfOfUserCredential, TeamsBotSsoPrompt, TeamsUserCredential, createApiClient, createPemCertOption, createPfxCertOption, getLogLevel, handleMessageExtensionQueryWithSSO, setLogFunction, setLogLevel, setLogger };
|
1
|
+
import{jwtDecode as e}from"jwt-decode";import{app as t,authentication as o}from"@microsoft/teams-js";import{PublicClientApplication as r}from"@azure/msal-browser";import n from"axios";var i,s;!function(e){e.InvalidParameter="InvalidParameter",e.InvalidConfiguration="InvalidConfiguration",e.InvalidCertificate="InvalidCertificate",e.InternalError="InternalError",e.ChannelNotSupported="ChannelNotSupported",e.FailedToRetrieveSsoToken="FailedToRetrieveSsoToken",e.FailedToProcessSsoHandler="FailedToProcessSsoHandler",e.CannotFindCommand="CannotFindCommand",e.FailedToRunSsoStep="FailedToRunSsoStep",e.FailedToRunDedupStep="FailedToRunDedupStep",e.SsoActivityHandlerIsUndefined="SsoActivityHandlerIsUndefined",e.RuntimeNotSupported="RuntimeNotSupported",e.ConsentFailed="ConsentFailed",e.UiRequiredError="UiRequiredError",e.TokenExpiredError="TokenExpiredError",e.ServiceError="ServiceError",e.FailedOperation="FailedOperation",e.InvalidResponse="InvalidResponse",e.AuthorizationInfoAlreadyExists="AuthorizationInfoAlreadyExists"}(i||(i={}));class a{}a.InvalidConfiguration="{0} in configuration is invalid: {1}.",a.ConfigurationNotExists="Configuration does not exist. {0}",a.ResourceConfigurationNotExists="{0} resource configuration does not exist.",a.MissingResourceConfiguration="Missing resource configuration with type: {0}, name: {1}.",a.AuthenticationConfigurationNotExists="Authentication configuration does not exist.",a.BrowserRuntimeNotSupported="{0} is not supported in browser.",a.NodejsRuntimeNotSupported="{0} is not supported in Node.",a.FailToAcquireTokenOnBehalfOfUser="Failed to acquire access token on behalf of user: {0}",a.OnlyMSTeamsChannelSupported="{0} is only supported in MS Teams Channel",a.FailedToProcessSsoHandler="Failed to process sso handler: {0}",a.FailedToRetrieveSsoToken="Failed to retrieve sso token, user failed to finish the AAD consent flow.",a.CannotFindCommand="Cannot find command: {0}",a.FailedToRunSsoStep="Failed to run dialog to retrieve sso token: {0}",a.FailedToRunDedupStep="Failed to run dialog to remove duplicated messages: {0}",a.SsoActivityHandlerIsNull="Sso command can only be used or added when sso activity handler is not undefined",a.AuthorizationHeaderAlreadyExists="Authorization header already exists!",a.BasicCredentialAlreadyExists="Basic credential already exists!",a.EmptyParameter="Parameter {0} is empty",a.DuplicateHttpsOptionProperty="Axios HTTPS agent already defined value for property {0}",a.DuplicateApiKeyInHeader="The request already defined api key in request header with name {0}.",a.DuplicateApiKeyInQueryParam="The request already defined api key in query parameter with name {0}.",a.OnlySupportInQueryActivity="The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.",a.OnlySupportInLinkQueryActivity="The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.";class u extends Error{constructor(e,t){if(!t)return super(e),this;super(e),Object.setPrototypeOf(this,u.prototype),this.name=`${new.target.name}.${t}`,this.code=t}}function d(e){c.level=e}function p(){return c.level}!function(e){e[e.Verbose=0]="Verbose",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(s||(s={}));const c=new class{constructor(e,t){this.level=void 0,this.defaultLogger={verbose:console.debug,info:console.info,warn:console.warn,error:console.error},this.name=e,this.level=t}error(e){this.log(s.Error,(e=>e.error),e)}warn(e){this.log(s.Warn,(e=>e.warn),e)}info(e){this.log(s.Info,(e=>e.info),e)}verbose(e){this.log(s.Verbose,(e=>e.verbose),e)}log(e,t,o){if(""===o.trim())return;const r=(new Date).toUTCString();let n;n=this.name?`[${r}] : @microsoft/teamsfx - ${this.name} : ${s[e]} - `:`[${r}] : @microsoft/teamsfx : ${s[e]} - `;const i=`${n}${o}`;void 0!==this.level&&this.level<=e&&(this.customLogger?t(this.customLogger)(i):this.customLogFunction?this.customLogFunction(e,i):t(this.defaultLogger)(i))}};function l(e){c.customLogger=e}function m(e){c.customLogFunction=e}function h(t){try{const o=e(t);if(!o||!o.exp)throw new u("Decoded token is null or exp claim does not exists.",i.InternalError);return o}catch(e){const t="Parse jwt token failed in node env with error: "+e.message;throw c.error(t),new u(t,i.InternalError)}}function w(e,...t){const o=t;return e.replace(/{(\d+)}/g,(function(e,t){return void 0!==o[t]?o[t]:e}))}function S(e){if("string"==typeof e||e instanceof String)return;if(Array.isArray(e)&&0===e.length)return;if(Array.isArray(e)&&e.length>0&&e.every((e=>"string"==typeof e)))return;const t="The type of scopes is not valid, it must be string or string array";throw c.error(t),new u(t,i.InvalidParameter)}class f{constructor(e){throw new u(w(a.BrowserRuntimeNotSupported,"AppCredential"),i.RuntimeNotSupported)}getToken(e,t){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"AppCredential"),i.RuntimeNotSupported))}}class g{constructor(e,t){throw new u(w(a.BrowserRuntimeNotSupported,"OnBehalfOfUserCredential"),i.RuntimeNotSupported)}getToken(e,t){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"OnBehalfOfUserCredential"),i.RuntimeNotSupported))}getUserInfo(){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"OnBehalfOfUserCredential"),i.RuntimeNotSupported))}}class R{constructor(e){c.info("Create teams user credential"),this.config=this.loadAndValidateConfig(e),this.ssoToken=null,this.initialized=!1}async login(e,r){S(e);const n="string"==typeof e?e:e.join(" ");let s;c.info(`Popup login page to get user's access token with scopes: ${n}`),this.initialized||await this.init(r),await t.initialize();try{const e={url:`${this.config.initiateLoginEndpoint?this.config.initiateLoginEndpoint:""}?clientId=${this.config.clientId?this.config.clientId:""}&scope=${encodeURI(n)}&loginHint=${this.loginHint?this.loginHint:""}`,width:600,height:535};if(s=await o.authenticate(e),!s){const e="Get empty authentication result from MSAL";throw c.error(e),new u(e,i.InternalError)}}catch(e){const t=`Consent failed for the scope ${n} with error: ${e.message}`;throw c.error(t),new u(t,i.ConsentFailed)}let a={};try{a="string"==typeof s?JSON.parse(s):s}catch(e){const t="Failed to parse response to Json.";throw c.error(t),new u(t,i.InvalidResponse)}if(a.code){const e=`Found auth code in response. Auth code is not support for current version of SDK. Please refer to the help link for how to fix the issue: ${"https://aka.ms/teamsfx-auth-code-flow"}.`;throw c.error(e),new u(e,i.InvalidResponse)}a.sessionStorage&&this.setSessionStorage(a.sessionStorage)}async getToken(e,t){S(e);const o=null==t?void 0:t.resources,r=await this.getSSOToken(o),n="string"==typeof e?e:e.join(" ");if(""===n)return c.info("Get SSO token"),r;{let t;c.info("Get access token with scopes: "+n),this.initialized||await this.init(o);const r="string"==typeof e?e.split(" "):e,s=window.location.origin;try{const e=this.msalInstance.getAccountByUsername(this.loginHint),o={scopes:r,account:null!=e?e:void 0,redirectUri:`${s}/blank-auth-end.html`};t=await this.msalInstance.acquireTokenSilent(o)}catch(e){const t=`Failed to call acquireTokenSilent. Reason: ${null==e?void 0:e.message}. `;c.verbose(t)}if(!t)try{const e={scopes:r,loginHint:this.loginHint,redirectUri:`${s}/blank-auth-end.html`};t=await this.msalInstance.ssoSilent(e)}catch(e){const t=`Failed to call ssoSilent. Reason: ${null==e?void 0:e.message}. `;c.verbose(t)}if(!t){const e="Failed to get access token cache silently, please login first: you need login first before get access token.";throw c.error(e),new u(e,i.UiRequiredError)}const a=function(e){try{const t="string"==typeof e?JSON.parse(e):e;if(!t||!t.accessToken){const e="Get empty access token from Auth Code token response.";throw c.error(e),new Error(e)}const o=t.accessToken,r=h(o);if("1.0"!==r.ver&&"2.0"!==r.ver){const e="SSO token is not valid with an unknown version: "+r.ver;throw c.error(e),new Error(e)}return{token:o,expiresOnTimestamp:1e3*r.exp}}catch(e){const t="Parse access token failed from Auth Code token response in node env with error: "+e.message;throw c.error(t),new u(t,i.InternalError)}}(t);return a}}async getUserInfo(e){c.info("Get basic user info from SSO token");return function(e){if(!e){const e="SSO token is undefined.";throw c.error(e),new u(e,i.InvalidParameter)}const t=h(e),o={displayName:t.name,objectId:t.oid,tenantId:t.tid,preferredUserName:""};return"2.0"===t.ver?o.preferredUserName=t.preferred_username:"1.0"===t.ver&&(o.preferredUserName=t.upn),o}((await this.getSSOToken(e)).token)}async init(e){const t=function(e){if(!e){const e="SSO token is undefined.";throw c.error(e),new u(e,i.InvalidParameter)}const t=h(e);return{tid:t.tid,loginHint:"2.0"===t.ver?t.preferred_username:t.upn}}((await this.getSSOToken(e)).token);this.loginHint=t.loginHint,this.tid=t.tid;const o={auth:{clientId:this.config.clientId,authority:`https://login.microsoftonline.com/${this.tid}`},cache:{cacheLocation:"sessionStorage"}};this.msalInstance=new r(o),await this.msalInstance.initialize(),this.initialized=!0}async getSSOToken(e){if(this.ssoToken&&this.ssoToken.expiresOnTimestamp-Date.now()>3e5)return c.verbose("Get SSO token from memory cache"),this.ssoToken;const r={resources:null!=e?e:[]};let n;try{await t.initialize()}catch(e){const t="Initialize teams sdk failed due to not running inside Teams environment";throw c.error(t),new u(t,i.InternalError)}try{n=await o.getAuthToken(r)}catch(e){const t="Get SSO token failed with error: "+e.message;throw c.error(t),new u(t,i.InternalError)}if(!n){const e="Get empty SSO token from Teams";throw c.error(e),new u(e,i.InternalError)}const s=h(n);if("1.0"!==s.ver&&"2.0"!==s.ver){const e="SSO token is not valid with an unknown version: "+s.ver;throw c.error(e),new u(e,i.InternalError)}const a={token:n,expiresOnTimestamp:1e3*s.exp};return this.ssoToken=a,a}loadAndValidateConfig(e){if(c.verbose("Validate authentication configuration"),e.initiateLoginEndpoint&&e.clientId)return e;const t=[];e.initiateLoginEndpoint||t.push("initiateLoginEndpoint"),e.clientId||t.push("clientId");const o=w(a.InvalidConfiguration,t.join(", "),"undefined");throw c.error(o),new u(o,i.InvalidConfiguration)}setSessionStorage(e){try{Object.keys(e).forEach((t=>{sessionStorage.setItem(t,e[t])}))}catch(e){const t=`Failed to set values in session storage. Error: ${e.message}`;throw c.error(t),new u(t,i.InternalError)}}}class N{constructor(e,t,o,r){throw new u(w(a.BrowserRuntimeNotSupported,"TeamsBotSsoPrompt"),i.RuntimeNotSupported)}beginDialog(e){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"TeamsBotSsoPrompt"),i.RuntimeNotSupported))}continueDialog(e){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"TeamsBotSsoPrompt"),i.RuntimeNotSupported))}}function B(e,t){const o=n.create({baseURL:e});return o.interceptors.request.use((async function(e){return await t.AddAuthenticationInfo(e)})),o}class y{constructor(e){this.getToken=e}async AddAuthenticationInfo(e){const t=await this.getToken();if(e.headers||(e.headers={}),e.headers.Authorization)throw new u(a.AuthorizationHeaderAlreadyExists,i.AuthorizationInfoAlreadyExists);return e.headers.Authorization=`Bearer ${t}`,e}}class v{constructor(e,t){throw new u(w(a.BrowserRuntimeNotSupported,"BasicAuthProvider"),i.RuntimeNotSupported)}AddAuthenticationInfo(e){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"BasicAuthProvider"),i.RuntimeNotSupported))}}class C{constructor(e,t,o){throw new u(w(a.BrowserRuntimeNotSupported,"ApiKeyProvider"),i.RuntimeNotSupported)}AddAuthenticationInfo(e){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"ApiKeyProvider"),i.RuntimeNotSupported))}}var A,I,T,k,P;!function(e){e[e.Header=0]="Header",e[e.QueryParams=1]="QueryParams"}(A||(A={}));class E{constructor(e){throw new u(w(a.BrowserRuntimeNotSupported,"CertificateAuthProvider"),i.RuntimeNotSupported)}AddAuthenticationInfo(e){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"CertificateAuthProvider"),i.RuntimeNotSupported))}}function x(e,t,o){throw new u(w(a.BrowserRuntimeNotSupported,"createPemCertOption"),i.RuntimeNotSupported)}function F(e,t){throw new u(w(a.BrowserRuntimeNotSupported,"createPfxCertOption"),i.RuntimeNotSupported)}!function(e){e.Channel="Channel",e.Group="Group",e.Person="Person"}(I||(I={})),function(e){e[e.ReplaceForInteractor=0]="ReplaceForInteractor",e[e.ReplaceForAll=1]="ReplaceForAll",e[e.NewForAll=2]="NewForAll"}(T||(T={})),function(e){e[e.BadRequest=400]="BadRequest",e[e.InternalServerError=500]="InternalServerError"}(k||(k={}));class j{constructor(e,t,o,...r){throw new u(w(a.BrowserRuntimeNotSupported,"BotSsoExecutionDialog"),i.RuntimeNotSupported)}addCommand(e,t){throw new u(w(a.BrowserRuntimeNotSupported,"BotSsoExecutionDialog"),i.RuntimeNotSupported)}run(e,t){throw new u(w(a.BrowserRuntimeNotSupported,"BotSsoExecutionDialog"),i.RuntimeNotSupported)}onEndDialog(e){throw new u(w(a.BrowserRuntimeNotSupported,"BotSsoExecutionDialog"),i.RuntimeNotSupported)}}function O(e,t,o,r,n){throw new u(w(a.BrowserRuntimeNotSupported,"queryWithToken in message extension"),i.RuntimeNotSupported)}!function(e){e[e.Person=1]="Person",e[e.Group=2]="Group",e[e.Channel=4]="Channel",e[e.All=7]="All"}(P||(P={}));var b=Object.freeze({__proto__:null,BotSsoExecutionDialog:j,CardActionBot:class{constructor(e,t){throw new u(w(a.BrowserRuntimeNotSupported,"CardActionBot"),i.RuntimeNotSupported)}registerHandler(e){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"CardActionBot"),i.RuntimeNotSupported))}registerHandlers(e){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"CardActionBot"),i.RuntimeNotSupported))}},Channel:class{constructor(e,t){throw this.type=I.Channel,new u(w(a.BrowserRuntimeNotSupported,"Channel"),i.RuntimeNotSupported)}sendMessage(e,t){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"Channel"),i.RuntimeNotSupported))}sendAdaptiveCard(e,t){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"Channel"),i.RuntimeNotSupported))}},CommandBot:class{constructor(e,t){throw new u(w(a.BrowserRuntimeNotSupported,"CommandBot"),i.RuntimeNotSupported)}registerCommand(e){throw new u(w(a.BrowserRuntimeNotSupported,"CommandBot"),i.RuntimeNotSupported)}registerCommands(e){throw new u(w(a.BrowserRuntimeNotSupported,"CommandBot"),i.RuntimeNotSupported)}registerSsoCommand(e){throw new u(w(a.BrowserRuntimeNotSupported,"CommandBot"),i.RuntimeNotSupported)}registerSsoCommands(e){throw new u(w(a.BrowserRuntimeNotSupported,"CommandBot"),i.RuntimeNotSupported)}},ConversationBot:class{constructor(e){throw new u(w(a.BrowserRuntimeNotSupported,"ConversationBot"),i.RuntimeNotSupported)}requestHandler(e,t,o){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"ConversationBot"),i.RuntimeNotSupported))}},Member:class{constructor(e,t){throw this.type=I.Person,new u(w(a.BrowserRuntimeNotSupported,"Member"),i.RuntimeNotSupported)}sendMessage(e,t){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"Member"),i.RuntimeNotSupported))}sendAdaptiveCard(e,t){return Promise.reject(Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"Member"),i.RuntimeNotSupported)))}},NotificationBot:class{constructor(e,t){throw new u(w(a.BrowserRuntimeNotSupported,"NotificationBot"),i.RuntimeNotSupported)}static installations(){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"NotificationBot"),i.RuntimeNotSupported))}findMember(e,t){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"NotificationBot"),i.RuntimeNotSupported))}findChannel(e){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"NotificationBot"),i.RuntimeNotSupported))}findAllMembers(e,t){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"NotificationBot"),i.RuntimeNotSupported))}findAllChannels(e){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"NotificationBot"),i.RuntimeNotSupported))}},TeamsBotInstallation:class{constructor(e,t){throw new u(w(a.BrowserRuntimeNotSupported,"TeamsBotInstallation"),i.RuntimeNotSupported)}sendMessage(e,t){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"TeamsBotInstallation"),i.RuntimeNotSupported))}sendAdaptiveCard(e,t){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"TeamsBotInstallation"),i.RuntimeNotSupported))}channels(){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"TeamsBotInstallation"),i.RuntimeNotSupported))}members(){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"TeamsBotInstallation"),i.RuntimeNotSupported))}getTeamDetails(){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"TeamsBotInstallation"),i.RuntimeNotSupported))}},sendAdaptiveCard:function(e,t,o){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"sendAdaptiveCard"),i.RuntimeNotSupported))},sendMessage:function(e,t,o){return Promise.reject(new u(w(a.BrowserRuntimeNotSupported,"sendMessage"),i.RuntimeNotSupported))}});export{T as AdaptiveCardResponse,A as ApiKeyLocation,C as ApiKeyProvider,f as AppCredential,v as BasicAuthProvider,y as BearerTokenAuthProvider,b as BotBuilderCloudAdapter,j as BotSsoExecutionDialog,E as CertificateAuthProvider,i as ErrorCode,u as ErrorWithCode,k as InvokeResponseErrorCode,s as LogLevel,I as NotificationTargetType,g as OnBehalfOfUserCredential,N as TeamsBotSsoPrompt,R as TeamsUserCredential,B as createApiClient,x as createPemCertOption,F as createPfxCertOption,p as getLogLevel,O as handleMessageExtensionQueryWithSSO,m as setLogFunction,d as setLogLevel,l as setLogger};
|
1735
2
|
//# sourceMappingURL=index.esm2017.js.map
|