@microsoft/teamsfx 2.3.1 → 2.3.2-beta.2024031405.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.node.cjs.js","sources":["../src/core/errors.ts","../src/util/logger.ts","../src/util/utils.ts","../src/util/utils.node.ts","../src/credential/appCredential.ts","../src/credential/onBehalfOfUserCredential.ts","../src/credential/teamsUserCredential.ts","../src/core/msGraphAuthProvider.ts","../src/core/msGraphClientProvider.ts","../src/core/defaultTediousConnectionConfiguration.ts","../src/models/identityType.ts","../src/bot/teamsBotSsoPrompt.ts","../src/apiClient/apiClient.ts","../src/apiClient/bearerTokenAuthProvider.ts","../src/apiClient/basicAuthProvider.ts","../src/apiClient/apiKeyProvider.ts","../src/apiClient/certificateAuthProvider.ts","../src/core/teamsfx.ts","../src/conversation/interface.ts","../src/conversation/invokeResponseFactory.ts","../src/conversation/middlewares/cardActionMiddleware.ts","../src/conversation/cardAction.ts","../src/conversation/middlewares/commandMiddleware.ts","../src/conversation/command.ts","../src/conversation/utils.ts","../src/conversation/middlewares/notificationMiddleware.ts","../src/conversation/storage.ts","../src/conversation/notification.ts","../src/conversation/sso/botSsoExecutionDialog.ts","../src/conversation/sso/defaultBotSsoExecutionActivityHandler.ts","../src/conversation/conversation.ts","../src/conversation/messageBuilder.ts","../src/messageExtension/executeWithSSO.ts","../src/conversationWithCloudAdapter/cardAction.ts","../src/conversationWithCloudAdapter/command.ts","../src/conversationWithCloudAdapter/notification.ts","../src/conversationWithCloudAdapter/conversation.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Error code to trace the error types.\n */\nexport enum ErrorCode {\n /**\n * Invalid parameter error.\n */\n InvalidParameter = \"InvalidParameter\",\n\n /**\n * Invalid configuration error.\n */\n InvalidConfiguration = \"InvalidConfiguration\",\n\n /**\n * Invalid certificate error.\n */\n InvalidCertificate = \"InvalidCertificate\",\n\n /**\n * Internal error.\n */\n InternalError = \"InternalError\",\n\n /**\n * Channel is not supported error.\n */\n ChannelNotSupported = \"ChannelNotSupported\",\n\n /**\n * Failed to retrieve sso token\n */\n FailedToRetrieveSsoToken = \"FailedToRetrieveSsoToken\",\n\n /**\n * Failed to process sso handler\n */\n FailedToProcessSsoHandler = \"FailedToProcessSsoHandler\",\n\n /**\n * Cannot find command\n */\n CannotFindCommand = \"CannotFindCommand\",\n\n /**\n * Failed to run sso step\n */\n FailedToRunSsoStep = \"FailedToRunSsoStep\",\n\n /**\n * Failed to run dedup step\n */\n FailedToRunDedupStep = \"FailedToRunDedupStep\",\n\n /**\n * Sso activity handler is undefined\n */\n SsoActivityHandlerIsUndefined = \"SsoActivityHandlerIsUndefined\",\n\n /**\n * Runtime is not supported error.\n */\n RuntimeNotSupported = \"RuntimeNotSupported\",\n\n /**\n * User failed to finish the AAD consent flow failed.\n */\n ConsentFailed = \"ConsentFailed\",\n\n /**\n * The user or administrator has not consented to use the application error.\n */\n UiRequiredError = \"UiRequiredError\",\n\n /**\n * Token is not within its valid time range error.\n */\n TokenExpiredError = \"TokenExpiredError\",\n\n /**\n * Call service (AAD or simple authentication server) failed.\n */\n ServiceError = \"ServiceError\",\n\n /**\n * Operation failed.\n */\n FailedOperation = \"FailedOperation\",\n\n /**\n * Invalid response error.\n */\n InvalidResponse = \"InvalidResponse\",\n\n /**\n * Identity type error.\n */\n IdentityTypeNotSupported = \"IdentityTypeNotSupported\",\n\n /**\n * Authentication info already exists error.\n */\n AuthorizationInfoAlreadyExists = \"AuthorizationInfoAlreadyExists\",\n}\n\n/**\n * @internal\n */\nexport class ErrorMessage {\n // InvalidConfiguration Error\n static readonly InvalidConfiguration = \"{0} in configuration is invalid: {1}.\";\n static readonly ConfigurationNotExists = \"Configuration does not exist. {0}\";\n static readonly ResourceConfigurationNotExists = \"{0} resource configuration does not exist.\";\n static readonly MissingResourceConfiguration =\n \"Missing resource configuration with type: {0}, name: {1}.\";\n static readonly AuthenticationConfigurationNotExists =\n \"Authentication configuration does not exist.\";\n\n // RuntimeNotSupported Error\n static readonly BrowserRuntimeNotSupported = \"{0} is not supported in browser.\";\n static readonly NodejsRuntimeNotSupported = \"{0} is not supported in Node.\";\n\n // Internal Error\n static readonly FailToAcquireTokenOnBehalfOfUser =\n \"Failed to acquire access token on behalf of user: {0}\";\n\n // ChannelNotSupported Error\n static readonly OnlyMSTeamsChannelSupported = \"{0} is only supported in MS Teams Channel\";\n\n static readonly FailedToProcessSsoHandler = \"Failed to process sso handler: {0}\";\n\n // FailedToRetrieveSsoToken Error\n static readonly FailedToRetrieveSsoToken =\n \"Failed to retrieve sso token, user failed to finish the AAD consent flow.\";\n\n // CannotFindCommand Error\n static readonly CannotFindCommand = \"Cannot find command: {0}\";\n\n static readonly FailedToRunSsoStep = \"Failed to run dialog to retrieve sso token: {0}\";\n\n static readonly FailedToRunDedupStep = \"Failed to run dialog to remove duplicated messages: {0}\";\n\n // SsoActivityHandlerIsUndefined Error\n static readonly SsoActivityHandlerIsNull =\n \"Sso command can only be used or added when sso activity handler is not undefined\";\n\n // IdentityTypeNotSupported Error\n static readonly IdentityTypeNotSupported = \"{0} identity is not supported in {1}\";\n\n // AuthorizationInfoError\n static readonly AuthorizationHeaderAlreadyExists = \"Authorization header already exists!\";\n static readonly BasicCredentialAlreadyExists = \"Basic credential already exists!\";\n // InvalidParameter Error\n static readonly EmptyParameter = \"Parameter {0} is empty\";\n static readonly DuplicateHttpsOptionProperty =\n \"Axios HTTPS agent already defined value for property {0}\";\n static readonly DuplicateApiKeyInHeader =\n \"The request already defined api key in request header with name {0}.\";\n static readonly DuplicateApiKeyInQueryParam =\n \"The request already defined api key in query parameter with name {0}.\";\n static readonly OnlySupportInQueryActivity =\n \"The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.\";\n static readonly OnlySupportInLinkQueryActivity =\n \"The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.\";\n}\n\n/**\n * Error class with code and message thrown by the SDK.\n */\nexport class ErrorWithCode extends Error {\n /**\n * Error code\n *\n * @readonly\n */\n code: string | undefined;\n\n /**\n * Constructor of ErrorWithCode.\n *\n * @param {string} message - error message.\n * @param {ErrorCode} code - error code.\n */\n constructor(message?: string, code?: ErrorCode) {\n if (!code) {\n super(message);\n return this;\n }\n\n super(message);\n Object.setPrototypeOf(this, ErrorWithCode.prototype);\n this.name = `${new.target.name}.${code}`;\n this.code = code;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Interface for customized logger.\n */\nexport interface Logger {\n /**\n * Writes to error level logging or lower.\n */\n error(message: string): void;\n /**\n * Writes to warning level logging or lower.\n */\n warn(message: string): void;\n /**\n * Writes to info level logging or lower.\n */\n info(message: string): void;\n /**\n * Writes to verbose level logging.\n */\n verbose(message: string): void;\n}\n\n/**\n * Log function for customized logging.\n */\nexport type LogFunction = (level: LogLevel, message: string) => void;\n\n/**\n * Log level.\n */\nexport enum LogLevel {\n /**\n * Show verbose, information, warning and error message.\n */\n Verbose,\n /**\n * Show information, warning and error message.\n */\n Info,\n /**\n * Show warning and error message.\n */\n Warn,\n /**\n * Show error message.\n */\n Error,\n}\n\n/**\n * Update log level helper.\n *\n * @param { LogLevel } level - log level in configuration\n */\nexport function setLogLevel(level: LogLevel): void {\n internalLogger.level = level;\n}\n\n/**\n * Get log level.\n *\n * @returns Log level\n */\nexport function getLogLevel(): LogLevel | undefined {\n return internalLogger.level;\n}\n\nexport class InternalLogger implements Logger {\n public name?: string;\n public level?: LogLevel = undefined;\n public customLogger: Logger | undefined;\n public customLogFunction: LogFunction | undefined;\n\n private defaultLogger: Logger = {\n verbose: console.debug,\n info: console.info,\n warn: console.warn,\n error: console.error,\n };\n\n constructor(name?: string, logLevel?: LogLevel) {\n this.name = name;\n this.level = logLevel;\n }\n\n public error(message: string): void {\n this.log(LogLevel.Error, (x: Logger) => x.error, message);\n }\n\n public warn(message: string): void {\n this.log(LogLevel.Warn, (x: Logger) => x.warn, message);\n }\n\n public info(message: string): void {\n this.log(LogLevel.Info, (x: Logger) => x.info, message);\n }\n\n public verbose(message: string): void {\n this.log(LogLevel.Verbose, (x: Logger) => x.verbose, message);\n }\n\n private log(\n logLevel: LogLevel,\n logFunction: (x: Logger) => (message: string) => void,\n message: string\n ): void {\n if (message.trim() === \"\") {\n return;\n }\n const timestamp = new Date().toUTCString();\n let logHeader: string;\n if (this.name) {\n logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;\n } else {\n logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;\n }\n const logMessage = `${logHeader}${message}`;\n if (this.level !== undefined && this.level <= logLevel) {\n if (this.customLogger) {\n logFunction(this.customLogger)(logMessage);\n } else if (this.customLogFunction) {\n this.customLogFunction(logLevel, logMessage);\n } else {\n logFunction(this.defaultLogger)(logMessage);\n }\n }\n }\n}\n\n/**\n * Logger instance used internally\n *\n * @internal\n */\nexport const internalLogger: InternalLogger = new InternalLogger();\n\n/**\n * Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.\n *\n * @param {Logger} logger - custom logger. If it's undefined, custom logger will be cleared.\n *\n * @example\n * ```typescript\n * setLogger({\n * verbose: console.debug,\n * info: console.info,\n * warn: console.warn,\n * error: console.error,\n * });\n * ```\n */\nexport function setLogger(logger?: Logger): void {\n internalLogger.customLogger = logger;\n}\n\n/**\n * Set custom log function. Use the function if it's set. Priority is lower than setLogger.\n *\n * @param {LogFunction} logFunction - custom log function. If it's undefined, custom log function will be cleared.\n *\n * @example\n * ```typescript\n * setLogFunction((level: LogLevel, message: string) => {\n * if (level === LogLevel.Error) {\n * console.log(message);\n * }\n * });\n * ```\n */\nexport function setLogFunction(logFunction?: LogFunction): void {\n internalLogger.customLogFunction = logFunction;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { ErrorWithCode, ErrorCode } from \"../core/errors\";\nimport { SSOTokenInfoBase, SSOTokenV1Info, SSOTokenV2Info } from \"../models/ssoTokenInfo\";\nimport { UserInfo, UserTenantIdAndLoginHint } from \"../models/userinfo\";\nimport jwt_decode from \"jwt-decode\";\nimport { internalLogger } from \"./logger\";\nimport { AccessToken } from \"@azure/identity\";\nimport { AuthenticationResult } from \"@azure/msal-browser\";\n\n/**\n * Parse jwt token payload\n *\n * @param token\n *\n * @returns Payload object\n *\n * @internal\n */\nexport function parseJwt(token: string): SSOTokenInfoBase {\n try {\n const tokenObj: SSOTokenInfoBase = jwt_decode(token);\n if (!tokenObj || !tokenObj.exp) {\n throw new ErrorWithCode(\n \"Decoded token is null or exp claim does not exists.\",\n ErrorCode.InternalError\n );\n }\n\n return tokenObj;\n } catch (err: any) {\n const errorMsg = \"Parse jwt token failed in node env with error: \" + (err.message as string);\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);\n }\n}\n\n/**\n * @internal\n */\nexport function getUserInfoFromSsoToken(ssoToken: string): UserInfo {\n if (!ssoToken) {\n const errorMsg = \"SSO token is undefined.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n const tokenObject = parseJwt(ssoToken) as SSOTokenV1Info | SSOTokenV2Info;\n\n const userInfo: UserInfo = {\n displayName: tokenObject.name,\n objectId: tokenObject.oid,\n tenantId: tokenObject.tid,\n preferredUserName: \"\",\n };\n\n if (tokenObject.ver === \"2.0\") {\n userInfo.preferredUserName = (tokenObject as SSOTokenV2Info).preferred_username;\n } else if (tokenObject.ver === \"1.0\") {\n userInfo.preferredUserName = (tokenObject as SSOTokenV1Info).upn;\n }\n return userInfo;\n}\n\n/**\n * @internal\n */\nexport function getTenantIdAndLoginHintFromSsoToken(ssoToken: string): UserTenantIdAndLoginHint {\n if (!ssoToken) {\n const errorMsg = \"SSO token is undefined.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n const tokenObject = parseJwt(ssoToken) as SSOTokenV1Info | SSOTokenV2Info;\n\n const userInfo: UserTenantIdAndLoginHint = {\n tid: tokenObject.tid,\n loginHint:\n tokenObject.ver === \"2.0\"\n ? (tokenObject as SSOTokenV2Info).preferred_username\n : (tokenObject as SSOTokenV1Info).upn,\n };\n\n return userInfo;\n}\n\n/**\n * @internal\n */\nexport function parseAccessTokenFromAuthCodeTokenResponse(\n tokenResponse: string | AuthenticationResult\n): AccessToken {\n try {\n const tokenResponseObject =\n typeof tokenResponse == \"string\"\n ? (JSON.parse(tokenResponse) as AuthenticationResult)\n : tokenResponse;\n if (!tokenResponseObject || !tokenResponseObject.accessToken) {\n const errorMsg = \"Get empty access token from Auth Code token response.\";\n\n internalLogger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n const token = tokenResponseObject.accessToken;\n const tokenObject = parseJwt(token);\n\n if (tokenObject.ver !== \"1.0\" && tokenObject.ver !== \"2.0\") {\n const errorMsg = \"SSO token is not valid with an unknown version: \" + tokenObject.ver;\n internalLogger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n const accessToken: AccessToken = {\n token: token,\n expiresOnTimestamp: tokenObject.exp * 1000,\n };\n return accessToken;\n } catch (error: any) {\n const errorMsg =\n \"Parse access token failed from Auth Code token response in node env with error: \" +\n (error.message as string);\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);\n }\n}\n\n/**\n * Format string template with replacements\n *\n * ```typescript\n * const template = \"{0} and {1} are fruit. {0} is my favorite one.\"\n * const formattedStr = formatString(template, \"apple\", \"pear\"); // formattedStr: \"apple and pear are fruit. apple is my favorite one.\"\n * ```\n *\n * @param str string template\n * @param replacements replacement string array\n * @returns Formatted string\n *\n * @internal\n */\nexport function formatString(str: string, ...replacements: string[]): string {\n const args = replacements;\n return str.replace(/{(\\d+)}/g, function (match, number) {\n return typeof args[number] != \"undefined\" ? args[number] : match;\n });\n}\n\n/**\n * @internal\n */\nexport function validateScopesType(value: any): void {\n // string\n if (typeof value === \"string\" || value instanceof String) {\n return;\n }\n\n // empty array\n if (Array.isArray(value) && value.length === 0) {\n return;\n }\n\n // string array\n if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === \"string\")) {\n return;\n }\n\n const errorMsg = \"The type of scopes is not valid, it must be string or string array\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n}\n\n/**\n * @internal\n */\nexport function getScopesArray(scopes: string | string[]): string[] {\n const scopesArray: string[] = typeof scopes === \"string\" ? scopes.split(\" \") : scopes;\n return scopesArray.filter((x) => x !== null && x !== \"\");\n}\n\n/**\n * @internal\n */\nexport function getAuthority(authorityHost: string, tenantId: string): string {\n const normalizedAuthorityHost = authorityHost.replace(/\\/+$/g, \"\");\n return normalizedAuthorityHost + \"/\" + tenantId;\n}\n\n/**\n * @internal\n */\nexport interface ClientCertificate {\n thumbprint: string;\n privateKey: string;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { ConfidentialClientApplication, NodeAuthOptions } from \"@azure/msal-node\";\nimport {\n AppCredentialAuthConfig,\n AuthenticationConfiguration,\n OnBehalfOfCredentialAuthConfig,\n} from \"../models/configuration\";\nimport { ClientCertificate, getAuthority } from \"./utils\";\nimport { internalLogger } from \"./logger\";\nimport { ErrorWithCode, ErrorCode } from \"../core/errors\";\nimport { createHash } from \"crypto\";\n\n/**\n * @internal\n */\nexport function createConfidentialClientApplication(\n authentication:\n | AuthenticationConfiguration\n | AppCredentialAuthConfig\n | OnBehalfOfCredentialAuthConfig\n): ConfidentialClientApplication {\n const authority = getAuthority(authentication.authorityHost!, authentication.tenantId!);\n const clientCertificate: ClientCertificate | undefined = parseCertificate(\n authentication.certificateContent\n );\n\n const auth: NodeAuthOptions = {\n clientId: authentication.clientId!,\n authority: authority,\n };\n\n if (clientCertificate) {\n auth.clientCertificate = clientCertificate;\n } else {\n auth.clientSecret = authentication.clientSecret;\n }\n\n return new ConfidentialClientApplication({\n auth,\n });\n}\n\n/**\n * @internal\n */\nexport function parseCertificate(\n certificateContent: string | undefined\n): ClientCertificate | undefined {\n if (!certificateContent) {\n return undefined;\n }\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/;\n const match = certificatePattern.exec(certificateContent);\n if (!match) {\n const errorMsg = \"The certificate content does not contain a PEM-encoded certificate.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidCertificate);\n }\n const thumbprint = createHash(\"sha1\")\n .update(Buffer.from(match[3], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return {\n thumbprint: thumbprint,\n privateKey: certificateContent,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/identity\";\nimport { AppCredentialAuthConfig, AuthenticationConfiguration } from \"../models/configuration\";\nimport { internalLogger } from \"../util/logger\";\nimport { validateScopesType, formatString, getScopesArray } from \"../util/utils\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\nimport { ConfidentialClientApplication } from \"@azure/msal-node\";\nimport { createConfidentialClientApplication } from \"../util/utils.node\";\n\n/**\n * Represent Microsoft 365 tenant identity, and it is usually used when user is not involved like time-triggered automation job.\n *\n * @example\n * ```typescript\n * loadConfiguration(); // load configuration from environment variables\n * const credential = new AppCredential();\n * ```\n *\n * @remarks\n * Only works in in server side.\n */\nexport class AppCredential implements TokenCredential {\n private readonly msalClient: ConfidentialClientApplication;\n\n /**\n * Constructor of AppCredential.\n *\n * @remarks\n * Only works in in server side.\n *\n * @param {AppCredentialAuthConfig} authConfig - The authentication configuration.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret or tenant id is not found in config.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n */\n constructor(authConfig: AppCredentialAuthConfig);\n /**\n * Constructor of AppCredential.\n *\n * @remarks\n * Only works in in server side.\n *\n * @param {AuthenticationConfiguration} authConfig - The authentication configuration. Use environment variables if not provided.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret or tenant id is not found in config.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n */\n constructor(authConfig: AuthenticationConfiguration);\n constructor(authConfig: AppCredentialAuthConfig | AuthenticationConfiguration) {\n internalLogger.info(\"Create M365 tenant credential\");\n\n const config = this.loadAndValidateConfig(authConfig);\n\n this.msalClient = createConfidentialClientApplication(config);\n }\n\n /**\n * Get access token for credential.\n *\n * @example\n * ```typescript\n * await credential.getToken([\"User.Read.All\"]) // Get Graph access token for single scope using string array\n * await credential.getToken(\"User.Read.All\") // Get Graph access token for single scope using string\n * await credential.getToken([\"User.Read.All\", \"Calendars.Read\"]) // Get Graph access token for multiple scopes using string array\n * await credential.getToken(\"User.Read.All Calendars.Read\") // Get Graph access token for multiple scopes using space-separated string\n * await credential.getToken(\"https://graph.microsoft.com/User.Read.All\") // Get Graph access token with full resource URI\n * await credential.getToken([\"https://outlook.office.com/Mail.Read\"]) // Get Outlook access token\n * ```\n *\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.\n *\n * @throws {@link ErrorCode|ServiceError} when get access token with authentication error.\n * @throws {@link ErrorCode|InternalError} when get access token with unknown error.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns Access token with expected scopes.\n * Throw error if get access token failed.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n let accessToken;\n validateScopesType(scopes);\n const scopesStr = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n internalLogger.info(\"Get access token with scopes: \" + scopesStr);\n\n try {\n const scopesArray = getScopesArray(scopes);\n const authenticationResult = await this.msalClient.acquireTokenByClientCredential({\n scopes: scopesArray,\n });\n if (authenticationResult) {\n accessToken = {\n token: authenticationResult.accessToken,\n expiresOnTimestamp: authenticationResult.expiresOn!.getTime(),\n };\n }\n } catch (err: any) {\n const errorMsg = \"Get M365 tenant credential failed with error: \" + (err.message as string);\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.ServiceError);\n }\n\n if (!accessToken) {\n const errorMsg = \"Get M365 tenant credential access token failed with empty access token\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);\n }\n\n return accessToken;\n }\n\n /**\n * Load and validate authentication configuration\n *\n * @param {AuthenticationConfiguration} authConfig - The authentication configuration. Use environment variables if not provided.\n *\n * @returns Authentication configuration\n */\n private loadAndValidateConfig(\n config: AuthenticationConfiguration | AppCredentialAuthConfig\n ): AuthenticationConfiguration | AppCredentialAuthConfig {\n internalLogger.verbose(\"Validate authentication configuration\");\n\n if (\n config.clientId &&\n (config.clientSecret || config.certificateContent) &&\n config.tenantId &&\n config.authorityHost\n ) {\n return config;\n }\n\n const missingValues = [];\n\n if (!config.clientId) {\n missingValues.push(\"clientId\");\n }\n\n if (!config.clientSecret && !config.certificateContent) {\n missingValues.push(\"clientSecret or certificateContent\");\n }\n\n if (!config.tenantId) {\n missingValues.push(\"tenantId\");\n }\n\n if (!config.authorityHost) {\n missingValues.push(\"authorityHost\");\n }\n\n const errorMsg = formatString(\n ErrorMessage.InvalidConfiguration,\n missingValues.join(\", \"),\n \"undefined\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/identity\";\nimport { AuthenticationResult, ConfidentialClientApplication } from \"@azure/msal-node\";\nimport { UserInfo } from \"../models/userinfo\";\nimport {\n AuthenticationConfiguration,\n OnBehalfOfCredentialAuthConfig,\n} from \"../models/configuration\";\nimport { internalLogger } from \"../util/logger\";\nimport {\n formatString,\n getScopesArray,\n getUserInfoFromSsoToken,\n parseJwt,\n validateScopesType,\n} from \"../util/utils\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { createConfidentialClientApplication } from \"../util/utils.node\";\n\n/**\n * Represent on-behalf-of flow to get user identity, and it is designed to be used in server side.\n *\n * @example\n * ```typescript\n * const credential = new OnBehalfOfUserCredential(ssoToken);\n * ```\n *\n * @remarks\n * Can only be used in server side.\n */\nexport class OnBehalfOfUserCredential implements TokenCredential {\n private msalClient: ConfidentialClientApplication;\n private ssoToken: AccessToken;\n\n /**\n * Constructor of OnBehalfOfUserCredential\n *\n * @remarks\n * Only works in in server side.\n *\n * @param {string} ssoToken - User token provided by Teams SSO feature.\n * @param {OnBehalfOfCredentialAuthConfig} config - The authentication configuration.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret, certificate content, authority host or tenant id is not found in config.\n * @throws {@link ErrorCode|InternalError} when SSO token is not valid.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(ssoToken: string, config: OnBehalfOfCredentialAuthConfig);\n /**\n * Constructor of OnBehalfOfUserCredential\n *\n * @remarks\n * Only works in in server side.\n *\n * @param {string} ssoToken - User token provided by Teams SSO feature.\n * @param {AuthenticationConfiguration} config - The authentication configuration. Use environment variables if not provided.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret, certificate content, authority host or tenant id is not found in config.\n * @throws {@link ErrorCode|InternalError} when SSO token is not valid.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(ssoToken: string, config: AuthenticationConfiguration);\n constructor(\n ssoToken: string,\n config: OnBehalfOfCredentialAuthConfig | AuthenticationConfiguration\n ) {\n internalLogger.info(\"Get on behalf of user credential\");\n\n const missingConfigurations: string[] = [];\n if (!config.clientId) {\n missingConfigurations.push(\"clientId\");\n }\n\n if (!config.authorityHost) {\n missingConfigurations.push(\"authorityHost\");\n }\n\n if (!config.clientSecret && !config.certificateContent) {\n missingConfigurations.push(\"clientSecret or certificateContent\");\n }\n\n if (!config.tenantId) {\n missingConfigurations.push(\"tenantId\");\n }\n\n if (missingConfigurations.length != 0) {\n const errorMsg = formatString(\n ErrorMessage.InvalidConfiguration,\n missingConfigurations.join(\", \"),\n \"undefined\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);\n }\n\n this.msalClient = createConfidentialClientApplication(config);\n\n const decodedSsoToken = parseJwt(ssoToken);\n this.ssoToken = {\n token: ssoToken,\n expiresOnTimestamp: decodedSsoToken.exp,\n };\n }\n\n /**\n * Get access token from credential.\n *\n * @example\n * ```typescript\n * await credential.getToken([]) // Get SSO token using empty string array\n * await credential.getToken(\"\") // Get SSO token using empty string\n * await credential.getToken([\".default\"]) // Get Graph access token with default scope using string array\n * await credential.getToken(\".default\") // Get Graph access token with default scope using string\n * await credential.getToken([\"User.Read\"]) // Get Graph access token for single scope using string array\n * await credential.getToken(\"User.Read\") // Get Graph access token for single scope using string\n * await credential.getToken([\"User.Read\", \"Application.Read.All\"]) // Get Graph access token for multiple scopes using string array\n * await credential.getToken(\"User.Read Application.Read.All\") // Get Graph access token for multiple scopes using space-separated string\n * await credential.getToken(\"https://graph.microsoft.com/User.Read\") // Get Graph access token with full resource URI\n * await credential.getToken([\"https://outlook.office.com/Mail.Read\"]) // Get Outlook access token\n * ```\n *\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.\n *\n * @throws {@link ErrorCode|InternalError} when failed to acquire access token on behalf of user with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n *\n * @returns Access token with expected scopes.\n *\n * @remarks\n * If scopes is empty string or array, it returns SSO token.\n * If scopes is non-empty, it returns access token for target scope.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n validateScopesType(scopes);\n\n const scopesArray = getScopesArray(scopes);\n\n let result: AccessToken | null;\n if (!scopesArray.length) {\n internalLogger.info(\"Get SSO token.\");\n if (Math.floor(Date.now() / 1000) > this.ssoToken.expiresOnTimestamp) {\n const errorMsg = \"Sso token has already expired.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.TokenExpiredError);\n }\n result = this.ssoToken;\n } else {\n internalLogger.info(\"Get access token with scopes: \" + scopesArray.join(\" \"));\n\n let authenticationResult: AuthenticationResult | null;\n try {\n authenticationResult = await this.msalClient.acquireTokenOnBehalfOf({\n oboAssertion: this.ssoToken.token,\n scopes: scopesArray,\n });\n } catch (error) {\n throw this.generateAuthServerError(error);\n }\n\n if (!authenticationResult) {\n const errorMsg = \"Access token is null\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(\n formatString(ErrorMessage.FailToAcquireTokenOnBehalfOfUser, errorMsg),\n ErrorCode.InternalError\n );\n }\n\n result = {\n token: authenticationResult.accessToken,\n expiresOnTimestamp: authenticationResult.expiresOn!.getTime(),\n };\n }\n\n return result;\n }\n\n /**\n * Get basic user info from SSO token.\n *\n * @example\n * ```typescript\n * const currentUser = getUserInfo();\n * ```\n *\n * @throws {@link ErrorCode|InternalError} when SSO token is not valid.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n *\n * @returns Basic user info with user displayName, objectId and preferredUserName.\n */\n public getUserInfo(): UserInfo {\n internalLogger.info(\"Get basic user info from SSO token\");\n return getUserInfoFromSsoToken(this.ssoToken.token);\n }\n\n private generateAuthServerError(err: any): Error {\n const errorMessage = err.errorMessage as string;\n if (err.name === \"InteractionRequiredAuthError\") {\n const fullErrorMsg =\n \"Failed to get access token from AAD server, interaction required: \" + errorMessage;\n internalLogger.warn(fullErrorMsg);\n return new ErrorWithCode(fullErrorMsg, ErrorCode.UiRequiredError);\n } else if (errorMessage && errorMessage.indexOf(\"AADSTS50013\") >= 0) {\n const fullErrorMsg =\n \"Failed to get access token from AAD server, assertion is invalid because of various reasons: \" +\n errorMessage;\n internalLogger.error(fullErrorMsg);\n return new ErrorWithCode(fullErrorMsg, ErrorCode.TokenExpiredError);\n } else {\n const fullErrorMsg = formatString(\n ErrorMessage.FailToAcquireTokenOnBehalfOfUser,\n errorMessage\n );\n internalLogger.error(fullErrorMsg);\n return new ErrorWithCode(fullErrorMsg, ErrorCode.ServiceError);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/identity\";\nimport { UserInfo } from \"../models/userinfo\";\nimport {\n AuthenticationConfiguration,\n TeamsUserCredentialAuthConfig,\n} from \"../models/configuration\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Represent Teams current user's identity, and it is used within Teams client applications.\n *\n * @remarks\n * Can only be used within Teams.\n */\nexport class TeamsUserCredential implements TokenCredential {\n /**\n * Constructor of TeamsUserCredential.\n * @remarks\n * Can only be used within Teams.\n */\n constructor(authConfig: TeamsUserCredentialAuthConfig);\n constructor(authConfig: AuthenticationConfiguration);\n constructor(authConfig: TeamsUserCredentialAuthConfig | AuthenticationConfiguration) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Popup login page to get user's access token with specific scopes.\n *\n * @param {string[]} resources - The optional list of resources for full trust Teams apps.\n *\n * @remarks\n * Can only be used within Teams.\n */\n public login(scopes: string | string[], resources?: string[]): Promise<void> {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n )\n );\n }\n\n /**\n * Get access token from credential.\n * @remarks\n * Can only be used within Teams.\n */\n getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken | null> {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n )\n );\n }\n\n /**\n * Get basic user info from SSO token\n *\n * @param {string[]} resources - The optional list of resources for full trust Teams apps.\n *\n * @remarks\n * Can only be used within Teams.\n */\n public getUserInfo(resources?: string[]): Promise<UserInfo> {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n )\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AuthenticationProvider } from \"@microsoft/microsoft-graph-client\";\nimport { ErrorWithCode, ErrorCode } from \"./errors\";\nimport { TeamsFxConfiguration } from \"../models/teamsfxConfiguration\";\nimport { internalLogger } from \"../util/logger\";\nimport { validateScopesType } from \"../util/utils\";\nimport { AccessToken, TokenCredential } from \"@azure/identity\";\n\nconst defaultScope = \"https://graph.microsoft.com/.default\";\n\n// eslint-disable-next-line no-secrets/no-secrets\n/**\n * Microsoft Graph auth provider for Teams Framework\n * @deprecated Use `TokenCredentialAuthenticationProvider` from `@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials` instead.\n */\nexport class MsGraphAuthProvider implements AuthenticationProvider {\n private credentialOrTeamsFx: TokenCredential | TeamsFxConfiguration;\n private scopes: string | string[];\n\n /**\n * Constructor of MsGraphAuthProvider.\n *\n * @param {TeamsFxConfiguration} teamsfx - Used to provide configuration and auth.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns An instance of MsGraphAuthProvider.\n */\n constructor(teamsfx: TeamsFxConfiguration, scopes?: string | string[]);\n /**\n * Constructor of MsGraphAuthProvider.\n *\n * @param {TokenCredential} credential - credential used to provide configuration and auth.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns An instance of MsGraphAuthProvider.\n */\n constructor(credential: TokenCredential, scopes?: string | string[]);\n constructor(\n credentialOrTeamsFx: TeamsFxConfiguration | TokenCredential,\n scopes?: string | string[]\n ) {\n this.credentialOrTeamsFx = credentialOrTeamsFx;\n\n let scopesStr = defaultScope;\n if (scopes) {\n validateScopesType(scopes);\n scopesStr = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n if (scopesStr === \"\") {\n scopesStr = defaultScope;\n }\n }\n\n internalLogger.info(\n `Create Microsoft Graph Authentication Provider with scopes: '${scopesStr}'`\n );\n\n this.scopes = scopesStr;\n }\n\n /**\n * Get access token for Microsoft Graph API requests.\n *\n * @throws {@link ErrorCode|InternalError} when get access token failed due to empty token or unknown other problems.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth or AAD server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns Access token from the credential.\n *\n */\n public async getAccessToken(): Promise<string> {\n internalLogger.info(`Get Graph Access token with scopes: '${this.scopes.toString()}'`);\n\n let accessToken: AccessToken | null;\n if ((this.credentialOrTeamsFx as TeamsFxConfiguration).getCredential) {\n accessToken = await (this.credentialOrTeamsFx as TeamsFxConfiguration)\n .getCredential()\n .getToken(this.scopes);\n } else {\n accessToken = await (this.credentialOrTeamsFx as TokenCredential).getToken(this.scopes);\n }\n\n return new Promise<string>((resolve, reject) => {\n if (accessToken) {\n resolve(accessToken.token);\n } else {\n const errorMsg = \"Graph access token is undefined or empty\";\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n }\n });\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Client } from \"@microsoft/microsoft-graph-client\";\nimport { MsGraphAuthProvider } from \"./msGraphAuthProvider\";\nimport { TeamsFxConfiguration } from \"../models/teamsfxConfiguration\";\nimport { internalLogger } from \"../util/logger\";\nimport { TokenCredential } from \"@azure/identity\";\n\n/**\n * Get Microsoft graph client.\n * @deprecated Use `TokenCredentialAuthenticationProvider` and `Client.initWithMiddleware` instead.\n * ```typescript\n * const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });\n * const graph = Client.initWithMiddleware({\n * authProvider: authProvider,\n * });\n * ```\n *\n * @example\n * Get Microsoft graph client by TokenCredential\n * ```typescript\n * // Sso token example (Azure Function)\n * const ssoToken = \"YOUR_TOKEN_STRING\";\n * const options = {\"AAD_APP_ID\", \"AAD_APP_SECRET\"};\n * const credential = new OnBehalfOfAADUserCredential(ssoToken, options);\n * const graphClient = await createMicrosoftGraphClient(credential);\n * const profile = await graphClient.api(\"/me\").get();\n *\n * // TeamsBotSsoPrompt example (Bot Application)\n * const requiredScopes = [\"User.Read\"];\n * const config: Configuration = {\n * loginUrl: loginUrl,\n * clientId: clientId,\n * clientSecret: clientSecret,\n * tenantId: tenantId\n * };\n * const prompt = new TeamsBotSsoPrompt(dialogId, {\n * config: config\n * scopes: [\"User.Read\"],\n * });\n * this.addDialog(prompt);\n *\n * const oboCredential = new OnBehalfOfAADUserCredential(\n * getUserId(dialogContext),\n * {\n * clientId: \"AAD_APP_ID\",\n * clientSecret: \"AAD_APP_SECRET\"\n * });\n * try {\n * const graphClient = await createMicrosoftGraphClient(credential);\n * const profile = await graphClient.api(\"/me\").get();\n * } catch (e) {\n * dialogContext.beginDialog(dialogId);\n * return Dialog.endOfTurn();\n * }\n * ```\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth.\n * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns Graph client with specified scopes.\n */\nexport function createMicrosoftGraphClient(\n teamsfx: TeamsFxConfiguration,\n scopes?: string | string[]\n): Client {\n internalLogger.info(\"Create Microsoft Graph Client\");\n const authProvider = new MsGraphAuthProvider(teamsfx, scopes);\n const graphClient = Client.initWithMiddleware({\n authProvider,\n });\n\n return graphClient;\n}\n\n// eslint-disable-next-line no-secrets/no-secrets\n/**\n * Get Microsoft graph client.\n * @deprecated Use `TokenCredentialAuthenticationProvider` and `Client.initWithMiddleware` instead.\n * ```typescript\n * const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });\n * const graph = Client.initWithMiddleware({\n * authProvider: authProvider,\n * });\n * ```\n * \n * @example\n * Get Microsoft graph client by TokenCredential\n * ```typescript\n * // In browser: TeamsUserCredential\n * const authConfig: TeamsUserCredentialAuthConfig = {\n * clientId: \"xxx\",\n initiateLoginEndpoint: \"https://xxx/auth-start.html\",\n * };\n\n * const credential = new TeamsUserCredential(authConfig);\n\n * const scope = \"User.Read\";\n * await credential.login(scope);\n\n * const client = createMicrosoftGraphClientWithCredential(credential, scope);\n\n * // In node: OnBehalfOfUserCredential\n * const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {\n * authorityHost: \"xxx\",\n * clientId: \"xxx\",\n * tenantId: \"xxx\",\n * clientSecret: \"xxx\",\n * };\n\n * const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);\n * const scope = \"User.Read\";\n * const client = createMicrosoftGraphClientWithCredential(oboCredential, scope);\n\n * // In node: AppCredential\n * const appAuthConfig: AppCredentialAuthConfig = {\n * authorityHost: \"xxx\",\n * clientId: \"xxx\",\n * tenantId: \"xxx\",\n * clientSecret: \"xxx\",\n * };\n * const appCredential = new AppCredential(appAuthConfig);\n * const scope = \"User.Read\";\n * const client = createMicrosoftGraphClientWithCredential(appCredential, scope);\n * \n * const profile = await client.api(\"/me\").get();\n * ```\n *\n * @param {TokenCredential} credential - Used to provide configuration and auth.\n * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns Graph client with specified scopes.\n */\nexport function createMicrosoftGraphClientWithCredential(\n credential: TokenCredential,\n scopes?: string | string[]\n): Client {\n internalLogger.info(\"Create Microsoft Graph Client\");\n const authProvider = new MsGraphAuthProvider(credential, scopes);\n const graphClient = Client.initWithMiddleware({\n authProvider,\n });\n return graphClient;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, ManagedIdentityCredential } from \"@azure/identity\";\nimport { ConnectionConfig } from \"tedious\";\nimport { ErrorWithCode, ErrorCode } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport { TeamsFx } from \"../core/teamsfx\";\n\n/**\n * MSSQL default scope\n * https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi\n */\nconst defaultSQLScope = \"https://database.windows.net/\";\n\n/**\n * Generate connection configuration consumed by tedious.\n *\n * @deprecated we recommend you compose your own Tedious configuration for better flexibility.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n * @param { string? } databaseName - specify database name to override default one if there are multiple databases.\n *\n * @returns Connection configuration of tedious for the SQL.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when SQL config resource configuration is invalid.\n * @throws {@link ErrorCode|InternalError} when get user MSI token failed or MSI token is invalid.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\nexport async function getTediousConnectionConfig(\n teamsfx: TeamsFx,\n databaseName?: string\n): Promise<ConnectionConfig> {\n internalLogger.info(\"Get SQL configuration\");\n\n try {\n isSQLConfigurationValid(teamsfx);\n } catch (err) {\n throw err;\n }\n\n if (databaseName === \"\") {\n internalLogger.warn(`SQL database name is empty string`);\n }\n const dbName: string | undefined =\n databaseName ??\n (teamsfx.hasConfig(\"sqlDatabaseName\") ? teamsfx.getConfig(\"sqlDatabaseName\") : undefined);\n if (!isMsiAuthentication(teamsfx)) {\n const configWithUPS = generateDefaultConfig(teamsfx, dbName);\n internalLogger.verbose(\"SQL configuration with username and password generated\");\n return configWithUPS;\n }\n\n try {\n const configWithToken = await generateTokenConfig(teamsfx, dbName);\n internalLogger.verbose(\"SQL configuration with MSI token generated\");\n return configWithToken;\n } catch (error) {\n throw error;\n }\n}\n\n/**\n * check configuration is an available configurations.\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n *\n * @returns true - SQL configuration has a valid SQL endpoints, SQL username with password or identity ID.\n * false - configuration is not valid.\n * @internal\n */\nfunction isSQLConfigurationValid(teamsfx: TeamsFx) {\n internalLogger.verbose(\"Check SQL configuration if valid\");\n if (!teamsfx.hasConfig(\"sqlServerEndpoint\")) {\n internalLogger.error(\"SQL configuration is not valid without SQL server endpoint exist\");\n throw new ErrorWithCode(\n \"SQL configuration error without SQL server endpoint exist\",\n ErrorCode.InvalidConfiguration\n );\n }\n if (\n !(teamsfx.hasConfig(\"sqlUsername\") && teamsfx.hasConfig(\"sqlPassword\")) &&\n !teamsfx.hasConfig(\"sqlIdentityId\")\n ) {\n const errMsg = `SQL configuration is not valid without ${\n teamsfx.hasConfig(\"sqlIdentityId\") ? \"\" : \"identity id \"\n } ${teamsfx.hasConfig(\"sqlUsername\") ? \"\" : \"SQL username \"} ${\n teamsfx.hasConfig(\"sqlPassword\") ? \"\" : \"SQL password\"\n } exist`;\n internalLogger.error(errMsg);\n throw new ErrorWithCode(errMsg, ErrorCode.InvalidConfiguration);\n }\n internalLogger.verbose(\"SQL configuration is valid\");\n}\n\n/**\n * Check SQL use MSI identity or username and password.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n *\n * @returns false - login with SQL MSI identity, true - login with username and password.\n * @internal\n */\nfunction isMsiAuthentication(teamsfx: TeamsFx): boolean {\n internalLogger.verbose(\"Check connection config using MSI access token or username and password\");\n if (teamsfx.hasConfig(\"sqlUsername\") && teamsfx.hasConfig(\"sqlPassword\")) {\n internalLogger.verbose(\"Login with username and password\");\n return false;\n }\n internalLogger.verbose(\"Login with MSI identity\");\n return true;\n}\n\n/**\n * Generate tedious connection configuration with default authentication type.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n * @param { string? } databaseName - specify database name to override default one if there are multiple databases.\n *\n * @returns Tedious connection configuration with username and password.\n * @internal\n */\nfunction generateDefaultConfig(teamsfx: TeamsFx, databaseName?: string): ConnectionConfig {\n internalLogger.verbose(\n `SQL server ${teamsfx.getConfig(\"sqlServerEndpoint\")}\n , user name ${teamsfx.getConfig(\"sqlUsername\")}\n , database name ${databaseName ? databaseName : \"\"}`\n );\n\n const config = {\n server: teamsfx.getConfig(\"sqlServerEndpoint\"),\n authentication: {\n type: TediousAuthenticationType.default,\n options: {\n userName: teamsfx.getConfig(\"sqlUsername\"),\n password: teamsfx.getConfig(\"sqlPassword\"),\n },\n },\n options: {\n database: databaseName,\n encrypt: true,\n },\n };\n return config;\n}\n\n/**\n * Generate tedious connection configuration with azure-active-directory-access-token authentication type.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n *\n * @returns Tedious connection configuration with access token.\n * @internal\n */\nasync function generateTokenConfig(\n teamsfx: TeamsFx,\n databaseName?: string\n): Promise<ConnectionConfig> {\n internalLogger.verbose(\"Generate tedious config with MSI token\");\n let token: AccessToken | null;\n try {\n const credential = new ManagedIdentityCredential(teamsfx.getConfig(\"sqlIdentityId\"));\n token = await credential.getToken(defaultSQLScope);\n } catch (error) {\n const errMsg = \"Get user MSI token failed\";\n internalLogger.error(errMsg);\n throw new ErrorWithCode(errMsg, ErrorCode.InternalError);\n }\n if (token) {\n const config = {\n server: teamsfx.getConfig(\"sqlServerEndpoint\"),\n authentication: {\n type: TediousAuthenticationType.MSI,\n options: {\n token: token.token,\n },\n },\n options: {\n database: databaseName,\n encrypt: true,\n },\n };\n internalLogger.verbose(\n `Generate token configuration success\n , server endpoint is ${teamsfx.getConfig(\"sqlServerEndpoint\")}\n , database name is ${databaseName ? databaseName : \"\"}`\n );\n return config;\n }\n internalLogger.error(\n `Generate token configuration\n , server endpoint is ${teamsfx.getConfig(\"sqlServerEndpoint\")}\n , MSI token is not valid`\n );\n throw new ErrorWithCode(\"MSI token is not valid\", ErrorCode.InternalError);\n}\n\n/**\n * tedious connection config authentication type.\n * https://tediousjs.github.io/tedious/api-connection.html\n * @internal\n */\nenum TediousAuthenticationType {\n default = \"default\",\n MSI = \"azure-active-directory-access-token\",\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Identity type to use in authentication.\n */\nexport enum IdentityType {\n /**\n * Represents the current user of Teams.\n */\n User = \"User\",\n /**\n * Represents the application itself.\n */\n App = \"Application\",\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken } from \"@azure/identity\";\nimport {\n Activity,\n ActivityTypes,\n CardFactory,\n Channels,\n MessageFactory,\n TurnContext,\n OAuthCard,\n ActionTypes,\n verifyStateOperationName,\n StatusCodes,\n TokenExchangeInvokeRequest,\n tokenExchangeOperationName,\n TokenExchangeResource,\n TeamsInfo,\n TeamsChannelAccount,\n} from \"botbuilder\";\nimport {\n Dialog,\n DialogContext,\n DialogTurnResult,\n PromptOptions,\n PromptRecognizerResult,\n} from \"botbuilder-dialogs\";\nimport { TeamsBotSsoPromptTokenResponse } from \"./teamsBotSsoPromptTokenResponse\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport { validateScopesType, formatString, parseJwt } from \"../util/utils\";\nimport { TeamsFx } from \"../core/teamsfx\";\nimport { IdentityType } from \"../models/identityType\";\nimport { OnBehalfOfCredentialAuthConfig } from \"../models/configuration\";\nimport { OnBehalfOfUserCredential } from \"../credential/onBehalfOfUserCredential\";\n\nconst invokeResponseType = \"invokeResponse\";\n/**\n * Response body returned for a token exchange invoke activity.\n */\nclass TokenExchangeInvokeResponse {\n /**\n * Response id\n */\n id: string;\n\n /**\n * Detailed error message\n */\n failureDetail: string;\n\n constructor(id: string, failureDetail: string) {\n this.id = id;\n this.failureDetail = failureDetail;\n }\n}\n\n/**\n * Settings used to configure an TeamsBotSsoPrompt instance.\n */\nexport interface TeamsBotSsoPromptSettings {\n /**\n * The array of strings that declare the desired permissions and the resources requested.\n */\n scopes: string[];\n\n /**\n * (Optional) number of milliseconds the prompt will wait for the user to authenticate.\n * Defaults to a value `900,000` (15 minutes.)\n */\n timeout?: number;\n\n /**\n * (Optional) value indicating whether the TeamsBotSsoPrompt should end upon receiving an\n * invalid message. Generally the TeamsBotSsoPrompt will end the auth flow when receives user\n * message not related to the auth flow. Setting the flag to false ignores the user's message instead.\n * Defaults to value `true`\n */\n endOnInvalidMessage?: boolean;\n}\n\n/**\n * Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and\n * help receive oauth token, asks the user to consent if needed.\n *\n * @remarks\n * The prompt will attempt to retrieve the users current token of the desired scopes and store it in\n * the token store.\n *\n * User will be automatically signed in leveraging Teams support of Bot Single Sign On(SSO):\n * https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots\n *\n * @example\n * When used with your bots `DialogSet` you can simply add a new instance of the prompt as a named\n * dialog using `DialogSet.add()`. You can then start the prompt from a waterfall step using either\n * `DialogContext.beginDialog()` or `DialogContext.prompt()`. The user will be prompted to sign in as\n * needed and their access token will be passed as an argument to the callers next waterfall step:\n *\n * ```JavaScript\n * const { ConversationState, MemoryStorage } = require('botbuilder');\n * const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');\n * const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx');\n *\n * const convoState = new ConversationState(new MemoryStorage());\n * const dialogState = convoState.createProperty('dialogState');\n * const dialogs = new DialogSet(dialogState);\n *\n * dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {\n * scopes: [\"User.Read\"],\n * }));\n *\n * dialogs.add(new WaterfallDialog('taskNeedingLogin', [\n * async (step) => {\n * return await step.beginDialog('TeamsBotSsoPrompt');\n * },\n * async (step) => {\n * const token = step.result;\n * if (token) {\n *\n * // ... continue with task needing access token ...\n *\n * } else {\n * await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);\n * return await step.endDialog();\n * }\n * }\n * ]));\n * ```\n */\nexport class TeamsBotSsoPrompt extends Dialog {\n private authConfig: OnBehalfOfCredentialAuthConfig;\n private initiateLoginEndpoint: string;\n private settings: TeamsBotSsoPromptSettings;\n /**\n * Constructor of TeamsBotSsoPrompt.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n * @param {string} dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.\n * @param {TeamsBotSsoPromptSettings} settings Settings used to configure the prompt.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(teamsfx: TeamsFx, dialogId: string, settings: TeamsBotSsoPromptSettings);\n /**\n * Constructor of TeamsBotSsoPrompt.\n *\n * @param {OnBehalfOfCredentialAuthConfig} authConfig - Used to provide configuration and auth\n * @param {string} initiateLoginEndpoint - Login URL for Teams to redirect to\n * @param {string} dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.\n * @param {TeamsBotSsoPromptSettings} settings Settings used to configure the prompt.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n dialogId: string,\n settings: TeamsBotSsoPromptSettings\n );\n constructor(authConfig: TeamsFx | OnBehalfOfCredentialAuthConfig, ...args: any) {\n super(arguments.length === 3 ? args[0] : args[1]);\n if ((authConfig as TeamsFx).getCredential) {\n const teamsfx = authConfig as TeamsFx;\n this.authConfig = this.loadAndValidateConfig(teamsfx);\n this.initiateLoginEndpoint = teamsfx.getConfig(\"initiateLoginEndpoint\");\n this.settings = args[1] as TeamsBotSsoPromptSettings;\n } else {\n this.initiateLoginEndpoint = args[0];\n this.authConfig = authConfig as OnBehalfOfCredentialAuthConfig;\n this.settings = args[2] as TeamsBotSsoPromptSettings;\n }\n\n validateScopesType(this.settings.scopes);\n\n internalLogger.info(\"Create a new Teams Bot SSO Prompt\");\n }\n\n /**\n * Called when a prompt dialog is pushed onto the dialog stack and is being activated.\n * @remarks\n * If the task is successful, the result indicates whether the prompt is still\n * active after the turn has been processed by the prompt.\n *\n * @param dc The DialogContext for the current turn of the conversation.\n *\n * @throws {@link ErrorCode|InvalidParameter} when timeout property in teams bot sso prompt settings is not number or is not positive.\n * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n *\n * @returns A `Promise` representing the asynchronous operation.\n */\n public async beginDialog(dc: DialogContext): Promise<DialogTurnResult> {\n internalLogger.info(\"Begin Teams Bot SSO Prompt\");\n this.ensureMsTeamsChannel(dc);\n\n // Initialize prompt state\n const default_timeout = 900000;\n let timeout: number = default_timeout;\n if (this.settings.timeout) {\n if (typeof this.settings.timeout != \"number\") {\n const errorMsg = \"type of timeout property in teamsBotSsoPromptSettings should be number.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n if (this.settings.timeout <= 0) {\n const errorMsg =\n \"value of timeout property in teamsBotSsoPromptSettings should be positive.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n timeout = this.settings.timeout;\n }\n\n if (this.settings.endOnInvalidMessage === undefined) {\n this.settings.endOnInvalidMessage = true;\n }\n const state: teamsBotSsoPromptState = dc.activeDialog?.state as teamsBotSsoPromptState;\n state.state = {};\n state.options = {};\n state.expires = new Date().getTime() + timeout;\n\n // Send OAuth card to get SSO token\n await this.sendOAuthCardAsync(dc.context);\n return Dialog.EndOfTurn;\n }\n\n /**\n * Called when a prompt dialog is the active dialog and the user replied with a new activity.\n *\n * @remarks\n * If the task is successful, the result indicates whether the dialog is still\n * active after the turn has been processed by the dialog.\n * The prompt generally continues to receive the user's replies until it accepts the\n * user's reply as valid input for the prompt.\n *\n * @param dc The DialogContext for the current turn of the conversation.\n *\n * @returns A `Promise` representing the asynchronous operation.\n *\n * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n public async continueDialog(dc: DialogContext): Promise<DialogTurnResult> {\n internalLogger.info(\"Continue Teams Bot SSO Prompt\");\n this.ensureMsTeamsChannel(dc);\n\n // Check for timeout\n const state: teamsBotSsoPromptState = dc.activeDialog?.state as teamsBotSsoPromptState;\n const isMessage: boolean = dc.context.activity.type === ActivityTypes.Message;\n const isTimeoutActivityType: boolean =\n isMessage ||\n this.isTeamsVerificationInvoke(dc.context) ||\n this.isTokenExchangeRequestInvoke(dc.context);\n\n // If the incoming Activity is a message, or an Activity Type normally handled by TeamsBotSsoPrompt,\n // check to see if this TeamsBotSsoPrompt Expiration has elapsed, and end the dialog if so.\n const hasTimedOut: boolean = isTimeoutActivityType && new Date().getTime() > state.expires;\n if (hasTimedOut) {\n internalLogger.warn(\"End Teams Bot SSO Prompt due to timeout\");\n return await dc.endDialog(undefined);\n } else {\n if (\n this.isTeamsVerificationInvoke(dc.context) ||\n this.isTokenExchangeRequestInvoke(dc.context)\n ) {\n // Recognize token\n const recognized: PromptRecognizerResult<TeamsBotSsoPromptTokenResponse> =\n await this.recognizeToken(dc);\n\n if (recognized.succeeded) {\n return await dc.endDialog(recognized.value);\n }\n } else if (isMessage && this.settings.endOnInvalidMessage) {\n internalLogger.warn(\"End Teams Bot SSO Prompt due to invalid message\");\n return await dc.endDialog(undefined);\n }\n\n return Dialog.EndOfTurn;\n }\n }\n\n private loadAndValidateConfig(teamsfx: TeamsFx): OnBehalfOfCredentialAuthConfig {\n if (teamsfx.getIdentityType() !== IdentityType.User) {\n const errorMsg = formatString(\n ErrorMessage.IdentityTypeNotSupported,\n teamsfx.getIdentityType().toString(),\n \"TeamsBotSsoPrompt\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.IdentityTypeNotSupported);\n }\n\n const missingConfigurations: string[] = [];\n\n if (!teamsfx.hasConfig(\"initiateLoginEndpoint\")) {\n missingConfigurations.push(\"initiateLoginEndpoint\");\n }\n\n if (!teamsfx.hasConfig(\"clientId\")) {\n missingConfigurations.push(\"clientId\");\n }\n\n if (!teamsfx.hasConfig(\"tenantId\")) {\n missingConfigurations.push(\"tenantId\");\n }\n\n if (missingConfigurations.length != 0) {\n const errorMsg = formatString(\n ErrorMessage.InvalidConfiguration,\n missingConfigurations.join(\", \"),\n \"undefined\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);\n }\n\n let authConfig: OnBehalfOfCredentialAuthConfig;\n if (teamsfx.getConfig(\"clientSecret\")) {\n authConfig = {\n authorityHost: teamsfx.getConfig(\"authorityHost\"),\n clientId: teamsfx.getConfig(\"clientId\"),\n tenantId: teamsfx.getConfig(\"tenantId\"),\n clientSecret: teamsfx.getConfig(\"clientSecret\"),\n };\n } else {\n authConfig = {\n authorityHost: teamsfx.getConfig(\"authorityHost\"),\n clientId: teamsfx.getConfig(\"clientId\"),\n tenantId: teamsfx.getConfig(\"tenantId\"),\n certificateContent: teamsfx.getConfig(\"certificateContent\"),\n };\n }\n return authConfig;\n }\n\n /**\n * Ensure bot is running in MS Teams since TeamsBotSsoPrompt is only supported in MS Teams channel.\n * @param dc dialog context\n * @throws {@link ErrorCode|ChannelNotSupported} if bot channel is not MS Teams\n * @internal\n */\n private ensureMsTeamsChannel(dc: DialogContext) {\n if (dc.context.activity.channelId != Channels.Msteams) {\n const errorMsg = formatString(\n ErrorMessage.OnlyMSTeamsChannelSupported,\n \"Teams Bot SSO Prompt\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.ChannelNotSupported);\n }\n }\n\n /**\n * Send OAuthCard that tells Teams to obtain an authentication token for the bot application.\n * For details see https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots.\n *\n * @internal\n */\n private async sendOAuthCardAsync(context: TurnContext): Promise<void> {\n internalLogger.verbose(\"Send OAuth card to get SSO token\");\n\n const account: TeamsChannelAccount = await TeamsInfo.getMember(\n context,\n context.activity.from.id\n );\n internalLogger.verbose(\n \"Get Teams member account user principal name: \" +\n (account.userPrincipalName ? account.userPrincipalName : \"\")\n );\n\n const loginHint: string = account.userPrincipalName ? account.userPrincipalName : \"\";\n const signInResource = this.getSignInResource(loginHint);\n const card = CardFactory.oauthCard(\n \"\",\n \"Teams SSO Sign In\",\n \"Sign In\",\n signInResource.signInLink,\n signInResource.tokenExchangeResource\n );\n (card.content as OAuthCard).buttons[0].type = ActionTypes.Signin;\n const msg: Partial<Activity> = MessageFactory.attachment(card);\n\n // Send prompt\n await context.sendActivity(msg);\n }\n\n /**\n * Get sign in resource.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} if client id, tenant id or initiate login endpoint is not found in config.\n *\n * @internal\n */\n private getSignInResource(loginHint: string) {\n internalLogger.verbose(\"Get sign in authentication configuration\");\n\n const signInLink = `${this.initiateLoginEndpoint}?scope=${encodeURI(\n this.settings.scopes.join(\" \")\n )}&clientId=${this.authConfig.clientId}&tenantId=${\n this.authConfig.tenantId\n }&loginHint=${loginHint}`;\n\n internalLogger.verbose(\"Sign in link: \" + signInLink);\n\n const tokenExchangeResource: TokenExchangeResource = {\n id: uuidv4(),\n };\n\n return {\n signInLink: signInLink,\n tokenExchangeResource: tokenExchangeResource,\n };\n }\n\n /**\n * @internal\n */\n private async recognizeToken(\n dc: DialogContext\n ): Promise<PromptRecognizerResult<TeamsBotSsoPromptTokenResponse>> {\n const context = dc.context;\n let tokenResponse: TeamsBotSsoPromptTokenResponse | undefined;\n\n if (this.isTokenExchangeRequestInvoke(context)) {\n internalLogger.verbose(\"Receive token exchange request\");\n // Received activity is not a token exchange request\n if (!(context.activity.value && this.isTokenExchangeRequest(context.activity.value))) {\n const warningMsg =\n \"The bot received an InvokeActivity that is missing a TokenExchangeInvokeRequest value. This is required to be sent with the InvokeActivity.\";\n\n internalLogger.warn(warningMsg);\n await context.sendActivity(\n this.getTokenExchangeInvokeResponse(StatusCodes.BAD_REQUEST, warningMsg)\n );\n } else {\n const ssoToken = context.activity.value.token;\n const credential = new OnBehalfOfUserCredential(ssoToken, this.authConfig);\n let exchangedToken: AccessToken | null;\n try {\n exchangedToken = await credential.getToken(this.settings.scopes);\n\n if (exchangedToken) {\n await context.sendActivity(\n this.getTokenExchangeInvokeResponse(StatusCodes.OK, \"\", context.activity.value.id)\n );\n\n const ssoTokenExpiration = parseJwt(ssoToken).exp;\n tokenResponse = {\n ssoToken: ssoToken,\n ssoTokenExpiration: new Date(ssoTokenExpiration * 1000).toISOString(),\n connectionName: \"\",\n token: exchangedToken.token,\n expiration: exchangedToken.expiresOnTimestamp.toString(),\n };\n }\n } catch (error) {\n const warningMsg = \"The bot is unable to exchange token. Ask for user consent.\";\n internalLogger.info(warningMsg);\n await context.sendActivity(\n this.getTokenExchangeInvokeResponse(\n StatusCodes.PRECONDITION_FAILED,\n warningMsg,\n context.activity.value.id\n )\n );\n }\n }\n } else if (this.isTeamsVerificationInvoke(context)) {\n internalLogger.verbose(\"Receive Teams state verification request\");\n await this.sendOAuthCardAsync(dc.context);\n await context.sendActivity({ type: invokeResponseType, value: { status: StatusCodes.OK } });\n }\n\n return tokenResponse !== undefined\n ? { succeeded: true, value: tokenResponse }\n : { succeeded: false };\n }\n\n /**\n * @internal\n */\n private getTokenExchangeInvokeResponse(\n status: number,\n failureDetail: string,\n id?: string\n ): Activity {\n const invokeResponse: Partial<Activity> = {\n type: invokeResponseType,\n value: { status, body: new TokenExchangeInvokeResponse(id as string, failureDetail) },\n };\n return invokeResponse as Activity;\n }\n\n /**\n * @internal\n */\n private isTeamsVerificationInvoke(context: TurnContext): boolean {\n const activity: Activity = context.activity;\n\n return activity.type === ActivityTypes.Invoke && activity.name === verifyStateOperationName;\n }\n\n /**\n * @internal\n */\n private isTokenExchangeRequestInvoke(context: TurnContext): boolean {\n const activity: Activity = context.activity;\n\n return activity.type === ActivityTypes.Invoke && activity.name === tokenExchangeOperationName;\n }\n\n /**\n * @internal\n */\n private isTokenExchangeRequest(obj: any): obj is TokenExchangeInvokeRequest {\n return obj.hasOwnProperty(\"token\");\n }\n}\n\n/**\n * @internal\n */\ninterface teamsBotSsoPromptState {\n state: any;\n options: PromptOptions;\n expires: number; // Timestamp of when the prompt will timeout.\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport axios, { AxiosInstance, InternalAxiosRequestConfig } from \"axios\";\nimport { AuthProvider } from \"./authProvider\";\n\n/**\n * Initializes new Axios instance with specific auth provider\n *\n * @param apiEndpoint - Base url of the API\n * @param authProvider - Auth provider that injects authentication info to each request\n * @returns axios instance configured with specfic auth provider\n *\n * @example\n * ```typescript\n * const client = createApiClient(\"https://my-api-endpoint-base-url\", new BasicAuthProvider(\"xxx\",\"xxx\"));\n * ```\n */\nexport function createApiClient(apiEndpoint: string, authProvider: AuthProvider): AxiosInstance {\n // Add a request interceptor\n const instance = axios.create({\n baseURL: apiEndpoint,\n });\n instance.interceptors.request.use(async function (config) {\n return (await authProvider.AddAuthenticationInfo(\n config\n )) as Promise<InternalAxiosRequestConfig>;\n });\n return instance;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AxiosRequestConfig } from \"axios\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { AuthProvider } from \"./authProvider\";\n\n/**\n * Provider that handles Bearer Token authentication\n */\nexport class BearerTokenAuthProvider implements AuthProvider {\n private getToken: () => Promise<string>;\n\n /**\n * @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request\n */\n constructor(getToken: () => Promise<string>) {\n this.getToken = getToken;\n }\n\n /**\n * Adds authentication info to http requests\n *\n * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.\n * Refer https://axios-http.com/docs/req_config for detailed document.\n *\n * @returns Updated axios request config.\n *\n * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.\n */\n public async AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n const token = await this.getToken();\n if (!config.headers) {\n config.headers = {};\n }\n if (config.headers[\"Authorization\"]) {\n throw new ErrorWithCode(\n ErrorMessage.AuthorizationHeaderAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n );\n }\n\n config.headers[\"Authorization\"] = `Bearer ${token}`;\n return config;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AxiosRequestConfig } from \"axios\";\nimport { AuthProvider } from \"./authProvider\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Provider that handles Basic authentication\n */\nexport class BasicAuthProvider implements AuthProvider {\n private userName: string;\n private password: string;\n\n /**\n *\n * @param { string } userName - Username used in basic auth\n * @param { string } password - Password used in basic auth\n *\n * @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(userName: string, password: string) {\n if (!userName) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"username\"),\n ErrorCode.InvalidParameter\n );\n }\n if (!password) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"password\"),\n ErrorCode.InvalidParameter\n );\n }\n this.userName = userName;\n this.password = password;\n }\n\n /**\n * Adds authentication info to http requests\n *\n * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.\n * Refer https://axios-http.com/docs/req_config for detailed document.\n *\n * @returns Updated axios request config.\n *\n * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n public AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n if (config.headers && config.headers[\"Authorization\"]) {\n return Promise.reject(\n new ErrorWithCode(\n ErrorMessage.AuthorizationHeaderAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n )\n );\n }\n if (config.auth) {\n return Promise.reject(\n new ErrorWithCode(\n ErrorMessage.BasicCredentialAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n )\n );\n }\n\n config.auth = {\n username: this.userName,\n password: this.password,\n };\n\n return Promise.resolve(config);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AxiosRequestConfig } from \"axios\";\nimport { AuthProvider } from \"./authProvider\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Provider that handles API Key authentication\n */\nexport class ApiKeyProvider implements AuthProvider {\n private keyName: string;\n private keyValue: string;\n private keyLocation: ApiKeyLocation;\n\n /**\n *\n * @param { string } keyName - The name of request header or query parameter that specifies API Key\n * @param { string } keyValue - The value of API Key\n * @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.\n *\n * @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(keyName: string, keyValue: string, keyLocation: ApiKeyLocation) {\n if (!keyName) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"keyName\"),\n ErrorCode.InvalidParameter\n );\n }\n if (!keyValue) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"keyVaule\"),\n ErrorCode.InvalidParameter\n );\n }\n this.keyName = keyName;\n this.keyValue = keyValue;\n this.keyLocation = keyLocation;\n }\n\n /**\n * Adds authentication info to http requests\n *\n * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.\n * Refer https://axios-http.com/docs/req_config for detailed document.\n *\n * @returns Updated axios request config.\n *\n * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n public AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n switch (this.keyLocation) {\n case ApiKeyLocation.Header:\n if (!config.headers) {\n config.headers = {};\n }\n if (config.headers[this.keyName]) {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.DuplicateApiKeyInHeader, this.keyName),\n ErrorCode.AuthorizationInfoAlreadyExists\n )\n );\n }\n config.headers[this.keyName] = this.keyValue;\n break;\n case ApiKeyLocation.QueryParams:\n if (!config.params) {\n config.params = {};\n }\n let urlHasDefinedApiKey = false;\n if (config.url) {\n const url = new URL(config.url, config.baseURL);\n urlHasDefinedApiKey = url.searchParams.has(this.keyName);\n }\n if (config.params[this.keyName] || urlHasDefinedApiKey) {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.DuplicateApiKeyInQueryParam, this.keyName),\n ErrorCode.AuthorizationInfoAlreadyExists\n )\n );\n }\n config.params[this.keyName] = this.keyValue;\n break;\n }\n\n return Promise.resolve(config);\n }\n}\n\n/**\n * Define available location for API Key location\n */\nexport enum ApiKeyLocation {\n /**\n * The API Key is placed in request header\n */\n Header,\n /**\n * The API Key is placed in query parameter\n */\n QueryParams,\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AxiosRequestConfig } from \"axios\";\nimport { Agent } from \"https\";\nimport { SecureContextOptions } from \"tls\";\nimport { AuthProvider } from \"./authProvider\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Provider that handles Certificate authentication\n */\n\nexport class CertificateAuthProvider implements AuthProvider {\n private certOption: SecureContextOptions;\n\n /**\n *\n * @param { SecureContextOptions } certOption - information about the cert used in http requests\n *\n * @throws {@link ErrorCode|InvalidParameter} - when cert option is empty.\n */\n constructor(certOption: SecureContextOptions) {\n if (certOption && Object.keys(certOption).length !== 0) {\n this.certOption = certOption;\n } else {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"certOption\"),\n ErrorCode.InvalidParameter\n );\n }\n }\n\n /**\n * Adds authentication info to http requests.\n *\n * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.\n * Refer https://axios-http.com/docs/req_config for detailed document.\n *\n * @returns Updated axios request config.\n *\n * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.\n */\n public AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n if (!config.httpsAgent) {\n config.httpsAgent = new Agent(this.certOption);\n } else {\n const existingProperties = new Set(Object.keys(config.httpsAgent.options));\n for (const property of Object.keys(this.certOption)) {\n if (existingProperties.has(property)) {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.DuplicateHttpsOptionProperty, property),\n ErrorCode.InvalidParameter\n )\n );\n }\n }\n Object.assign(config.httpsAgent.options, this.certOption);\n }\n return Promise.resolve(config);\n }\n}\n\n/**\n * Helper to create SecureContextOptions from PEM format cert\n *\n * @param { string | Buffer } cert - The cert chain in PEM format\n * @param { string | Buffer } key - The private key for the cert chain\n * @param { {passphrase?: string; ca?: string | Buffer} } options - Optional settings when create the cert options.\n *\n * @returns Instance of SecureContextOptions\n *\n * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty\n *\n */\nexport function createPemCertOption(\n cert: string | Buffer,\n key: string | Buffer,\n options?: {\n passphrase?: string;\n ca?: string | Buffer;\n }\n): SecureContextOptions {\n if (cert.length === 0) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"cert\"),\n ErrorCode.InvalidParameter\n );\n }\n if (key.length === 0) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"key\"),\n ErrorCode.InvalidParameter\n );\n }\n\n return {\n cert,\n key,\n passphrase: options?.passphrase,\n ca: options?.ca,\n };\n}\n\n/**\n * Helper to create SecureContextOptions from PFX format cert\n *\n * @param { string | Buffer } pfx - The content of .pfx file\n * @param { {passphrase?: string} } options - Optional settings when create the cert options.\n *\n * @returns Instance of SecureContextOptions\n *\n * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty\n *\n */\nexport function createPfxCertOption(\n pfx: string | Buffer,\n options?: {\n passphrase?: string;\n }\n): SecureContextOptions {\n if (pfx.length === 0) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"pfx\"),\n ErrorCode.InvalidParameter\n );\n }\n\n return {\n pfx,\n passphrase: options?.passphrase,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TokenCredential } from \"@azure/identity\";\nimport { AppCredential } from \"../credential/appCredential\";\nimport { OnBehalfOfUserCredential } from \"../credential/onBehalfOfUserCredential\";\nimport { IdentityType } from \"../models/identityType\";\nimport { UserInfo } from \"../models/userinfo\";\nimport { formatString } from \"../util/utils\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport { TeamsFxConfiguration } from \"../models/teamsfxConfiguration\";\nimport { AuthenticationConfiguration } from \"../models/configuration\";\n\n// Following keys are used by SDK internally\nconst ReservedKey: Set<string> = new Set<string>([\n \"authorityHost\",\n \"tenantId\",\n \"clientId\",\n \"clientSecret\",\n \"initiateLoginEndpoint\",\n \"applicationIdUri\",\n \"apiEndpoint\",\n \"apiName\",\n \"sqlServerEndpoint\",\n \"sqlUsername\",\n \"sqlPassword\",\n \"sqlDatabaseName\",\n \"sqlIdentityId\",\n]);\n\n/**\n * A class providing credential and configuration.\n * @deprecated Please use {@link TeamsUserCredential}\n * in browser environment and {@link OnBehalfOfUserCredential} or {@link AppCredential} in NodeJS.\n */\nexport class TeamsFx implements TeamsFxConfiguration {\n private configuration: Map<string, string | undefined>;\n private oboUserCredential?: OnBehalfOfUserCredential;\n private appCredential?: AppCredential;\n private identityType: IdentityType;\n\n /**\n * Constructor of TeamsFx\n *\n * @param {IdentityType} identityType - Choose user or app identity\n * @param customConfig - key/value pairs of customized configuration that overrides default ones.\n *\n * @throws {@link ErrorCode|IdentityTypeNotSupported} when setting app identity in browser.\n */\n constructor(\n identityType?: IdentityType,\n customConfig?: Record<string, string> | AuthenticationConfiguration\n ) {\n this.identityType = identityType ?? IdentityType.User;\n this.configuration = new Map<string, string>();\n this.loadFromEnv();\n if (customConfig) {\n const myConfig: Record<string, string> = { ...customConfig };\n for (const key of Object.keys(myConfig)) {\n const value = myConfig[key];\n if (value) {\n this.configuration.set(key, value);\n }\n }\n }\n }\n\n /**\n * Identity type set by user.\n *\n * @returns identity type.\n */\n getIdentityType(): IdentityType {\n return this.identityType;\n }\n\n /**\n * Credential instance according to identity type choice.\n *\n * @remarks If user identity is chose, will return {@link TeamsUserCredential}\n * in browser environment and {@link OnBehalfOfUserCredential} in NodeJS. If app\n * identity is chose, will return {@link AppCredential}.\n *\n * @returns instance implements TokenCredential interface.\n */\n public getCredential(): TokenCredential {\n if (this.identityType === IdentityType.User) {\n if (this.oboUserCredential) {\n return this.oboUserCredential;\n }\n const errorMsg = \"SSO token is required to user identity. Please use setSsoToken().\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n } else {\n if (!this.appCredential) {\n this.appCredential = new AppCredential(Object.fromEntries(this.configuration));\n }\n return this.appCredential;\n }\n }\n\n /**\n * Get user information.\n * @param {string[]} resources - The optional list of resources for full trust Teams apps.\n * @returns UserInfo object.\n */\n public async getUserInfo(resources?: string[]): Promise<UserInfo> {\n if (this.identityType !== IdentityType.User) {\n const errorMsg = formatString(\n ErrorMessage.IdentityTypeNotSupported,\n this.identityType.toString(),\n \"TeamsFx\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.IdentityTypeNotSupported);\n }\n return Promise.resolve((this.getCredential() as OnBehalfOfUserCredential).getUserInfo());\n }\n\n /**\n * Popup login page to get user's access token with specific scopes.\n *\n * @remarks\n * Only works in Teams client APP. User will be redirected to the authorization page to login and consent.\n *\n * @example\n * ```typescript\n * await teamsfx.login([\"https://graph.microsoft.com/User.Read\"]); // single scope using string array\n * await teamsfx.login(\"https://graph.microsoft.com/User.Read\"); // single scopes using string\n * await teamsfx.login([\"https://graph.microsoft.com/User.Read\", \"Calendars.Read\"]); // multiple scopes using string array\n * await teamsfx.login(\"https://graph.microsoft.com/User.Read Calendars.Read\"); // multiple scopes using string\n * ```\n * @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.\n * @param {string[]} resources - The optional list of resources for full trust Teams apps.\n *\n * @throws {@link ErrorCode|InternalError} when failed to login with unknown error.\n * @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n */\n public async login(scopes: string | string[], resources?: string[]): Promise<void> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"login\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Set SSO token when using user identity in NodeJS.\n * @param {string} ssoToken - used for on behalf of user flow.\n * @returns self instance.\n */\n public setSsoToken(ssoToken: string): TeamsFx {\n if (this.identityType !== IdentityType.User) {\n throw new Error();\n }\n this.oboUserCredential = new OnBehalfOfUserCredential(\n ssoToken,\n Object.fromEntries(this.configuration)\n );\n return this;\n }\n\n /**\n * Usually used by service plugins to retrieve specific config\n * @param {string} key - configuration key.\n * @returns value in configuration.\n */\n public getConfig(key: string): string {\n const value = this.configuration.get(key);\n if (!value) {\n const errorMsg = `Cannot find ${key} in configuration`;\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);\n }\n return value;\n }\n\n /**\n * Check the value of specific key.\n * @param {string} key - configuration key.\n * @returns true if corresponding value is not empty string.\n */\n public hasConfig(key: string): boolean {\n const value = this.configuration.get(key);\n return !!value;\n }\n\n /**\n * Get all configurations.\n * @returns key value mappings.\n */\n public getConfigs(): Record<string, string> {\n const config: Record<string, string> = {};\n for (const key of this.configuration.keys()) {\n const value = this.configuration.get(key);\n if (value) {\n config[key] = value;\n }\n }\n return config;\n }\n\n /**\n * Load configuration from environment variables.\n */\n private loadFromEnv(): void {\n const env = process.env;\n this.configuration.set(\"authorityHost\", env.M365_AUTHORITY_HOST);\n this.configuration.set(\"tenantId\", env.M365_TENANT_ID);\n this.configuration.set(\"clientId\", env.M365_CLIENT_ID);\n this.configuration.set(\"clientSecret\", env.M365_CLIENT_SECRET);\n this.configuration.set(\"initiateLoginEndpoint\", env.INITIATE_LOGIN_ENDPOINT);\n this.configuration.set(\"applicationIdUri\", env.M365_APPLICATION_ID_URI);\n this.configuration.set(\"apiEndpoint\", env.API_ENDPOINT);\n this.configuration.set(\"apiName\", env.API_NAME);\n this.configuration.set(\"sqlServerEndpoint\", env.SQL_ENDPOINT);\n this.configuration.set(\"sqlUsername\", env.SQL_USER_NAME);\n this.configuration.set(\"sqlPassword\", env.SQL_PASSWORD);\n this.configuration.set(\"sqlDatabaseName\", env.SQL_DATABASE_NAME);\n this.configuration.set(\"sqlIdentityId\", env.IDENTITY_ID);\n\n Object.keys(env).forEach((key: string) => {\n if (ReservedKey.has(key)) {\n internalLogger.warn(\n `The name of environment variable ${key} is preserved. Will not load it as configuration.`\n );\n }\n this.configuration.set(key, env[key]);\n });\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n BotFrameworkAdapter,\n ConversationState,\n ConversationReference,\n UserState,\n Activity,\n TurnContext,\n InvokeResponse,\n Storage,\n SigninStateVerificationQuery,\n} from \"botbuilder\";\nimport { TeamsBotSsoPromptTokenResponse } from \"../bot/teamsBotSsoPromptTokenResponse\";\nimport {\n AuthenticationConfiguration,\n OnBehalfOfCredentialAuthConfig,\n} from \"../models/configuration\";\n\n/**\n * The response of a message action, e.g., `sendMessage`, `sendAdaptiveCard`.\n */\nexport interface MessageResponse {\n /**\n * Id of the message.\n */\n id?: string;\n}\n\n/**\n * The target type where the notification will be sent to.\n *\n * @remarks\n * - \"Channel\" means to a team channel. (By default, notification to a team will be sent to its \"General\" channel.)\n * - \"Group\" means to a group chat.\n * - \"Person\" means to a personal chat.\n */\nexport enum NotificationTargetType {\n /**\n * The notification will be sent to a team channel.\n * (By default, notification to a team will be sent to its \"General\" channel.)\n */\n Channel = \"Channel\",\n /**\n * The notification will be sent to a group chat.\n */\n Group = \"Group\",\n /**\n * The notification will be sent to a personal chat.\n */\n Person = \"Person\",\n}\n\n/**\n * Represent a notification target.\n */\nexport interface NotificationTarget {\n /**\n * The type of target, could be \"Channel\" or \"Group\" or \"Person\".\n */\n readonly type?: NotificationTargetType;\n\n /**\n * Send a plain text message.\n *\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns the response of sending message.\n */\n sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse>;\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns the response of sending adaptive card message.\n */\n sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse>;\n}\n\n/**\n * Interface for a storage provider that stores and retrieves notification target references.\n *\n * @deprecated Use ConversationReferenceStore to customize the way\n * to persist bot notification connections instead.\n */\nexport interface NotificationTargetStorage {\n /**\n * Read one notification target by its key.\n *\n * @param key - the key of a notification target.\n *\n * @returns - the notification target. Or undefined if not found.\n */\n read(key: string): Promise<{ [key: string]: unknown } | undefined>;\n\n /**\n * List all stored notification targets.\n *\n * @returns - an array of notification target. Or an empty array if nothing is stored.\n */\n list(): Promise<{ [key: string]: unknown }[]>;\n\n /**\n * Write one notification target by its key.\n *\n * @param key - the key of a notification target.\n * @param object - the notification target.\n */\n write(key: string, object: { [key: string]: unknown }): Promise<void>;\n\n /**\n * Delete one notification target by its key.\n *\n * @param key - the key of a notification target.\n */\n delete(key: string): Promise<void>;\n}\n\n/**\n * Options to initialize {@link NotificationBot}.\n * @deprecated Please use BotBuilderCloudAdapter.NotificationOptions instead.\n */\nexport interface NotificationOptions {\n /**\n * An optional storage to persist bot notification connections.\n *\n * @remarks\n * If `storage` is not provided, a default local file storage will be used,\n * which stores notification connections into:\n * - \".notification.localstore.json\" if running locally\n * - \"${process.env.TEMP}/.notification.localstore.json\" if `process.env.RUNNING_ON_AZURE` is set to \"1\"\n *\n * It's recommended to use your own shared storage for production environment.\n */\n storage?: NotificationTargetStorage;\n}\n\n/**\n * A store to persist notification target references.\n */\nexport interface ConversationReferenceStore {\n /**\n * Add a conversation reference to the store. If overwrite, update existing one, otherwise add when not exist.\n *\n * @param key the key of the conversation reference.\n * @param reference the conversation reference to add.\n * @param options the options to add the conversation reference.\n *\n * @returns true if added or updated, false if not changed.\n */\n add(\n key: string,\n reference: Partial<ConversationReference>,\n options: ConversationReferenceStoreAddOptions\n ): Promise<boolean>;\n\n /**\n * Remove a conversation reference from the store.\n *\n * @param key the key of the conversation reference.\n * @param reference the conversation reference to remove.\n *\n * @returns true if exist and removed, false if not changed.\n */\n remove(key: string, reference: Partial<ConversationReference>): Promise<boolean>;\n\n /**\n * List stored conversation reference by page.\n *\n * @param pageSize the page size.\n * @param continuationToken the continuation token to get next page.\n *\n * @returns a paged list of conversation references.\n */\n list(\n pageSize?: number,\n continuationToken?: string\n ): Promise<PagedData<Partial<ConversationReference>>>;\n}\n\n/**\n * Options to add a conversation reference to the store.\n */\nexport interface ConversationReferenceStoreAddOptions {\n /**\n * Whether to overwrite the existing conversation reference.\n */\n overwrite?: boolean;\n}\n\n/**\n * Represents a page of data.\n */\nexport interface PagedData<T> {\n /**\n * Page of data.\n */\n data: T[];\n\n /**\n * The Continuation Token to pass to get the next page of results.\n *\n * @remarks\n * Undefined or empty token means the page reaches the end.\n */\n continuationToken?: string;\n}\n\n/**\n * The trigger pattern used to trigger a {@link TeamsFxBotCommandHandler} instance.\n */\nexport type TriggerPatterns = string | RegExp | (string | RegExp)[];\n\n/**\n * Interface for a command message that can handled in a command handler.\n */\nexport interface CommandMessage {\n /**\n * Text of the message sent by the user.\n */\n text: string;\n\n /**\n * The capture groups that matched to the {@link TriggerPatterns} in a {@link TeamsFxBotCommandHandler} instance.\n */\n matches?: RegExpMatchArray;\n}\n\n/**\n * Interface for a command handler that can process command to a TeamsFx bot and return a response.\n */\nexport interface TeamsFxBotCommandHandler {\n /**\n * The string or regular expression patterns that can trigger this handler.\n */\n triggerPatterns: TriggerPatterns;\n\n /**\n * Handles a bot command received activity.\n *\n * @param context The bot context.\n * @param message The command message the user types from Teams.\n * @returns A `Promise` representing an activity or text to send as the command response.\n * Or no return value if developers want to send the response activity by themselves in this method.\n */\n handleCommandReceived(\n context: TurnContext,\n message: CommandMessage\n ): Promise<string | Partial<Activity> | void>;\n}\n\n/**\n * Interface for a command handler that can process sso command to a TeamsFx bot and return a response.\n */\nexport interface TeamsFxBotSsoCommandHandler {\n /**\n * The string or regular expression patterns that can trigger this handler.\n */\n triggerPatterns: TriggerPatterns;\n\n /**\n * Handles a bot command received activity.\n *\n * @param context The bot context.\n * @param message The command message the user types from Teams.\n * @param tokenResponse The tokenResponse which contains sso token that can be used to exchange access token for the bot.\n * @returns A `Promise` representing an activity or text to send as the command response.\n * Or no return value if developers want to send the response activity by themselves in this method.\n */\n handleCommandReceived(\n context: TurnContext,\n message: CommandMessage,\n tokenResponse: TeamsBotSsoPromptTokenResponse\n ): Promise<string | Partial<Activity> | void>;\n}\n\n/**\n * Options to initialize {@link CommandBot}.\n */\nexport interface CommandOptions {\n /**\n * The commands to registered with the command bot. Each command should implement the interface {@link TeamsFxBotCommandHandler} so that it can be correctly handled by this command bot.\n */\n commands?: TeamsFxBotCommandHandler[];\n\n /**\n * The commands to registered with the sso command bot. Each sso command should implement the interface {@link TeamsFxBotSsoCommandHandler} so that it can be correctly handled by this command bot.\n */\n ssoCommands?: TeamsFxBotSsoCommandHandler[];\n}\n\n/**\n * Options to initialize {@link CardActionBot}.\n */\nexport interface CardActionOptions {\n /**\n * The action handlers to registered with the action bot. Each command should implement the interface {@link TeamsFxAdaptiveCardActionHandler} so that it can be correctly handled by this bot.\n */\n actions?: TeamsFxAdaptiveCardActionHandler[];\n}\n\n/**\n * Options used to control how the response card will be sent to users.\n */\nexport enum AdaptiveCardResponse {\n /**\n * The response card will be replaced the current one for the interactor who trigger the action.\n */\n ReplaceForInteractor,\n\n /**\n * The response card will be replaced the current one for all users in the chat.\n */\n ReplaceForAll,\n\n /**\n * The response card will be sent as a new message for all users in the chat.\n */\n NewForAll,\n}\n\n/**\n * Status code for an `application/vnd.microsoft.error` invoke response.\n */\nexport enum InvokeResponseErrorCode {\n /**\n * Invalid request.\n */\n BadRequest = 400,\n\n /**\n * Internal server error.\n */\n InternalServerError = 500,\n}\n\n/**\n * Interface for adaptive card action handler that can process card action invoke and return a response.\n */\nexport interface TeamsFxAdaptiveCardActionHandler {\n /**\n * The verb defined in adaptive card action that can trigger this handler.\n * The verb string here is case-insensitive.\n */\n triggerVerb: string;\n\n /**\n * Specify the behavior for how the card response will be sent in Teams conversation.\n * The default value is `AdaptiveCardResponse.ReplaceForInteractor`, which means the card\n * response will replace the current one only for the interactor.\n */\n adaptiveCardResponse?: AdaptiveCardResponse;\n\n /**\n * The handler function that will be invoked when the action is fired.\n * @param context The turn context.\n * @param actionData The contextual data that associated with the action.\n * \n * @returns A `Promise` representing a invoke response for the adaptive card invoke action.\n * You can use the `InvokeResponseFactory` utility class to create an invoke response from\n * - A text message: \n * ```typescript \n * return InvokeResponseFactory.textMessage(\"Action is processed successfully!\");\n * ```\n * - An adaptive card:\n * ```typescript\n * const responseCard = AdaptiveCards.declare(helloWorldCard).render(actionData);\n return InvokeResponseFactory.adaptiveCard(responseCard);\n * ```\n * - An error response:\n * ```typescript\n * return InvokeResponseFactory.errorResponse(InvokeResponseErrorCode.BadRequest, \"Invalid request\");\n * ```\n * \n * @remarks For more details about the invoke response format, refer to https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model#response-format.\n */\n handleActionInvoked(context: TurnContext, actionData: any): Promise<InvokeResponse>;\n}\n\n/**\n * Interface for SSO configuration for Bot SSO\n */\nexport interface BotSsoConfig {\n /**\n * aad related configurations\n */\n aad: {\n /**\n * The list of scopes for which the token will have access\n */\n scopes: string[];\n } & (\n | (OnBehalfOfCredentialAuthConfig & { initiateLoginEndpoint: string })\n | AuthenticationConfiguration\n );\n\n dialog?: {\n /**\n * Custom sso execution activity handler class which should implement the interface {@link BotSsoExecutionActivityHandler}. If not provided, it will use {@link DefaultBotSsoExecutionActivityHandler} by default\n */\n CustomBotSsoExecutionActivityHandler?: new (\n ssoConfig: BotSsoConfig\n ) => BotSsoExecutionActivityHandler;\n\n /**\n * Conversation state for sso command bot, if not provided, it will use internal memory storage to create a new one.\n */\n conversationState?: ConversationState;\n\n /**\n * User state for sso command bot, if not provided, it will use internal memory storage to create a new one.\n */\n userState?: UserState;\n\n /**\n * Used by {@link BotSsoExecutionDialog} to remove duplicated messages, if not provided, it will use internal memory storage\n */\n dedupStorage?: Storage;\n\n /**\n * Settings used to configure an teams sso prompt dialog.\n */\n ssoPromptConfig?: {\n /**\n * Number of milliseconds the prompt will wait for the user to authenticate.\n * Defaults to a value `900,000` (15 minutes.)\n */\n timeout?: number;\n\n /**\n * Value indicating whether the TeamsBotSsoPrompt should end upon receiving an\n * invalid message. Generally the TeamsBotSsoPrompt will end the auth flow when receives user\n * message not related to the auth flow. Setting the flag to false ignores the user's message instead.\n * Defaults to value `true`\n */\n endOnInvalidMessage?: boolean;\n };\n };\n}\n\n/**\n * Options to initialize {@link ConversationBot}\n * @deprecated Please use BotBuilderCloudAdapter.ConversationOptions instead.\n */\nexport interface ConversationOptions {\n /**\n * The bot adapter. If not provided, a default adapter will be created:\n * - with `adapterConfig` as constructor parameter.\n * - with a default error handler that logs error to console, sends trace activity, and sends error message to user.\n *\n * @remarks\n * If neither `adapter` nor `adapterConfig` is provided, will use BOT_ID and BOT_PASSWORD from environment variables.\n */\n adapter?: BotFrameworkAdapter;\n\n /**\n * If `adapter` is not provided, this `adapterConfig` will be passed to the new `BotFrameworkAdapter` when created internally.\n *\n * @remarks\n * If neither `adapter` nor `adapterConfig` is provided, will use BOT_ID and BOT_PASSWORD from environment variables.\n */\n adapterConfig?: { [key: string]: unknown };\n\n /**\n * Configurations for sso command bot\n */\n ssoConfig?: BotSsoConfig;\n\n /**\n * The command part.\n */\n command?: CommandOptions & {\n /**\n * Whether to enable command or not.\n */\n enabled?: boolean;\n };\n\n /**\n * The notification part.\n */\n notification?: NotificationOptions & {\n /**\n * Whether to enable notification or not.\n */\n enabled?: boolean;\n };\n\n /**\n * The adaptive card action handler part.\n */\n cardAction?: CardActionOptions & {\n /**\n * Whether to enable adaptive card actions or not.\n */\n enabled?: boolean;\n };\n}\n\n/**\n * Interface for user to customize SSO execution activity handler\n *\n * @remarks\n * Bot SSO execution activity handler is to handle SSO login process and trigger SSO command using {@link BotSsoExecutionDialog}.\n * You can use this interface to implement your own SSO execution dialog, and pass it to ConversationBot options:\n *\n * ```typescript\n * export const commandBot = new ConversationBot({\n * ...\n * ssoConfig: {\n * ...\n * dialog: {\n * CustomBotSsoExecutionActivityHandler: YourCustomBotSsoExecutionActivityHandler,\n * }\n * },\n * ...\n * });\n * ```\n * For details information about how to implement a BotSsoExecutionActivityHandler, please refer DefaultBotSsoExecutionActivityHandler class source code: https://aka.ms/teamsfx-default-sso-execution-activity-handler\n */\nexport interface BotSsoExecutionActivityHandler {\n /**\n * Add {@link TeamsFxBotSsoCommandHandler} instance to {@link BotSsoExecutionDialog}\n * @param handler {@link BotSsoExecutionDialogHandler} callback function\n * @param triggerPatterns The trigger pattern\n *\n * @remarks\n * This function is used to add SSO command to {@link BotSsoExecutionDialog} instance.\n */\n addCommand(handler: BotSsoExecutionDialogHandler, triggerPatterns: TriggerPatterns): void;\n\n /**\n * Called to initiate the event emission process.\n * @param context The context object for the current turn.\n */\n run(context: TurnContext): Promise<void>;\n\n /**\n * Receives invoke activities with Activity name of 'signin/verifyState'.\n * @param context A context object for this turn.\n * @param query Signin state (part of signin action auth flow) verification invoke query.\n * @returns A promise that represents the work queued.\n *\n * @remarks\n * It should trigger {@link BotSsoExecutionDialog} instance to handle signin process\n */\n handleTeamsSigninVerifyState(\n context: TurnContext,\n query: SigninStateVerificationQuery\n ): Promise<void>;\n\n /**\n * Receives invoke activities with Activity name of 'signin/tokenExchange'\n * @param context A context object for this turn.\n * @param query Signin state (part of signin action auth flow) verification invoke query\n * @returns A promise that represents the work queued.\n *\n * @remarks\n * It should trigger {@link BotSsoExecutionDialog} instance to handle signin process\n */\n handleTeamsSigninTokenExchange(\n context: TurnContext,\n query: SigninStateVerificationQuery\n ): Promise<void>;\n}\n\nexport type BotSsoExecutionDialogHandler = (\n context: TurnContext,\n tokenResponse: TeamsBotSsoPromptTokenResponse,\n message: CommandMessage\n) => Promise<void>;\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { InvokeResponse, StatusCodes } from \"botbuilder\";\nimport { InvokeResponseErrorCode } from \"./interface\";\n\n/**\n * Available response type for an adaptive card invoke response.\n * @internal\n */\nexport enum InvokeResponseType {\n AdaptiveCard = \"application/vnd.microsoft.card.adaptive\",\n Message = \"application/vnd.microsoft.activity.message\",\n Error = \"application/vnd.microsoft.error\",\n}\n\n/**\n * Provides methods for formatting various invoke responses a bot can send to respond to an invoke request.\n *\n * @remarks\n * All of these functions return an `InvokeResponse` object, which can be\n * passed as input to generate a new `invokeResponse` activity.\n *\n * This example sends an invoke response that contains an adaptive card.\n *\n * ```typescript\n *\n * const myCard = {\n * type: \"AdaptiveCard\",\n * body: [\n * {\n * \"type\": \"TextBlock\",\n * \"text\": \"This is a sample card\"\n * }],\n * $schema: \"http://adaptivecards.io/schemas/adaptive-card.json\",\n * version: \"1.4\"\n * };\n *\n * const invokeResponse = InvokeResponseFactory.adaptiveCard(myCard);\n * await context.sendActivity({\n * type: ActivityTypes.InvokeResponse,\n * value: invokeResponse,\n * });\n * ```\n */\nexport class InvokeResponseFactory {\n /**\n * Create an invoke response from a text message.\n * The type of the invoke response is `application/vnd.microsoft.activity.message`\n * indicates the request was successfully processed.\n *\n * @param message - A text message included in a invoke response.\n *\n * @returns An `InvokeResponse` object.\n */\n public static textMessage(message: string): InvokeResponse {\n if (!message) {\n throw new Error(\"The text message cannot be null or empty\");\n }\n\n return {\n status: StatusCodes.OK,\n body: {\n statusCode: StatusCodes.OK,\n type: InvokeResponseType.Message,\n value: message,\n },\n };\n }\n\n /**\n * Create an invoke response from an adaptive card.\n *\n * The type of the invoke response is `application/vnd.microsoft.card.adaptive` indicates\n * the request was successfully processed, and the response includes an adaptive card\n * that the client should display in place of the current one.\n *\n * @param card - The adaptive card JSON payload.\n *\n * @returns An `InvokeResponse` object.\n */\n public static adaptiveCard(card: unknown): InvokeResponse {\n if (!card) {\n throw new Error(\"The adaptive card content cannot be null or undefined\");\n }\n\n return {\n status: StatusCodes.OK,\n body: {\n statusCode: StatusCodes.OK,\n type: InvokeResponseType.AdaptiveCard,\n value: card,\n },\n };\n }\n\n /**\n * Create an invoke response with error code and message.\n *\n * The type of the invoke response is `application/vnd.microsoft.error` indicates\n * the request was failed to processed.\n *\n * @param errorCode - The status code indicates error, available values:\n * - 400 (BadRequest): indicate the incoming request was invalid.\n * - 500 (InternalServerError): indicate an unexpected error occurred.\n * @param errorMessage - The error message.\n *\n * @returns An `InvokeResponse` object.\n */\n public static errorResponse(\n errorCode: InvokeResponseErrorCode,\n errorMessage: string\n ): InvokeResponse {\n return {\n status: StatusCodes.OK,\n body: {\n statusCode: errorCode,\n type: InvokeResponseType.Error,\n value: {\n code: errorCode.toString(),\n message: errorMessage,\n },\n },\n };\n }\n\n /**\n * Create an invoke response with status code and response value.\n * @param statusCode - The status code.\n * @param body - The value of the response body.\n *\n * @returns An `InvokeResponse` object.\n */\n public static createInvokeResponse(statusCode: StatusCodes, body?: unknown): InvokeResponse {\n return {\n status: statusCode,\n body: body,\n };\n }\n}\n","import {\n ActivityTypes,\n CardFactory,\n InvokeResponse,\n MessageFactory,\n Middleware,\n TurnContext,\n} from \"botbuilder\";\nimport {\n AdaptiveCardResponse,\n InvokeResponseErrorCode,\n TeamsFxAdaptiveCardActionHandler,\n} from \"../interface\";\nimport { InvokeResponseFactory, InvokeResponseType } from \"../invokeResponseFactory\";\n\n/**\n * @internal\n */\nexport class CardActionMiddleware implements Middleware {\n public readonly actionHandlers: TeamsFxAdaptiveCardActionHandler[] = [];\n private readonly defaultMessage: string = \"Your response was sent to the app\";\n\n constructor(handlers?: TeamsFxAdaptiveCardActionHandler[]) {\n if (handlers && handlers.length > 0) {\n this.actionHandlers.push(...handlers);\n }\n }\n\n async onTurn(context: TurnContext, next: () => Promise<void>): Promise<void> {\n if (context.activity.name === \"adaptiveCard/action\") {\n const action = context.activity.value.action;\n const actionVerb = action.verb;\n\n for (const handler of this.actionHandlers) {\n if (handler.triggerVerb?.toLowerCase() === actionVerb?.toLowerCase()) {\n let response: InvokeResponse;\n try {\n response = await handler.handleActionInvoked(context, action.data);\n } catch (error: any) {\n const errorResponse = InvokeResponseFactory.errorResponse(\n InvokeResponseErrorCode.InternalServerError,\n error.message\n );\n await this.sendInvokeResponse(context, errorResponse);\n throw error;\n }\n\n const responseType = response.body?.type;\n switch (responseType) {\n case InvokeResponseType.AdaptiveCard:\n const card = response.body?.value;\n if (!card) {\n const errorMessage = \"Adaptive card content cannot be found in the response body\";\n await this.sendInvokeResponse(\n context,\n InvokeResponseFactory.errorResponse(\n InvokeResponseErrorCode.InternalServerError,\n errorMessage\n )\n );\n throw new Error(errorMessage);\n }\n\n if (card.refresh && handler.adaptiveCardResponse !== AdaptiveCardResponse.NewForAll) {\n // Card won't be refreshed with AdaptiveCardResponse.ReplaceForInteractor.\n // So set to AdaptiveCardResponse.ReplaceForAll here.\n handler.adaptiveCardResponse = AdaptiveCardResponse.ReplaceForAll;\n }\n\n const activity = MessageFactory.attachment(CardFactory.adaptiveCard(card));\n if (handler.adaptiveCardResponse === AdaptiveCardResponse.NewForAll) {\n await this.sendInvokeResponse(\n context,\n InvokeResponseFactory.textMessage(this.defaultMessage)\n );\n await context.sendActivity(activity);\n } else if (handler.adaptiveCardResponse === AdaptiveCardResponse.ReplaceForAll) {\n activity.id = context.activity.replyToId;\n await context.updateActivity(activity);\n await this.sendInvokeResponse(context, response);\n } else {\n await this.sendInvokeResponse(context, response);\n }\n break;\n case InvokeResponseType.Message:\n case InvokeResponseType.Error:\n default:\n await this.sendInvokeResponse(context, response);\n break;\n }\n\n break;\n }\n }\n }\n\n await next();\n }\n\n private async sendInvokeResponse(context: TurnContext, response: InvokeResponse) {\n await context.sendActivity({\n type: ActivityTypes.InvokeResponse,\n value: response,\n });\n }\n}\n","import { BotFrameworkAdapter } from \"botbuilder\";\nimport { CardActionMiddleware } from \"./middlewares/cardActionMiddleware\";\nimport { CardActionOptions, TeamsFxAdaptiveCardActionHandler } from \"./interface\";\n\n/**\n * A card action bot to respond to adaptive card universal actions.\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.CardActionBot` instead.\n */\nexport class CardActionBot {\n private readonly adapter: BotFrameworkAdapter;\n private middleware: CardActionMiddleware;\n\n /**\n * Creates a new instance of the `CardActionBot`.\n *\n * @param adapter The bound `BotFrameworkAdapter`.\n * @param options - initialize options\n */\n constructor(adapter: BotFrameworkAdapter, options?: CardActionOptions) {\n this.middleware = new CardActionMiddleware(options?.actions);\n this.adapter = adapter.use(this.middleware);\n }\n\n /**\n * Registers a card action handler to the bot.\n * @param actionHandler A card action handler to be registered.\n */\n registerHandler(actionHandler: TeamsFxAdaptiveCardActionHandler) {\n if (actionHandler) {\n this.middleware.actionHandlers.push(actionHandler);\n }\n }\n\n /**\n * Registers card action handlers to the bot.\n * @param actionHandlers A set of card action handlers to be registered.\n */\n registerHandlers(actionHandlers: TeamsFxAdaptiveCardActionHandler[]) {\n if (actionHandlers) {\n this.middleware.actionHandlers.push(...actionHandlers);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Activity, ActivityTypes, Middleware, TurnContext } from \"botbuilder\";\nimport { TeamsBotSsoPromptTokenResponse } from \"../../bot/teamsBotSsoPromptTokenResponse\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../../core/errors\";\nimport { internalLogger } from \"../../util/logger\";\nimport {\n CommandMessage,\n BotSsoExecutionActivityHandler,\n TeamsFxBotCommandHandler,\n TeamsFxBotSsoCommandHandler,\n TriggerPatterns,\n} from \"../interface\";\n\n/**\n * @internal\n */\nexport class CommandResponseMiddleware implements Middleware {\n public readonly commandHandlers: TeamsFxBotCommandHandler[] = [];\n public readonly ssoCommandHandlers: TeamsFxBotSsoCommandHandler[] = [];\n\n public ssoActivityHandler: BotSsoExecutionActivityHandler | undefined;\n public hasSsoCommand: boolean;\n\n constructor(\n handlers?: TeamsFxBotCommandHandler[],\n ssoHandlers?: TeamsFxBotSsoCommandHandler[],\n activityHandler?: BotSsoExecutionActivityHandler\n ) {\n handlers = handlers ?? [];\n ssoHandlers = ssoHandlers ?? [];\n this.hasSsoCommand = ssoHandlers.length > 0;\n this.ssoActivityHandler = activityHandler;\n\n if (this.hasSsoCommand && !this.ssoActivityHandler) {\n internalLogger.error(ErrorMessage.SsoActivityHandlerIsNull);\n throw new ErrorWithCode(\n ErrorMessage.SsoActivityHandlerIsNull,\n ErrorCode.SsoActivityHandlerIsUndefined\n );\n }\n\n this.commandHandlers.push(...handlers);\n for (const ssoHandler of ssoHandlers) {\n this.addSsoCommand(ssoHandler);\n }\n }\n\n public addSsoCommand(ssoHandler: TeamsFxBotSsoCommandHandler): void {\n this.ssoActivityHandler?.addCommand(\n async (\n context: TurnContext,\n tokenResponse: TeamsBotSsoPromptTokenResponse,\n message: CommandMessage\n ) => {\n const matchResult = this.shouldTrigger(ssoHandler.triggerPatterns, message.text);\n message.matches = Array.isArray(matchResult) ? matchResult : void 0;\n const response = await ssoHandler.handleCommandReceived(context, message, tokenResponse);\n await this.processResponse(context, response);\n },\n ssoHandler.triggerPatterns\n );\n this.ssoCommandHandlers.push(ssoHandler);\n this.hasSsoCommand = true;\n }\n\n public async onTurn(context: TurnContext, next: () => Promise<void>): Promise<void> {\n if (context.activity.type === ActivityTypes.Message) {\n // Invoke corresponding command handler for the command response\n const commandText = this.getActivityText(context.activity);\n let alreadyProcessed = false;\n for (const handler of this.commandHandlers) {\n const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);\n\n // It is important to note that the command bot will stop processing handlers\n // when the first command handler is matched.\n if (!!matchResult) {\n const message: CommandMessage = {\n text: commandText,\n };\n message.matches = Array.isArray(matchResult) ? matchResult : void 0;\n const response = await handler.handleCommandReceived(context, message);\n\n await this.processResponse(context, response);\n alreadyProcessed = true;\n break;\n }\n }\n\n if (!alreadyProcessed) {\n for (const handler of this.ssoCommandHandlers) {\n const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);\n if (!!matchResult) {\n await this.ssoActivityHandler?.run(context);\n break;\n }\n }\n }\n } else {\n if (this.hasSsoCommand) {\n await this.ssoActivityHandler?.run(context);\n }\n }\n await next();\n }\n\n private async processResponse(context: TurnContext, response: string | void | Partial<Activity>) {\n if (typeof response === \"string\") {\n await context.sendActivity(response);\n } else {\n const replyActivity = response as Partial<Activity>;\n if (replyActivity) {\n await context.sendActivity(replyActivity);\n }\n }\n }\n\n private matchPattern(pattern: string | RegExp, text: string): boolean | RegExpMatchArray {\n if (text) {\n if (typeof pattern === \"string\") {\n const regExp = new RegExp(pattern, \"i\");\n return regExp.test(text);\n }\n\n if (pattern instanceof RegExp) {\n const matches = text.match(pattern);\n return matches ?? false;\n }\n }\n\n return false;\n }\n\n private shouldTrigger(patterns: TriggerPatterns, text: string): RegExpMatchArray | boolean {\n const expressions = Array.isArray(patterns) ? patterns : [patterns];\n\n for (const ex of expressions) {\n const arg = this.matchPattern(ex, text);\n if (arg) return arg;\n }\n\n return false;\n }\n\n private getActivityText(activity: Activity): string {\n let text = activity.text;\n const removedMentionText = TurnContext.removeRecipientMention(activity);\n if (removedMentionText) {\n text = removedMentionText\n .toLowerCase()\n .replace(/\\n|\\r\\n/g, \"\")\n .trim();\n }\n\n return text;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { BotFrameworkAdapter } from \"botbuilder\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport {\n CommandOptions,\n BotSsoConfig,\n BotSsoExecutionActivityHandler,\n TeamsFxBotCommandHandler,\n TeamsFxBotSsoCommandHandler,\n} from \"./interface\";\nimport { CommandResponseMiddleware } from \"./middlewares/commandMiddleware\";\n\n/**\n * A command bot for receiving commands and sending responses in Teams.\n *\n * @remarks\n * Ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.CommandBot` instead.\n */\nexport class CommandBot {\n private readonly adapter: BotFrameworkAdapter;\n private readonly middleware: CommandResponseMiddleware;\n private readonly ssoConfig: BotSsoConfig | undefined;\n\n /**\n * Creates a new instance of the `CommandBot`.\n *\n * @param adapter The bound `BotFrameworkAdapter`.\n * @param options - initialize options\n */\n constructor(\n adapter: BotFrameworkAdapter,\n options?: CommandOptions,\n ssoCommandActivityHandler?: BotSsoExecutionActivityHandler,\n ssoConfig?: BotSsoConfig\n ) {\n this.ssoConfig = ssoConfig;\n\n this.middleware = new CommandResponseMiddleware(\n options?.commands,\n options?.ssoCommands,\n ssoCommandActivityHandler\n );\n this.adapter = adapter.use(this.middleware);\n }\n\n /**\n * Registers a command into the command bot.\n *\n * @param command The command to register.\n */\n public registerCommand(command: TeamsFxBotCommandHandler): void {\n if (command) {\n this.middleware.commandHandlers.push(command);\n }\n }\n\n /**\n * Registers commands into the command bot.\n *\n * @param commands The commands to register.\n */\n public registerCommands(commands: TeamsFxBotCommandHandler[]): void {\n if (commands) {\n this.middleware.commandHandlers.push(...commands);\n }\n }\n\n /**\n * Registers a sso command into the command bot.\n *\n * @param command The command to register.\n */\n public registerSsoCommand(ssoCommand: TeamsFxBotSsoCommandHandler): void {\n this.validateSsoActivityHandler();\n this.middleware.addSsoCommand(ssoCommand);\n }\n\n /**\n * Registers commands into the command bot.\n *\n * @param commands The commands to register.\n */\n public registerSsoCommands(ssoCommands: TeamsFxBotSsoCommandHandler[]): void {\n if (ssoCommands.length > 0) {\n this.validateSsoActivityHandler();\n for (const ssoCommand of ssoCommands) {\n this.middleware.addSsoCommand(ssoCommand);\n }\n }\n }\n\n private validateSsoActivityHandler() {\n if (!this.middleware.ssoActivityHandler) {\n internalLogger.error(ErrorMessage.SsoActivityHandlerIsNull);\n throw new ErrorWithCode(\n ErrorMessage.SsoActivityHandlerIsNull,\n ErrorCode.SsoActivityHandlerIsUndefined\n );\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ConversationReference, TurnContext } from \"botbuilder\";\nimport { NotificationTargetType } from \"./interface\";\n\n/**\n * @internal\n */\nexport function cloneConversation(\n conversation: Partial<ConversationReference>\n): ConversationReference {\n return JSON.parse(JSON.stringify(conversation));\n}\n\n/**\n * @internal\n */\nexport function getKey(reference: Partial<ConversationReference>): string {\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `_${reference.conversation?.tenantId}_${reference.conversation?.id}`;\n}\n\n/**\n * @internal\n */\nexport function getTargetType(\n conversationReference: Partial<ConversationReference>\n): NotificationTargetType | undefined {\n const conversationType = conversationReference.conversation?.conversationType;\n if (conversationType === \"personal\") {\n return NotificationTargetType.Person;\n } else if (conversationType === \"groupChat\") {\n return NotificationTargetType.Group;\n } else if (conversationType === \"channel\") {\n return NotificationTargetType.Channel;\n } else {\n return undefined;\n }\n}\n\n/**\n * @internal\n */\nexport function getTeamsBotInstallationId(context: TurnContext): string | undefined {\n const teamId = context.activity?.channelData?.team?.id;\n if (teamId) {\n return teamId;\n }\n\n // Fallback to use conversation id.\n // The conversation id is equal to team id only when the bot app is installed into the General channel.\n if (context.activity.conversation.name === undefined) {\n return context.activity.conversation.id;\n }\n\n return undefined;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Activity, Middleware, TurnContext } from \"botbuilder\";\nimport { cloneConversation, getKey } from \"../utils\";\nimport { ConversationReferenceStore } from \"../interface\";\n\n/**\n * @internal\n */\nenum ActivityType {\n CurrentBotInstalled,\n CurrentBotMessaged,\n CurrentBotUninstalled,\n TeamDeleted,\n TeamRestored,\n Unknown,\n}\n\n/**\n * @internal\n */\nexport interface NotificationMiddlewareOptions {\n conversationReferenceStore: ConversationReferenceStore;\n}\n\n/**\n * @internal\n */\nexport class NotificationMiddleware implements Middleware {\n private readonly conversationReferenceStore: ConversationReferenceStore;\n\n constructor(options: NotificationMiddlewareOptions) {\n this.conversationReferenceStore = options.conversationReferenceStore;\n }\n\n public async onTurn(context: TurnContext, next: () => Promise<void>): Promise<void> {\n const type = this.classifyActivity(context.activity);\n switch (type) {\n case ActivityType.CurrentBotInstalled:\n case ActivityType.TeamRestored: {\n const reference = TurnContext.getConversationReference(context.activity);\n await this.conversationReferenceStore.add(getKey(reference), reference, {\n overwrite: true,\n });\n break;\n }\n case ActivityType.CurrentBotMessaged: {\n await this.tryAddMessagedReference(context);\n break;\n }\n case ActivityType.CurrentBotUninstalled:\n case ActivityType.TeamDeleted: {\n const reference = TurnContext.getConversationReference(context.activity);\n await this.conversationReferenceStore.remove(getKey(reference), reference);\n break;\n }\n default:\n break;\n }\n\n await next();\n }\n\n private classifyActivity(activity: Activity): ActivityType {\n const activityType = activity.type;\n if (activityType === \"installationUpdate\") {\n const action = activity.action?.toLowerCase();\n if (action === \"add\") {\n return ActivityType.CurrentBotInstalled;\n } else {\n return ActivityType.CurrentBotUninstalled;\n }\n } else if (activityType === \"conversationUpdate\") {\n const eventType = activity.channelData?.eventType as string;\n if (eventType === \"teamDeleted\") {\n return ActivityType.TeamDeleted;\n } else if (eventType === \"teamRestored\") {\n return ActivityType.TeamRestored;\n }\n } else if (activityType === \"message\") {\n return ActivityType.CurrentBotMessaged;\n }\n\n return ActivityType.Unknown;\n }\n\n private async tryAddMessagedReference(context: TurnContext): Promise<void> {\n const reference = TurnContext.getConversationReference(context.activity);\n const conversationType = reference?.conversation?.conversationType;\n if (conversationType === \"personal\" || conversationType === \"groupChat\") {\n await this.conversationReferenceStore.add(getKey(reference), reference, { overwrite: false });\n } else if (conversationType === \"channel\") {\n const teamId = context.activity?.channelData?.team?.id;\n const channelId = context.activity.channelData?.channel?.id;\n // `teamId === channelId` means General channel. Ignore messaging in non-General channel.\n if (teamId !== undefined && (channelId === undefined || teamId === channelId)) {\n const teamReference = cloneConversation(reference);\n teamReference.conversation.id = teamId;\n await this.conversationReferenceStore.add(getKey(teamReference), teamReference, {\n overwrite: false,\n });\n }\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ConversationReference } from \"botbuilder\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport {\n NotificationTargetStorage,\n ConversationReferenceStore,\n ConversationReferenceStoreAddOptions,\n PagedData,\n} from \"./interface\";\n\n/**\n * @internal\n */\nexport class LocalFileStorage implements NotificationTargetStorage {\n private readonly localFileName =\n process.env.TEAMSFX_NOTIFICATION_STORE_FILENAME ?? \".notification.localstore.json\";\n private readonly filePath: string;\n\n constructor(fileDir: string) {\n this.filePath = path.resolve(fileDir, this.localFileName);\n }\n\n async read(key: string): Promise<{ [key: string]: unknown } | undefined> {\n if (!(await this.storeFileExists())) {\n return undefined;\n }\n\n const data = await this.readFromFile();\n\n return data[key];\n }\n\n async list(): Promise<{ [key: string]: unknown }[]> {\n if (!(await this.storeFileExists())) {\n return [];\n }\n\n const data = await this.readFromFile();\n\n return Object.entries(data).map((entry) => entry[1] as { [key: string]: unknown });\n }\n\n async write(key: string, object: { [key: string]: unknown }): Promise<void> {\n if (!(await this.storeFileExists())) {\n await this.writeToFile({ [key]: object });\n return;\n }\n\n const data = await this.readFromFile();\n await this.writeToFile(Object.assign(data, { [key]: object }));\n }\n\n async delete(key: string): Promise<void> {\n if (await this.storeFileExists()) {\n const data = await this.readFromFile();\n if (data[key] !== undefined) {\n delete data[key];\n await this.writeToFile(data);\n }\n }\n }\n\n private storeFileExists(): Promise<boolean> {\n return new Promise((resolve) => {\n try {\n fs.access(this.filePath, (err) => {\n if (err) {\n resolve(false);\n } else {\n resolve(true);\n }\n });\n } catch (error: unknown) {\n resolve(false);\n }\n });\n }\n\n private readFromFile(): Promise<any> {\n return new Promise((resolve, reject) => {\n try {\n fs.readFile(this.filePath, { encoding: \"utf-8\" }, (err, rawData) => {\n if (err) {\n reject(err);\n } else {\n resolve(JSON.parse(rawData));\n }\n });\n } catch (error: unknown) {\n reject(error);\n }\n });\n }\n\n private async writeToFile(data: unknown): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n const rawData = JSON.stringify(data, undefined, 2);\n fs.writeFile(this.filePath, rawData, { encoding: \"utf-8\" }, (err) => {\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n });\n } catch (error: unknown) {\n reject(error);\n }\n });\n }\n}\n\n/**\n * @internal\n */\nexport class DefaultConversationReferenceStore implements ConversationReferenceStore {\n private readonly storage: NotificationTargetStorage;\n\n constructor(storage: NotificationTargetStorage) {\n this.storage = storage;\n }\n\n async add(\n key: string,\n reference: Partial<ConversationReference>,\n options: ConversationReferenceStoreAddOptions\n ): Promise<boolean> {\n if (options.overwrite) {\n await this.storage.write(key, reference);\n return true;\n }\n\n const ref = await this.storage.read(key);\n if (ref === undefined) {\n await this.storage.write(key, reference);\n return true;\n }\n\n return false;\n }\n\n async remove(key: string, reference: Partial<ConversationReference>): Promise<boolean> {\n const ref = await this.storage.read(key);\n if (ref === undefined) {\n return false;\n }\n\n await this.storage.delete(key);\n return true;\n }\n\n async list(\n pageSize?: number,\n continuationToken?: string\n ): Promise<PagedData<Partial<ConversationReference>>> {\n const data = await this.storage.list();\n return {\n data,\n continuationToken: \"\",\n };\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n BotFrameworkAdapter,\n CardFactory,\n ChannelInfo,\n ConversationParameters,\n ConversationReference,\n TeamDetails,\n TeamsChannelAccount,\n TeamsInfo,\n TurnContext,\n} from \"botbuilder\";\nimport type { ConnectorClient } from \"botframework-connector\";\nimport * as path from \"path\";\nimport {\n NotificationTarget,\n NotificationTargetType,\n NotificationOptions,\n MessageResponse,\n} from \"./interface\";\nimport { NotificationMiddleware } from \"./middlewares/notificationMiddleware\";\nimport { DefaultConversationReferenceStore, LocalFileStorage } from \"./storage\";\nimport * as utils from \"./utils\";\n\n/**\n * Send a plain text message to a notification target.\n *\n * @param target - the notification target.\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending message.\n */\nexport function sendMessage(\n target: NotificationTarget,\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n): Promise<MessageResponse> {\n return target.sendMessage(text, onError);\n}\n\n/**\n * Send an adaptive card message to a notification target.\n *\n * @param target - the notification target.\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending adaptive card message.\n */\nexport function sendAdaptiveCard(\n target: NotificationTarget,\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n): Promise<MessageResponse> {\n return target.sendAdaptiveCard(card, onError);\n}\n\n/**\n * A {@link NotificationTarget} that represents a team channel.\n *\n * @remarks\n * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.\n */\nexport class Channel implements NotificationTarget {\n /**\n * The parent {@link TeamsBotInstallation} where this channel is created from.\n */\n public readonly parent: TeamsBotInstallation;\n\n /**\n * Detailed channel information.\n */\n public readonly info: ChannelInfo;\n\n /**\n * Notification target type. For channel it's always \"Channel\".\n */\n public readonly type: NotificationTargetType = NotificationTargetType.Channel;\n\n /**\n * Constructor.\n *\n * @remarks\n * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.\n *\n * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.\n * @param info - Detailed channel information.\n */\n constructor(parent: TeamsBotInstallation, info: ChannelInfo) {\n this.parent = parent;\n this.info = info;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversation(\n this.parent.conversationReference,\n async (context) => {\n const conversation = this.newConversation(context);\n await this.parent.adapter.continueConversation(conversation, async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n });\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversation(\n this.parent.conversationReference,\n async (context) => {\n const conversation = this.newConversation(context);\n await this.parent.adapter.continueConversation(conversation, async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n });\n }\n );\n return response;\n }\n\n /**\n * @internal\n */\n private newConversation(context: TurnContext): ConversationReference {\n const reference = TurnContext.getConversationReference(context.activity);\n const channelConversation = utils.cloneConversation(reference);\n channelConversation.conversation.id = this.info.id || \"\";\n\n return channelConversation;\n }\n}\n\n/**\n * A {@link NotificationTarget} that represents a team member.\n *\n * @remarks\n * It's recommended to get members from {@link TeamsBotInstallation.members()}.\n */\nexport class Member implements NotificationTarget {\n /**\n * The parent {@link TeamsBotInstallation} where this member is created from.\n */\n public readonly parent: TeamsBotInstallation;\n\n /**\n * Detailed member account information.\n */\n public readonly account: TeamsChannelAccount;\n\n /**\n * Notification target type. For member it's always \"Person\".\n */\n public readonly type: NotificationTargetType = NotificationTargetType.Person;\n\n /**\n * Constructor.\n *\n * @remarks\n * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.\n *\n * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.\n * @param account - Detailed member account information.\n */\n constructor(parent: TeamsBotInstallation, account: TeamsChannelAccount) {\n this.parent = parent;\n this.account = account;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversation(\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversation(conversation, async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n });\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversation(\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversation(conversation, async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n });\n }\n );\n return response;\n }\n\n /**\n * @internal\n */\n private async newConversation(context: TurnContext): Promise<ConversationReference> {\n const reference = TurnContext.getConversationReference(context.activity);\n const personalConversation = utils.cloneConversation(reference);\n\n const connectorClient: ConnectorClient = context.turnState.get(\n this.parent.adapter.ConnectorClientKey\n );\n const conversation = await connectorClient.conversations.createConversation({\n isGroup: false,\n tenantId: context.activity.conversation.tenantId,\n bot: context.activity.recipient,\n members: [this.account],\n channelData: {},\n } as ConversationParameters);\n personalConversation.conversation.id = conversation.id;\n\n return personalConversation;\n }\n}\n\n/**\n * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into\n * - Personal chat\n * - Group chat\n * - Team (by default the `General` channel)\n *\n * @remarks\n * It's recommended to get bot installations from {@link ConversationBot.installations()}.\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.TeamsBotInstallation` instead.\n */\nexport class TeamsBotInstallation implements NotificationTarget {\n /**\n * The bound `BotFrameworkAdapter`.\n */\n public readonly adapter: BotFrameworkAdapter;\n\n /**\n * The bound `ConversationReference`.\n */\n public readonly conversationReference: Partial<ConversationReference>;\n\n /**\n * Notification target type.\n *\n * @remarks\n * - \"Channel\" means bot is installed into a team and notification will be sent to its \"General\" channel.\n * - \"Group\" means bot is installed into a group chat.\n * - \"Person\" means bot is installed into a personal scope and notification will be sent to personal chat.\n */\n public readonly type?: NotificationTargetType;\n\n /**\n * Constructor\n *\n * @remarks\n * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.\n *\n * @param adapter - the bound `BotFrameworkAdapter`.\n * @param conversationReference - the bound `ConversationReference`.\n */\n constructor(adapter: BotFrameworkAdapter, conversationReference: Partial<ConversationReference>) {\n this.adapter = adapter;\n this.conversationReference = conversationReference;\n this.type = utils.getTargetType(conversationReference);\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n try {\n const res = await context.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(context, error as Error);\n } else {\n throw error;\n }\n }\n });\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n try {\n const res = await context.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(context, error as Error);\n } else {\n throw error;\n }\n }\n });\n return response;\n }\n\n /**\n * Get channels from this bot installation.\n *\n * @returns an array of channels if bot is installed into a team, otherwise returns an empty array.\n */\n public async channels(): Promise<Channel[]> {\n const channels: Channel[] = [];\n if (this.type !== NotificationTargetType.Channel) {\n return channels;\n }\n\n let teamsChannels: ChannelInfo[] = [];\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n const teamId = utils.getTeamsBotInstallationId(context);\n if (teamId !== undefined) {\n teamsChannels = await TeamsInfo.getTeamChannels(context, teamId);\n }\n });\n\n for (const channel of teamsChannels) {\n channels.push(new Channel(this, channel));\n }\n\n return channels;\n }\n\n /**\n * Get members from this bot installation.\n *\n * @returns an array of members from where the bot is installed.\n */\n public async members(): Promise<Member[]> {\n const members: Member[] = [];\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n let continuationToken: string | undefined;\n do {\n const pagedMembers = await TeamsInfo.getPagedMembers(context, undefined, continuationToken);\n continuationToken = pagedMembers.continuationToken;\n for (const member of pagedMembers.members) {\n members.push(new Member(this, member));\n }\n } while (continuationToken !== undefined);\n });\n\n return members;\n }\n\n /**\n * Get team details from this bot installation\n *\n * @returns the team details if bot is installed into a team, otherwise returns undefined.\n */\n public async getTeamDetails(): Promise<TeamDetails | undefined> {\n if (this.type !== NotificationTargetType.Channel) {\n return undefined;\n }\n\n let teamDetails: TeamDetails | undefined;\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n const teamId = utils.getTeamsBotInstallationId(context);\n if (teamId !== undefined) {\n teamDetails = await TeamsInfo.getTeamDetails(context, teamId);\n }\n });\n\n return teamDetails;\n }\n}\n\n/**\n * Provide utilities to send notification to varies targets (e.g., member, group, channel).\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.NotificationBot` instead.\n */\nexport class NotificationBot {\n private readonly conversationReferenceStore: DefaultConversationReferenceStore;\n private readonly adapter: BotFrameworkAdapter;\n\n /**\n * constructor of the notification bot.\n *\n * @remarks\n * To ensure accuracy, it's recommended to initialize before handling any message.\n *\n * @param adapter - the bound `BotFrameworkAdapter`\n * @param options - initialize options\n */\n public constructor(adapter: BotFrameworkAdapter, options?: NotificationOptions) {\n const storage =\n options?.storage ??\n new LocalFileStorage(\n path.resolve(process.env.RUNNING_ON_AZURE === \"1\" ? process.env.TEMP ?? \"./\" : \"./\")\n );\n\n this.conversationReferenceStore = new DefaultConversationReferenceStore(storage);\n this.adapter = adapter.use(\n new NotificationMiddleware({\n conversationReferenceStore: this.conversationReferenceStore,\n })\n );\n }\n\n /**\n * Get all targets where the bot is installed.\n *\n * @remarks\n * The result is retrieving from the persisted storage.\n *\n * @returns - an array of {@link TeamsBotInstallation}.\n */\n public async installations(): Promise<TeamsBotInstallation[]> {\n if (this.conversationReferenceStore === undefined || this.adapter === undefined) {\n throw new Error(\"NotificationBot has not been initialized.\");\n }\n\n const { data: references } = await this.conversationReferenceStore.list();\n const targets: TeamsBotInstallation[] = [];\n for (const reference of references) {\n // validate connection\n let valid = true;\n await this.adapter.continueConversation(reference, async (context) => {\n try {\n // try get member to see if the installation is still valid\n await TeamsInfo.getPagedMembers(context, 1);\n } catch (error: any) {\n if ((error.code as string) === \"BotNotInConversationRoster\") {\n valid = false;\n }\n }\n });\n\n if (valid) {\n targets.push(new TeamsBotInstallation(this.adapter, reference));\n } else {\n await this.conversationReferenceStore.remove(utils.getKey(reference), reference);\n }\n }\n\n return targets;\n }\n\n /**\n * Returns the first {@link Member} where predicate is true, and undefined otherwise.\n *\n * @param predicate find calls predicate once for each member of the installation,\n * until it finds one where predicate returns true. If such a member is found, find\n * immediately returns that member. Otherwise, find returns undefined.\n * @param scope the scope to find members from the installations\n * (personal chat, group chat, Teams channel).\n * @returns the first {@link Member} where predicate is true, and undefined otherwise.\n */\n public async findMember(\n predicate: (member: Member) => Promise<boolean>,\n scope?: SearchScope\n ): Promise<Member | undefined> {\n for (const target of await this.installations()) {\n if (this.matchSearchScope(target, scope)) {\n for (const member of await target.members()) {\n if (await predicate(member)) {\n return member;\n }\n }\n }\n }\n\n return;\n }\n\n /**\n * Returns the first {@link Channel} where predicate is true, and undefined otherwise.\n * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)\n *\n * @param predicate find calls predicate once for each channel of the installation,\n * until it finds one where predicate returns true. If such a channel is found, find\n * immediately returns that channel. Otherwise, find returns undefined.\n * @returns the first {@link Channel} where predicate is true, and undefined otherwise.\n */\n public async findChannel(\n predicate: (channel: Channel, teamDetails: TeamDetails | undefined) => Promise<boolean>\n ): Promise<Channel | undefined> {\n for (const target of await this.installations()) {\n if (target.type === NotificationTargetType.Channel) {\n const teamDetails = await target.getTeamDetails();\n for (const channel of await target.channels()) {\n if (await predicate(channel, teamDetails)) {\n return channel;\n }\n }\n }\n }\n\n return;\n }\n\n /**\n * Returns all {@link Member} where predicate is true, and empty array otherwise.\n *\n * @param predicate find calls predicate for each member of the installation.\n * @param scope the scope to find members from the installations\n * (personal chat, group chat, Teams channel).\n * @returns an array of {@link Member} where predicate is true, and empty array otherwise.\n */\n public async findAllMembers(\n predicate: (member: Member) => Promise<boolean>,\n scope?: SearchScope\n ): Promise<Member[]> {\n const members: Member[] = [];\n for (const target of await this.installations()) {\n if (this.matchSearchScope(target, scope)) {\n for (const member of await target.members()) {\n if (await predicate(member)) {\n members.push(member);\n }\n }\n }\n }\n\n return members;\n }\n\n /**\n * Returns all {@link Channel} where predicate is true, and empty array otherwise.\n * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)\n *\n * @param predicate find calls predicate for each channel of the installation.\n * @returns an array of {@link Channel} where predicate is true, and empty array otherwise.\n */\n public async findAllChannels(\n predicate: (channel: Channel, teamDetails: TeamDetails | undefined) => Promise<boolean>\n ): Promise<Channel[]> {\n const channels: Channel[] = [];\n for (const target of await this.installations()) {\n if (target.type === NotificationTargetType.Channel) {\n const teamDetails = await target.getTeamDetails();\n for (const channel of await target.channels()) {\n if (await predicate(channel, teamDetails)) {\n channels.push(channel);\n }\n }\n }\n }\n\n return channels;\n }\n\n private matchSearchScope(target: NotificationTarget, scope?: SearchScope): boolean {\n scope = scope ?? SearchScope.All;\n\n return (\n (target.type === NotificationTargetType.Channel && (scope & SearchScope.Channel) !== 0) ||\n (target.type === NotificationTargetType.Group && (scope & SearchScope.Group) !== 0) ||\n (target.type === NotificationTargetType.Person && (scope & SearchScope.Person) !== 0)\n );\n }\n}\n\n/**\n * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.\n * The search scope is a flagged enum and it can be combined with `|`.\n * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.\n */\nexport enum SearchScope {\n /**\n * Search members from the installations in personal chat only.\n */\n Person = 1,\n\n /**\n * Search members from the installations in group chat only.\n */\n Group = 2,\n\n /**\n * Search members from the installations in Teams channel only.\n */\n Channel = 4,\n\n /**\n * Search members from all installations including personal chat, group chat and Teams channel.\n */\n All = Person | Group | Channel,\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n ComponentDialog,\n WaterfallDialog,\n Dialog,\n DialogSet,\n DialogTurnStatus,\n DialogContext,\n} from \"botbuilder-dialogs\";\nimport {\n Activity,\n ActivityTypes,\n Channels,\n StatePropertyAccessor,\n Storage,\n tokenExchangeOperationName,\n TurnContext,\n} from \"botbuilder\";\nimport { CommandMessage, BotSsoExecutionDialogHandler, TriggerPatterns } from \"../interface\";\nimport { TeamsBotSsoPrompt, TeamsBotSsoPromptSettings } from \"../../bot/teamsBotSsoPrompt\";\nimport { TeamsBotSsoPromptTokenResponse } from \"../../bot/teamsBotSsoPromptTokenResponse\";\nimport { TeamsFx } from \"../../core/teamsfx\";\nimport { formatString } from \"../../util/utils\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../../core/errors\";\nimport { internalLogger } from \"../../util/logger\";\nimport { createHash } from \"crypto\";\nimport { OnBehalfOfCredentialAuthConfig } from \"../../models/configuration\";\n\nlet DIALOG_NAME = \"BotSsoExecutionDialog\";\nlet TEAMS_SSO_PROMPT_ID = \"TeamsFxSsoPrompt\";\nlet COMMAND_ROUTE_DIALOG = \"CommandRouteDialog\";\n\n/**\n * Sso execution dialog, use to handle sso command\n */\nexport class BotSsoExecutionDialog extends ComponentDialog {\n private dedupStorage: Storage;\n private dedupStorageKeys: string[] = [];\n\n // Map to store the commandId and triggerPatterns, key: commandId, value: triggerPatterns\n private commandMapping: Map<string, string | RegExp | (string | RegExp)[]> = new Map<\n string,\n string | RegExp | (string | RegExp)[]\n >();\n\n /**\n * Creates a new instance of the BotSsoExecutionDialog.\n * @param {@link Storage} dedupStorage Helper storage to remove duplicated messages\n * @param {@link TeamsBotSsoPromptSettings} settings The list of scopes for which the token will have access\n * @param {@link TeamsFx} teamsfx instance for authentication\n * @param {string} dialogName custom dialog name\n */\n constructor(\n dedupStorage: Storage,\n ssoPromptSettings: TeamsBotSsoPromptSettings,\n teamsfx: TeamsFx,\n dialogName?: string\n );\n /**\n * Creates a new instance of the BotSsoExecutionDialog.\n * @param {@link Storage} dedupStorage Helper storage to remove duplicated messages\n * @param {@link TeamsBotSsoPromptSettings} settings The list of scopes for which the token will have access\n * @param {@link OnBehalfOfCredentialAuthConfig} authConfig The authentication configuration.\n * @param {string} initiateLoginEndpoint Login URL for Teams to redirect to.\n * @param {string} dialogName custom dialog name\n */\n constructor(\n dedupStorage: Storage,\n ssoPromptSettings: TeamsBotSsoPromptSettings,\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n dialogName?: string\n );\n constructor(\n dedupStorage: Storage,\n ssoPromptSettings: TeamsBotSsoPromptSettings,\n authConfig: TeamsFx | OnBehalfOfCredentialAuthConfig,\n ...args: any\n ) {\n super(((authConfig as TeamsFx).getCredential ? args[0] : args[1]) ?? DIALOG_NAME);\n const dialogName: string = (authConfig as TeamsFx).getCredential ? args[0] : args[1];\n\n if (dialogName) {\n DIALOG_NAME = dialogName;\n TEAMS_SSO_PROMPT_ID = dialogName + TEAMS_SSO_PROMPT_ID;\n COMMAND_ROUTE_DIALOG = dialogName + COMMAND_ROUTE_DIALOG;\n }\n\n let ssoDialog: TeamsBotSsoPrompt;\n if ((authConfig as TeamsFx).getCredential) {\n ssoDialog = new TeamsBotSsoPrompt(\n authConfig as TeamsFx,\n TEAMS_SSO_PROMPT_ID,\n ssoPromptSettings\n );\n } else {\n ssoDialog = new TeamsBotSsoPrompt(\n authConfig as OnBehalfOfCredentialAuthConfig,\n args[0],\n TEAMS_SSO_PROMPT_ID,\n ssoPromptSettings\n );\n }\n\n this.addDialog(ssoDialog);\n\n this.initialDialogId = COMMAND_ROUTE_DIALOG;\n\n this.dedupStorage = dedupStorage;\n this.dedupStorageKeys = [];\n\n const commandRouteDialog = new WaterfallDialog(COMMAND_ROUTE_DIALOG, [\n this.commandRouteStep.bind(this),\n ]);\n this.addDialog(commandRouteDialog);\n }\n\n /**\n * Add TeamsFxBotSsoCommandHandler instance\n * @param handler {@link BotSsoExecutionDialogHandler} callback function\n * @param triggerPatterns The trigger pattern\n */\n public addCommand(handler: BotSsoExecutionDialogHandler, triggerPatterns: TriggerPatterns): void {\n const commandId = this.getCommandHash(triggerPatterns);\n const dialog = new WaterfallDialog(commandId, [\n this.ssoStep.bind(this),\n this.dedupStep.bind(this),\n async (stepContext: any) => {\n const tokenResponse: TeamsBotSsoPromptTokenResponse = stepContext.result.tokenResponse;\n const context: TurnContext = stepContext.context;\n const message: CommandMessage = stepContext.result.message;\n\n try {\n if (tokenResponse) {\n await handler(context, tokenResponse, message);\n } else {\n throw new Error(ErrorMessage.FailedToRetrieveSsoToken);\n }\n return await stepContext.endDialog();\n } catch (error: unknown) {\n const errorMsg = formatString(\n ErrorMessage.FailedToProcessSsoHandler,\n (error as Error).message\n );\n internalLogger.error(errorMsg);\n return await stepContext.endDialog(\n new ErrorWithCode(errorMsg, ErrorCode.FailedToProcessSsoHandler)\n );\n }\n },\n ]);\n\n this.commandMapping.set(commandId, triggerPatterns);\n this.addDialog(dialog);\n }\n\n private getCommandHash(patterns: TriggerPatterns): string {\n const expressions = Array.isArray(patterns) ? patterns : [patterns];\n const patternStr = expressions.join();\n const patternStrWithoutSpecialChar = patternStr.replace(/[^a-zA-Z0-9]/g, \"\");\n const hash = createHash(\"sha256\").update(patternStr).digest(\"hex\").toLowerCase();\n return patternStrWithoutSpecialChar + hash;\n }\n\n /**\n * The run method handles the incoming activity (in the form of a DialogContext) and passes it through the dialog system.\n *\n * @param context The context object for the current turn.\n * @param accessor The instance of StatePropertyAccessor for dialog system.\n */\n public async run(context: TurnContext, accessor: StatePropertyAccessor) {\n const dialogSet = new DialogSet(accessor);\n dialogSet.add(this);\n\n const dialogContext = await dialogSet.createContext(context);\n this.ensureMsTeamsChannel(dialogContext);\n const results = await dialogContext.continueDialog();\n if (results && results.status === DialogTurnStatus.empty) {\n await dialogContext.beginDialog(this.id);\n } else if (\n results &&\n results.status === DialogTurnStatus.complete &&\n results.result instanceof Error\n ) {\n throw results.result;\n }\n }\n\n private getActivityText(activity: Activity): string {\n let text = activity.text;\n const removedMentionText = TurnContext.removeRecipientMention(activity);\n if (removedMentionText) {\n text = removedMentionText\n .toLowerCase()\n .replace(/\\n|\\r\\n/g, \"\")\n .trim();\n }\n\n return text;\n }\n\n private async commandRouteStep(stepContext: any) {\n const turnContext = stepContext.context as TurnContext;\n\n const text = this.getActivityText(turnContext.activity);\n\n const commandId = this.getMatchesCommandId(text);\n if (commandId) {\n return await stepContext.beginDialog(commandId);\n }\n\n const errorMsg = formatString(ErrorMessage.CannotFindCommand, turnContext.activity.text);\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.CannotFindCommand);\n }\n\n private async ssoStep(stepContext: any) {\n try {\n const turnContext = stepContext.context as TurnContext;\n\n const text = this.getActivityText(turnContext.activity);\n const message: CommandMessage = {\n text,\n };\n\n stepContext.options.commandMessage = message;\n\n return await stepContext.beginDialog(TEAMS_SSO_PROMPT_ID);\n } catch (error: unknown) {\n const errorMsg = formatString(ErrorMessage.FailedToRunSsoStep, (error as Error).message);\n internalLogger.error(errorMsg);\n return await stepContext.endDialog(new ErrorWithCode(errorMsg, ErrorCode.FailedToRunSsoStep));\n }\n }\n\n private async dedupStep(stepContext: any) {\n const tokenResponse = stepContext.result;\n if (!tokenResponse) {\n internalLogger.error(ErrorMessage.FailedToRetrieveSsoToken);\n return await stepContext.endDialog(\n new ErrorWithCode(ErrorMessage.FailedToRetrieveSsoToken, ErrorCode.FailedToRunSsoStep)\n );\n }\n\n try {\n // Only dedup after ssoStep to make sure that all Teams client would receive the login request\n if (tokenResponse && (await this.shouldDedup(stepContext.context))) {\n return Dialog.EndOfTurn;\n }\n return await stepContext.next({\n tokenResponse,\n message: stepContext.options.commandMessage,\n });\n } catch (error: unknown) {\n const errorMsg = formatString(ErrorMessage.FailedToRunDedupStep, (error as Error).message);\n internalLogger.error(errorMsg);\n return await stepContext.endDialog(\n new ErrorWithCode(errorMsg, ErrorCode.FailedToRunDedupStep)\n );\n }\n }\n\n /**\n * Called when the component is ending.\n *\n * @param context Context for the current turn of conversation.\n */\n protected async onEndDialog(context: TurnContext) {\n const conversationId = context.activity.conversation.id;\n const currentDedupKeys = this.dedupStorageKeys.filter((key) => key.indexOf(conversationId) > 0);\n await this.dedupStorage.delete(currentDedupKeys);\n this.dedupStorageKeys = this.dedupStorageKeys.filter((key) => key.indexOf(conversationId) < 0);\n }\n\n /**\n * If a user is signed into multiple Teams clients, the Bot might receive a \"signin/tokenExchange\" from each client.\n * Each token exchange request for a specific user login will have an identical activity.value.Id.\n * Only one of these token exchange requests should be processed by the bot. For a distributed bot in production,\n * this requires a distributed storage to ensure only one token exchange is processed.\n * @param context Context for the current turn of conversation.\n * @returns boolean value indicate whether the message should be removed\n */\n private async shouldDedup(context: TurnContext): Promise<boolean> {\n const storeItem = {\n eTag: context.activity.value.id,\n };\n\n const key = this.getStorageKey(context);\n const storeItems = { [key]: storeItem };\n\n try {\n await this.dedupStorage.write(storeItems);\n this.dedupStorageKeys.push(key);\n } catch (err: unknown) {\n if (err instanceof Error && err.message.indexOf(\"eTag conflict\")) {\n return true;\n }\n throw err;\n }\n return false;\n }\n\n private getStorageKey(context: TurnContext): string {\n if (!context || !context.activity || !context.activity.conversation) {\n throw new Error(\"Invalid context, can not get storage key!\");\n }\n const activity = context.activity;\n const channelId = activity.channelId;\n const conversationId = activity.conversation.id;\n if (activity.type !== ActivityTypes.Invoke || activity.name !== tokenExchangeOperationName) {\n throw new Error(\"TokenExchangeState can only be used with Invokes of signin/tokenExchange.\");\n }\n const value = activity.value;\n if (!value || !value.id) {\n throw new Error(\"Invalid signin/tokenExchange. Missing activity.value.id.\");\n }\n return `${channelId}/${conversationId}/${value.id as string}`;\n }\n\n private matchPattern(pattern: string | RegExp, text: string): boolean | RegExpMatchArray {\n if (text) {\n if (typeof pattern === \"string\") {\n const regExp = new RegExp(pattern, \"i\");\n return regExp.test(text);\n }\n\n if (pattern instanceof RegExp) {\n const matches = text.match(pattern);\n return matches ?? false;\n }\n }\n\n return false;\n }\n\n private isPatternMatched(patterns: TriggerPatterns, text: string): boolean {\n const expressions = Array.isArray(patterns) ? patterns : [patterns];\n\n for (const ex of expressions) {\n const matches = this.matchPattern(ex, text);\n return !!matches;\n }\n\n return false;\n }\n\n private getMatchesCommandId(text: string): string | undefined {\n for (const command of this.commandMapping) {\n const pattern: TriggerPatterns = command[1];\n\n if (this.isPatternMatched(pattern, text)) {\n return command[0];\n }\n }\n\n return undefined;\n }\n\n /**\n * Ensure bot is running in MS Teams since TeamsBotSsoPrompt is only supported in MS Teams channel.\n * @param dc dialog context\n * @throws {@link ErrorCode|ChannelNotSupported} if bot channel is not MS Teams\n * @internal\n */\n private ensureMsTeamsChannel(dc: DialogContext) {\n if (dc.context.activity.channelId != Channels.Msteams) {\n const errorMsg = formatString(\n ErrorMessage.OnlyMSTeamsChannelSupported,\n \"SSO execution dialog\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.ChannelNotSupported);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n BotState,\n ConversationState,\n MemoryStorage,\n SigninStateVerificationQuery,\n StatePropertyAccessor,\n TeamsActivityHandler,\n TurnContext,\n UserState,\n} from \"botbuilder\";\nimport { TeamsBotSsoPromptSettings } from \"../../bot/teamsBotSsoPrompt\";\nimport { TeamsFx } from \"../../core/teamsfx\";\nimport { IdentityType } from \"../../models/identityType\";\nimport {\n BotSsoConfig,\n BotSsoExecutionActivityHandler,\n BotSsoExecutionDialogHandler,\n TriggerPatterns,\n} from \"../interface\";\nimport { BotSsoExecutionDialog } from \"./botSsoExecutionDialog\";\nimport { OnBehalfOfCredentialAuthConfig } from \"../..\";\n\n/**\n * Default SSO execution activity handler\n */\nexport class DefaultBotSsoExecutionActivityHandler\n extends TeamsActivityHandler\n implements BotSsoExecutionActivityHandler\n{\n private ssoExecutionDialog: BotSsoExecutionDialog;\n private userState: BotState;\n private conversationState: BotState;\n private dialogState: StatePropertyAccessor;\n\n /**\n * Creates a new instance of the DefaultBotSsoExecutionActivityHandler.\n * @param ssoConfig configuration for SSO command bot\n *\n * @remarks\n * In the constructor, it uses BotSsoConfig parameter which from {@link ConversationBot} options to initialize {@link BotSsoExecutionDialog}.\n * It also need to register an event handler for the message event which trigger {@link BotSsoExecutionDialog} instance.\n */\n constructor(ssoConfig: BotSsoConfig) {\n super();\n const memoryStorage = new MemoryStorage();\n const userState = ssoConfig.dialog?.userState ?? new UserState(memoryStorage);\n const conversationState =\n ssoConfig.dialog?.conversationState ?? new ConversationState(memoryStorage);\n const dedupStorage = ssoConfig.dialog?.dedupStorage ?? memoryStorage;\n\n const { scopes, ...customConfig } = ssoConfig.aad;\n const settings: TeamsBotSsoPromptSettings = {\n scopes: scopes,\n timeout: ssoConfig.dialog?.ssoPromptConfig?.timeout,\n endOnInvalidMessage: ssoConfig.dialog?.ssoPromptConfig?.endOnInvalidMessage,\n };\n\n this.ssoExecutionDialog = new BotSsoExecutionDialog(\n dedupStorage,\n settings,\n customConfig as OnBehalfOfCredentialAuthConfig,\n customConfig.initiateLoginEndpoint!\n );\n\n this.conversationState = conversationState;\n this.dialogState = conversationState.createProperty(\"DialogState\");\n this.userState = userState;\n\n this.onMessage(async (context, next) => {\n await this.ssoExecutionDialog.run(context, this.dialogState);\n await next();\n });\n }\n\n /**\n * Add TeamsFxBotSsoCommandHandler instance to SSO execution dialog\n * @param handler {@link BotSsoExecutionDialogHandler} callback function\n * @param triggerPatterns The trigger pattern\n *\n * @remarks\n * This function is used to add SSO command to {@link BotSsoExecutionDialog} instance.\n */\n addCommand(handler: BotSsoExecutionDialogHandler, triggerPatterns: TriggerPatterns): void {\n this.ssoExecutionDialog.addCommand(handler, triggerPatterns);\n }\n\n /**\n * Called to initiate the event emission process.\n * @param context The context object for the current turn.\n */\n async run(context: TurnContext) {\n try {\n await super.run(context);\n } finally {\n await this.conversationState.saveChanges(context, false);\n await this.userState.saveChanges(context, false);\n }\n }\n\n /**\n * Receives invoke activities with Activity name of 'signin/verifyState'.\n * @param context A context object for this turn.\n * @param query Signin state (part of signin action auth flow) verification invoke query.\n * @returns A promise that represents the work queued.\n *\n * @remarks\n * It should trigger {@link BotSsoExecutionDialog} instance to handle signin process\n */\n async handleTeamsSigninVerifyState(context: TurnContext, query: SigninStateVerificationQuery) {\n await this.ssoExecutionDialog.run(context, this.dialogState);\n }\n\n /**\n * Receives invoke activities with Activity name of 'signin/tokenExchange'\n * @param context A context object for this turn.\n * @param query Signin state (part of signin action auth flow) verification invoke query\n * @returns A promise that represents the work queued.\n *\n * @remarks\n * It should trigger {@link BotSsoExecutionDialog} instance to handle signin process\n */\n async handleTeamsSigninTokenExchange(context: TurnContext, query: SigninStateVerificationQuery) {\n await this.ssoExecutionDialog.run(context, this.dialogState);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { BotFrameworkAdapter, TurnContext, WebRequest, WebResponse } from \"botbuilder\";\nimport { CardActionBot } from \"./cardAction\";\nimport { CommandBot } from \"./command\";\nimport { ConversationOptions, BotSsoExecutionActivityHandler } from \"./interface\";\nimport { NotificationBot } from \"./notification\";\nimport { DefaultBotSsoExecutionActivityHandler } from \"./sso/defaultBotSsoExecutionActivityHandler\";\n\n/**\n * Provide utilities for bot conversation, including:\n * - handle command and response.\n * - send notification to varies targets (e.g., member, group, channel).\n *\n * @example\n * For command and response, you can register your commands through the constructor, or use the `registerCommand` and `registerCommands` API to add commands later.\n *\n * ```typescript\n * // register through constructor\n * const conversationBot = new ConversationBot({\n * command: {\n * enabled: true,\n * commands: [ new HelloWorldCommandHandler() ],\n * },\n * });\n *\n * // register through `register*` API\n * conversationBot.command.registerCommand(new HelpCommandHandler());\n * ```\n *\n * For notification, you can enable notification at initialization, then send notifications at any time.\n *\n * ```typescript\n * // enable through constructor\n * const conversationBot = new ConversationBot({\n * notification: {\n * enabled: true,\n * },\n * });\n *\n * // get all bot installations and send message\n * for (const target of await conversationBot.notification.installations()) {\n * await target.sendMessage(\"Hello Notification\");\n * }\n *\n * // alternative - send message to all members\n * for (const target of await conversationBot.notification.installations()) {\n * for (const member of await target.members()) {\n * await member.sendMessage(\"Hello Notification\");\n * }\n * }\n * ```\n *\n * @remarks\n * Set `adapter` in {@link ConversationOptions} to use your own bot adapter.\n *\n * For command and response, ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.\n *\n * For notification, set `notification.storage` in {@link ConversationOptions} to use your own storage implementation.\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.ConversationBot` instead.\n */\nexport class ConversationBot {\n /**\n * The bot adapter.\n */\n public readonly adapter: BotFrameworkAdapter;\n\n /**\n * The entrypoint of command and response.\n */\n public readonly command?: CommandBot;\n\n /**\n * The entrypoint of notification.\n */\n public readonly notification?: NotificationBot;\n\n /**\n * The action handler used for adaptive card universal actions.\n */\n public readonly cardAction?: CardActionBot;\n\n /**\n * Creates new instance of the `ConversationBot`.\n *\n * @remarks\n * It's recommended to create your own adapter and storage for production environment instead of the default one.\n *\n * @param options - initialize options\n */\n public constructor(options: ConversationOptions) {\n if (options.adapter) {\n this.adapter = options.adapter;\n } else {\n this.adapter = this.createDefaultAdapter(options.adapterConfig);\n }\n\n let ssoCommandActivityHandler: BotSsoExecutionActivityHandler | undefined;\n\n if (options?.ssoConfig) {\n if (options.ssoConfig.dialog?.CustomBotSsoExecutionActivityHandler) {\n ssoCommandActivityHandler =\n new options.ssoConfig.dialog.CustomBotSsoExecutionActivityHandler(options.ssoConfig);\n } else {\n ssoCommandActivityHandler = new DefaultBotSsoExecutionActivityHandler(options.ssoConfig);\n }\n }\n\n if (options.command?.enabled) {\n this.command = new CommandBot(\n this.adapter,\n options.command,\n ssoCommandActivityHandler,\n options.ssoConfig\n );\n }\n\n if (options.notification?.enabled) {\n this.notification = new NotificationBot(this.adapter, options.notification);\n }\n\n if (options.cardAction?.enabled) {\n this.cardAction = new CardActionBot(this.adapter, options.cardAction);\n }\n }\n\n private createDefaultAdapter(adapterConfig?: { [key: string]: unknown }): BotFrameworkAdapter {\n const adapter =\n adapterConfig === undefined\n ? new BotFrameworkAdapter({\n appId: process.env.BOT_ID,\n appPassword: process.env.BOT_PASSWORD,\n })\n : new BotFrameworkAdapter(adapterConfig);\n\n // the default error handler\n adapter.onTurnError = async (context, error) => {\n // This check writes out errors to console.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n console.error(`[onTurnError] unhandled error: ${error}`);\n\n // Send a trace activity, which will be displayed in Bot Framework Emulator\n await context.sendTraceActivity(\n \"OnTurnError Trace\",\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${error}`,\n \"https://www.botframework.com/schemas/error\",\n \"TurnError\"\n );\n\n // Send a message to the user\n await context.sendActivity(`The bot encountered unhandled error: ${error.message}`);\n await context.sendActivity(\"To continue to run this bot, please fix the bot source code.\");\n };\n\n return adapter;\n }\n\n /**\n * The request handler to integrate with web request.\n *\n * @param req - an Express or Restify style request object.\n * @param res - an Express or Restify style response object.\n * @param logic - the additional function to handle bot context.\n *\n * @example\n * For example, to use with Restify:\n * ``` typescript\n * // The default/empty behavior\n * server.post(\"api/messages\", conversationBot.requestHandler);\n *\n * // Or, add your own logic\n * server.post(\"api/messages\", async (req, res) => {\n * await conversationBot.requestHandler(req, res, async (context) => {\n * // your-own-context-logic\n * });\n * });\n * ```\n */\n public async requestHandler(\n req: WebRequest,\n res: WebResponse,\n logic?: (context: TurnContext) => Promise<any>\n ): Promise<void> {\n if (logic === undefined) {\n // create empty logic\n logic = async () => {};\n }\n\n await this.adapter.processActivity(req, res, logic);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n Activity,\n Attachment,\n CardAction,\n CardFactory,\n CardImage,\n HeroCard,\n O365ConnectorCard,\n ReceiptCard,\n ThumbnailCard,\n} from \"botbuilder\";\nimport { AdaptiveCards } from \"@microsoft/adaptivecards-tools\";\n\n/**\n * Provides utility method to build bot message with cards that supported in Teams.\n */\nexport class MessageBuilder {\n /**\n * Build a bot message activity attached with adaptive card.\n *\n * @param cardTemplate The adaptive card template.\n * @param data card data used to render the template.\n * @returns A bot message activity attached with an adaptive card.\n *\n * @example\n * ```javascript\n * const cardTemplate = {\n * type: \"AdaptiveCard\",\n * body: [\n * {\n * \"type\": \"TextBlock\",\n * \"text\": \"${title}\",\n * \"size\": \"Large\"\n * },\n * {\n * \"type\": \"TextBlock\",\n * \"text\": \"${description}\"\n * }],\n * $schema: \"http://adaptivecards.io/schemas/adaptive-card.json\",\n * version: \"1.4\"\n * };\n *\n * type CardData = {\n * title: string,\n * description: string\n * };\n * const card = MessageBuilder.attachAdaptiveCard<CardData>(\n * cardTemplate, {\n * title: \"sample card title\",\n * description: \"sample card description\"\n * });\n * ```\n */\n public static attachAdaptiveCard<TData extends object>(\n cardTemplate: unknown,\n data: TData\n ): Partial<Activity> {\n return {\n attachments: [CardFactory.adaptiveCard(AdaptiveCards.declare(cardTemplate).render(data))],\n };\n }\n\n /**\n * Build a bot message activity attached with an adaptive card.\n *\n * @param card The adaptive card content.\n * @returns A bot message activity attached with an adaptive card.\n */\n public static attachAdaptiveCardWithoutData(card: unknown): Partial<Activity> {\n return {\n attachments: [CardFactory.adaptiveCard(AdaptiveCards.declareWithoutData(card).render())],\n };\n }\n\n /**\n * Build a bot message activity attached with an hero card.\n *\n * @param title The card title.\n * @param images Optional. The array of images to include on the card.\n * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array\n * is converted to an `imBack` button with a title and value set to the value of the string.\n * @param other Optional. Any additional properties to include on the card.\n *\n * @returns A bot message activity attached with a hero card.\n *\n * @example\n * ```javascript\n * const message = MessageBuilder.attachHeroCard(\n * 'sample title',\n * ['https://example.com/sample.jpg'],\n * ['action']\n * );\n * ```\n */\n public static attachHeroCard(\n title: string,\n images?: (CardImage | string)[],\n buttons?: (CardAction | string)[],\n other?: Partial<HeroCard>\n ): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.heroCard(title, images, buttons, other));\n }\n\n /**\n * Returns an attachment for a sign-in card.\n *\n * @param title The title for the card's sign-in button.\n * @param url The URL of the sign-in page to use.\n * @param text Optional. Additional text to include on the card.\n *\n * @returns A bot message activity attached with a sign-in card.\n *\n * @remarks\n * For channels that don't natively support sign-in cards, an alternative message is rendered.\n */\n public static attachSigninCard(title: string, url: string, text?: string): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.signinCard(title, url, text));\n }\n\n /**\n * Build a bot message activity attached with an Office 365 connector card.\n *\n * @param card A description of the Office 365 connector card.\n * @returns A bot message activity attached with an Office 365 connector card.\n */\n public static attachO365ConnectorCard(card: O365ConnectorCard): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.o365ConnectorCard(card));\n }\n\n /**\n * Build a message activity attached with a receipt card.\n * @param card A description of the receipt card.\n * @returns A message activity attached with a receipt card.\n */\n public static AttachReceiptCard(card: ReceiptCard): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.receiptCard(card));\n }\n\n /**\n *\n * @param title The card title.\n * @param images Optional. The array of images to include on the card.\n * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array\n * is converted to an `imBack` button with a title and value set to the value of the string.\n * @param other Optional. Any additional properties to include on the card.\n * @returns A message activity attached with a thumbnail card\n */\n public static attachThumbnailCard(\n title: string,\n images?: (CardImage | string)[],\n buttons?: (CardAction | string)[],\n other?: Partial<ThumbnailCard>\n ): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.thumbnailCard(title, images, buttons, other));\n }\n\n /**\n * Add an attachement to a bot activity.\n * @param attachement The attachment object to attach.\n * @returns A message activity with an attachment.\n */\n public static attachContent(attachement: Attachment): Partial<Activity> {\n return {\n attachments: [attachement],\n };\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken } from \"@azure/identity\";\nimport { TurnContext, MessagingExtensionResponse, ActivityTypes } from \"botbuilder\";\nimport { parseJwt, getScopesArray, formatString } from \"../util/utils\";\nimport { MessageExtensionTokenResponse } from \"./teamsMsgExtTokenResponse\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport {\n AuthenticationConfiguration,\n OnBehalfOfCredentialAuthConfig,\n} from \"../models/configuration\";\nimport { IdentityType } from \"../models/identityType\";\nimport { internalLogger } from \"../util/logger\";\nimport { TeamsFx } from \"../core/teamsfx\";\nimport { OnBehalfOfUserCredential } from \"../credential/onBehalfOfUserCredential\";\n/**\n * Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions.\n * This method only work on MessageExtension with Query now.\n *\n * @param {OnBehalfOfCredentialAuthConfig} authConfig - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @returns SignIn link SilentAuth CardAction with 200 status code.\n */\nfunction getSignInResponseForMessageExtensionWithSilentAuthConfig(\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[]\n): any {\n const scopesArray = getScopesArray(scopes);\n const signInLink = `${initiateLoginEndpoint}?scope=${encodeURI(scopesArray.join(\" \"))}&clientId=${\n authConfig.clientId\n }&tenantId=${authConfig.tenantId}`;\n return {\n composeExtension: {\n type: \"silentAuth\",\n suggestedActions: {\n actions: [\n {\n type: \"openUrl\",\n value: signInLink,\n title: \"Message Extension OAuth\",\n },\n ],\n },\n },\n };\n}\n\n/**\n * Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions.\n * This method just a workaround for link unfurling now.\n *\n * @param {OnBehalfOfCredentialAuthConfig} authConfig - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @returns SignIn link Auth CardAction with 200 status code.\n */\nfunction getSignInResponseForMessageExtensionWithAuthConfig(\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[]\n): any {\n const scopesArray = getScopesArray(scopes);\n const signInLink = `${initiateLoginEndpoint}?scope=${encodeURI(scopesArray.join(\" \"))}&clientId=${\n authConfig.clientId\n }&tenantId=${authConfig.tenantId}`;\n return {\n composeExtension: {\n type: \"auth\",\n suggestedActions: {\n actions: [\n {\n type: \"openUrl\",\n value: signInLink,\n title: \"Message Extension OAuth\",\n },\n ],\n },\n },\n };\n}\n\n/**\n * Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions.\n * This method only work on MessageExtension with Query now.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @returns SignIn link CardAction with 200 status code.\n */\nfunction getSignInResponseForMessageExtension(teamsfx: TeamsFx, scopes: string | string[]): any {\n const scopesArray = getScopesArray(scopes);\n const signInLink = `${teamsfx.getConfig(\"initiateLoginEndpoint\")}?scope=${encodeURI(\n scopesArray.join(\" \")\n )}&clientId=${teamsfx.getConfig(\"clientId\")}&tenantId=${teamsfx.getConfig(\"tenantId\")}`;\n return {\n composeExtension: {\n type: \"silentAuth\",\n suggestedActions: {\n actions: [\n {\n type: \"openUrl\",\n value: signInLink,\n title: \"Message Extension OAuth\",\n },\n ],\n },\n },\n };\n}\n\n/**\n * execution in message extension with SSO token.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {OnBehalfOfCredentialAuthConfig} authConfig - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function executionWithTokenAndConfig(\n context: TurnContext,\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[],\n logic?: (token: MessageExtensionTokenResponse) => Promise<any>\n): Promise<MessagingExtensionResponse | void> {\n const valueObj = context.activity.value;\n if (!valueObj.authentication || !valueObj.authentication.token) {\n internalLogger.verbose(\"No AccessToken in request, return silentAuth for AccessToken\");\n return getSignInResponseForMessageExtensionWithSilentAuthConfig(\n authConfig,\n initiateLoginEndpoint,\n scopes\n );\n }\n try {\n const credential = new OnBehalfOfUserCredential(valueObj.authentication.token, authConfig);\n const token: AccessToken | null = await credential.getToken(scopes);\n const ssoTokenExpiration: number = parseJwt(valueObj.authentication.token).exp;\n const tokenRes: MessageExtensionTokenResponse = {\n ssoToken: valueObj.authentication.token,\n ssoTokenExpiration: new Date(ssoTokenExpiration * 1000).toISOString(),\n token: token!.token,\n expiration: token!.expiresOnTimestamp.toString(),\n connectionName: \"\",\n };\n if (logic) {\n return await logic(tokenRes);\n }\n } catch (err) {\n if (\n err instanceof ErrorWithCode &&\n err.code === ErrorCode.UiRequiredError &&\n context.activity.name === \"composeExtension/query\"\n ) {\n internalLogger.verbose(\"User not consent yet, return 412 to user consent first.\");\n const response = { status: 412 };\n await context.sendActivity({ value: response, type: ActivityTypes.InvokeResponse });\n return;\n } else if (\n err instanceof ErrorWithCode &&\n err.code === ErrorCode.UiRequiredError &&\n context.activity.name === \"composeExtension/queryLink\"\n ) {\n internalLogger.verbose(\"User not consent yet, return auth card for user login\");\n const response = getSignInResponseForMessageExtensionWithAuthConfig(\n authConfig,\n initiateLoginEndpoint,\n scopes\n );\n await context.sendActivity({\n value: { status: 200, body: response },\n type: ActivityTypes.InvokeResponse,\n });\n return;\n }\n throw err;\n }\n}\n\n/**\n * execution in message extension with SSO token.\n * @deprecated Use {@link executionWithTokenAndConfig} instead.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {AuthenticationConfiguration} config - User custom the message extension authentication configuration.\n * @param {string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function executionWithToken(\n context: TurnContext,\n config: AuthenticationConfiguration,\n scopes: string | string[],\n logic?: (token: MessageExtensionTokenResponse) => Promise<any>\n): Promise<MessagingExtensionResponse | void> {\n const valueObj = context.activity.value;\n if (!valueObj.authentication || !valueObj.authentication.token) {\n internalLogger.verbose(\"No AccessToken in request, return silentAuth for AccessToken\");\n return getSignInResponseForMessageExtension(new TeamsFx(IdentityType.User, config), scopes);\n }\n try {\n const teamsfx = new TeamsFx(IdentityType.User, config).setSsoToken(\n valueObj.authentication.token\n );\n const token: AccessToken | null = await teamsfx.getCredential().getToken(scopes);\n const ssoTokenExpiration: number = parseJwt(valueObj.authentication.token).exp;\n const tokenRes: MessageExtensionTokenResponse = {\n ssoToken: valueObj.authentication.token,\n ssoTokenExpiration: new Date(ssoTokenExpiration * 1000).toISOString(),\n token: token!.token,\n expiration: token!.expiresOnTimestamp.toString(),\n connectionName: \"\",\n };\n if (logic) {\n return await logic(tokenRes);\n }\n } catch (err) {\n if (err instanceof ErrorWithCode && err.code === ErrorCode.UiRequiredError) {\n internalLogger.verbose(\"User not consent yet, return 412 to user consent first.\");\n const response = { status: 412 };\n await context.sendActivity({ value: response, type: ActivityTypes.InvokeResponse });\n return;\n }\n throw err;\n }\n}\n\n// eslint-disable-next-line no-secrets/no-secrets\n/**\n * Users execute query in message extension with SSO or access token.\n * @deprecated Use {@link handleMessageExtensionQueryWithSSO} instead.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {AuthenticationConfiguration} config - User custom the message extension authentication configuration.\n * @param {string| string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when User invoke not response to message extension query.\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function handleMessageExtensionQueryWithToken(\n context: TurnContext,\n config: AuthenticationConfiguration | null,\n scopes: string | string[],\n logic: (token: MessageExtensionTokenResponse) => Promise<any>\n): Promise<MessagingExtensionResponse | void> {\n if (context.activity.name != \"composeExtension/query\") {\n internalLogger.error(ErrorMessage.OnlySupportInQueryActivity);\n throw new ErrorWithCode(\n formatString(ErrorMessage.OnlySupportInQueryActivity),\n ErrorCode.FailedOperation\n );\n }\n return await executionWithToken(context, config ?? {}, scopes, logic);\n}\n\n/**\n * Users execute query in message extension with SSO or access token.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {OnBehalfOfCredentialAuthConfig} config - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string| string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when User invoke not response to message extension query.\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function handleMessageExtensionQueryWithSSO(\n context: TurnContext,\n config: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[],\n logic: (token: MessageExtensionTokenResponse) => Promise<any>\n) {\n if (context.activity.name != \"composeExtension/query\") {\n internalLogger.error(ErrorMessage.OnlySupportInQueryActivity);\n throw new ErrorWithCode(\n formatString(ErrorMessage.OnlySupportInQueryActivity),\n ErrorCode.FailedOperation\n );\n }\n return await executionWithTokenAndConfig(\n context,\n config ?? {},\n initiateLoginEndpoint,\n scopes,\n logic\n );\n}\n\n/**\n * Users execute link query in message extension with SSO or access token.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {OnBehalfOfCredentialAuthConfig} config - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string| string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the link query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when User invoke not response to message extension link query.\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function handleMessageExtensionLinkQueryWithSSO(\n context: TurnContext,\n config: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[],\n logic: (token: MessageExtensionTokenResponse) => Promise<any>\n) {\n if (context.activity.name != \"composeExtension/queryLink\") {\n internalLogger.error(ErrorMessage.OnlySupportInLinkQueryActivity);\n throw new ErrorWithCode(\n formatString(ErrorMessage.OnlySupportInLinkQueryActivity),\n ErrorCode.FailedOperation\n );\n }\n return await executionWithTokenAndConfig(\n context,\n config ?? {},\n initiateLoginEndpoint,\n scopes,\n logic\n );\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { CloudAdapter } from \"botbuilder\";\nimport { CardActionMiddleware } from \"../conversation/middlewares/cardActionMiddleware\";\nimport { CardActionOptions, TeamsFxAdaptiveCardActionHandler } from \"../conversation/interface\";\n\n/**\n * A card action bot to respond to adaptive card universal actions.\n */\nexport class CardActionBot {\n private readonly adapter: CloudAdapter;\n private middleware: CardActionMiddleware;\n\n /**\n * Create a new instance of the `CardActionBot`.\n *\n * @param adapter - The bound `CloudAdapter`.\n * @param options - The initialize options.\n */\n constructor(adapter: CloudAdapter, options?: CardActionOptions) {\n this.middleware = new CardActionMiddleware(options?.actions);\n this.adapter = adapter.use(this.middleware);\n }\n\n /**\n * Register a card action handler to the bot.\n *\n * @param actionHandler - A card action handler to be registered.\n */\n registerHandler(actionHandler: TeamsFxAdaptiveCardActionHandler) {\n if (actionHandler) {\n this.middleware.actionHandlers.push(actionHandler);\n }\n }\n\n /**\n * Register card action handlers to the bot.\n *\n * @param actionHandlers - A set of card action handlers to be registered.\n */\n registerHandlers(actionHandlers: TeamsFxAdaptiveCardActionHandler[]) {\n if (actionHandlers) {\n this.middleware.actionHandlers.push(...actionHandlers);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CloudAdapter } from \"botbuilder\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport {\n CommandOptions,\n BotSsoConfig,\n BotSsoExecutionActivityHandler,\n TeamsFxBotCommandHandler,\n TeamsFxBotSsoCommandHandler,\n} from \"../conversation/interface\";\nimport { CommandResponseMiddleware } from \"../conversation/middlewares/commandMiddleware\";\n\n/**\n * A command bot for receiving commands and sending responses in Teams.\n *\n * @remarks\n * Ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.\n */\nexport class CommandBot {\n private readonly adapter: CloudAdapter;\n private readonly middleware: CommandResponseMiddleware;\n private readonly ssoConfig: BotSsoConfig | undefined;\n\n // eslint-disable-next-line no-secrets/no-secrets\n /**\n * Create a new instance of the `CommandBot`.\n *\n * @param adapter - The bound `CloudAdapter`.\n * @param options - The initialize options\n * @param ssoCommandActivityHandler - SSO execution activity handler.\n * @param ssoConfig - SSO configuration for Bot SSO.\n */\n constructor(\n adapter: CloudAdapter,\n options?: CommandOptions,\n ssoCommandActivityHandler?: BotSsoExecutionActivityHandler,\n ssoConfig?: BotSsoConfig\n ) {\n this.ssoConfig = ssoConfig;\n\n this.middleware = new CommandResponseMiddleware(\n options?.commands,\n options?.ssoCommands,\n ssoCommandActivityHandler\n );\n this.adapter = adapter.use(this.middleware);\n }\n\n /**\n * Register a command into the command bot.\n *\n * @param command - The command to be registered.\n */\n public registerCommand(command: TeamsFxBotCommandHandler): void {\n if (command) {\n this.middleware.commandHandlers.push(command);\n }\n }\n\n /**\n * Register commands into the command bot.\n *\n * @param commands - The commands to be registered.\n */\n public registerCommands(commands: TeamsFxBotCommandHandler[]): void {\n if (commands) {\n this.middleware.commandHandlers.push(...commands);\n }\n }\n\n /**\n * Register a sso command into the command bot.\n *\n * @param ssoCommand - The sso command to be registered.\n */\n public registerSsoCommand(ssoCommand: TeamsFxBotSsoCommandHandler): void {\n this.validateSsoActivityHandler();\n this.middleware.addSsoCommand(ssoCommand);\n }\n\n /**\n * Register sso commands into the command bot.\n *\n * @param ssoCommands - The sso commands to be registered.\n */\n public registerSsoCommands(ssoCommands: TeamsFxBotSsoCommandHandler[]): void {\n if (ssoCommands.length > 0) {\n this.validateSsoActivityHandler();\n for (const ssoCommand of ssoCommands) {\n this.middleware.addSsoCommand(ssoCommand);\n }\n }\n }\n\n private validateSsoActivityHandler() {\n if (!this.middleware.ssoActivityHandler) {\n internalLogger.error(ErrorMessage.SsoActivityHandlerIsNull);\n throw new ErrorWithCode(\n ErrorMessage.SsoActivityHandlerIsNull,\n ErrorCode.SsoActivityHandlerIsUndefined\n );\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n CloudAdapter,\n CardFactory,\n ChannelInfo,\n ConversationParameters,\n ConversationReference,\n TeamDetails,\n TeamsChannelAccount,\n TeamsInfo,\n TurnContext,\n} from \"botbuilder\";\nimport type { ConnectorClient } from \"botframework-connector\";\nimport * as path from \"path\";\nimport {\n NotificationTarget,\n NotificationTargetType,\n MessageResponse,\n ConversationReferenceStore,\n PagedData,\n} from \"../conversation/interface\";\nimport { NotificationOptions } from \"./interface\";\nimport { NotificationMiddleware } from \"../conversation/middlewares/notificationMiddleware\";\nimport { DefaultConversationReferenceStore, LocalFileStorage } from \"../conversation/storage\";\nimport * as utils from \"../conversation/utils\";\n\n/**\n * Send a plain text message to a notification target.\n *\n * @param target - The notification target.\n * @param text - The plain text message.\n * @param onError - An optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending message.\n */\nexport function sendMessage(\n target: NotificationTarget,\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n): Promise<MessageResponse> {\n return target.sendMessage(text, onError);\n}\n\n/**\n * Send an adaptive card message to a notification target.\n *\n * @param target - The notification target.\n * @param card - The adaptive card raw JSON.\n * @param onError - An optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending adaptive card message.\n */\nexport function sendAdaptiveCard(\n target: NotificationTarget,\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n): Promise<MessageResponse> {\n return target.sendAdaptiveCard(card, onError);\n}\n\n/**\n * A {@link NotificationTarget} that represents a team channel.\n *\n * @remarks\n * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.\n */\nexport class Channel implements NotificationTarget {\n /**\n * The parent {@link TeamsBotInstallation} where this channel is created from.\n */\n public readonly parent: TeamsBotInstallation;\n\n /**\n * Detailed channel information.\n */\n public readonly info: ChannelInfo;\n\n /**\n * Notification target type. For channel it's always \"Channel\".\n */\n public readonly type: NotificationTargetType = NotificationTargetType.Channel;\n\n /**\n * Constructor.\n *\n * @remarks\n * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.\n *\n * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.\n * @param info - Detailed channel information.\n */\n constructor(parent: TeamsBotInstallation, info: ChannelInfo) {\n this.parent = parent;\n this.info = info;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - The plain text message.\n * @param onError - An optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n conversation,\n async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - The adaptive card raw JSON.\n * @param onError - An optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n conversation,\n async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n }\n );\n return response;\n }\n\n /**\n * @internal\n */\n private newConversation(context: TurnContext): Promise<ConversationReference> {\n const reference = TurnContext.getConversationReference(context.activity);\n const channelConversation = utils.cloneConversation(reference);\n channelConversation.conversation.id = this.info.id || \"\";\n\n return Promise.resolve(channelConversation);\n }\n}\n\n/**\n * A {@link NotificationTarget} that represents a team member.\n *\n * @remarks\n * It's recommended to get members from {@link TeamsBotInstallation.members()}.\n */\nexport class Member implements NotificationTarget {\n /**\n * The parent {@link TeamsBotInstallation} where this member is created from.\n */\n public readonly parent: TeamsBotInstallation;\n\n /**\n * Detailed member account information.\n */\n public readonly account: TeamsChannelAccount;\n\n /**\n * Notification target type. For member it's always \"Person\".\n */\n public readonly type: NotificationTargetType = NotificationTargetType.Person;\n\n /**\n * Constructor.\n *\n * @remarks\n * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.\n *\n * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.\n * @param account - Detailed member account information.\n */\n constructor(parent: TeamsBotInstallation, account: TeamsChannelAccount) {\n this.parent = parent;\n this.account = account;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - The plain text message.\n * @param onError - An optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n conversation,\n async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - The adaptive card raw JSON.\n * @param onError - An optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n conversation,\n async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n }\n );\n return response;\n }\n\n /**\n * @internal\n */\n private async newConversation(context: TurnContext): Promise<ConversationReference> {\n const reference = TurnContext.getConversationReference(context.activity);\n const personalConversation = utils.cloneConversation(reference);\n\n const connectorClient: ConnectorClient = context.turnState.get(\n this.parent.adapter.ConnectorClientKey\n );\n const conversation = await connectorClient.conversations.createConversation({\n isGroup: false,\n tenantId: context.activity.conversation.tenantId,\n bot: context.activity.recipient,\n members: [this.account],\n channelData: {},\n } as ConversationParameters);\n personalConversation.conversation.id = conversation.id;\n\n return personalConversation;\n }\n}\n\n/**\n * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into\n * - Personal chat\n * - Group chat\n * - Team (by default the `General` channel)\n *\n * @remarks\n * It's recommended to get bot installations from {@link ConversationBot.installations()}.\n */\nexport class TeamsBotInstallation implements NotificationTarget {\n /**\n * The bound `CloudAdapter`.\n */\n public readonly adapter: CloudAdapter;\n\n /**\n * The bound `ConversationReference`.\n */\n public readonly conversationReference: Partial<ConversationReference>;\n\n /**\n * The bot app id.\n */\n public readonly botAppId: string;\n /**\n * Notification target type.\n *\n * @remarks\n * - \"Channel\" means bot is installed into a team and notification will be sent to its \"General\" channel.\n * - \"Group\" means bot is installed into a group chat.\n * - \"Person\" means bot is installed into a personal scope and notification will be sent to personal chat.\n */\n public readonly type?: NotificationTargetType;\n\n /**\n * Constructor\n *\n * @remarks\n * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.\n *\n * @param adapter - The bound `CloudAdapter`.\n * @param conversationReference - The bound `ConversationReference`.\n * @param botAppId - The bot app id.\n */\n constructor(\n adapter: CloudAdapter,\n conversationReference: Partial<ConversationReference>,\n botAppId: string\n ) {\n this.adapter = adapter;\n this.conversationReference = conversationReference;\n this.type = utils.getTargetType(conversationReference);\n this.botAppId = botAppId;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - The plain text message.\n * @param onError - An optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n try {\n const res = await context.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(context, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - The adaptive card raw JSON.\n * @param onError - An optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n try {\n const res = await context.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(context, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n return response;\n }\n\n /**\n * Get channels from this bot installation.\n *\n * @returns An array of channels if bot is installed into a team, otherwise returns an empty array.\n */\n public async channels(): Promise<Channel[]> {\n const channels: Channel[] = [];\n if (this.type !== NotificationTargetType.Channel) {\n return channels;\n }\n\n let teamsChannels: ChannelInfo[] = [];\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n const teamId = utils.getTeamsBotInstallationId(context);\n if (teamId !== undefined) {\n teamsChannels = await TeamsInfo.getTeamChannels(context, teamId);\n }\n }\n );\n\n for (const channel of teamsChannels) {\n channels.push(new Channel(this, channel));\n }\n\n return channels;\n }\n\n /**\n * Gets a pagined list of members from this bot installation.\n *\n * @param pageSize - Suggested number of entries on a page.\n * @param continuationToken - A continuation token.\n * @returns An array of members from where the bot is installed.\n */\n public async getPagedMembers(\n pageSize?: number,\n continuationToken?: string\n ): Promise<PagedData<Member>> {\n let result: PagedData<Member> = {\n data: [],\n continuationToken: \"\",\n };\n\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n const pagedMembers = await TeamsInfo.getPagedMembers(context, pageSize, continuationToken);\n\n result = {\n data: pagedMembers.members.map((m) => new Member(this, m)),\n continuationToken: pagedMembers.continuationToken,\n };\n }\n );\n\n return result;\n }\n\n /**\n * Get members from this bot installation.\n *\n * @returns An array of members from where the bot is installed.\n *\n * @deprecated Use `getPagedMembers` instead.\n */\n public async members(): Promise<Member[]> {\n const members: Member[] = [];\n\n let continuationToken: string | undefined;\n do {\n const pagedData = await this.getPagedMembers(undefined, continuationToken);\n continuationToken = pagedData.continuationToken;\n members.push(...pagedData.data);\n } while (continuationToken);\n\n return members;\n }\n\n /**\n * Get team details from this bot installation\n *\n * @returns The team details if bot is installed into a team, otherwise returns `undefined`.\n */\n public async getTeamDetails(): Promise<TeamDetails | undefined> {\n if (this.type !== NotificationTargetType.Channel) {\n return undefined;\n }\n\n let teamDetails: TeamDetails | undefined;\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n const teamId = utils.getTeamsBotInstallationId(context);\n if (teamId !== undefined) {\n teamDetails = await TeamsInfo.getTeamDetails(context, teamId);\n }\n }\n );\n\n return teamDetails;\n }\n}\n\n/**\n * Provide utilities to send notification to varies targets (e.g., member, group, channel).\n */\nexport class NotificationBot {\n private readonly conversationReferenceStore: ConversationReferenceStore;\n private readonly adapter: CloudAdapter;\n private readonly botAppId: string;\n\n /**\n * Constructor of the notification bot.\n *\n * @remarks\n * To ensure accuracy, it's recommended to initialize before handling any message.\n *\n * @param adapter - The bound `CloudAdapter`\n * @param options - The initialize options\n */\n public constructor(adapter: CloudAdapter, options?: NotificationOptions) {\n if (options?.store) {\n this.conversationReferenceStore = options.store;\n } else {\n const storage =\n options?.storage ??\n new LocalFileStorage(\n path.resolve(process.env.RUNNING_ON_AZURE === \"1\" ? process.env.TEMP ?? \"./\" : \"./\")\n );\n\n this.conversationReferenceStore = new DefaultConversationReferenceStore(storage);\n }\n\n this.adapter = adapter.use(\n new NotificationMiddleware({\n conversationReferenceStore: this.conversationReferenceStore,\n })\n );\n this.botAppId = (options?.botAppId ?? process.env.BOT_ID) as string;\n }\n\n /**\n * Create a {@link TeamsBotInstallation} instance with conversation reference.\n *\n * @param conversationReference - The bound `ConversationReference`.\n * @returns - The {@link TeamsBotInstallation} instance or null.\n */\n public buildTeamsBotInstallation(\n conversationReference: Partial<ConversationReference>\n ): TeamsBotInstallation | null {\n if (!conversationReference) {\n throw new Error(\"conversationReference is required.\");\n }\n\n return new TeamsBotInstallation(this.adapter, conversationReference, this.botAppId);\n }\n\n /**\n * Validate the installation by getting paged memebers.\n *\n * @param conversationReference The bound `ConversationReference`.\n * @returns Returns false if recieves `BotNotInConversationRoster` error, otherwise returns true.\n */\n public async validateInstallation(\n conversationReference: Partial<ConversationReference>\n ): Promise<boolean> {\n let isValid = true;\n await this.adapter.continueConversationAsync(\n this.botAppId,\n conversationReference,\n async (context) => {\n try {\n // try get member to see if the installation is still valid\n await TeamsInfo.getPagedMembers(context, 1);\n } catch (error: any) {\n if ((error.code as string) === \"BotNotInConversationRoster\") {\n isValid = false;\n }\n }\n }\n );\n return isValid;\n }\n\n /**\n * Gets a pagined list of targets where the bot is installed.\n *\n * @remarks\n * The result is retrieving from the persisted storage.\n *\n * @param pageSize - Suggested number of entries on a page.\n * @param continuationToken - A continuation token.\n *\n * @returns An array of {@link TeamsBotInstallation} with paged data and continuation token.\n */\n public async getPagedInstallations(\n pageSize?: number,\n continuationToken?: string,\n validationEnabled = true\n ): Promise<PagedData<TeamsBotInstallation>> {\n if (this.conversationReferenceStore === undefined || this.adapter === undefined) {\n throw new Error(\"NotificationBot has not been initialized.\");\n }\n\n const references = await this.conversationReferenceStore.list(pageSize, continuationToken);\n const targets: TeamsBotInstallation[] = [];\n for (const reference of references.data) {\n // validate connection\n let valid;\n if (validationEnabled) {\n // try get member to see if the installation is still valid\n valid = await this.validateInstallation(reference);\n }\n\n if (!validationEnabled || (validationEnabled && valid)) {\n targets.push(new TeamsBotInstallation(this.adapter, reference, this.botAppId));\n } else {\n await this.conversationReferenceStore.remove(utils.getKey(reference), reference);\n }\n }\n\n return {\n data: targets,\n continuationToken: references.continuationToken,\n };\n }\n\n /**\n * Get all targets where the bot is installed.\n *\n * @remarks\n * The result is retrieving from the persisted storage.\n *\n * @returns An array of {@link TeamsBotInstallation}.\n *\n * @deprecated Use getPagedInstallations instead.\n */\n public async installations(): Promise<TeamsBotInstallation[]> {\n let continuationToken: string | undefined;\n const targets: TeamsBotInstallation[] = [];\n do {\n const result = await this.getPagedInstallations(undefined, continuationToken);\n continuationToken = result.continuationToken;\n targets.push(...result.data);\n } while (continuationToken);\n\n return targets;\n }\n\n /**\n * Return the first {@link Member} where predicate is true, and undefined otherwise.\n *\n * @param predicate - Find calls predicate once for each member of the installation,\n * until it finds one where predicate returns true. If such a member is found, find\n * immediately returns that member. Otherwise, find returns undefined.\n * @param scope - The scope to find members from the installations\n * (personal chat, group chat, Teams channel).\n *\n * @returns The first {@link Member} where predicate is true, and `undefined` otherwise.\n */\n public async findMember(\n predicate: (member: Member) => Promise<boolean>,\n scope?: SearchScope\n ): Promise<Member | undefined> {\n for (const target of await this.installations()) {\n if (this.matchSearchScope(target, scope)) {\n for (const member of await target.members()) {\n if (await predicate(member)) {\n return member;\n }\n }\n }\n }\n\n return;\n }\n\n /**\n * Return the first {@link Channel} where predicate is true, and undefined otherwise.\n * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)\n *\n * @param predicate - Find calls predicate once for each channel of the installation,\n * until it finds one where predicate returns true. If such a channel is found, find\n * immediately returns that channel. Otherwise, find returns `undefined`.\n *\n * @returns The first {@link Channel} where predicate is true, and `undefined` otherwise.\n */\n public async findChannel(\n predicate: (channel: Channel, teamDetails: TeamDetails | undefined) => Promise<boolean>\n ): Promise<Channel | undefined> {\n for (const target of await this.installations()) {\n if (target.type === NotificationTargetType.Channel) {\n const teamDetails = await target.getTeamDetails();\n for (const channel of await target.channels()) {\n if (await predicate(channel, teamDetails)) {\n return channel;\n }\n }\n }\n }\n\n return;\n }\n\n /**\n * Return all {@link Member} where predicate is true, and empty array otherwise.\n *\n * @param predicate - Find calls predicate for each member of the installation.\n * @param scope - The scope to find members from the installations\n * (personal chat, group chat, Teams channel).\n *\n * @returns An array of {@link Member} where predicate is true, and empty array otherwise.\n */\n public async findAllMembers(\n predicate: (member: Member) => Promise<boolean>,\n scope?: SearchScope\n ): Promise<Member[]> {\n const members: Member[] = [];\n for (const target of await this.installations()) {\n if (this.matchSearchScope(target, scope)) {\n for (const member of await target.members()) {\n if (await predicate(member)) {\n members.push(member);\n }\n }\n }\n }\n\n return members;\n }\n\n /**\n * Return all {@link Channel} where predicate is true, and empty array otherwise.\n * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)\n *\n * @param predicate - Find calls predicate for each channel of the installation.\n *\n * @returns An array of {@link Channel} where predicate is true, and empty array otherwise.\n */\n public async findAllChannels(\n predicate: (channel: Channel, teamDetails: TeamDetails | undefined) => Promise<boolean>\n ): Promise<Channel[]> {\n const channels: Channel[] = [];\n for (const target of await this.installations()) {\n if (target.type === NotificationTargetType.Channel) {\n const teamDetails = await target.getTeamDetails();\n for (const channel of await target.channels()) {\n if (await predicate(channel, teamDetails)) {\n channels.push(channel);\n }\n }\n }\n }\n\n return channels;\n }\n\n private matchSearchScope(target: NotificationTarget, scope?: SearchScope): boolean {\n scope = scope ?? SearchScope.All;\n\n return (\n (target.type === NotificationTargetType.Channel && (scope & SearchScope.Channel) !== 0) ||\n (target.type === NotificationTargetType.Group && (scope & SearchScope.Group) !== 0) ||\n (target.type === NotificationTargetType.Person && (scope & SearchScope.Person) !== 0)\n );\n }\n}\n\n/**\n * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.\n * The search scope is a flagged enum and it can be combined with `|`.\n * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.\n */\nexport enum SearchScope {\n /**\n * Search members from the installations in personal chat only.\n */\n Person = 1,\n\n /**\n * Search members from the installations in group chat only.\n */\n Group = 2,\n\n /**\n * Search members from the installations in Teams channel only.\n */\n Channel = 4,\n\n /**\n * Search members from all installations including personal chat, group chat and Teams channel.\n */\n All = Person | Group | Channel,\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n CloudAdapter,\n ConfigurationServiceClientCredentialFactory,\n ConfigurationBotFrameworkAuthentication,\n TurnContext,\n Request,\n Response,\n} from \"botbuilder\";\nimport { CardActionBot } from \"./cardAction\";\nimport { CommandBot } from \"./command\";\nimport { BotSsoExecutionActivityHandler } from \"../conversation/interface\";\nimport { ConversationOptions } from \"./interface\";\nimport { NotificationBot } from \"./notification\";\nimport { DefaultBotSsoExecutionActivityHandler } from \"../conversation/sso/defaultBotSsoExecutionActivityHandler\";\n\n/**\n * Provide utilities for bot conversation, including:\n * - handle command and response.\n * - send notification to varies targets (e.g., member, group, channel).\n *\n * @example\n * For command and response, you can register your commands through the constructor, or use the `registerCommand` and `registerCommands` API to add commands later.\n *\n * ```typescript\n * import { BotBuilderCloudAdapter } from \"@microsoft/teamsfx\";\n * import ConversationBot = BotBuilderCloudAdapter.ConversationBot;\n *\n * // register through constructor\n * const conversationBot = new ConversationBot({\n * command: {\n * enabled: true,\n * commands: [ new HelloWorldCommandHandler() ],\n * },\n * });\n *\n * // register through `register*` API\n * conversationBot.command.registerCommand(new HelpCommandHandler());\n * ```\n *\n * For notification, you can enable notification at initialization, then send notifications at any time.\n *\n * ```typescript\n * import { BotBuilderCloudAdapter } from \"@microsoft/teamsfx\";\n * import ConversationBot = BotBuilderCloudAdapter.ConversationBot;\n *\n * // enable through constructor\n * const conversationBot = new ConversationBot({\n * notification: {\n * enabled: true,\n * },\n * });\n *\n * // get all bot installations and send message\n * for (const target of await conversationBot.notification.installations()) {\n * await target.sendMessage(\"Hello Notification\");\n * }\n *\n * // alternative - send message to all members\n * for (const target of await conversationBot.notification.installations()) {\n * for (const member of await target.members()) {\n * await member.sendMessage(\"Hello Notification\");\n * }\n * }\n * ```\n *\n * @remarks\n * Set `adapter` in {@link ConversationOptions} to use your own bot adapter.\n *\n * For command and response, ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.\n *\n * For notification, set `notification.storage` in {@link ConversationOptions} to use your own storage implementation.\n */\nexport class ConversationBot {\n /**\n * The bot adapter.\n */\n public readonly adapter: CloudAdapter;\n\n /**\n * The entrypoint of command and response.\n */\n public readonly command?: CommandBot;\n\n /**\n * The entrypoint of notification.\n */\n public readonly notification?: NotificationBot;\n\n /**\n * The action handler used for adaptive card universal actions.\n */\n public readonly cardAction?: CardActionBot;\n\n /**\n * Create new instance of the `ConversationBot`.\n *\n * @remarks\n * It's recommended to create your own adapter and storage for production environment instead of the default one.\n *\n * @param options - The initialize options.\n */\n public constructor(options: ConversationOptions) {\n if (options.adapter) {\n this.adapter = options.adapter;\n } else {\n this.adapter = this.createDefaultAdapter(options.adapterConfig);\n }\n\n let ssoCommandActivityHandler: BotSsoExecutionActivityHandler | undefined;\n\n if (options?.ssoConfig) {\n if (options.ssoConfig.dialog?.CustomBotSsoExecutionActivityHandler) {\n ssoCommandActivityHandler =\n new options.ssoConfig.dialog.CustomBotSsoExecutionActivityHandler(options.ssoConfig);\n } else {\n ssoCommandActivityHandler = new DefaultBotSsoExecutionActivityHandler(options.ssoConfig);\n }\n }\n\n if (options.command?.enabled) {\n this.command = new CommandBot(\n this.adapter,\n options.command,\n ssoCommandActivityHandler,\n options.ssoConfig\n );\n }\n\n if (options.notification?.enabled) {\n this.notification = new NotificationBot(this.adapter, options.notification);\n }\n\n if (options.cardAction?.enabled) {\n this.cardAction = new CardActionBot(this.adapter, options.cardAction);\n }\n }\n\n private createDefaultAdapter(adapterConfig?: { [key: string]: unknown }): CloudAdapter {\n const credentialsFactory =\n adapterConfig === undefined\n ? new ConfigurationServiceClientCredentialFactory({\n MicrosoftAppId: process.env.BOT_ID,\n MicrosoftAppPassword: process.env.BOT_PASSWORD,\n MicrosoftAppType: \"MultiTenant\",\n })\n : new ConfigurationServiceClientCredentialFactory(adapterConfig);\n const botFrameworkAuthentication = new ConfigurationBotFrameworkAuthentication(\n {},\n credentialsFactory\n );\n const adapter = new CloudAdapter(botFrameworkAuthentication);\n\n // the default error handler\n adapter.onTurnError = async (context, error) => {\n // This check writes out errors to console.\n console.error(`[onTurnError] unhandled error`, error);\n\n // Only send error message for user messages, not for other message types so the bot doesn't spam a channel or chat.\n if (context.activity.type === \"message\") {\n // Send a trace activity, which will be displayed in Bot Framework Emulator\n await context.sendTraceActivity(\n \"OnTurnError Trace\",\n error instanceof Error ? error.message : error,\n \"https://www.botframework.com/schemas/error\",\n \"TurnError\"\n );\n\n // Send a message to the user\n await context.sendActivity(`The bot encountered unhandled error: ${error.message}`);\n await context.sendActivity(\"To continue to run this bot, please fix the bot source code.\");\n }\n };\n\n return adapter;\n }\n\n /**\n * The request handler to integrate with web request.\n *\n * @param req - An incoming HTTP [Request](xref:botbuilder.Request).\n * @param res - The corresponding HTTP [Response](xref:botbuilder.Response).\n * @param logic - The additional function to handle bot context.\n *\n * @example\n * For example, to use with Restify:\n * ``` typescript\n * // The default/empty behavior\n * server.use(restify.plugins.bodyParser());\n * server.post(\"api/messages\", conversationBot.requestHandler);\n *\n * // Or, add your own logic\n * server.use(restify.plugins.bodyParser());\n * server.post(\"api/messages\", async (req, res) => {\n * await conversationBot.requestHandler(req, res, async (context) => {\n * // your-own-context-logic\n * });\n * });\n * ```\n */\n public async requestHandler(\n req: Request,\n res: Response,\n logic?: (context: TurnContext) => Promise<any>\n ): Promise<void> {\n if (logic === undefined) {\n // create empty logic\n logic = async () => {};\n }\n\n await this.adapter.process(req, res, logic);\n }\n}\n"],"names":["ErrorCode","LogLevel","jwt_decode","ConfidentialClientApplication","createHash","Client","ManagedIdentityCredential","IdentityType","Dialog","ActivityTypes","Channels","TeamsInfo","CardFactory","ActionTypes","MessageFactory","uuidv4","StatusCodes","verifyStateOperationName","tokenExchangeOperationName","axios","ApiKeyLocation","Agent","NotificationTargetType","AdaptiveCardResponse","InvokeResponseErrorCode","CardActionBot","TurnContext","CommandBot","path","fs","sendMessage","sendAdaptiveCard","Channel","utils.cloneConversation","Member","TeamsBotInstallation","utils.getTargetType","utils.getTeamsBotInstallationId","NotificationBot","utils.getKey","SearchScope","ComponentDialog","WaterfallDialog","DialogSet","DialogTurnStatus","TeamsActivityHandler","MemoryStorage","UserState","ConversationState","ConversationBot","BotFrameworkAdapter","AdaptiveCards","ConfigurationServiceClientCredentialFactory","ConfigurationBotFrameworkAuthentication","CloudAdapter"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAEA;;;AAGYA;AAAZ,WAAY,SAAS;;;;IAInB,kDAAqC,CAAA;;;;IAKrC,0DAA6C,CAAA;;;;IAK7C,sDAAyC,CAAA;;;;IAKzC,4CAA+B,CAAA;;;;IAK/B,wDAA2C,CAAA;;;;IAK3C,kEAAqD,CAAA;;;;IAKrD,oEAAuD,CAAA;;;;IAKvD,oDAAuC,CAAA;;;;IAKvC,sDAAyC,CAAA;;;;IAKzC,0DAA6C,CAAA;;;;IAK7C,4EAA+D,CAAA;;;;IAK/D,wDAA2C,CAAA;;;;IAK3C,4CAA+B,CAAA;;;;IAK/B,gDAAm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AE,KAAK,CAAC,CAAC;;YAGtD,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,KAAK,SAAS,EAAE;;gBAEvC,MAAM,OAAO,CAAC,iBAAiB,CAC7B,mBAAmB,EACnB,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,KAAK,EAC9C,4CAA4C,EAC5C,WAAW,CACZ,CAAC;;gBAGF,MAAM,OAAO,CAAC,YAAY,CAAC,wCAAwC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;gBACpF,MAAM,OAAO,CAAC,YAAY,CAAC,8DAA8D,CAAC,CAAC;aAC5F;SACF,CAAA,CAAC;QAEF,OAAO,OAAO,CAAC;KAChB;;;;;;;;;;;;;;;;;;;;;;;;IAyBY,cAAc,CACzB,GAAY,EACZ,GAAa,EACb,KAA8C;;YAE9C,IAAI,KAAK,KAAK,SAAS,EAAE;;gBAEvB,KAAK,GAAG,sDAAc,CAAA,CAAC;aACxB;YAED,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;SAC7C;KAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.node.cjs.js","sources":["../src/core/errors.ts","../src/util/logger.ts","../src/util/utils.ts","../src/util/utils.node.ts","../src/credential/appCredential.ts","../src/credential/onBehalfOfUserCredential.ts","../src/credential/teamsUserCredential.ts","../src/core/msGraphAuthProvider.ts","../src/core/msGraphClientProvider.ts","../src/core/defaultTediousConnectionConfiguration.ts","../src/models/identityType.ts","../src/bot/teamsBotSsoPrompt.ts","../src/apiClient/apiClient.ts","../src/apiClient/bearerTokenAuthProvider.ts","../src/apiClient/basicAuthProvider.ts","../src/apiClient/apiKeyProvider.ts","../src/apiClient/certificateAuthProvider.ts","../src/core/teamsfx.ts","../src/conversation/interface.ts","../src/conversation/invokeResponseFactory.ts","../src/conversation/middlewares/cardActionMiddleware.ts","../src/conversation/cardAction.ts","../src/conversation/middlewares/commandMiddleware.ts","../src/conversation/command.ts","../src/conversation/utils.ts","../src/conversation/middlewares/notificationMiddleware.ts","../src/conversation/storage.ts","../src/conversation/notification.ts","../src/conversation/sso/botSsoExecutionDialog.ts","../src/conversation/sso/defaultBotSsoExecutionActivityHandler.ts","../src/conversation/conversation.ts","../src/conversation/messageBuilder.ts","../src/messageExtension/executeWithSSO.ts","../src/conversationWithCloudAdapter/cardAction.ts","../src/conversationWithCloudAdapter/command.ts","../src/conversationWithCloudAdapter/notification.ts","../src/conversationWithCloudAdapter/conversation.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Error code to trace the error types.\n */\nexport enum ErrorCode {\n /**\n * Invalid parameter error.\n */\n InvalidParameter = \"InvalidParameter\",\n\n /**\n * Invalid configuration error.\n */\n InvalidConfiguration = \"InvalidConfiguration\",\n\n /**\n * Invalid certificate error.\n */\n InvalidCertificate = \"InvalidCertificate\",\n\n /**\n * Internal error.\n */\n InternalError = \"InternalError\",\n\n /**\n * Channel is not supported error.\n */\n ChannelNotSupported = \"ChannelNotSupported\",\n\n /**\n * Failed to retrieve sso token\n */\n FailedToRetrieveSsoToken = \"FailedToRetrieveSsoToken\",\n\n /**\n * Failed to process sso handler\n */\n FailedToProcessSsoHandler = \"FailedToProcessSsoHandler\",\n\n /**\n * Cannot find command\n */\n CannotFindCommand = \"CannotFindCommand\",\n\n /**\n * Failed to run sso step\n */\n FailedToRunSsoStep = \"FailedToRunSsoStep\",\n\n /**\n * Failed to run dedup step\n */\n FailedToRunDedupStep = \"FailedToRunDedupStep\",\n\n /**\n * Sso activity handler is undefined\n */\n SsoActivityHandlerIsUndefined = \"SsoActivityHandlerIsUndefined\",\n\n /**\n * Runtime is not supported error.\n */\n RuntimeNotSupported = \"RuntimeNotSupported\",\n\n /**\n * User failed to finish the AAD consent flow failed.\n */\n ConsentFailed = \"ConsentFailed\",\n\n /**\n * The user or administrator has not consented to use the application error.\n */\n UiRequiredError = \"UiRequiredError\",\n\n /**\n * Token is not within its valid time range error.\n */\n TokenExpiredError = \"TokenExpiredError\",\n\n /**\n * Call service (AAD or simple authentication server) failed.\n */\n ServiceError = \"ServiceError\",\n\n /**\n * Operation failed.\n */\n FailedOperation = \"FailedOperation\",\n\n /**\n * Invalid response error.\n */\n InvalidResponse = \"InvalidResponse\",\n\n /**\n * Identity type error.\n */\n IdentityTypeNotSupported = \"IdentityTypeNotSupported\",\n\n /**\n * Authentication info already exists error.\n */\n AuthorizationInfoAlreadyExists = \"AuthorizationInfoAlreadyExists\",\n}\n\n/**\n * @internal\n */\nexport class ErrorMessage {\n // InvalidConfiguration Error\n static readonly InvalidConfiguration = \"{0} in configuration is invalid: {1}.\";\n static readonly ConfigurationNotExists = \"Configuration does not exist. {0}\";\n static readonly ResourceConfigurationNotExists = \"{0} resource configuration does not exist.\";\n static readonly MissingResourceConfiguration =\n \"Missing resource configuration with type: {0}, name: {1}.\";\n static readonly AuthenticationConfigurationNotExists =\n \"Authentication configuration does not exist.\";\n\n // RuntimeNotSupported Error\n static readonly BrowserRuntimeNotSupported = \"{0} is not supported in browser.\";\n static readonly NodejsRuntimeNotSupported = \"{0} is not supported in Node.\";\n\n // Internal Error\n static readonly FailToAcquireTokenOnBehalfOfUser =\n \"Failed to acquire access token on behalf of user: {0}\";\n\n // ChannelNotSupported Error\n static readonly OnlyMSTeamsChannelSupported = \"{0} is only supported in MS Teams Channel\";\n\n static readonly FailedToProcessSsoHandler = \"Failed to process sso handler: {0}\";\n\n // FailedToRetrieveSsoToken Error\n static readonly FailedToRetrieveSsoToken =\n \"Failed to retrieve sso token, user failed to finish the AAD consent flow.\";\n\n // CannotFindCommand Error\n static readonly CannotFindCommand = \"Cannot find command: {0}\";\n\n static readonly FailedToRunSsoStep = \"Failed to run dialog to retrieve sso token: {0}\";\n\n static readonly FailedToRunDedupStep = \"Failed to run dialog to remove duplicated messages: {0}\";\n\n // SsoActivityHandlerIsUndefined Error\n static readonly SsoActivityHandlerIsNull =\n \"Sso command can only be used or added when sso activity handler is not undefined\";\n\n // IdentityTypeNotSupported Error\n static readonly IdentityTypeNotSupported = \"{0} identity is not supported in {1}\";\n\n // AuthorizationInfoError\n static readonly AuthorizationHeaderAlreadyExists = \"Authorization header already exists!\";\n static readonly BasicCredentialAlreadyExists = \"Basic credential already exists!\";\n // InvalidParameter Error\n static readonly EmptyParameter = \"Parameter {0} is empty\";\n static readonly DuplicateHttpsOptionProperty =\n \"Axios HTTPS agent already defined value for property {0}\";\n static readonly DuplicateApiKeyInHeader =\n \"The request already defined api key in request header with name {0}.\";\n static readonly DuplicateApiKeyInQueryParam =\n \"The request already defined api key in query parameter with name {0}.\";\n static readonly OnlySupportInQueryActivity =\n \"The handleMessageExtensionQueryWithToken only support in handleTeamsMessagingExtensionQuery with composeExtension/query type.\";\n static readonly OnlySupportInLinkQueryActivity =\n \"The handleMessageExtensionLinkQueryWithSSO only support in handleTeamsAppBasedLinkQuery with composeExtension/queryLink type.\";\n}\n\n/**\n * Error class with code and message thrown by the SDK.\n */\nexport class ErrorWithCode extends Error {\n /**\n * Error code\n *\n * @readonly\n */\n code: string | undefined;\n\n /**\n * Constructor of ErrorWithCode.\n *\n * @param {string} message - error message.\n * @param {ErrorCode} code - error code.\n */\n constructor(message?: string, code?: ErrorCode) {\n if (!code) {\n super(message);\n return this;\n }\n\n super(message);\n Object.setPrototypeOf(this, ErrorWithCode.prototype);\n this.name = `${new.target.name}.${code}`;\n this.code = code;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Interface for customized logger.\n */\nexport interface Logger {\n /**\n * Writes to error level logging or lower.\n */\n error(message: string): void;\n /**\n * Writes to warning level logging or lower.\n */\n warn(message: string): void;\n /**\n * Writes to info level logging or lower.\n */\n info(message: string): void;\n /**\n * Writes to verbose level logging.\n */\n verbose(message: string): void;\n}\n\n/**\n * Log function for customized logging.\n */\nexport type LogFunction = (level: LogLevel, message: string) => void;\n\n/**\n * Log level.\n */\nexport enum LogLevel {\n /**\n * Show verbose, information, warning and error message.\n */\n Verbose,\n /**\n * Show information, warning and error message.\n */\n Info,\n /**\n * Show warning and error message.\n */\n Warn,\n /**\n * Show error message.\n */\n Error,\n}\n\n/**\n * Update log level helper.\n *\n * @param { LogLevel } level - log level in configuration\n */\nexport function setLogLevel(level: LogLevel): void {\n internalLogger.level = level;\n}\n\n/**\n * Get log level.\n *\n * @returns Log level\n */\nexport function getLogLevel(): LogLevel | undefined {\n return internalLogger.level;\n}\n\nexport class InternalLogger implements Logger {\n public name?: string;\n public level?: LogLevel = undefined;\n public customLogger: Logger | undefined;\n public customLogFunction: LogFunction | undefined;\n\n private defaultLogger: Logger = {\n verbose: console.debug,\n info: console.info,\n warn: console.warn,\n error: console.error,\n };\n\n constructor(name?: string, logLevel?: LogLevel) {\n this.name = name;\n this.level = logLevel;\n }\n\n public error(message: string): void {\n this.log(LogLevel.Error, (x: Logger) => x.error, message);\n }\n\n public warn(message: string): void {\n this.log(LogLevel.Warn, (x: Logger) => x.warn, message);\n }\n\n public info(message: string): void {\n this.log(LogLevel.Info, (x: Logger) => x.info, message);\n }\n\n public verbose(message: string): void {\n this.log(LogLevel.Verbose, (x: Logger) => x.verbose, message);\n }\n\n private log(\n logLevel: LogLevel,\n logFunction: (x: Logger) => (message: string) => void,\n message: string\n ): void {\n if (message.trim() === \"\") {\n return;\n }\n const timestamp = new Date().toUTCString();\n let logHeader: string;\n if (this.name) {\n logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;\n } else {\n logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;\n }\n const logMessage = `${logHeader}${message}`;\n if (this.level !== undefined && this.level <= logLevel) {\n if (this.customLogger) {\n logFunction(this.customLogger)(logMessage);\n } else if (this.customLogFunction) {\n this.customLogFunction(logLevel, logMessage);\n } else {\n logFunction(this.defaultLogger)(logMessage);\n }\n }\n }\n}\n\n/**\n * Logger instance used internally\n *\n * @internal\n */\nexport const internalLogger: InternalLogger = new InternalLogger();\n\n/**\n * Set custom logger. Use the output functions if it's set. Priority is higher than setLogFunction.\n *\n * @param {Logger} logger - custom logger. If it's undefined, custom logger will be cleared.\n *\n * @example\n * ```typescript\n * setLogger({\n * verbose: console.debug,\n * info: console.info,\n * warn: console.warn,\n * error: console.error,\n * });\n * ```\n */\nexport function setLogger(logger?: Logger): void {\n internalLogger.customLogger = logger;\n}\n\n/**\n * Set custom log function. Use the function if it's set. Priority is lower than setLogger.\n *\n * @param {LogFunction} logFunction - custom log function. If it's undefined, custom log function will be cleared.\n *\n * @example\n * ```typescript\n * setLogFunction((level: LogLevel, message: string) => {\n * if (level === LogLevel.Error) {\n * console.log(message);\n * }\n * });\n * ```\n */\nexport function setLogFunction(logFunction?: LogFunction): void {\n internalLogger.customLogFunction = logFunction;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { ErrorWithCode, ErrorCode } from \"../core/errors\";\nimport { SSOTokenInfoBase, SSOTokenV1Info, SSOTokenV2Info } from \"../models/ssoTokenInfo\";\nimport { UserInfo, UserTenantIdAndLoginHint } from \"../models/userinfo\";\nimport jwt_decode from \"jwt-decode\";\nimport { internalLogger } from \"./logger\";\nimport { AccessToken } from \"@azure/identity\";\nimport { AuthenticationResult } from \"@azure/msal-browser\";\n\n/**\n * Parse jwt token payload\n *\n * @param token\n *\n * @returns Payload object\n *\n * @internal\n */\nexport function parseJwt(token: string): SSOTokenInfoBase {\n try {\n const tokenObj: SSOTokenInfoBase = jwt_decode(token);\n if (!tokenObj || !tokenObj.exp) {\n throw new ErrorWithCode(\n \"Decoded token is null or exp claim does not exists.\",\n ErrorCode.InternalError\n );\n }\n\n return tokenObj;\n } catch (err: any) {\n const errorMsg = \"Parse jwt token failed in node env with error: \" + (err.message as string);\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);\n }\n}\n\n/**\n * @internal\n */\nexport function getUserInfoFromSsoToken(ssoToken: string): UserInfo {\n if (!ssoToken) {\n const errorMsg = \"SSO token is undefined.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n const tokenObject = parseJwt(ssoToken) as SSOTokenV1Info | SSOTokenV2Info;\n\n const userInfo: UserInfo = {\n displayName: tokenObject.name,\n objectId: tokenObject.oid,\n tenantId: tokenObject.tid,\n preferredUserName: \"\",\n };\n\n if (tokenObject.ver === \"2.0\") {\n userInfo.preferredUserName = (tokenObject as SSOTokenV2Info).preferred_username;\n } else if (tokenObject.ver === \"1.0\") {\n userInfo.preferredUserName = (tokenObject as SSOTokenV1Info).upn;\n }\n return userInfo;\n}\n\n/**\n * @internal\n */\nexport function getTenantIdAndLoginHintFromSsoToken(ssoToken: string): UserTenantIdAndLoginHint {\n if (!ssoToken) {\n const errorMsg = \"SSO token is undefined.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n const tokenObject = parseJwt(ssoToken) as SSOTokenV1Info | SSOTokenV2Info;\n\n const userInfo: UserTenantIdAndLoginHint = {\n tid: tokenObject.tid,\n loginHint:\n tokenObject.ver === \"2.0\"\n ? (tokenObject as SSOTokenV2Info).preferred_username\n : (tokenObject as SSOTokenV1Info).upn,\n };\n\n return userInfo;\n}\n\n/**\n * @internal\n */\nexport function parseAccessTokenFromAuthCodeTokenResponse(\n tokenResponse: string | AuthenticationResult\n): AccessToken {\n try {\n const tokenResponseObject =\n typeof tokenResponse == \"string\"\n ? (JSON.parse(tokenResponse) as AuthenticationResult)\n : tokenResponse;\n if (!tokenResponseObject || !tokenResponseObject.accessToken) {\n const errorMsg = \"Get empty access token from Auth Code token response.\";\n\n internalLogger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n const token = tokenResponseObject.accessToken;\n const tokenObject = parseJwt(token);\n\n if (tokenObject.ver !== \"1.0\" && tokenObject.ver !== \"2.0\") {\n const errorMsg = \"SSO token is not valid with an unknown version: \" + tokenObject.ver;\n internalLogger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n const accessToken: AccessToken = {\n token: token,\n expiresOnTimestamp: tokenObject.exp * 1000,\n };\n return accessToken;\n } catch (error: any) {\n const errorMsg =\n \"Parse access token failed from Auth Code token response in node env with error: \" +\n (error.message as string);\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);\n }\n}\n\n/**\n * Format string template with replacements\n *\n * ```typescript\n * const template = \"{0} and {1} are fruit. {0} is my favorite one.\"\n * const formattedStr = formatString(template, \"apple\", \"pear\"); // formattedStr: \"apple and pear are fruit. apple is my favorite one.\"\n * ```\n *\n * @param str string template\n * @param replacements replacement string array\n * @returns Formatted string\n *\n * @internal\n */\nexport function formatString(str: string, ...replacements: string[]): string {\n const args = replacements;\n return str.replace(/{(\\d+)}/g, function (match, number) {\n return typeof args[number] != \"undefined\" ? args[number] : match;\n });\n}\n\n/**\n * @internal\n */\nexport function validateScopesType(value: any): void {\n // string\n if (typeof value === \"string\" || value instanceof String) {\n return;\n }\n\n // empty array\n if (Array.isArray(value) && value.length === 0) {\n return;\n }\n\n // string array\n if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === \"string\")) {\n return;\n }\n\n const errorMsg = \"The type of scopes is not valid, it must be string or string array\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n}\n\n/**\n * @internal\n */\nexport function getScopesArray(scopes: string | string[]): string[] {\n const scopesArray: string[] = typeof scopes === \"string\" ? scopes.split(\" \") : scopes;\n return scopesArray.filter((x) => x !== null && x !== \"\");\n}\n\n/**\n * @internal\n */\nexport function getAuthority(authorityHost: string, tenantId: string): string {\n const normalizedAuthorityHost = authorityHost.replace(/\\/+$/g, \"\");\n return normalizedAuthorityHost + \"/\" + tenantId;\n}\n\n/**\n * @internal\n */\nexport interface ClientCertificate {\n thumbprint: string;\n privateKey: string;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { ConfidentialClientApplication, NodeAuthOptions } from \"@azure/msal-node\";\nimport {\n AppCredentialAuthConfig,\n AuthenticationConfiguration,\n OnBehalfOfCredentialAuthConfig,\n} from \"../models/configuration\";\nimport { ClientCertificate, getAuthority } from \"./utils\";\nimport { internalLogger } from \"./logger\";\nimport { ErrorWithCode, ErrorCode } from \"../core/errors\";\nimport { createHash } from \"crypto\";\n\n/**\n * @internal\n */\nexport function createConfidentialClientApplication(\n authentication:\n | AuthenticationConfiguration\n | AppCredentialAuthConfig\n | OnBehalfOfCredentialAuthConfig\n): ConfidentialClientApplication {\n const authority = getAuthority(authentication.authorityHost!, authentication.tenantId!);\n const clientCertificate: ClientCertificate | undefined = parseCertificate(\n authentication.certificateContent\n );\n\n const auth: NodeAuthOptions = {\n clientId: authentication.clientId!,\n authority: authority,\n };\n\n if (clientCertificate) {\n auth.clientCertificate = clientCertificate;\n } else {\n auth.clientSecret = authentication.clientSecret;\n }\n\n return new ConfidentialClientApplication({\n auth,\n });\n}\n\n/**\n * @internal\n */\nexport function parseCertificate(\n certificateContent: string | undefined\n): ClientCertificate | undefined {\n if (!certificateContent) {\n return undefined;\n }\n\n const certificatePattern =\n /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9+/\\n\\r]+=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/;\n const match = certificatePattern.exec(certificateContent);\n if (!match) {\n const errorMsg = \"The certificate content does not contain a PEM-encoded certificate.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidCertificate);\n }\n const thumbprint = createHash(\"sha1\")\n .update(Buffer.from(match[3], \"base64\"))\n .digest(\"hex\")\n .toUpperCase();\n\n return {\n thumbprint: thumbprint,\n privateKey: certificateContent,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/identity\";\nimport { AppCredentialAuthConfig, AuthenticationConfiguration } from \"../models/configuration\";\nimport { internalLogger } from \"../util/logger\";\nimport { validateScopesType, formatString, getScopesArray } from \"../util/utils\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\nimport { ConfidentialClientApplication } from \"@azure/msal-node\";\nimport { createConfidentialClientApplication } from \"../util/utils.node\";\n\n/**\n * Represent Microsoft 365 tenant identity, and it is usually used when user is not involved like time-triggered automation job.\n *\n * @example\n * ```typescript\n * loadConfiguration(); // load configuration from environment variables\n * const credential = new AppCredential();\n * ```\n *\n * @remarks\n * Only works in in server side.\n */\nexport class AppCredential implements TokenCredential {\n private readonly msalClient: ConfidentialClientApplication;\n\n /**\n * Constructor of AppCredential.\n *\n * @remarks\n * Only works in in server side.\n *\n * @param {AppCredentialAuthConfig} authConfig - The authentication configuration.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret or tenant id is not found in config.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n */\n constructor(authConfig: AppCredentialAuthConfig);\n /**\n * Constructor of AppCredential.\n *\n * @remarks\n * Only works in in server side.\n *\n * @param {AuthenticationConfiguration} authConfig - The authentication configuration. Use environment variables if not provided.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret or tenant id is not found in config.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n */\n constructor(authConfig: AuthenticationConfiguration);\n constructor(authConfig: AppCredentialAuthConfig | AuthenticationConfiguration) {\n internalLogger.info(\"Create M365 tenant credential\");\n\n const config = this.loadAndValidateConfig(authConfig);\n\n this.msalClient = createConfidentialClientApplication(config);\n }\n\n /**\n * Get access token for credential.\n *\n * @example\n * ```typescript\n * await credential.getToken([\"User.Read.All\"]) // Get Graph access token for single scope using string array\n * await credential.getToken(\"User.Read.All\") // Get Graph access token for single scope using string\n * await credential.getToken([\"User.Read.All\", \"Calendars.Read\"]) // Get Graph access token for multiple scopes using string array\n * await credential.getToken(\"User.Read.All Calendars.Read\") // Get Graph access token for multiple scopes using space-separated string\n * await credential.getToken(\"https://graph.microsoft.com/User.Read.All\") // Get Graph access token with full resource URI\n * await credential.getToken([\"https://outlook.office.com/Mail.Read\"]) // Get Outlook access token\n * ```\n *\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.\n *\n * @throws {@link ErrorCode|ServiceError} when get access token with authentication error.\n * @throws {@link ErrorCode|InternalError} when get access token with unknown error.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns Access token with expected scopes.\n * Throw error if get access token failed.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n let accessToken;\n validateScopesType(scopes);\n const scopesStr = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n internalLogger.info(\"Get access token with scopes: \" + scopesStr);\n\n try {\n const scopesArray = getScopesArray(scopes);\n const authenticationResult = await this.msalClient.acquireTokenByClientCredential({\n scopes: scopesArray,\n });\n if (authenticationResult) {\n accessToken = {\n token: authenticationResult.accessToken,\n expiresOnTimestamp: authenticationResult.expiresOn!.getTime(),\n };\n }\n } catch (err: any) {\n const errorMsg = \"Get M365 tenant credential failed with error: \" + (err.message as string);\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.ServiceError);\n }\n\n if (!accessToken) {\n const errorMsg = \"Get M365 tenant credential access token failed with empty access token\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);\n }\n\n return accessToken;\n }\n\n /**\n * Load and validate authentication configuration\n *\n * @param {AuthenticationConfiguration} authConfig - The authentication configuration. Use environment variables if not provided.\n *\n * @returns Authentication configuration\n */\n private loadAndValidateConfig(\n config: AuthenticationConfiguration | AppCredentialAuthConfig\n ): AuthenticationConfiguration | AppCredentialAuthConfig {\n internalLogger.verbose(\"Validate authentication configuration\");\n\n if (\n config.clientId &&\n (config.clientSecret || config.certificateContent) &&\n config.tenantId &&\n config.authorityHost\n ) {\n return config;\n }\n\n const missingValues = [];\n\n if (!config.clientId) {\n missingValues.push(\"clientId\");\n }\n\n if (!config.clientSecret && !config.certificateContent) {\n missingValues.push(\"clientSecret or certificateContent\");\n }\n\n if (!config.tenantId) {\n missingValues.push(\"tenantId\");\n }\n\n if (!config.authorityHost) {\n missingValues.push(\"authorityHost\");\n }\n\n const errorMsg = formatString(\n ErrorMessage.InvalidConfiguration,\n missingValues.join(\", \"),\n \"undefined\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/identity\";\nimport { AuthenticationResult, ConfidentialClientApplication } from \"@azure/msal-node\";\nimport { UserInfo } from \"../models/userinfo\";\nimport {\n AuthenticationConfiguration,\n OnBehalfOfCredentialAuthConfig,\n} from \"../models/configuration\";\nimport { internalLogger } from \"../util/logger\";\nimport {\n formatString,\n getScopesArray,\n getUserInfoFromSsoToken,\n parseJwt,\n validateScopesType,\n} from \"../util/utils\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { createConfidentialClientApplication } from \"../util/utils.node\";\n\n/**\n * Represent on-behalf-of flow to get user identity, and it is designed to be used in server side.\n *\n * @example\n * ```typescript\n * const credential = new OnBehalfOfUserCredential(ssoToken);\n * ```\n *\n * @remarks\n * Can only be used in server side.\n */\nexport class OnBehalfOfUserCredential implements TokenCredential {\n private msalClient: ConfidentialClientApplication;\n private ssoToken: AccessToken;\n\n /**\n * Constructor of OnBehalfOfUserCredential\n *\n * @remarks\n * Only works in in server side.\n *\n * @param {string} ssoToken - User token provided by Teams SSO feature.\n * @param {OnBehalfOfCredentialAuthConfig} config - The authentication configuration.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret, certificate content, authority host or tenant id is not found in config.\n * @throws {@link ErrorCode|InternalError} when SSO token is not valid.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(ssoToken: string, config: OnBehalfOfCredentialAuthConfig);\n /**\n * Constructor of OnBehalfOfUserCredential\n *\n * @remarks\n * Only works in in server side.\n *\n * @param {string} ssoToken - User token provided by Teams SSO feature.\n * @param {AuthenticationConfiguration} config - The authentication configuration. Use environment variables if not provided.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, client secret, certificate content, authority host or tenant id is not found in config.\n * @throws {@link ErrorCode|InternalError} when SSO token is not valid.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(ssoToken: string, config: AuthenticationConfiguration);\n constructor(\n ssoToken: string,\n config: OnBehalfOfCredentialAuthConfig | AuthenticationConfiguration\n ) {\n internalLogger.info(\"Get on behalf of user credential\");\n\n const missingConfigurations: string[] = [];\n if (!config.clientId) {\n missingConfigurations.push(\"clientId\");\n }\n\n if (!config.authorityHost) {\n missingConfigurations.push(\"authorityHost\");\n }\n\n if (!config.clientSecret && !config.certificateContent) {\n missingConfigurations.push(\"clientSecret or certificateContent\");\n }\n\n if (!config.tenantId) {\n missingConfigurations.push(\"tenantId\");\n }\n\n if (missingConfigurations.length != 0) {\n const errorMsg = formatString(\n ErrorMessage.InvalidConfiguration,\n missingConfigurations.join(\", \"),\n \"undefined\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);\n }\n\n this.msalClient = createConfidentialClientApplication(config);\n\n const decodedSsoToken = parseJwt(ssoToken);\n this.ssoToken = {\n token: ssoToken,\n expiresOnTimestamp: decodedSsoToken.exp,\n };\n }\n\n /**\n * Get access token from credential.\n *\n * @example\n * ```typescript\n * await credential.getToken([]) // Get SSO token using empty string array\n * await credential.getToken(\"\") // Get SSO token using empty string\n * await credential.getToken([\".default\"]) // Get Graph access token with default scope using string array\n * await credential.getToken(\".default\") // Get Graph access token with default scope using string\n * await credential.getToken([\"User.Read\"]) // Get Graph access token for single scope using string array\n * await credential.getToken(\"User.Read\") // Get Graph access token for single scope using string\n * await credential.getToken([\"User.Read\", \"Application.Read.All\"]) // Get Graph access token for multiple scopes using string array\n * await credential.getToken(\"User.Read Application.Read.All\") // Get Graph access token for multiple scopes using space-separated string\n * await credential.getToken(\"https://graph.microsoft.com/User.Read\") // Get Graph access token with full resource URI\n * await credential.getToken([\"https://outlook.office.com/Mail.Read\"]) // Get Outlook access token\n * ```\n *\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make.\n *\n * @throws {@link ErrorCode|InternalError} when failed to acquire access token on behalf of user with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n *\n * @returns Access token with expected scopes.\n *\n * @remarks\n * If scopes is empty string or array, it returns SSO token.\n * If scopes is non-empty, it returns access token for target scope.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n validateScopesType(scopes);\n\n const scopesArray = getScopesArray(scopes);\n\n let result: AccessToken | null;\n if (!scopesArray.length) {\n internalLogger.info(\"Get SSO token.\");\n if (Math.floor(Date.now() / 1000) > this.ssoToken.expiresOnTimestamp) {\n const errorMsg = \"Sso token has already expired.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.TokenExpiredError);\n }\n result = this.ssoToken;\n } else {\n internalLogger.info(\"Get access token with scopes: \" + scopesArray.join(\" \"));\n\n let authenticationResult: AuthenticationResult | null;\n try {\n authenticationResult = await this.msalClient.acquireTokenOnBehalfOf({\n oboAssertion: this.ssoToken.token,\n scopes: scopesArray,\n });\n } catch (error) {\n throw this.generateAuthServerError(error);\n }\n\n if (!authenticationResult) {\n const errorMsg = \"Access token is null\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(\n formatString(ErrorMessage.FailToAcquireTokenOnBehalfOfUser, errorMsg),\n ErrorCode.InternalError\n );\n }\n\n result = {\n token: authenticationResult.accessToken,\n expiresOnTimestamp: authenticationResult.expiresOn!.getTime(),\n };\n }\n\n return result;\n }\n\n /**\n * Get basic user info from SSO token.\n *\n * @example\n * ```typescript\n * const currentUser = getUserInfo();\n * ```\n *\n * @throws {@link ErrorCode|InternalError} when SSO token is not valid.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n *\n * @returns Basic user info with user displayName, objectId and preferredUserName.\n */\n public getUserInfo(): UserInfo {\n internalLogger.info(\"Get basic user info from SSO token\");\n return getUserInfoFromSsoToken(this.ssoToken.token);\n }\n\n private generateAuthServerError(err: any): Error {\n const errorMessage = err.errorMessage as string;\n if (err.name === \"InteractionRequiredAuthError\") {\n const fullErrorMsg =\n \"Failed to get access token from AAD server, interaction required: \" + errorMessage;\n internalLogger.warn(fullErrorMsg);\n return new ErrorWithCode(fullErrorMsg, ErrorCode.UiRequiredError);\n } else if (errorMessage && errorMessage.indexOf(\"AADSTS50013\") >= 0) {\n const fullErrorMsg =\n \"Failed to get access token from AAD server, assertion is invalid because of various reasons: \" +\n errorMessage;\n internalLogger.error(fullErrorMsg);\n return new ErrorWithCode(fullErrorMsg, ErrorCode.TokenExpiredError);\n } else {\n const fullErrorMsg = formatString(\n ErrorMessage.FailToAcquireTokenOnBehalfOfUser,\n errorMessage\n );\n internalLogger.error(fullErrorMsg);\n return new ErrorWithCode(fullErrorMsg, ErrorCode.ServiceError);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/identity\";\nimport { UserInfo } from \"../models/userinfo\";\nimport {\n AuthenticationConfiguration,\n TeamsUserCredentialAuthConfig,\n} from \"../models/configuration\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Represent Teams current user's identity, and it is used within Teams client applications.\n *\n * @remarks\n * Can only be used within Teams.\n */\nexport class TeamsUserCredential implements TokenCredential {\n /**\n * Constructor of TeamsUserCredential.\n * @remarks\n * Can only be used within Teams.\n */\n constructor(authConfig: TeamsUserCredentialAuthConfig);\n constructor(authConfig: AuthenticationConfiguration);\n constructor(authConfig: TeamsUserCredentialAuthConfig | AuthenticationConfiguration) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Popup login page to get user's access token with specific scopes.\n *\n * @param {string[]} resources - The optional list of resources for full trust Teams apps.\n *\n * @remarks\n * Can only be used within Teams.\n */\n public login(scopes: string | string[], resources?: string[]): Promise<void> {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n )\n );\n }\n\n /**\n * Get access token from credential.\n * @remarks\n * Can only be used within Teams.\n */\n getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken | null> {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n )\n );\n }\n\n /**\n * Get basic user info from SSO token\n *\n * @param {string[]} resources - The optional list of resources for full trust Teams apps.\n *\n * @remarks\n * Can only be used within Teams.\n */\n public getUserInfo(resources?: string[]): Promise<UserInfo> {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n )\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AuthenticationProvider } from \"@microsoft/microsoft-graph-client\";\nimport { ErrorWithCode, ErrorCode } from \"./errors\";\nimport { TeamsFxConfiguration } from \"../models/teamsfxConfiguration\";\nimport { internalLogger } from \"../util/logger\";\nimport { validateScopesType } from \"../util/utils\";\nimport { AccessToken, TokenCredential } from \"@azure/identity\";\n\nconst defaultScope = \"https://graph.microsoft.com/.default\";\n\n// eslint-disable-next-line no-secrets/no-secrets\n/**\n * Microsoft Graph auth provider for Teams Framework\n * @deprecated Use `TokenCredentialAuthenticationProvider` from `@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials` instead.\n */\nexport class MsGraphAuthProvider implements AuthenticationProvider {\n private credentialOrTeamsFx: TokenCredential | TeamsFxConfiguration;\n private scopes: string | string[];\n\n /**\n * Constructor of MsGraphAuthProvider.\n *\n * @param {TeamsFxConfiguration} teamsfx - Used to provide configuration and auth.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns An instance of MsGraphAuthProvider.\n */\n constructor(teamsfx: TeamsFxConfiguration, scopes?: string | string[]);\n /**\n * Constructor of MsGraphAuthProvider.\n *\n * @param {TokenCredential} credential - credential used to provide configuration and auth.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns An instance of MsGraphAuthProvider.\n */\n constructor(credential: TokenCredential, scopes?: string | string[]);\n constructor(\n credentialOrTeamsFx: TeamsFxConfiguration | TokenCredential,\n scopes?: string | string[]\n ) {\n this.credentialOrTeamsFx = credentialOrTeamsFx;\n\n let scopesStr = defaultScope;\n if (scopes) {\n validateScopesType(scopes);\n scopesStr = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n if (scopesStr === \"\") {\n scopesStr = defaultScope;\n }\n }\n\n internalLogger.info(\n `Create Microsoft Graph Authentication Provider with scopes: '${scopesStr}'`\n );\n\n this.scopes = scopesStr;\n }\n\n /**\n * Get access token for Microsoft Graph API requests.\n *\n * @throws {@link ErrorCode|InternalError} when get access token failed due to empty token or unknown other problems.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth or AAD server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns Access token from the credential.\n *\n */\n public async getAccessToken(): Promise<string> {\n internalLogger.info(`Get Graph Access token with scopes: '${this.scopes.toString()}'`);\n\n let accessToken: AccessToken | null;\n if ((this.credentialOrTeamsFx as TeamsFxConfiguration).getCredential) {\n accessToken = await (this.credentialOrTeamsFx as TeamsFxConfiguration)\n .getCredential()\n .getToken(this.scopes);\n } else {\n accessToken = await (this.credentialOrTeamsFx as TokenCredential).getToken(this.scopes);\n }\n\n return new Promise<string>((resolve, reject) => {\n if (accessToken) {\n resolve(accessToken.token);\n } else {\n const errorMsg = \"Graph access token is undefined or empty\";\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n }\n });\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Client } from \"@microsoft/microsoft-graph-client\";\nimport { MsGraphAuthProvider } from \"./msGraphAuthProvider\";\nimport { TeamsFxConfiguration } from \"../models/teamsfxConfiguration\";\nimport { internalLogger } from \"../util/logger\";\nimport { TokenCredential } from \"@azure/identity\";\n\n/**\n * Get Microsoft graph client.\n * @deprecated Use `TokenCredentialAuthenticationProvider` and `Client.initWithMiddleware` instead.\n * ```typescript\n * const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });\n * const graph = Client.initWithMiddleware({\n * authProvider: authProvider,\n * });\n * ```\n *\n * @example\n * Get Microsoft graph client by TokenCredential\n * ```typescript\n * // Sso token example (Azure Function)\n * const ssoToken = \"YOUR_TOKEN_STRING\";\n * const options = {\"AAD_APP_ID\", \"AAD_APP_SECRET\"};\n * const credential = new OnBehalfOfAADUserCredential(ssoToken, options);\n * const graphClient = await createMicrosoftGraphClient(credential);\n * const profile = await graphClient.api(\"/me\").get();\n *\n * // TeamsBotSsoPrompt example (Bot Application)\n * const requiredScopes = [\"User.Read\"];\n * const config: Configuration = {\n * loginUrl: loginUrl,\n * clientId: clientId,\n * clientSecret: clientSecret,\n * tenantId: tenantId\n * };\n * const prompt = new TeamsBotSsoPrompt(dialogId, {\n * config: config\n * scopes: [\"User.Read\"],\n * });\n * this.addDialog(prompt);\n *\n * const oboCredential = new OnBehalfOfAADUserCredential(\n * getUserId(dialogContext),\n * {\n * clientId: \"AAD_APP_ID\",\n * clientSecret: \"AAD_APP_SECRET\"\n * });\n * try {\n * const graphClient = await createMicrosoftGraphClient(credential);\n * const profile = await graphClient.api(\"/me\").get();\n * } catch (e) {\n * dialogContext.beginDialog(dialogId);\n * return Dialog.endOfTurn();\n * }\n * ```\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth.\n * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns Graph client with specified scopes.\n */\nexport function createMicrosoftGraphClient(\n teamsfx: TeamsFxConfiguration,\n scopes?: string | string[]\n): Client {\n internalLogger.info(\"Create Microsoft Graph Client\");\n const authProvider = new MsGraphAuthProvider(teamsfx, scopes);\n const graphClient = Client.initWithMiddleware({\n authProvider,\n });\n\n return graphClient;\n}\n\n// eslint-disable-next-line no-secrets/no-secrets\n/**\n * Get Microsoft graph client.\n * @deprecated Use `TokenCredentialAuthenticationProvider` and `Client.initWithMiddleware` instead.\n * ```typescript\n * const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: scope });\n * const graph = Client.initWithMiddleware({\n * authProvider: authProvider,\n * });\n * ```\n * \n * @example\n * Get Microsoft graph client by TokenCredential\n * ```typescript\n * // In browser: TeamsUserCredential\n * const authConfig: TeamsUserCredentialAuthConfig = {\n * clientId: \"xxx\",\n initiateLoginEndpoint: \"https://xxx/auth-start.html\",\n * };\n\n * const credential = new TeamsUserCredential(authConfig);\n\n * const scope = \"User.Read\";\n * await credential.login(scope);\n\n * const client = createMicrosoftGraphClientWithCredential(credential, scope);\n\n * // In node: OnBehalfOfUserCredential\n * const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {\n * authorityHost: \"xxx\",\n * clientId: \"xxx\",\n * tenantId: \"xxx\",\n * clientSecret: \"xxx\",\n * };\n\n * const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);\n * const scope = \"User.Read\";\n * const client = createMicrosoftGraphClientWithCredential(oboCredential, scope);\n\n * // In node: AppCredential\n * const appAuthConfig: AppCredentialAuthConfig = {\n * authorityHost: \"xxx\",\n * clientId: \"xxx\",\n * tenantId: \"xxx\",\n * clientSecret: \"xxx\",\n * };\n * const appCredential = new AppCredential(appAuthConfig);\n * const scope = \"User.Read\";\n * const client = createMicrosoftGraphClientWithCredential(appCredential, scope);\n * \n * const profile = await client.api(\"/me\").get();\n * ```\n *\n * @param {TokenCredential} credential - Used to provide configuration and auth.\n * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n *\n * @returns Graph client with specified scopes.\n */\nexport function createMicrosoftGraphClientWithCredential(\n credential: TokenCredential,\n scopes?: string | string[]\n): Client {\n internalLogger.info(\"Create Microsoft Graph Client\");\n const authProvider = new MsGraphAuthProvider(credential, scopes);\n const graphClient = Client.initWithMiddleware({\n authProvider,\n });\n return graphClient;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, ManagedIdentityCredential } from \"@azure/identity\";\nimport { ConnectionConfig } from \"tedious\";\nimport { ErrorWithCode, ErrorCode } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport { TeamsFx } from \"../core/teamsfx\";\n\n/**\n * MSSQL default scope\n * https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi\n */\nconst defaultSQLScope = \"https://database.windows.net/\";\n\n/**\n * Generate connection configuration consumed by tedious.\n *\n * @deprecated we recommend you compose your own Tedious configuration for better flexibility.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n * @param { string? } databaseName - specify database name to override default one if there are multiple databases.\n *\n * @returns Connection configuration of tedious for the SQL.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when SQL config resource configuration is invalid.\n * @throws {@link ErrorCode|InternalError} when get user MSI token failed or MSI token is invalid.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\nexport async function getTediousConnectionConfig(\n teamsfx: TeamsFx,\n databaseName?: string\n): Promise<ConnectionConfig> {\n internalLogger.info(\"Get SQL configuration\");\n\n try {\n isSQLConfigurationValid(teamsfx);\n } catch (err) {\n throw err;\n }\n\n if (databaseName === \"\") {\n internalLogger.warn(`SQL database name is empty string`);\n }\n const dbName: string | undefined =\n databaseName ??\n (teamsfx.hasConfig(\"sqlDatabaseName\") ? teamsfx.getConfig(\"sqlDatabaseName\") : undefined);\n if (!isMsiAuthentication(teamsfx)) {\n const configWithUPS = generateDefaultConfig(teamsfx, dbName);\n internalLogger.verbose(\"SQL configuration with username and password generated\");\n return configWithUPS;\n }\n\n try {\n const configWithToken = await generateTokenConfig(teamsfx, dbName);\n internalLogger.verbose(\"SQL configuration with MSI token generated\");\n return configWithToken;\n } catch (error) {\n throw error;\n }\n}\n\n/**\n * check configuration is an available configurations.\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n *\n * @returns true - SQL configuration has a valid SQL endpoints, SQL username with password or identity ID.\n * false - configuration is not valid.\n * @internal\n */\nfunction isSQLConfigurationValid(teamsfx: TeamsFx) {\n internalLogger.verbose(\"Check SQL configuration if valid\");\n if (!teamsfx.hasConfig(\"sqlServerEndpoint\")) {\n internalLogger.error(\"SQL configuration is not valid without SQL server endpoint exist\");\n throw new ErrorWithCode(\n \"SQL configuration error without SQL server endpoint exist\",\n ErrorCode.InvalidConfiguration\n );\n }\n if (\n !(teamsfx.hasConfig(\"sqlUsername\") && teamsfx.hasConfig(\"sqlPassword\")) &&\n !teamsfx.hasConfig(\"sqlIdentityId\")\n ) {\n const errMsg = `SQL configuration is not valid without ${\n teamsfx.hasConfig(\"sqlIdentityId\") ? \"\" : \"identity id \"\n } ${teamsfx.hasConfig(\"sqlUsername\") ? \"\" : \"SQL username \"} ${\n teamsfx.hasConfig(\"sqlPassword\") ? \"\" : \"SQL password\"\n } exist`;\n internalLogger.error(errMsg);\n throw new ErrorWithCode(errMsg, ErrorCode.InvalidConfiguration);\n }\n internalLogger.verbose(\"SQL configuration is valid\");\n}\n\n/**\n * Check SQL use MSI identity or username and password.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n *\n * @returns false - login with SQL MSI identity, true - login with username and password.\n * @internal\n */\nfunction isMsiAuthentication(teamsfx: TeamsFx): boolean {\n internalLogger.verbose(\"Check connection config using MSI access token or username and password\");\n if (teamsfx.hasConfig(\"sqlUsername\") && teamsfx.hasConfig(\"sqlPassword\")) {\n internalLogger.verbose(\"Login with username and password\");\n return false;\n }\n internalLogger.verbose(\"Login with MSI identity\");\n return true;\n}\n\n/**\n * Generate tedious connection configuration with default authentication type.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n * @param { string? } databaseName - specify database name to override default one if there are multiple databases.\n *\n * @returns Tedious connection configuration with username and password.\n * @internal\n */\nfunction generateDefaultConfig(teamsfx: TeamsFx, databaseName?: string): ConnectionConfig {\n internalLogger.verbose(\n `SQL server ${teamsfx.getConfig(\"sqlServerEndpoint\")}\n , user name ${teamsfx.getConfig(\"sqlUsername\")}\n , database name ${databaseName ? databaseName : \"\"}`\n );\n\n const config = {\n server: teamsfx.getConfig(\"sqlServerEndpoint\"),\n authentication: {\n type: TediousAuthenticationType.default,\n options: {\n userName: teamsfx.getConfig(\"sqlUsername\"),\n password: teamsfx.getConfig(\"sqlPassword\"),\n },\n },\n options: {\n database: databaseName,\n encrypt: true,\n },\n };\n return config;\n}\n\n/**\n * Generate tedious connection configuration with azure-active-directory-access-token authentication type.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n *\n * @returns Tedious connection configuration with access token.\n * @internal\n */\nasync function generateTokenConfig(\n teamsfx: TeamsFx,\n databaseName?: string\n): Promise<ConnectionConfig> {\n internalLogger.verbose(\"Generate tedious config with MSI token\");\n let token: AccessToken | null;\n try {\n const credential = new ManagedIdentityCredential(teamsfx.getConfig(\"sqlIdentityId\"));\n token = await credential.getToken(defaultSQLScope);\n } catch (error) {\n const errMsg = \"Get user MSI token failed\";\n internalLogger.error(errMsg);\n throw new ErrorWithCode(errMsg, ErrorCode.InternalError);\n }\n if (token) {\n const config = {\n server: teamsfx.getConfig(\"sqlServerEndpoint\"),\n authentication: {\n type: TediousAuthenticationType.MSI,\n options: {\n token: token.token,\n },\n },\n options: {\n database: databaseName,\n encrypt: true,\n },\n };\n internalLogger.verbose(\n `Generate token configuration success\n , server endpoint is ${teamsfx.getConfig(\"sqlServerEndpoint\")}\n , database name is ${databaseName ? databaseName : \"\"}`\n );\n return config;\n }\n internalLogger.error(\n `Generate token configuration\n , server endpoint is ${teamsfx.getConfig(\"sqlServerEndpoint\")}\n , MSI token is not valid`\n );\n throw new ErrorWithCode(\"MSI token is not valid\", ErrorCode.InternalError);\n}\n\n/**\n * tedious connection config authentication type.\n * https://tediousjs.github.io/tedious/api-connection.html\n * @internal\n */\nenum TediousAuthenticationType {\n default = \"default\",\n MSI = \"azure-active-directory-access-token\",\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Identity type to use in authentication.\n */\nexport enum IdentityType {\n /**\n * Represents the current user of Teams.\n */\n User = \"User\",\n /**\n * Represents the application itself.\n */\n App = \"Application\",\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken } from \"@azure/identity\";\nimport {\n Activity,\n ActivityTypes,\n CardFactory,\n Channels,\n MessageFactory,\n TurnContext,\n OAuthCard,\n ActionTypes,\n verifyStateOperationName,\n StatusCodes,\n TokenExchangeInvokeRequest,\n tokenExchangeOperationName,\n TokenExchangeResource,\n TeamsInfo,\n TeamsChannelAccount,\n} from \"botbuilder\";\nimport {\n Dialog,\n DialogContext,\n DialogTurnResult,\n PromptOptions,\n PromptRecognizerResult,\n} from \"botbuilder-dialogs\";\nimport { TeamsBotSsoPromptTokenResponse } from \"./teamsBotSsoPromptTokenResponse\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport { validateScopesType, formatString, parseJwt } from \"../util/utils\";\nimport { TeamsFx } from \"../core/teamsfx\";\nimport { IdentityType } from \"../models/identityType\";\nimport { OnBehalfOfCredentialAuthConfig } from \"../models/configuration\";\nimport { OnBehalfOfUserCredential } from \"../credential/onBehalfOfUserCredential\";\n\nconst invokeResponseType = \"invokeResponse\";\n/**\n * Response body returned for a token exchange invoke activity.\n */\nclass TokenExchangeInvokeResponse {\n /**\n * Response id\n */\n id: string;\n\n /**\n * Detailed error message\n */\n failureDetail: string;\n\n constructor(id: string, failureDetail: string) {\n this.id = id;\n this.failureDetail = failureDetail;\n }\n}\n\n/**\n * Settings used to configure an TeamsBotSsoPrompt instance.\n */\nexport interface TeamsBotSsoPromptSettings {\n /**\n * The array of strings that declare the desired permissions and the resources requested.\n */\n scopes: string[];\n\n /**\n * (Optional) number of milliseconds the prompt will wait for the user to authenticate.\n * Defaults to a value `900,000` (15 minutes.)\n */\n timeout?: number;\n\n /**\n * (Optional) value indicating whether the TeamsBotSsoPrompt should end upon receiving an\n * invalid message. Generally the TeamsBotSsoPrompt will end the auth flow when receives user\n * message not related to the auth flow. Setting the flag to false ignores the user's message instead.\n * Defaults to value `true`\n */\n endOnInvalidMessage?: boolean;\n}\n\n/**\n * Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and\n * help receive oauth token, asks the user to consent if needed.\n *\n * @remarks\n * The prompt will attempt to retrieve the users current token of the desired scopes and store it in\n * the token store.\n *\n * User will be automatically signed in leveraging Teams support of Bot Single Sign On(SSO):\n * https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots\n *\n * @example\n * When used with your bots `DialogSet` you can simply add a new instance of the prompt as a named\n * dialog using `DialogSet.add()`. You can then start the prompt from a waterfall step using either\n * `DialogContext.beginDialog()` or `DialogContext.prompt()`. The user will be prompted to sign in as\n * needed and their access token will be passed as an argument to the callers next waterfall step:\n *\n * ```JavaScript\n * const { ConversationState, MemoryStorage } = require('botbuilder');\n * const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs');\n * const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx');\n *\n * const convoState = new ConversationState(new MemoryStorage());\n * const dialogState = convoState.createProperty('dialogState');\n * const dialogs = new DialogSet(dialogState);\n *\n * dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', {\n * scopes: [\"User.Read\"],\n * }));\n *\n * dialogs.add(new WaterfallDialog('taskNeedingLogin', [\n * async (step) => {\n * return await step.beginDialog('TeamsBotSsoPrompt');\n * },\n * async (step) => {\n * const token = step.result;\n * if (token) {\n *\n * // ... continue with task needing access token ...\n *\n * } else {\n * await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);\n * return await step.endDialog();\n * }\n * }\n * ]));\n * ```\n */\nexport class TeamsBotSsoPrompt extends Dialog {\n private authConfig: OnBehalfOfCredentialAuthConfig;\n private initiateLoginEndpoint: string;\n private settings: TeamsBotSsoPromptSettings;\n /**\n * Constructor of TeamsBotSsoPrompt.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n * @param {string} dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.\n * @param {TeamsBotSsoPromptSettings} settings Settings used to configure the prompt.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(teamsfx: TeamsFx, dialogId: string, settings: TeamsBotSsoPromptSettings);\n /**\n * Constructor of TeamsBotSsoPrompt.\n *\n * @param {OnBehalfOfCredentialAuthConfig} authConfig - Used to provide configuration and auth\n * @param {string} initiateLoginEndpoint - Login URL for Teams to redirect to\n * @param {string} dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.\n * @param {TeamsBotSsoPromptSettings} settings Settings used to configure the prompt.\n *\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n dialogId: string,\n settings: TeamsBotSsoPromptSettings\n );\n constructor(authConfig: TeamsFx | OnBehalfOfCredentialAuthConfig, ...args: any) {\n super(arguments.length === 3 ? args[0] : args[1]);\n if ((authConfig as TeamsFx).getCredential) {\n const teamsfx = authConfig as TeamsFx;\n this.authConfig = this.loadAndValidateConfig(teamsfx);\n this.initiateLoginEndpoint = teamsfx.getConfig(\"initiateLoginEndpoint\");\n this.settings = args[1] as TeamsBotSsoPromptSettings;\n } else {\n this.initiateLoginEndpoint = args[0];\n this.authConfig = authConfig as OnBehalfOfCredentialAuthConfig;\n this.settings = args[2] as TeamsBotSsoPromptSettings;\n }\n\n validateScopesType(this.settings.scopes);\n\n internalLogger.info(\"Create a new Teams Bot SSO Prompt\");\n }\n\n /**\n * Called when a prompt dialog is pushed onto the dialog stack and is being activated.\n * @remarks\n * If the task is successful, the result indicates whether the prompt is still\n * active after the turn has been processed by the prompt.\n *\n * @param dc The DialogContext for the current turn of the conversation.\n *\n * @throws {@link ErrorCode|InvalidParameter} when timeout property in teams bot sso prompt settings is not number or is not positive.\n * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n *\n * @returns A `Promise` representing the asynchronous operation.\n */\n public async beginDialog(dc: DialogContext): Promise<DialogTurnResult> {\n internalLogger.info(\"Begin Teams Bot SSO Prompt\");\n this.ensureMsTeamsChannel(dc);\n\n // Initialize prompt state\n const default_timeout = 900000;\n let timeout: number = default_timeout;\n if (this.settings.timeout) {\n if (typeof this.settings.timeout != \"number\") {\n const errorMsg = \"type of timeout property in teamsBotSsoPromptSettings should be number.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n if (this.settings.timeout <= 0) {\n const errorMsg =\n \"value of timeout property in teamsBotSsoPromptSettings should be positive.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n timeout = this.settings.timeout;\n }\n\n if (this.settings.endOnInvalidMessage === undefined) {\n this.settings.endOnInvalidMessage = true;\n }\n const state: teamsBotSsoPromptState = dc.activeDialog?.state as teamsBotSsoPromptState;\n state.state = {};\n state.options = {};\n state.expires = new Date().getTime() + timeout;\n\n // Send OAuth card to get SSO token\n await this.sendOAuthCardAsync(dc.context);\n return Dialog.EndOfTurn;\n }\n\n /**\n * Called when a prompt dialog is the active dialog and the user replied with a new activity.\n *\n * @remarks\n * If the task is successful, the result indicates whether the dialog is still\n * active after the turn has been processed by the dialog.\n * The prompt generally continues to receive the user's replies until it accepts the\n * user's reply as valid input for the prompt.\n *\n * @param dc The DialogContext for the current turn of the conversation.\n *\n * @returns A `Promise` representing the asynchronous operation.\n *\n * @throws {@link ErrorCode|ChannelNotSupported} when bot channel is not MS Teams.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n public async continueDialog(dc: DialogContext): Promise<DialogTurnResult> {\n internalLogger.info(\"Continue Teams Bot SSO Prompt\");\n this.ensureMsTeamsChannel(dc);\n\n // Check for timeout\n const state: teamsBotSsoPromptState = dc.activeDialog?.state as teamsBotSsoPromptState;\n const isMessage: boolean = dc.context.activity.type === ActivityTypes.Message;\n const isTimeoutActivityType: boolean =\n isMessage ||\n this.isTeamsVerificationInvoke(dc.context) ||\n this.isTokenExchangeRequestInvoke(dc.context);\n\n // If the incoming Activity is a message, or an Activity Type normally handled by TeamsBotSsoPrompt,\n // check to see if this TeamsBotSsoPrompt Expiration has elapsed, and end the dialog if so.\n const hasTimedOut: boolean = isTimeoutActivityType && new Date().getTime() > state.expires;\n if (hasTimedOut) {\n internalLogger.warn(\"End Teams Bot SSO Prompt due to timeout\");\n return await dc.endDialog(undefined);\n } else {\n if (\n this.isTeamsVerificationInvoke(dc.context) ||\n this.isTokenExchangeRequestInvoke(dc.context)\n ) {\n // Recognize token\n const recognized: PromptRecognizerResult<TeamsBotSsoPromptTokenResponse> =\n await this.recognizeToken(dc);\n\n if (recognized.succeeded) {\n return await dc.endDialog(recognized.value);\n }\n } else if (isMessage && this.settings.endOnInvalidMessage) {\n internalLogger.warn(\"End Teams Bot SSO Prompt due to invalid message\");\n return await dc.endDialog(undefined);\n }\n\n return Dialog.EndOfTurn;\n }\n }\n\n private loadAndValidateConfig(teamsfx: TeamsFx): OnBehalfOfCredentialAuthConfig {\n if (teamsfx.getIdentityType() !== IdentityType.User) {\n const errorMsg = formatString(\n ErrorMessage.IdentityTypeNotSupported,\n teamsfx.getIdentityType().toString(),\n \"TeamsBotSsoPrompt\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.IdentityTypeNotSupported);\n }\n\n const missingConfigurations: string[] = [];\n\n if (!teamsfx.hasConfig(\"initiateLoginEndpoint\")) {\n missingConfigurations.push(\"initiateLoginEndpoint\");\n }\n\n if (!teamsfx.hasConfig(\"clientId\")) {\n missingConfigurations.push(\"clientId\");\n }\n\n if (!teamsfx.hasConfig(\"tenantId\")) {\n missingConfigurations.push(\"tenantId\");\n }\n\n if (missingConfigurations.length != 0) {\n const errorMsg = formatString(\n ErrorMessage.InvalidConfiguration,\n missingConfigurations.join(\", \"),\n \"undefined\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);\n }\n\n let authConfig: OnBehalfOfCredentialAuthConfig;\n if (teamsfx.getConfig(\"clientSecret\")) {\n authConfig = {\n authorityHost: teamsfx.getConfig(\"authorityHost\"),\n clientId: teamsfx.getConfig(\"clientId\"),\n tenantId: teamsfx.getConfig(\"tenantId\"),\n clientSecret: teamsfx.getConfig(\"clientSecret\"),\n };\n } else {\n authConfig = {\n authorityHost: teamsfx.getConfig(\"authorityHost\"),\n clientId: teamsfx.getConfig(\"clientId\"),\n tenantId: teamsfx.getConfig(\"tenantId\"),\n certificateContent: teamsfx.getConfig(\"certificateContent\"),\n };\n }\n return authConfig;\n }\n\n /**\n * Ensure bot is running in MS Teams since TeamsBotSsoPrompt is only supported in MS Teams channel.\n * @param dc dialog context\n * @throws {@link ErrorCode|ChannelNotSupported} if bot channel is not MS Teams\n * @internal\n */\n private ensureMsTeamsChannel(dc: DialogContext) {\n if (dc.context.activity.channelId != Channels.Msteams) {\n const errorMsg = formatString(\n ErrorMessage.OnlyMSTeamsChannelSupported,\n \"Teams Bot SSO Prompt\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.ChannelNotSupported);\n }\n }\n\n /**\n * Send OAuthCard that tells Teams to obtain an authentication token for the bot application.\n * For details see https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots.\n *\n * @internal\n */\n private async sendOAuthCardAsync(context: TurnContext): Promise<void> {\n internalLogger.verbose(\"Send OAuth card to get SSO token\");\n\n const account: TeamsChannelAccount = await TeamsInfo.getMember(\n context,\n context.activity.from.id\n );\n internalLogger.verbose(\n \"Get Teams member account user principal name: \" +\n (account.userPrincipalName ? account.userPrincipalName : \"\")\n );\n\n const loginHint: string = account.userPrincipalName ? account.userPrincipalName : \"\";\n const signInResource = this.getSignInResource(loginHint);\n const card = CardFactory.oauthCard(\n \"\",\n \"Teams SSO Sign In\",\n \"Sign In\",\n signInResource.signInLink,\n signInResource.tokenExchangeResource\n );\n (card.content as OAuthCard).buttons[0].type = ActionTypes.Signin;\n const msg: Partial<Activity> = MessageFactory.attachment(card);\n\n // Send prompt\n await context.sendActivity(msg);\n }\n\n /**\n * Get sign in resource.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} if client id, tenant id or initiate login endpoint is not found in config.\n *\n * @internal\n */\n private getSignInResource(loginHint: string) {\n internalLogger.verbose(\"Get sign in authentication configuration\");\n\n const signInLink = `${this.initiateLoginEndpoint}?scope=${encodeURI(\n this.settings.scopes.join(\" \")\n )}&clientId=${this.authConfig.clientId}&tenantId=${\n this.authConfig.tenantId\n }&loginHint=${loginHint}`;\n\n internalLogger.verbose(\"Sign in link: \" + signInLink);\n\n const tokenExchangeResource: TokenExchangeResource = {\n id: uuidv4(),\n };\n\n return {\n signInLink: signInLink,\n tokenExchangeResource: tokenExchangeResource,\n };\n }\n\n /**\n * @internal\n */\n private async recognizeToken(\n dc: DialogContext\n ): Promise<PromptRecognizerResult<TeamsBotSsoPromptTokenResponse>> {\n const context = dc.context;\n let tokenResponse: TeamsBotSsoPromptTokenResponse | undefined;\n\n if (this.isTokenExchangeRequestInvoke(context)) {\n internalLogger.verbose(\"Receive token exchange request\");\n // Received activity is not a token exchange request\n if (!(context.activity.value && this.isTokenExchangeRequest(context.activity.value))) {\n const warningMsg =\n \"The bot received an InvokeActivity that is missing a TokenExchangeInvokeRequest value. This is required to be sent with the InvokeActivity.\";\n\n internalLogger.warn(warningMsg);\n await context.sendActivity(\n this.getTokenExchangeInvokeResponse(StatusCodes.BAD_REQUEST, warningMsg)\n );\n } else {\n const ssoToken = context.activity.value.token;\n const credential = new OnBehalfOfUserCredential(ssoToken, this.authConfig);\n let exchangedToken: AccessToken | null;\n try {\n exchangedToken = await credential.getToken(this.settings.scopes);\n\n if (exchangedToken) {\n await context.sendActivity(\n this.getTokenExchangeInvokeResponse(StatusCodes.OK, \"\", context.activity.value.id)\n );\n\n const ssoTokenExpiration = parseJwt(ssoToken).exp;\n tokenResponse = {\n ssoToken: ssoToken,\n ssoTokenExpiration: new Date(ssoTokenExpiration * 1000).toISOString(),\n connectionName: \"\",\n token: exchangedToken.token,\n expiration: exchangedToken.expiresOnTimestamp.toString(),\n };\n }\n } catch (error) {\n const warningMsg = \"The bot is unable to exchange token. Ask for user consent.\";\n internalLogger.info(warningMsg);\n await context.sendActivity(\n this.getTokenExchangeInvokeResponse(\n StatusCodes.PRECONDITION_FAILED,\n warningMsg,\n context.activity.value.id\n )\n );\n }\n }\n } else if (this.isTeamsVerificationInvoke(context)) {\n internalLogger.verbose(\"Receive Teams state verification request\");\n await this.sendOAuthCardAsync(dc.context);\n await context.sendActivity({ type: invokeResponseType, value: { status: StatusCodes.OK } });\n }\n\n return tokenResponse !== undefined\n ? { succeeded: true, value: tokenResponse }\n : { succeeded: false };\n }\n\n /**\n * @internal\n */\n private getTokenExchangeInvokeResponse(\n status: number,\n failureDetail: string,\n id?: string\n ): Activity {\n const invokeResponse: Partial<Activity> = {\n type: invokeResponseType,\n value: { status, body: new TokenExchangeInvokeResponse(id as string, failureDetail) },\n };\n return invokeResponse as Activity;\n }\n\n /**\n * @internal\n */\n private isTeamsVerificationInvoke(context: TurnContext): boolean {\n const activity: Activity = context.activity;\n\n return activity.type === ActivityTypes.Invoke && activity.name === verifyStateOperationName;\n }\n\n /**\n * @internal\n */\n private isTokenExchangeRequestInvoke(context: TurnContext): boolean {\n const activity: Activity = context.activity;\n\n return activity.type === ActivityTypes.Invoke && activity.name === tokenExchangeOperationName;\n }\n\n /**\n * @internal\n */\n private isTokenExchangeRequest(obj: any): obj is TokenExchangeInvokeRequest {\n return obj.hasOwnProperty(\"token\");\n }\n}\n\n/**\n * @internal\n */\ninterface teamsBotSsoPromptState {\n state: any;\n options: PromptOptions;\n expires: number; // Timestamp of when the prompt will timeout.\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport axios, { AxiosInstance, InternalAxiosRequestConfig } from \"axios\";\nimport { AuthProvider } from \"./authProvider\";\n\n/**\n * Initializes new Axios instance with specific auth provider\n *\n * @param apiEndpoint - Base url of the API\n * @param authProvider - Auth provider that injects authentication info to each request\n * @returns axios instance configured with specfic auth provider\n *\n * @example\n * ```typescript\n * const client = createApiClient(\"https://my-api-endpoint-base-url\", new BasicAuthProvider(\"xxx\",\"xxx\"));\n * ```\n */\nexport function createApiClient(apiEndpoint: string, authProvider: AuthProvider): AxiosInstance {\n // Add a request interceptor\n const instance = axios.create({\n baseURL: apiEndpoint,\n });\n instance.interceptors.request.use(async function (config) {\n return (await authProvider.AddAuthenticationInfo(\n config\n )) as Promise<InternalAxiosRequestConfig>;\n });\n return instance;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AxiosRequestConfig } from \"axios\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { AuthProvider } from \"./authProvider\";\n\n/**\n * Provider that handles Bearer Token authentication\n */\nexport class BearerTokenAuthProvider implements AuthProvider {\n private getToken: () => Promise<string>;\n\n /**\n * @param { () => Promise<string> } getToken - Function that returns the content of bearer token used in http request\n */\n constructor(getToken: () => Promise<string>) {\n this.getToken = getToken;\n }\n\n /**\n * Adds authentication info to http requests\n *\n * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.\n * Refer https://axios-http.com/docs/req_config for detailed document.\n *\n * @returns Updated axios request config.\n *\n * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header already exists in request configuration.\n */\n public async AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n const token = await this.getToken();\n if (!config.headers) {\n config.headers = {};\n }\n if (config.headers[\"Authorization\"]) {\n throw new ErrorWithCode(\n ErrorMessage.AuthorizationHeaderAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n );\n }\n\n config.headers[\"Authorization\"] = `Bearer ${token}`;\n return config;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AxiosRequestConfig } from \"axios\";\nimport { AuthProvider } from \"./authProvider\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Provider that handles Basic authentication\n */\nexport class BasicAuthProvider implements AuthProvider {\n private userName: string;\n private password: string;\n\n /**\n *\n * @param { string } userName - Username used in basic auth\n * @param { string } password - Password used in basic auth\n *\n * @throws {@link ErrorCode|InvalidParameter} - when username or password is empty.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(userName: string, password: string) {\n if (!userName) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"username\"),\n ErrorCode.InvalidParameter\n );\n }\n if (!password) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"password\"),\n ErrorCode.InvalidParameter\n );\n }\n this.userName = userName;\n this.password = password;\n }\n\n /**\n * Adds authentication info to http requests\n *\n * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.\n * Refer https://axios-http.com/docs/req_config for detailed document.\n *\n * @returns Updated axios request config.\n *\n * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when Authorization header or auth property already exists in request configuration.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n public AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n if (config.headers && config.headers[\"Authorization\"]) {\n return Promise.reject(\n new ErrorWithCode(\n ErrorMessage.AuthorizationHeaderAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n )\n );\n }\n if (config.auth) {\n return Promise.reject(\n new ErrorWithCode(\n ErrorMessage.BasicCredentialAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n )\n );\n }\n\n config.auth = {\n username: this.userName,\n password: this.password,\n };\n\n return Promise.resolve(config);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AxiosRequestConfig } from \"axios\";\nimport { AuthProvider } from \"./authProvider\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Provider that handles API Key authentication\n */\nexport class ApiKeyProvider implements AuthProvider {\n private keyName: string;\n private keyValue: string;\n private keyLocation: ApiKeyLocation;\n\n /**\n *\n * @param { string } keyName - The name of request header or query parameter that specifies API Key\n * @param { string } keyValue - The value of API Key\n * @param { ApiKeyLocation } keyLocation - The location of API Key: request header or query parameter.\n *\n * @throws {@link ErrorCode|InvalidParameter} - when key name or key value is empty.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n constructor(keyName: string, keyValue: string, keyLocation: ApiKeyLocation) {\n if (!keyName) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"keyName\"),\n ErrorCode.InvalidParameter\n );\n }\n if (!keyValue) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"keyVaule\"),\n ErrorCode.InvalidParameter\n );\n }\n this.keyName = keyName;\n this.keyValue = keyValue;\n this.keyLocation = keyLocation;\n }\n\n /**\n * Adds authentication info to http requests\n *\n * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.\n * Refer https://axios-http.com/docs/req_config for detailed document.\n *\n * @returns Updated axios request config.\n *\n * @throws {@link ErrorCode|AuthorizationInfoAlreadyExists} - when API key already exists in request header or url query parameter.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is browser.\n */\n public AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n switch (this.keyLocation) {\n case ApiKeyLocation.Header:\n if (!config.headers) {\n config.headers = {};\n }\n if (config.headers[this.keyName]) {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.DuplicateApiKeyInHeader, this.keyName),\n ErrorCode.AuthorizationInfoAlreadyExists\n )\n );\n }\n config.headers[this.keyName] = this.keyValue;\n break;\n case ApiKeyLocation.QueryParams:\n if (!config.params) {\n config.params = {};\n }\n let urlHasDefinedApiKey = false;\n if (config.url) {\n const url = new URL(config.url, config.baseURL);\n urlHasDefinedApiKey = url.searchParams.has(this.keyName);\n }\n if (config.params[this.keyName] || urlHasDefinedApiKey) {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.DuplicateApiKeyInQueryParam, this.keyName),\n ErrorCode.AuthorizationInfoAlreadyExists\n )\n );\n }\n config.params[this.keyName] = this.keyValue;\n break;\n }\n\n return Promise.resolve(config);\n }\n}\n\n/**\n * Define available location for API Key location\n */\nexport enum ApiKeyLocation {\n /**\n * The API Key is placed in request header\n */\n Header,\n /**\n * The API Key is placed in query parameter\n */\n QueryParams,\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AxiosRequestConfig } from \"axios\";\nimport { Agent } from \"https\";\nimport { SecureContextOptions } from \"tls\";\nimport { AuthProvider } from \"./authProvider\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Provider that handles Certificate authentication\n */\n\nexport class CertificateAuthProvider implements AuthProvider {\n private certOption: SecureContextOptions;\n\n /**\n *\n * @param { SecureContextOptions } certOption - information about the cert used in http requests\n *\n * @throws {@link ErrorCode|InvalidParameter} - when cert option is empty.\n */\n constructor(certOption: SecureContextOptions) {\n if (certOption && Object.keys(certOption).length !== 0) {\n this.certOption = certOption;\n } else {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"certOption\"),\n ErrorCode.InvalidParameter\n );\n }\n }\n\n /**\n * Adds authentication info to http requests.\n *\n * @param { AxiosRequestConfig } config - Contains all the request information and can be updated to include extra authentication info.\n * Refer https://axios-http.com/docs/req_config for detailed document.\n *\n * @returns Updated axios request config.\n *\n * @throws {@link ErrorCode|InvalidParameter} - when custom httpsAgent in the request has duplicate properties with certOption provided in constructor.\n */\n public AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n if (!config.httpsAgent) {\n config.httpsAgent = new Agent(this.certOption);\n } else {\n const existingProperties = new Set(Object.keys(config.httpsAgent.options));\n for (const property of Object.keys(this.certOption)) {\n if (existingProperties.has(property)) {\n return Promise.reject(\n new ErrorWithCode(\n formatString(ErrorMessage.DuplicateHttpsOptionProperty, property),\n ErrorCode.InvalidParameter\n )\n );\n }\n }\n Object.assign(config.httpsAgent.options, this.certOption);\n }\n return Promise.resolve(config);\n }\n}\n\n/**\n * Helper to create SecureContextOptions from PEM format cert\n *\n * @param { string | Buffer } cert - The cert chain in PEM format\n * @param { string | Buffer } key - The private key for the cert chain\n * @param { {passphrase?: string; ca?: string | Buffer} } options - Optional settings when create the cert options.\n *\n * @returns Instance of SecureContextOptions\n *\n * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty\n *\n */\nexport function createPemCertOption(\n cert: string | Buffer,\n key: string | Buffer,\n options?: {\n passphrase?: string;\n ca?: string | Buffer;\n }\n): SecureContextOptions {\n if (cert.length === 0) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"cert\"),\n ErrorCode.InvalidParameter\n );\n }\n if (key.length === 0) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"key\"),\n ErrorCode.InvalidParameter\n );\n }\n\n return {\n cert,\n key,\n passphrase: options?.passphrase,\n ca: options?.ca,\n };\n}\n\n/**\n * Helper to create SecureContextOptions from PFX format cert\n *\n * @param { string | Buffer } pfx - The content of .pfx file\n * @param { {passphrase?: string} } options - Optional settings when create the cert options.\n *\n * @returns Instance of SecureContextOptions\n *\n * @throws {@link ErrorCode|InvalidParameter} - when any parameter is empty\n *\n */\nexport function createPfxCertOption(\n pfx: string | Buffer,\n options?: {\n passphrase?: string;\n }\n): SecureContextOptions {\n if (pfx.length === 0) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.EmptyParameter, \"pfx\"),\n ErrorCode.InvalidParameter\n );\n }\n\n return {\n pfx,\n passphrase: options?.passphrase,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TokenCredential } from \"@azure/identity\";\nimport { AppCredential } from \"../credential/appCredential\";\nimport { OnBehalfOfUserCredential } from \"../credential/onBehalfOfUserCredential\";\nimport { IdentityType } from \"../models/identityType\";\nimport { UserInfo } from \"../models/userinfo\";\nimport { formatString } from \"../util/utils\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport { TeamsFxConfiguration } from \"../models/teamsfxConfiguration\";\nimport { AuthenticationConfiguration } from \"../models/configuration\";\n\n// Following keys are used by SDK internally\nconst ReservedKey: Set<string> = new Set<string>([\n \"authorityHost\",\n \"tenantId\",\n \"clientId\",\n \"clientSecret\",\n \"initiateLoginEndpoint\",\n \"applicationIdUri\",\n \"apiEndpoint\",\n \"apiName\",\n \"sqlServerEndpoint\",\n \"sqlUsername\",\n \"sqlPassword\",\n \"sqlDatabaseName\",\n \"sqlIdentityId\",\n]);\n\n/**\n * A class providing credential and configuration.\n * @deprecated Please use {@link TeamsUserCredential}\n * in browser environment and {@link OnBehalfOfUserCredential} or {@link AppCredential} in NodeJS.\n */\nexport class TeamsFx implements TeamsFxConfiguration {\n private configuration: Map<string, string | undefined>;\n private oboUserCredential?: OnBehalfOfUserCredential;\n private appCredential?: AppCredential;\n private identityType: IdentityType;\n\n /**\n * Constructor of TeamsFx\n *\n * @param {IdentityType} identityType - Choose user or app identity\n * @param customConfig - key/value pairs of customized configuration that overrides default ones.\n *\n * @throws {@link ErrorCode|IdentityTypeNotSupported} when setting app identity in browser.\n */\n constructor(\n identityType?: IdentityType,\n customConfig?: Record<string, string> | AuthenticationConfiguration\n ) {\n this.identityType = identityType ?? IdentityType.User;\n this.configuration = new Map<string, string>();\n this.loadFromEnv();\n if (customConfig) {\n const myConfig: Record<string, string> = { ...customConfig };\n for (const key of Object.keys(myConfig)) {\n const value = myConfig[key];\n if (value) {\n this.configuration.set(key, value);\n }\n }\n }\n }\n\n /**\n * Identity type set by user.\n *\n * @returns identity type.\n */\n getIdentityType(): IdentityType {\n return this.identityType;\n }\n\n /**\n * Credential instance according to identity type choice.\n *\n * @remarks If user identity is chose, will return {@link TeamsUserCredential}\n * in browser environment and {@link OnBehalfOfUserCredential} in NodeJS. If app\n * identity is chose, will return {@link AppCredential}.\n *\n * @returns instance implements TokenCredential interface.\n */\n public getCredential(): TokenCredential {\n if (this.identityType === IdentityType.User) {\n if (this.oboUserCredential) {\n return this.oboUserCredential;\n }\n const errorMsg = \"SSO token is required to user identity. Please use setSsoToken().\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n } else {\n if (!this.appCredential) {\n this.appCredential = new AppCredential(Object.fromEntries(this.configuration));\n }\n return this.appCredential;\n }\n }\n\n /**\n * Get user information.\n * @param {string[]} resources - The optional list of resources for full trust Teams apps.\n * @returns UserInfo object.\n */\n public async getUserInfo(resources?: string[]): Promise<UserInfo> {\n if (this.identityType !== IdentityType.User) {\n const errorMsg = formatString(\n ErrorMessage.IdentityTypeNotSupported,\n this.identityType.toString(),\n \"TeamsFx\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.IdentityTypeNotSupported);\n }\n return Promise.resolve((this.getCredential() as OnBehalfOfUserCredential).getUserInfo());\n }\n\n /**\n * Popup login page to get user's access token with specific scopes.\n *\n * @remarks\n * Only works in Teams client APP. User will be redirected to the authorization page to login and consent.\n *\n * @example\n * ```typescript\n * await teamsfx.login([\"https://graph.microsoft.com/User.Read\"]); // single scope using string array\n * await teamsfx.login(\"https://graph.microsoft.com/User.Read\"); // single scopes using string\n * await teamsfx.login([\"https://graph.microsoft.com/User.Read\", \"Calendars.Read\"]); // multiple scopes using string array\n * await teamsfx.login(\"https://graph.microsoft.com/User.Read Calendars.Read\"); // multiple scopes using string\n * ```\n * @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.\n * @param {string[]} resources - The optional list of resources for full trust Teams apps.\n *\n * @throws {@link ErrorCode|InternalError} when failed to login with unknown error.\n * @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n */\n public async login(scopes: string | string[], resources?: string[]): Promise<void> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"login\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Set SSO token when using user identity in NodeJS.\n * @param {string} ssoToken - used for on behalf of user flow.\n * @returns self instance.\n */\n public setSsoToken(ssoToken: string): TeamsFx {\n if (this.identityType !== IdentityType.User) {\n throw new Error();\n }\n this.oboUserCredential = new OnBehalfOfUserCredential(\n ssoToken,\n Object.fromEntries(this.configuration)\n );\n return this;\n }\n\n /**\n * Usually used by service plugins to retrieve specific config\n * @param {string} key - configuration key.\n * @returns value in configuration.\n */\n public getConfig(key: string): string {\n const value = this.configuration.get(key);\n if (!value) {\n const errorMsg = `Cannot find ${key} in configuration`;\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);\n }\n return value;\n }\n\n /**\n * Check the value of specific key.\n * @param {string} key - configuration key.\n * @returns true if corresponding value is not empty string.\n */\n public hasConfig(key: string): boolean {\n const value = this.configuration.get(key);\n return !!value;\n }\n\n /**\n * Get all configurations.\n * @returns key value mappings.\n */\n public getConfigs(): Record<string, string> {\n const config: Record<string, string> = {};\n for (const key of this.configuration.keys()) {\n const value = this.configuration.get(key);\n if (value) {\n config[key] = value;\n }\n }\n return config;\n }\n\n /**\n * Load configuration from environment variables.\n */\n private loadFromEnv(): void {\n const env = process.env;\n this.configuration.set(\"authorityHost\", env.M365_AUTHORITY_HOST);\n this.configuration.set(\"tenantId\", env.M365_TENANT_ID);\n this.configuration.set(\"clientId\", env.M365_CLIENT_ID);\n this.configuration.set(\"clientSecret\", env.M365_CLIENT_SECRET);\n this.configuration.set(\"initiateLoginEndpoint\", env.INITIATE_LOGIN_ENDPOINT);\n this.configuration.set(\"applicationIdUri\", env.M365_APPLICATION_ID_URI);\n this.configuration.set(\"apiEndpoint\", env.API_ENDPOINT);\n this.configuration.set(\"apiName\", env.API_NAME);\n this.configuration.set(\"sqlServerEndpoint\", env.SQL_ENDPOINT);\n this.configuration.set(\"sqlUsername\", env.SQL_USER_NAME);\n this.configuration.set(\"sqlPassword\", env.SQL_PASSWORD);\n this.configuration.set(\"sqlDatabaseName\", env.SQL_DATABASE_NAME);\n this.configuration.set(\"sqlIdentityId\", env.IDENTITY_ID);\n\n Object.keys(env).forEach((key: string) => {\n if (ReservedKey.has(key)) {\n internalLogger.warn(\n `The name of environment variable ${key} is preserved. Will not load it as configuration.`\n );\n }\n this.configuration.set(key, env[key]);\n });\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n BotFrameworkAdapter,\n ConversationState,\n ConversationReference,\n UserState,\n Activity,\n TurnContext,\n InvokeResponse,\n Storage,\n SigninStateVerificationQuery,\n} from \"botbuilder\";\nimport { TeamsBotSsoPromptTokenResponse } from \"../bot/teamsBotSsoPromptTokenResponse\";\nimport {\n AuthenticationConfiguration,\n OnBehalfOfCredentialAuthConfig,\n} from \"../models/configuration\";\n\n/**\n * The response of a message action, e.g., `sendMessage`, `sendAdaptiveCard`.\n */\nexport interface MessageResponse {\n /**\n * Id of the message.\n */\n id?: string;\n}\n\n/**\n * The target type where the notification will be sent to.\n *\n * @remarks\n * - \"Channel\" means to a team channel. (By default, notification to a team will be sent to its \"General\" channel.)\n * - \"Group\" means to a group chat.\n * - \"Person\" means to a personal chat.\n */\nexport enum NotificationTargetType {\n /**\n * The notification will be sent to a team channel.\n * (By default, notification to a team will be sent to its \"General\" channel.)\n */\n Channel = \"Channel\",\n /**\n * The notification will be sent to a group chat.\n */\n Group = \"Group\",\n /**\n * The notification will be sent to a personal chat.\n */\n Person = \"Person\",\n}\n\n/**\n * Represent a notification target.\n */\nexport interface NotificationTarget {\n /**\n * The type of target, could be \"Channel\" or \"Group\" or \"Person\".\n */\n readonly type?: NotificationTargetType;\n\n /**\n * Send a plain text message.\n *\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns the response of sending message.\n */\n sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse>;\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns the response of sending adaptive card message.\n */\n sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse>;\n}\n\n/**\n * Interface for a storage provider that stores and retrieves notification target references.\n *\n * @deprecated Use ConversationReferenceStore to customize the way\n * to persist bot notification connections instead.\n */\nexport interface NotificationTargetStorage {\n /**\n * Read one notification target by its key.\n *\n * @param key - the key of a notification target.\n *\n * @returns - the notification target. Or undefined if not found.\n */\n read(key: string): Promise<{ [key: string]: unknown } | undefined>;\n\n /**\n * List all stored notification targets.\n *\n * @returns - an array of notification target. Or an empty array if nothing is stored.\n */\n list(): Promise<{ [key: string]: unknown }[]>;\n\n /**\n * Write one notification target by its key.\n *\n * @param key - the key of a notification target.\n * @param object - the notification target.\n */\n write(key: string, object: { [key: string]: unknown }): Promise<void>;\n\n /**\n * Delete one notification target by its key.\n *\n * @param key - the key of a notification target.\n */\n delete(key: string): Promise<void>;\n}\n\n/**\n * Options to initialize {@link NotificationBot}.\n * @deprecated Please use BotBuilderCloudAdapter.NotificationOptions instead.\n */\nexport interface NotificationOptions {\n /**\n * An optional storage to persist bot notification connections.\n *\n * @remarks\n * If `storage` is not provided, a default local file storage will be used,\n * which stores notification connections into:\n * - \".notification.localstore.json\" if running locally\n * - \"${process.env.TEMP}/.notification.localstore.json\" if `process.env.RUNNING_ON_AZURE` is set to \"1\"\n *\n * It's recommended to use your own shared storage for production environment.\n */\n storage?: NotificationTargetStorage;\n}\n\n/**\n * A store to persist notification target references.\n */\nexport interface ConversationReferenceStore {\n /**\n * Add a conversation reference to the store. If overwrite, update existing one, otherwise add when not exist.\n *\n * @param key the key of the conversation reference.\n * @param reference the conversation reference to add.\n * @param options the options to add the conversation reference.\n *\n * @returns true if added or updated, false if not changed.\n */\n add(\n key: string,\n reference: Partial<ConversationReference>,\n options: ConversationReferenceStoreAddOptions\n ): Promise<boolean>;\n\n /**\n * Remove a conversation reference from the store.\n *\n * @param key the key of the conversation reference.\n * @param reference the conversation reference to remove.\n *\n * @returns true if exist and removed, false if not changed.\n */\n remove(key: string, reference: Partial<ConversationReference>): Promise<boolean>;\n\n /**\n * List stored conversation reference by page.\n *\n * @param pageSize the page size.\n * @param continuationToken the continuation token to get next page.\n *\n * @returns a paged list of conversation references.\n */\n list(\n pageSize?: number,\n continuationToken?: string\n ): Promise<PagedData<Partial<ConversationReference>>>;\n}\n\n/**\n * Options to add a conversation reference to the store.\n */\nexport interface ConversationReferenceStoreAddOptions {\n /**\n * Whether to overwrite the existing conversation reference.\n */\n overwrite?: boolean;\n}\n\n/**\n * Represents a page of data.\n */\nexport interface PagedData<T> {\n /**\n * Page of data.\n */\n data: T[];\n\n /**\n * The Continuation Token to pass to get the next page of results.\n *\n * @remarks\n * Undefined or empty token means the page reaches the end.\n */\n continuationToken?: string;\n}\n\n/**\n * The trigger pattern used to trigger a {@link TeamsFxBotCommandHandler} instance.\n */\nexport type TriggerPatterns = string | RegExp | (string | RegExp)[];\n\n/**\n * Interface for a command message that can handled in a command handler.\n */\nexport interface CommandMessage {\n /**\n * Text of the message sent by the user.\n */\n text: string;\n\n /**\n * The capture groups that matched to the {@link TriggerPatterns} in a {@link TeamsFxBotCommandHandler} instance.\n */\n matches?: RegExpMatchArray;\n}\n\n/**\n * Interface for a command handler that can process command to a TeamsFx bot and return a response.\n */\nexport interface TeamsFxBotCommandHandler {\n /**\n * The string or regular expression patterns that can trigger this handler.\n */\n triggerPatterns: TriggerPatterns;\n\n /**\n * Handles a bot command received activity.\n *\n * @param context The bot context.\n * @param message The command message the user types from Teams.\n * @returns A `Promise` representing an activity or text to send as the command response.\n * Or no return value if developers want to send the response activity by themselves in this method.\n */\n handleCommandReceived(\n context: TurnContext,\n message: CommandMessage\n ): Promise<string | Partial<Activity> | void>;\n}\n\n/**\n * Interface for a command handler that can process sso command to a TeamsFx bot and return a response.\n */\nexport interface TeamsFxBotSsoCommandHandler {\n /**\n * The string or regular expression patterns that can trigger this handler.\n */\n triggerPatterns: TriggerPatterns;\n\n /**\n * Handles a bot command received activity.\n *\n * @param context The bot context.\n * @param message The command message the user types from Teams.\n * @param tokenResponse The tokenResponse which contains sso token that can be used to exchange access token for the bot.\n * @returns A `Promise` representing an activity or text to send as the command response.\n * Or no return value if developers want to send the response activity by themselves in this method.\n */\n handleCommandReceived(\n context: TurnContext,\n message: CommandMessage,\n tokenResponse: TeamsBotSsoPromptTokenResponse\n ): Promise<string | Partial<Activity> | void>;\n}\n\n/**\n * Options to initialize {@link CommandBot}.\n */\nexport interface CommandOptions {\n /**\n * The commands to registered with the command bot. Each command should implement the interface {@link TeamsFxBotCommandHandler} so that it can be correctly handled by this command bot.\n */\n commands?: TeamsFxBotCommandHandler[];\n\n /**\n * The commands to registered with the sso command bot. Each sso command should implement the interface {@link TeamsFxBotSsoCommandHandler} so that it can be correctly handled by this command bot.\n */\n ssoCommands?: TeamsFxBotSsoCommandHandler[];\n}\n\n/**\n * Options to initialize {@link CardActionBot}.\n */\nexport interface CardActionOptions {\n /**\n * The action handlers to registered with the action bot. Each command should implement the interface {@link TeamsFxAdaptiveCardActionHandler} so that it can be correctly handled by this bot.\n */\n actions?: TeamsFxAdaptiveCardActionHandler[];\n}\n\n/**\n * Options used to control how the response card will be sent to users.\n */\nexport enum AdaptiveCardResponse {\n /**\n * The response card will be replaced the current one for the interactor who trigger the action.\n */\n ReplaceForInteractor,\n\n /**\n * The response card will be replaced the current one for all users in the chat.\n */\n ReplaceForAll,\n\n /**\n * The response card will be sent as a new message for all users in the chat.\n */\n NewForAll,\n}\n\n/**\n * Status code for an `application/vnd.microsoft.error` invoke response.\n */\nexport enum InvokeResponseErrorCode {\n /**\n * Invalid request.\n */\n BadRequest = 400,\n\n /**\n * Internal server error.\n */\n InternalServerError = 500,\n}\n\n/**\n * Interface for adaptive card action handler that can process card action invoke and return a response.\n */\nexport interface TeamsFxAdaptiveCardActionHandler {\n /**\n * The verb defined in adaptive card action that can trigger this handler.\n * The verb string here is case-insensitive.\n */\n triggerVerb: string;\n\n /**\n * Specify the behavior for how the card response will be sent in Teams conversation.\n * The default value is `AdaptiveCardResponse.ReplaceForInteractor`, which means the card\n * response will replace the current one only for the interactor.\n */\n adaptiveCardResponse?: AdaptiveCardResponse;\n\n /**\n * The handler function that will be invoked when the action is fired.\n * @param context The turn context.\n * @param actionData The contextual data that associated with the action.\n * \n * @returns A `Promise` representing a invoke response for the adaptive card invoke action.\n * You can use the `InvokeResponseFactory` utility class to create an invoke response from\n * - A text message: \n * ```typescript \n * return InvokeResponseFactory.textMessage(\"Action is processed successfully!\");\n * ```\n * - An adaptive card:\n * ```typescript\n * const responseCard = AdaptiveCards.declare(helloWorldCard).render(actionData);\n return InvokeResponseFactory.adaptiveCard(responseCard);\n * ```\n * - An error response:\n * ```typescript\n * return InvokeResponseFactory.errorResponse(InvokeResponseErrorCode.BadRequest, \"Invalid request\");\n * ```\n * \n * @remarks For more details about the invoke response format, refer to https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model#response-format.\n */\n handleActionInvoked(context: TurnContext, actionData: any): Promise<InvokeResponse>;\n}\n\n/**\n * Interface for SSO configuration for Bot SSO\n */\nexport interface BotSsoConfig {\n /**\n * aad related configurations\n */\n aad: {\n /**\n * The list of scopes for which the token will have access\n */\n scopes: string[];\n } & (\n | (OnBehalfOfCredentialAuthConfig & { initiateLoginEndpoint: string })\n | AuthenticationConfiguration\n );\n\n dialog?: {\n /**\n * Custom sso execution activity handler class which should implement the interface {@link BotSsoExecutionActivityHandler}. If not provided, it will use {@link DefaultBotSsoExecutionActivityHandler} by default\n */\n CustomBotSsoExecutionActivityHandler?: new (\n ssoConfig: BotSsoConfig\n ) => BotSsoExecutionActivityHandler;\n\n /**\n * Conversation state for sso command bot, if not provided, it will use internal memory storage to create a new one.\n */\n conversationState?: ConversationState;\n\n /**\n * User state for sso command bot, if not provided, it will use internal memory storage to create a new one.\n */\n userState?: UserState;\n\n /**\n * Used by {@link BotSsoExecutionDialog} to remove duplicated messages, if not provided, it will use internal memory storage\n */\n dedupStorage?: Storage;\n\n /**\n * Settings used to configure an teams sso prompt dialog.\n */\n ssoPromptConfig?: {\n /**\n * Number of milliseconds the prompt will wait for the user to authenticate.\n * Defaults to a value `900,000` (15 minutes.)\n */\n timeout?: number;\n\n /**\n * Value indicating whether the TeamsBotSsoPrompt should end upon receiving an\n * invalid message. Generally the TeamsBotSsoPrompt will end the auth flow when receives user\n * message not related to the auth flow. Setting the flag to false ignores the user's message instead.\n * Defaults to value `true`\n */\n endOnInvalidMessage?: boolean;\n };\n };\n}\n\n/**\n * Options to initialize {@link ConversationBot}\n * @deprecated Please use BotBuilderCloudAdapter.ConversationOptions instead.\n */\nexport interface ConversationOptions {\n /**\n * The bot adapter. If not provided, a default adapter will be created:\n * - with `adapterConfig` as constructor parameter.\n * - with a default error handler that logs error to console, sends trace activity, and sends error message to user.\n *\n * @remarks\n * If neither `adapter` nor `adapterConfig` is provided, will use BOT_ID and BOT_PASSWORD from environment variables.\n */\n adapter?: BotFrameworkAdapter;\n\n /**\n * If `adapter` is not provided, this `adapterConfig` will be passed to the new `BotFrameworkAdapter` when created internally.\n *\n * @remarks\n * If neither `adapter` nor `adapterConfig` is provided, will use BOT_ID and BOT_PASSWORD from environment variables.\n */\n adapterConfig?: { [key: string]: unknown };\n\n /**\n * Configurations for sso command bot\n */\n ssoConfig?: BotSsoConfig;\n\n /**\n * The command part.\n */\n command?: CommandOptions & {\n /**\n * Whether to enable command or not.\n */\n enabled?: boolean;\n };\n\n /**\n * The notification part.\n */\n notification?: NotificationOptions & {\n /**\n * Whether to enable notification or not.\n */\n enabled?: boolean;\n };\n\n /**\n * The adaptive card action handler part.\n */\n cardAction?: CardActionOptions & {\n /**\n * Whether to enable adaptive card actions or not.\n */\n enabled?: boolean;\n };\n}\n\n/**\n * Interface for user to customize SSO execution activity handler\n *\n * @remarks\n * Bot SSO execution activity handler is to handle SSO login process and trigger SSO command using {@link BotSsoExecutionDialog}.\n * You can use this interface to implement your own SSO execution dialog, and pass it to ConversationBot options:\n *\n * ```typescript\n * export const commandBot = new ConversationBot({\n * ...\n * ssoConfig: {\n * ...\n * dialog: {\n * CustomBotSsoExecutionActivityHandler: YourCustomBotSsoExecutionActivityHandler,\n * }\n * },\n * ...\n * });\n * ```\n * For details information about how to implement a BotSsoExecutionActivityHandler, please refer DefaultBotSsoExecutionActivityHandler class source code: https://aka.ms/teamsfx-default-sso-execution-activity-handler\n */\nexport interface BotSsoExecutionActivityHandler {\n /**\n * Add {@link TeamsFxBotSsoCommandHandler} instance to {@link BotSsoExecutionDialog}\n * @param handler {@link BotSsoExecutionDialogHandler} callback function\n * @param triggerPatterns The trigger pattern\n *\n * @remarks\n * This function is used to add SSO command to {@link BotSsoExecutionDialog} instance.\n */\n addCommand(handler: BotSsoExecutionDialogHandler, triggerPatterns: TriggerPatterns): void;\n\n /**\n * Called to initiate the event emission process.\n * @param context The context object for the current turn.\n */\n run(context: TurnContext): Promise<void>;\n\n /**\n * Receives invoke activities with Activity name of 'signin/verifyState'.\n * @param context A context object for this turn.\n * @param query Signin state (part of signin action auth flow) verification invoke query.\n * @returns A promise that represents the work queued.\n *\n * @remarks\n * It should trigger {@link BotSsoExecutionDialog} instance to handle signin process\n */\n handleTeamsSigninVerifyState(\n context: TurnContext,\n query: SigninStateVerificationQuery\n ): Promise<void>;\n\n /**\n * Receives invoke activities with Activity name of 'signin/tokenExchange'\n * @param context A context object for this turn.\n * @param query Signin state (part of signin action auth flow) verification invoke query\n * @returns A promise that represents the work queued.\n *\n * @remarks\n * It should trigger {@link BotSsoExecutionDialog} instance to handle signin process\n */\n handleTeamsSigninTokenExchange(\n context: TurnContext,\n query: SigninStateVerificationQuery\n ): Promise<void>;\n}\n\nexport type BotSsoExecutionDialogHandler = (\n context: TurnContext,\n tokenResponse: TeamsBotSsoPromptTokenResponse,\n message: CommandMessage\n) => Promise<void>;\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { InvokeResponse, StatusCodes } from \"botbuilder\";\nimport { InvokeResponseErrorCode } from \"./interface\";\n\n/**\n * Available response type for an adaptive card invoke response.\n * @internal\n */\nexport enum InvokeResponseType {\n AdaptiveCard = \"application/vnd.microsoft.card.adaptive\",\n Message = \"application/vnd.microsoft.activity.message\",\n Error = \"application/vnd.microsoft.error\",\n}\n\n/**\n * Provides methods for formatting various invoke responses a bot can send to respond to an invoke request.\n *\n * @remarks\n * All of these functions return an `InvokeResponse` object, which can be\n * passed as input to generate a new `invokeResponse` activity.\n *\n * This example sends an invoke response that contains an adaptive card.\n *\n * ```typescript\n *\n * const myCard = {\n * type: \"AdaptiveCard\",\n * body: [\n * {\n * \"type\": \"TextBlock\",\n * \"text\": \"This is a sample card\"\n * }],\n * $schema: \"http://adaptivecards.io/schemas/adaptive-card.json\",\n * version: \"1.4\"\n * };\n *\n * const invokeResponse = InvokeResponseFactory.adaptiveCard(myCard);\n * await context.sendActivity({\n * type: ActivityTypes.InvokeResponse,\n * value: invokeResponse,\n * });\n * ```\n */\nexport class InvokeResponseFactory {\n /**\n * Create an invoke response from a text message.\n * The type of the invoke response is `application/vnd.microsoft.activity.message`\n * indicates the request was successfully processed.\n *\n * @param message - A text message included in a invoke response.\n *\n * @returns An `InvokeResponse` object.\n */\n public static textMessage(message: string): InvokeResponse {\n if (!message) {\n throw new Error(\"The text message cannot be null or empty\");\n }\n\n return {\n status: StatusCodes.OK,\n body: {\n statusCode: StatusCodes.OK,\n type: InvokeResponseType.Message,\n value: message,\n },\n };\n }\n\n /**\n * Create an invoke response from an adaptive card.\n *\n * The type of the invoke response is `application/vnd.microsoft.card.adaptive` indicates\n * the request was successfully processed, and the response includes an adaptive card\n * that the client should display in place of the current one.\n *\n * @param card - The adaptive card JSON payload.\n *\n * @returns An `InvokeResponse` object.\n */\n public static adaptiveCard(card: unknown): InvokeResponse {\n if (!card) {\n throw new Error(\"The adaptive card content cannot be null or undefined\");\n }\n\n return {\n status: StatusCodes.OK,\n body: {\n statusCode: StatusCodes.OK,\n type: InvokeResponseType.AdaptiveCard,\n value: card,\n },\n };\n }\n\n /**\n * Create an invoke response with error code and message.\n *\n * The type of the invoke response is `application/vnd.microsoft.error` indicates\n * the request was failed to processed.\n *\n * @param errorCode - The status code indicates error, available values:\n * - 400 (BadRequest): indicate the incoming request was invalid.\n * - 500 (InternalServerError): indicate an unexpected error occurred.\n * @param errorMessage - The error message.\n *\n * @returns An `InvokeResponse` object.\n */\n public static errorResponse(\n errorCode: InvokeResponseErrorCode,\n errorMessage: string\n ): InvokeResponse {\n return {\n status: StatusCodes.OK,\n body: {\n statusCode: errorCode,\n type: InvokeResponseType.Error,\n value: {\n code: errorCode.toString(),\n message: errorMessage,\n },\n },\n };\n }\n\n /**\n * Create an invoke response with status code and response value.\n * @param statusCode - The status code.\n * @param body - The value of the response body.\n *\n * @returns An `InvokeResponse` object.\n */\n public static createInvokeResponse(statusCode: StatusCodes, body?: unknown): InvokeResponse {\n return {\n status: statusCode,\n body: body,\n };\n }\n}\n","import {\n ActivityTypes,\n CardFactory,\n InvokeResponse,\n MessageFactory,\n Middleware,\n TurnContext,\n} from \"botbuilder\";\nimport {\n AdaptiveCardResponse,\n InvokeResponseErrorCode,\n TeamsFxAdaptiveCardActionHandler,\n} from \"../interface\";\nimport { InvokeResponseFactory, InvokeResponseType } from \"../invokeResponseFactory\";\n\n/**\n * @internal\n */\nexport class CardActionMiddleware implements Middleware {\n public readonly actionHandlers: TeamsFxAdaptiveCardActionHandler[] = [];\n private readonly defaultMessage: string = \"Your response was sent to the app\";\n\n constructor(handlers?: TeamsFxAdaptiveCardActionHandler[]) {\n if (handlers && handlers.length > 0) {\n this.actionHandlers.push(...handlers);\n }\n }\n\n async onTurn(context: TurnContext, next: () => Promise<void>): Promise<void> {\n if (context.activity.name === \"adaptiveCard/action\") {\n const action = context.activity.value.action;\n const actionVerb = action.verb;\n\n for (const handler of this.actionHandlers) {\n if (handler.triggerVerb?.toLowerCase() === actionVerb?.toLowerCase()) {\n let response: InvokeResponse;\n try {\n response = await handler.handleActionInvoked(context, action.data);\n } catch (error: any) {\n const errorResponse = InvokeResponseFactory.errorResponse(\n InvokeResponseErrorCode.InternalServerError,\n error.message\n );\n await this.sendInvokeResponse(context, errorResponse);\n throw error;\n }\n\n const responseType = response.body?.type;\n switch (responseType) {\n case InvokeResponseType.AdaptiveCard:\n const card = response.body?.value;\n if (!card) {\n const errorMessage = \"Adaptive card content cannot be found in the response body\";\n await this.sendInvokeResponse(\n context,\n InvokeResponseFactory.errorResponse(\n InvokeResponseErrorCode.InternalServerError,\n errorMessage\n )\n );\n throw new Error(errorMessage);\n }\n\n if (card.refresh && handler.adaptiveCardResponse !== AdaptiveCardResponse.NewForAll) {\n // Card won't be refreshed with AdaptiveCardResponse.ReplaceForInteractor.\n // So set to AdaptiveCardResponse.ReplaceForAll here.\n handler.adaptiveCardResponse = AdaptiveCardResponse.ReplaceForAll;\n }\n\n const activity = MessageFactory.attachment(CardFactory.adaptiveCard(card));\n if (handler.adaptiveCardResponse === AdaptiveCardResponse.NewForAll) {\n await this.sendInvokeResponse(\n context,\n InvokeResponseFactory.textMessage(this.defaultMessage)\n );\n await context.sendActivity(activity);\n } else if (handler.adaptiveCardResponse === AdaptiveCardResponse.ReplaceForAll) {\n activity.id = context.activity.replyToId;\n await context.updateActivity(activity);\n await this.sendInvokeResponse(context, response);\n } else {\n await this.sendInvokeResponse(context, response);\n }\n break;\n case InvokeResponseType.Message:\n case InvokeResponseType.Error:\n default:\n await this.sendInvokeResponse(context, response);\n break;\n }\n\n break;\n }\n }\n }\n\n await next();\n }\n\n private async sendInvokeResponse(context: TurnContext, response: InvokeResponse) {\n await context.sendActivity({\n type: ActivityTypes.InvokeResponse,\n value: response,\n });\n }\n}\n","import { BotFrameworkAdapter } from \"botbuilder\";\nimport { CardActionMiddleware } from \"./middlewares/cardActionMiddleware\";\nimport { CardActionOptions, TeamsFxAdaptiveCardActionHandler } from \"./interface\";\n\n/**\n * A card action bot to respond to adaptive card universal actions.\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.CardActionBot` instead.\n */\nexport class CardActionBot {\n private readonly adapter: BotFrameworkAdapter;\n private middleware: CardActionMiddleware;\n\n /**\n * Creates a new instance of the `CardActionBot`.\n *\n * @param adapter The bound `BotFrameworkAdapter`.\n * @param options - initialize options\n */\n constructor(adapter: BotFrameworkAdapter, options?: CardActionOptions) {\n this.middleware = new CardActionMiddleware(options?.actions);\n this.adapter = adapter.use(this.middleware);\n }\n\n /**\n * Registers a card action handler to the bot.\n * @param actionHandler A card action handler to be registered.\n */\n registerHandler(actionHandler: TeamsFxAdaptiveCardActionHandler) {\n if (actionHandler) {\n this.middleware.actionHandlers.push(actionHandler);\n }\n }\n\n /**\n * Registers card action handlers to the bot.\n * @param actionHandlers A set of card action handlers to be registered.\n */\n registerHandlers(actionHandlers: TeamsFxAdaptiveCardActionHandler[]) {\n if (actionHandlers) {\n this.middleware.actionHandlers.push(...actionHandlers);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Activity, ActivityTypes, Middleware, TurnContext } from \"botbuilder\";\nimport { TeamsBotSsoPromptTokenResponse } from \"../../bot/teamsBotSsoPromptTokenResponse\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../../core/errors\";\nimport { internalLogger } from \"../../util/logger\";\nimport {\n CommandMessage,\n BotSsoExecutionActivityHandler,\n TeamsFxBotCommandHandler,\n TeamsFxBotSsoCommandHandler,\n TriggerPatterns,\n} from \"../interface\";\n\n/**\n * @internal\n */\nexport class CommandResponseMiddleware implements Middleware {\n public readonly commandHandlers: TeamsFxBotCommandHandler[] = [];\n public readonly ssoCommandHandlers: TeamsFxBotSsoCommandHandler[] = [];\n\n public ssoActivityHandler: BotSsoExecutionActivityHandler | undefined;\n public hasSsoCommand: boolean;\n\n constructor(\n handlers?: TeamsFxBotCommandHandler[],\n ssoHandlers?: TeamsFxBotSsoCommandHandler[],\n activityHandler?: BotSsoExecutionActivityHandler\n ) {\n handlers = handlers ?? [];\n ssoHandlers = ssoHandlers ?? [];\n this.hasSsoCommand = ssoHandlers.length > 0;\n this.ssoActivityHandler = activityHandler;\n\n if (this.hasSsoCommand && !this.ssoActivityHandler) {\n internalLogger.error(ErrorMessage.SsoActivityHandlerIsNull);\n throw new ErrorWithCode(\n ErrorMessage.SsoActivityHandlerIsNull,\n ErrorCode.SsoActivityHandlerIsUndefined\n );\n }\n\n this.commandHandlers.push(...handlers);\n for (const ssoHandler of ssoHandlers) {\n this.addSsoCommand(ssoHandler);\n }\n }\n\n public addSsoCommand(ssoHandler: TeamsFxBotSsoCommandHandler): void {\n this.ssoActivityHandler?.addCommand(\n async (\n context: TurnContext,\n tokenResponse: TeamsBotSsoPromptTokenResponse,\n message: CommandMessage\n ) => {\n const matchResult = this.shouldTrigger(ssoHandler.triggerPatterns, message.text);\n message.matches = Array.isArray(matchResult) ? matchResult : void 0;\n const response = await ssoHandler.handleCommandReceived(context, message, tokenResponse);\n await this.processResponse(context, response);\n },\n ssoHandler.triggerPatterns\n );\n this.ssoCommandHandlers.push(ssoHandler);\n this.hasSsoCommand = true;\n }\n\n public async onTurn(context: TurnContext, next: () => Promise<void>): Promise<void> {\n if (context.activity.type === ActivityTypes.Message) {\n // Invoke corresponding command handler for the command response\n const commandText = this.getActivityText(context.activity);\n let alreadyProcessed = false;\n for (const handler of this.commandHandlers) {\n const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);\n\n // It is important to note that the command bot will stop processing handlers\n // when the first command handler is matched.\n if (!!matchResult) {\n const message: CommandMessage = {\n text: commandText,\n };\n message.matches = Array.isArray(matchResult) ? matchResult : void 0;\n const response = await handler.handleCommandReceived(context, message);\n\n await this.processResponse(context, response);\n alreadyProcessed = true;\n break;\n }\n }\n\n if (!alreadyProcessed) {\n for (const handler of this.ssoCommandHandlers) {\n const matchResult = this.shouldTrigger(handler.triggerPatterns, commandText);\n if (!!matchResult) {\n await this.ssoActivityHandler?.run(context);\n break;\n }\n }\n }\n } else {\n if (this.hasSsoCommand) {\n await this.ssoActivityHandler?.run(context);\n }\n }\n await next();\n }\n\n private async processResponse(context: TurnContext, response: string | void | Partial<Activity>) {\n if (typeof response === \"string\") {\n await context.sendActivity(response);\n } else {\n const replyActivity = response as Partial<Activity>;\n if (replyActivity) {\n await context.sendActivity(replyActivity);\n }\n }\n }\n\n private matchPattern(pattern: string | RegExp, text: string): boolean | RegExpMatchArray {\n if (text) {\n if (typeof pattern === \"string\") {\n const regExp = new RegExp(pattern, \"i\");\n return regExp.test(text);\n }\n\n if (pattern instanceof RegExp) {\n const matches = text.match(pattern);\n return matches ?? false;\n }\n }\n\n return false;\n }\n\n private shouldTrigger(patterns: TriggerPatterns, text: string): RegExpMatchArray | boolean {\n const expressions = Array.isArray(patterns) ? patterns : [patterns];\n\n for (const ex of expressions) {\n const arg = this.matchPattern(ex, text);\n if (arg) return arg;\n }\n\n return false;\n }\n\n private getActivityText(activity: Activity): string {\n let text = activity.text;\n const removedMentionText = TurnContext.removeRecipientMention(activity);\n if (removedMentionText) {\n text = removedMentionText\n .toLowerCase()\n .replace(/\\n|\\r\\n/g, \"\")\n .trim();\n }\n\n return text;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { BotFrameworkAdapter } from \"botbuilder\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport {\n CommandOptions,\n BotSsoConfig,\n BotSsoExecutionActivityHandler,\n TeamsFxBotCommandHandler,\n TeamsFxBotSsoCommandHandler,\n} from \"./interface\";\nimport { CommandResponseMiddleware } from \"./middlewares/commandMiddleware\";\n\n/**\n * A command bot for receiving commands and sending responses in Teams.\n *\n * @remarks\n * Ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.CommandBot` instead.\n */\nexport class CommandBot {\n private readonly adapter: BotFrameworkAdapter;\n private readonly middleware: CommandResponseMiddleware;\n private readonly ssoConfig: BotSsoConfig | undefined;\n\n /**\n * Creates a new instance of the `CommandBot`.\n *\n * @param adapter The bound `BotFrameworkAdapter`.\n * @param options - initialize options\n */\n constructor(\n adapter: BotFrameworkAdapter,\n options?: CommandOptions,\n ssoCommandActivityHandler?: BotSsoExecutionActivityHandler,\n ssoConfig?: BotSsoConfig\n ) {\n this.ssoConfig = ssoConfig;\n\n this.middleware = new CommandResponseMiddleware(\n options?.commands,\n options?.ssoCommands,\n ssoCommandActivityHandler\n );\n this.adapter = adapter.use(this.middleware);\n }\n\n /**\n * Registers a command into the command bot.\n *\n * @param command The command to register.\n */\n public registerCommand(command: TeamsFxBotCommandHandler): void {\n if (command) {\n this.middleware.commandHandlers.push(command);\n }\n }\n\n /**\n * Registers commands into the command bot.\n *\n * @param commands The commands to register.\n */\n public registerCommands(commands: TeamsFxBotCommandHandler[]): void {\n if (commands) {\n this.middleware.commandHandlers.push(...commands);\n }\n }\n\n /**\n * Registers a sso command into the command bot.\n *\n * @param command The command to register.\n */\n public registerSsoCommand(ssoCommand: TeamsFxBotSsoCommandHandler): void {\n this.validateSsoActivityHandler();\n this.middleware.addSsoCommand(ssoCommand);\n }\n\n /**\n * Registers commands into the command bot.\n *\n * @param commands The commands to register.\n */\n public registerSsoCommands(ssoCommands: TeamsFxBotSsoCommandHandler[]): void {\n if (ssoCommands.length > 0) {\n this.validateSsoActivityHandler();\n for (const ssoCommand of ssoCommands) {\n this.middleware.addSsoCommand(ssoCommand);\n }\n }\n }\n\n private validateSsoActivityHandler() {\n if (!this.middleware.ssoActivityHandler) {\n internalLogger.error(ErrorMessage.SsoActivityHandlerIsNull);\n throw new ErrorWithCode(\n ErrorMessage.SsoActivityHandlerIsNull,\n ErrorCode.SsoActivityHandlerIsUndefined\n );\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ConversationReference, TurnContext } from \"botbuilder\";\nimport { NotificationTargetType } from \"./interface\";\n\n/**\n * @internal\n */\nexport function cloneConversation(\n conversation: Partial<ConversationReference>\n): ConversationReference {\n return JSON.parse(JSON.stringify(conversation));\n}\n\n/**\n * @internal\n */\nexport function getKey(reference: Partial<ConversationReference>): string {\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `_${reference.conversation?.tenantId}_${reference.conversation?.id}`;\n}\n\n/**\n * @internal\n */\nexport function getTargetType(\n conversationReference: Partial<ConversationReference>\n): NotificationTargetType | undefined {\n const conversationType = conversationReference.conversation?.conversationType;\n if (conversationType === \"personal\") {\n return NotificationTargetType.Person;\n } else if (conversationType === \"groupChat\") {\n return NotificationTargetType.Group;\n } else if (conversationType === \"channel\") {\n return NotificationTargetType.Channel;\n } else {\n return undefined;\n }\n}\n\n/**\n * @internal\n */\nexport function getTeamsBotInstallationId(context: TurnContext): string | undefined {\n const teamId = context.activity?.channelData?.team?.id;\n if (teamId) {\n return teamId;\n }\n\n // Fallback to use conversation id.\n // The conversation id is equal to team id only when the bot app is installed into the General channel.\n if (context.activity.conversation.name === undefined) {\n return context.activity.conversation.id;\n }\n\n return undefined;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Activity, Middleware, TurnContext } from \"botbuilder\";\nimport { cloneConversation, getKey } from \"../utils\";\nimport { ConversationReferenceStore } from \"../interface\";\n\n/**\n * @internal\n */\nenum ActivityType {\n CurrentBotInstalled,\n CurrentBotMessaged,\n CurrentBotUninstalled,\n TeamDeleted,\n TeamRestored,\n Unknown,\n}\n\n/**\n * @internal\n */\nexport interface NotificationMiddlewareOptions {\n conversationReferenceStore: ConversationReferenceStore;\n}\n\n/**\n * @internal\n */\nexport class NotificationMiddleware implements Middleware {\n private readonly conversationReferenceStore: ConversationReferenceStore;\n\n constructor(options: NotificationMiddlewareOptions) {\n this.conversationReferenceStore = options.conversationReferenceStore;\n }\n\n public async onTurn(context: TurnContext, next: () => Promise<void>): Promise<void> {\n const type = this.classifyActivity(context.activity);\n switch (type) {\n case ActivityType.CurrentBotInstalled:\n case ActivityType.TeamRestored: {\n const reference = TurnContext.getConversationReference(context.activity);\n await this.conversationReferenceStore.add(getKey(reference), reference, {\n overwrite: true,\n });\n break;\n }\n case ActivityType.CurrentBotMessaged: {\n await this.tryAddMessagedReference(context);\n break;\n }\n case ActivityType.CurrentBotUninstalled:\n case ActivityType.TeamDeleted: {\n const reference = TurnContext.getConversationReference(context.activity);\n await this.conversationReferenceStore.remove(getKey(reference), reference);\n break;\n }\n default:\n break;\n }\n\n await next();\n }\n\n private classifyActivity(activity: Activity): ActivityType {\n const activityType = activity.type;\n if (activityType === \"installationUpdate\") {\n const action = activity.action?.toLowerCase();\n if (action === \"add\") {\n return ActivityType.CurrentBotInstalled;\n } else {\n return ActivityType.CurrentBotUninstalled;\n }\n } else if (activityType === \"conversationUpdate\") {\n const eventType = activity.channelData?.eventType as string;\n if (eventType === \"teamDeleted\") {\n return ActivityType.TeamDeleted;\n } else if (eventType === \"teamRestored\") {\n return ActivityType.TeamRestored;\n }\n } else if (activityType === \"message\") {\n return ActivityType.CurrentBotMessaged;\n }\n\n return ActivityType.Unknown;\n }\n\n private async tryAddMessagedReference(context: TurnContext): Promise<void> {\n const reference = TurnContext.getConversationReference(context.activity);\n const conversationType = reference?.conversation?.conversationType;\n if (conversationType === \"personal\" || conversationType === \"groupChat\") {\n await this.conversationReferenceStore.add(getKey(reference), reference, { overwrite: false });\n } else if (conversationType === \"channel\") {\n const teamId = context.activity?.channelData?.team?.id;\n const channelId = context.activity.channelData?.channel?.id;\n // `teamId === channelId` means General channel. Ignore messaging in non-General channel.\n if (teamId !== undefined && (channelId === undefined || teamId === channelId)) {\n const teamReference = cloneConversation(reference);\n teamReference.conversation.id = teamId;\n await this.conversationReferenceStore.add(getKey(teamReference), teamReference, {\n overwrite: false,\n });\n }\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ConversationReference } from \"botbuilder\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport {\n NotificationTargetStorage,\n ConversationReferenceStore,\n ConversationReferenceStoreAddOptions,\n PagedData,\n} from \"./interface\";\n\n/**\n * @internal\n */\nexport class LocalFileStorage implements NotificationTargetStorage {\n private readonly localFileName =\n process.env.TEAMSFX_NOTIFICATION_STORE_FILENAME ?? \".notification.localstore.json\";\n private readonly filePath: string;\n\n constructor(fileDir: string) {\n this.filePath = path.resolve(fileDir, this.localFileName);\n }\n\n async read(key: string): Promise<{ [key: string]: unknown } | undefined> {\n if (!(await this.storeFileExists())) {\n return undefined;\n }\n\n const data = await this.readFromFile();\n\n return data[key];\n }\n\n async list(): Promise<{ [key: string]: unknown }[]> {\n if (!(await this.storeFileExists())) {\n return [];\n }\n\n const data = await this.readFromFile();\n\n return Object.entries(data).map((entry) => entry[1] as { [key: string]: unknown });\n }\n\n async write(key: string, object: { [key: string]: unknown }): Promise<void> {\n if (!(await this.storeFileExists())) {\n await this.writeToFile({ [key]: object });\n return;\n }\n\n const data = await this.readFromFile();\n await this.writeToFile(Object.assign(data, { [key]: object }));\n }\n\n async delete(key: string): Promise<void> {\n if (await this.storeFileExists()) {\n const data = await this.readFromFile();\n if (data[key] !== undefined) {\n delete data[key];\n await this.writeToFile(data);\n }\n }\n }\n\n private storeFileExists(): Promise<boolean> {\n return new Promise((resolve) => {\n try {\n fs.access(this.filePath, (err) => {\n if (err) {\n resolve(false);\n } else {\n resolve(true);\n }\n });\n } catch (error: unknown) {\n resolve(false);\n }\n });\n }\n\n private readFromFile(): Promise<any> {\n return new Promise((resolve, reject) => {\n try {\n fs.readFile(this.filePath, { encoding: \"utf-8\" }, (err, rawData) => {\n if (err) {\n reject(err);\n } else {\n resolve(JSON.parse(rawData));\n }\n });\n } catch (error: unknown) {\n reject(error);\n }\n });\n }\n\n private async writeToFile(data: unknown): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n const rawData = JSON.stringify(data, undefined, 2);\n fs.writeFile(this.filePath, rawData, { encoding: \"utf-8\" }, (err) => {\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n });\n } catch (error: unknown) {\n reject(error);\n }\n });\n }\n}\n\n/**\n * @internal\n */\nexport class DefaultConversationReferenceStore implements ConversationReferenceStore {\n private readonly storage: NotificationTargetStorage;\n\n constructor(storage: NotificationTargetStorage) {\n this.storage = storage;\n }\n\n async add(\n key: string,\n reference: Partial<ConversationReference>,\n options: ConversationReferenceStoreAddOptions\n ): Promise<boolean> {\n if (options.overwrite) {\n await this.storage.write(key, reference);\n return true;\n }\n\n const ref = await this.storage.read(key);\n if (ref === undefined) {\n await this.storage.write(key, reference);\n return true;\n }\n\n return false;\n }\n\n async remove(key: string, reference: Partial<ConversationReference>): Promise<boolean> {\n const ref = await this.storage.read(key);\n if (ref === undefined) {\n return false;\n }\n\n await this.storage.delete(key);\n return true;\n }\n\n async list(\n pageSize?: number,\n continuationToken?: string\n ): Promise<PagedData<Partial<ConversationReference>>> {\n const data = await this.storage.list();\n return {\n data,\n continuationToken: \"\",\n };\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n BotFrameworkAdapter,\n CardFactory,\n ChannelInfo,\n ConversationParameters,\n ConversationReference,\n TeamDetails,\n TeamsChannelAccount,\n TeamsInfo,\n TurnContext,\n} from \"botbuilder\";\nimport type { ConnectorClient } from \"botframework-connector\";\nimport * as path from \"path\";\nimport {\n NotificationTarget,\n NotificationTargetType,\n NotificationOptions,\n MessageResponse,\n} from \"./interface\";\nimport { NotificationMiddleware } from \"./middlewares/notificationMiddleware\";\nimport { DefaultConversationReferenceStore, LocalFileStorage } from \"./storage\";\nimport * as utils from \"./utils\";\n\n/**\n * Send a plain text message to a notification target.\n *\n * @param target - the notification target.\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending message.\n */\nexport function sendMessage(\n target: NotificationTarget,\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n): Promise<MessageResponse> {\n return target.sendMessage(text, onError);\n}\n\n/**\n * Send an adaptive card message to a notification target.\n *\n * @param target - the notification target.\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending adaptive card message.\n */\nexport function sendAdaptiveCard(\n target: NotificationTarget,\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n): Promise<MessageResponse> {\n return target.sendAdaptiveCard(card, onError);\n}\n\n/**\n * A {@link NotificationTarget} that represents a team channel.\n *\n * @remarks\n * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.\n */\nexport class Channel implements NotificationTarget {\n /**\n * The parent {@link TeamsBotInstallation} where this channel is created from.\n */\n public readonly parent: TeamsBotInstallation;\n\n /**\n * Detailed channel information.\n */\n public readonly info: ChannelInfo;\n\n /**\n * Notification target type. For channel it's always \"Channel\".\n */\n public readonly type: NotificationTargetType = NotificationTargetType.Channel;\n\n /**\n * Constructor.\n *\n * @remarks\n * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.\n *\n * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.\n * @param info - Detailed channel information.\n */\n constructor(parent: TeamsBotInstallation, info: ChannelInfo) {\n this.parent = parent;\n this.info = info;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversation(\n this.parent.conversationReference,\n async (context) => {\n const conversation = this.newConversation(context);\n await this.parent.adapter.continueConversation(conversation, async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n });\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversation(\n this.parent.conversationReference,\n async (context) => {\n const conversation = this.newConversation(context);\n await this.parent.adapter.continueConversation(conversation, async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n });\n }\n );\n return response;\n }\n\n /**\n * @internal\n */\n private newConversation(context: TurnContext): ConversationReference {\n const reference = TurnContext.getConversationReference(context.activity);\n const channelConversation = utils.cloneConversation(reference);\n channelConversation.conversation.id = this.info.id || \"\";\n\n return channelConversation;\n }\n}\n\n/**\n * A {@link NotificationTarget} that represents a team member.\n *\n * @remarks\n * It's recommended to get members from {@link TeamsBotInstallation.members()}.\n */\nexport class Member implements NotificationTarget {\n /**\n * The parent {@link TeamsBotInstallation} where this member is created from.\n */\n public readonly parent: TeamsBotInstallation;\n\n /**\n * Detailed member account information.\n */\n public readonly account: TeamsChannelAccount;\n\n /**\n * Notification target type. For member it's always \"Person\".\n */\n public readonly type: NotificationTargetType = NotificationTargetType.Person;\n\n /**\n * Constructor.\n *\n * @remarks\n * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.\n *\n * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.\n * @param account - Detailed member account information.\n */\n constructor(parent: TeamsBotInstallation, account: TeamsChannelAccount) {\n this.parent = parent;\n this.account = account;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversation(\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversation(conversation, async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n });\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversation(\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversation(conversation, async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n });\n }\n );\n return response;\n }\n\n /**\n * @internal\n */\n private async newConversation(context: TurnContext): Promise<ConversationReference> {\n const reference = TurnContext.getConversationReference(context.activity);\n const personalConversation = utils.cloneConversation(reference);\n\n const connectorClient: ConnectorClient = context.turnState.get(\n this.parent.adapter.ConnectorClientKey\n );\n const conversation = await connectorClient.conversations.createConversation({\n isGroup: false,\n tenantId: context.activity.conversation.tenantId,\n bot: context.activity.recipient,\n members: [this.account],\n channelData: {},\n } as ConversationParameters);\n personalConversation.conversation.id = conversation.id;\n\n return personalConversation;\n }\n}\n\n/**\n * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into\n * - Personal chat\n * - Group chat\n * - Team (by default the `General` channel)\n *\n * @remarks\n * It's recommended to get bot installations from {@link ConversationBot.installations()}.\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.TeamsBotInstallation` instead.\n */\nexport class TeamsBotInstallation implements NotificationTarget {\n /**\n * The bound `BotFrameworkAdapter`.\n */\n public readonly adapter: BotFrameworkAdapter;\n\n /**\n * The bound `ConversationReference`.\n */\n public readonly conversationReference: Partial<ConversationReference>;\n\n /**\n * Notification target type.\n *\n * @remarks\n * - \"Channel\" means bot is installed into a team and notification will be sent to its \"General\" channel.\n * - \"Group\" means bot is installed into a group chat.\n * - \"Person\" means bot is installed into a personal scope and notification will be sent to personal chat.\n */\n public readonly type?: NotificationTargetType;\n\n /**\n * Constructor\n *\n * @remarks\n * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.\n *\n * @param adapter - the bound `BotFrameworkAdapter`.\n * @param conversationReference - the bound `ConversationReference`.\n */\n constructor(adapter: BotFrameworkAdapter, conversationReference: Partial<ConversationReference>) {\n this.adapter = adapter;\n this.conversationReference = conversationReference;\n this.type = utils.getTargetType(conversationReference);\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - the plain text message.\n * @param onError - an optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n try {\n const res = await context.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(context, error as Error);\n } else {\n throw error;\n }\n }\n });\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @param onError - an optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n try {\n const res = await context.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(context, error as Error);\n } else {\n throw error;\n }\n }\n });\n return response;\n }\n\n /**\n * Get channels from this bot installation.\n *\n * @returns an array of channels if bot is installed into a team, otherwise returns an empty array.\n */\n public async channels(): Promise<Channel[]> {\n const channels: Channel[] = [];\n if (this.type !== NotificationTargetType.Channel) {\n return channels;\n }\n\n let teamsChannels: ChannelInfo[] = [];\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n const teamId = utils.getTeamsBotInstallationId(context);\n if (teamId !== undefined) {\n teamsChannels = await TeamsInfo.getTeamChannels(context, teamId);\n }\n });\n\n for (const channel of teamsChannels) {\n channels.push(new Channel(this, channel));\n }\n\n return channels;\n }\n\n /**\n * Get members from this bot installation.\n *\n * @returns an array of members from where the bot is installed.\n */\n public async members(): Promise<Member[]> {\n const members: Member[] = [];\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n let continuationToken: string | undefined;\n do {\n const pagedMembers = await TeamsInfo.getPagedMembers(context, undefined, continuationToken);\n continuationToken = pagedMembers.continuationToken;\n for (const member of pagedMembers.members) {\n members.push(new Member(this, member));\n }\n } while (continuationToken !== undefined);\n });\n\n return members;\n }\n\n /**\n * Get team details from this bot installation\n *\n * @returns the team details if bot is installed into a team, otherwise returns undefined.\n */\n public async getTeamDetails(): Promise<TeamDetails | undefined> {\n if (this.type !== NotificationTargetType.Channel) {\n return undefined;\n }\n\n let teamDetails: TeamDetails | undefined;\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n const teamId = utils.getTeamsBotInstallationId(context);\n if (teamId !== undefined) {\n teamDetails = await TeamsInfo.getTeamDetails(context, teamId);\n }\n });\n\n return teamDetails;\n }\n}\n\n/**\n * Provide utilities to send notification to varies targets (e.g., member, group, channel).\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.NotificationBot` instead.\n */\nexport class NotificationBot {\n private readonly conversationReferenceStore: DefaultConversationReferenceStore;\n private readonly adapter: BotFrameworkAdapter;\n\n /**\n * constructor of the notification bot.\n *\n * @remarks\n * To ensure accuracy, it's recommended to initialize before handling any message.\n *\n * @param adapter - the bound `BotFrameworkAdapter`\n * @param options - initialize options\n */\n public constructor(adapter: BotFrameworkAdapter, options?: NotificationOptions) {\n const storage =\n options?.storage ??\n new LocalFileStorage(\n path.resolve(process.env.RUNNING_ON_AZURE === \"1\" ? process.env.TEMP ?? \"./\" : \"./\")\n );\n\n this.conversationReferenceStore = new DefaultConversationReferenceStore(storage);\n this.adapter = adapter.use(\n new NotificationMiddleware({\n conversationReferenceStore: this.conversationReferenceStore,\n })\n );\n }\n\n /**\n * Get all targets where the bot is installed.\n *\n * @remarks\n * The result is retrieving from the persisted storage.\n *\n * @returns - an array of {@link TeamsBotInstallation}.\n */\n public async installations(): Promise<TeamsBotInstallation[]> {\n if (this.conversationReferenceStore === undefined || this.adapter === undefined) {\n throw new Error(\"NotificationBot has not been initialized.\");\n }\n\n const { data: references } = await this.conversationReferenceStore.list();\n const targets: TeamsBotInstallation[] = [];\n for (const reference of references) {\n // validate connection\n let valid = true;\n await this.adapter.continueConversation(reference, async (context) => {\n try {\n // try get member to see if the installation is still valid\n await TeamsInfo.getPagedMembers(context, 1);\n } catch (error: any) {\n if ((error.code as string) === \"BotNotInConversationRoster\") {\n valid = false;\n }\n }\n });\n\n if (valid) {\n targets.push(new TeamsBotInstallation(this.adapter, reference));\n } else {\n await this.conversationReferenceStore.remove(utils.getKey(reference), reference);\n }\n }\n\n return targets;\n }\n\n /**\n * Returns the first {@link Member} where predicate is true, and undefined otherwise.\n *\n * @param predicate find calls predicate once for each member of the installation,\n * until it finds one where predicate returns true. If such a member is found, find\n * immediately returns that member. Otherwise, find returns undefined.\n * @param scope the scope to find members from the installations\n * (personal chat, group chat, Teams channel).\n * @returns the first {@link Member} where predicate is true, and undefined otherwise.\n */\n public async findMember(\n predicate: (member: Member) => Promise<boolean>,\n scope?: SearchScope\n ): Promise<Member | undefined> {\n for (const target of await this.installations()) {\n if (this.matchSearchScope(target, scope)) {\n for (const member of await target.members()) {\n if (await predicate(member)) {\n return member;\n }\n }\n }\n }\n\n return;\n }\n\n /**\n * Returns the first {@link Channel} where predicate is true, and undefined otherwise.\n * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)\n *\n * @param predicate find calls predicate once for each channel of the installation,\n * until it finds one where predicate returns true. If such a channel is found, find\n * immediately returns that channel. Otherwise, find returns undefined.\n * @returns the first {@link Channel} where predicate is true, and undefined otherwise.\n */\n public async findChannel(\n predicate: (channel: Channel, teamDetails: TeamDetails | undefined) => Promise<boolean>\n ): Promise<Channel | undefined> {\n for (const target of await this.installations()) {\n if (target.type === NotificationTargetType.Channel) {\n const teamDetails = await target.getTeamDetails();\n for (const channel of await target.channels()) {\n if (await predicate(channel, teamDetails)) {\n return channel;\n }\n }\n }\n }\n\n return;\n }\n\n /**\n * Returns all {@link Member} where predicate is true, and empty array otherwise.\n *\n * @param predicate find calls predicate for each member of the installation.\n * @param scope the scope to find members from the installations\n * (personal chat, group chat, Teams channel).\n * @returns an array of {@link Member} where predicate is true, and empty array otherwise.\n */\n public async findAllMembers(\n predicate: (member: Member) => Promise<boolean>,\n scope?: SearchScope\n ): Promise<Member[]> {\n const members: Member[] = [];\n for (const target of await this.installations()) {\n if (this.matchSearchScope(target, scope)) {\n for (const member of await target.members()) {\n if (await predicate(member)) {\n members.push(member);\n }\n }\n }\n }\n\n return members;\n }\n\n /**\n * Returns all {@link Channel} where predicate is true, and empty array otherwise.\n * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)\n *\n * @param predicate find calls predicate for each channel of the installation.\n * @returns an array of {@link Channel} where predicate is true, and empty array otherwise.\n */\n public async findAllChannels(\n predicate: (channel: Channel, teamDetails: TeamDetails | undefined) => Promise<boolean>\n ): Promise<Channel[]> {\n const channels: Channel[] = [];\n for (const target of await this.installations()) {\n if (target.type === NotificationTargetType.Channel) {\n const teamDetails = await target.getTeamDetails();\n for (const channel of await target.channels()) {\n if (await predicate(channel, teamDetails)) {\n channels.push(channel);\n }\n }\n }\n }\n\n return channels;\n }\n\n private matchSearchScope(target: NotificationTarget, scope?: SearchScope): boolean {\n scope = scope ?? SearchScope.All;\n\n return (\n (target.type === NotificationTargetType.Channel && (scope & SearchScope.Channel) !== 0) ||\n (target.type === NotificationTargetType.Group && (scope & SearchScope.Group) !== 0) ||\n (target.type === NotificationTargetType.Person && (scope & SearchScope.Person) !== 0)\n );\n }\n}\n\n/**\n * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.\n * The search scope is a flagged enum and it can be combined with `|`.\n * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.\n */\nexport enum SearchScope {\n /**\n * Search members from the installations in personal chat only.\n */\n Person = 1,\n\n /**\n * Search members from the installations in group chat only.\n */\n Group = 2,\n\n /**\n * Search members from the installations in Teams channel only.\n */\n Channel = 4,\n\n /**\n * Search members from all installations including personal chat, group chat and Teams channel.\n */\n All = Person | Group | Channel,\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n ComponentDialog,\n WaterfallDialog,\n Dialog,\n DialogSet,\n DialogTurnStatus,\n DialogContext,\n} from \"botbuilder-dialogs\";\nimport {\n Activity,\n ActivityTypes,\n Channels,\n StatePropertyAccessor,\n Storage,\n tokenExchangeOperationName,\n TurnContext,\n} from \"botbuilder\";\nimport { CommandMessage, BotSsoExecutionDialogHandler, TriggerPatterns } from \"../interface\";\nimport { TeamsBotSsoPrompt, TeamsBotSsoPromptSettings } from \"../../bot/teamsBotSsoPrompt\";\nimport { TeamsBotSsoPromptTokenResponse } from \"../../bot/teamsBotSsoPromptTokenResponse\";\nimport { TeamsFx } from \"../../core/teamsfx\";\nimport { formatString } from \"../../util/utils\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../../core/errors\";\nimport { internalLogger } from \"../../util/logger\";\nimport { createHash } from \"crypto\";\nimport { OnBehalfOfCredentialAuthConfig } from \"../../models/configuration\";\n\nlet DIALOG_NAME = \"BotSsoExecutionDialog\";\nlet TEAMS_SSO_PROMPT_ID = \"TeamsFxSsoPrompt\";\nlet COMMAND_ROUTE_DIALOG = \"CommandRouteDialog\";\n\n/**\n * Sso execution dialog, use to handle sso command\n */\nexport class BotSsoExecutionDialog extends ComponentDialog {\n private dedupStorage: Storage;\n private dedupStorageKeys: string[] = [];\n\n // Map to store the commandId and triggerPatterns, key: commandId, value: triggerPatterns\n private commandMapping: Map<string, string | RegExp | (string | RegExp)[]> = new Map<\n string,\n string | RegExp | (string | RegExp)[]\n >();\n\n /**\n * Creates a new instance of the BotSsoExecutionDialog.\n * @param {@link Storage} dedupStorage Helper storage to remove duplicated messages\n * @param {@link TeamsBotSsoPromptSettings} settings The list of scopes for which the token will have access\n * @param {@link TeamsFx} teamsfx instance for authentication\n * @param {string} dialogName custom dialog name\n */\n constructor(\n dedupStorage: Storage,\n ssoPromptSettings: TeamsBotSsoPromptSettings,\n teamsfx: TeamsFx,\n dialogName?: string\n );\n /**\n * Creates a new instance of the BotSsoExecutionDialog.\n * @param {@link Storage} dedupStorage Helper storage to remove duplicated messages\n * @param {@link TeamsBotSsoPromptSettings} settings The list of scopes for which the token will have access\n * @param {@link OnBehalfOfCredentialAuthConfig} authConfig The authentication configuration.\n * @param {string} initiateLoginEndpoint Login URL for Teams to redirect to.\n * @param {string} dialogName custom dialog name\n */\n constructor(\n dedupStorage: Storage,\n ssoPromptSettings: TeamsBotSsoPromptSettings,\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n dialogName?: string\n );\n constructor(\n dedupStorage: Storage,\n ssoPromptSettings: TeamsBotSsoPromptSettings,\n authConfig: TeamsFx | OnBehalfOfCredentialAuthConfig,\n ...args: any\n ) {\n super(((authConfig as TeamsFx).getCredential ? args[0] : args[1]) ?? DIALOG_NAME);\n const dialogName: string = (authConfig as TeamsFx).getCredential ? args[0] : args[1];\n\n if (dialogName) {\n DIALOG_NAME = dialogName;\n TEAMS_SSO_PROMPT_ID = dialogName + TEAMS_SSO_PROMPT_ID;\n COMMAND_ROUTE_DIALOG = dialogName + COMMAND_ROUTE_DIALOG;\n }\n\n let ssoDialog: TeamsBotSsoPrompt;\n if ((authConfig as TeamsFx).getCredential) {\n ssoDialog = new TeamsBotSsoPrompt(\n authConfig as TeamsFx,\n TEAMS_SSO_PROMPT_ID,\n ssoPromptSettings\n );\n } else {\n ssoDialog = new TeamsBotSsoPrompt(\n authConfig as OnBehalfOfCredentialAuthConfig,\n args[0],\n TEAMS_SSO_PROMPT_ID,\n ssoPromptSettings\n );\n }\n\n this.addDialog(ssoDialog);\n\n this.initialDialogId = COMMAND_ROUTE_DIALOG;\n\n this.dedupStorage = dedupStorage;\n this.dedupStorageKeys = [];\n\n const commandRouteDialog = new WaterfallDialog(COMMAND_ROUTE_DIALOG, [\n this.commandRouteStep.bind(this),\n ]);\n this.addDialog(commandRouteDialog);\n }\n\n /**\n * Add TeamsFxBotSsoCommandHandler instance\n * @param handler {@link BotSsoExecutionDialogHandler} callback function\n * @param triggerPatterns The trigger pattern\n */\n public addCommand(handler: BotSsoExecutionDialogHandler, triggerPatterns: TriggerPatterns): void {\n const commandId = this.getCommandHash(triggerPatterns);\n const dialog = new WaterfallDialog(commandId, [\n this.ssoStep.bind(this),\n this.dedupStep.bind(this),\n async (stepContext: any) => {\n const tokenResponse: TeamsBotSsoPromptTokenResponse = stepContext.result.tokenResponse;\n const context: TurnContext = stepContext.context;\n const message: CommandMessage = stepContext.result.message;\n\n try {\n if (tokenResponse) {\n await handler(context, tokenResponse, message);\n } else {\n throw new Error(ErrorMessage.FailedToRetrieveSsoToken);\n }\n return await stepContext.endDialog();\n } catch (error: unknown) {\n const errorMsg = formatString(\n ErrorMessage.FailedToProcessSsoHandler,\n (error as Error).message\n );\n internalLogger.error(errorMsg);\n return await stepContext.endDialog(\n new ErrorWithCode(errorMsg, ErrorCode.FailedToProcessSsoHandler)\n );\n }\n },\n ]);\n\n this.commandMapping.set(commandId, triggerPatterns);\n this.addDialog(dialog);\n }\n\n private getCommandHash(patterns: TriggerPatterns): string {\n const expressions = Array.isArray(patterns) ? patterns : [patterns];\n const patternStr = expressions.join();\n const patternStrWithoutSpecialChar = patternStr.replace(/[^a-zA-Z0-9]/g, \"\");\n const hash = createHash(\"sha256\").update(patternStr).digest(\"hex\").toLowerCase();\n return patternStrWithoutSpecialChar + hash;\n }\n\n /**\n * The run method handles the incoming activity (in the form of a DialogContext) and passes it through the dialog system.\n *\n * @param context The context object for the current turn.\n * @param accessor The instance of StatePropertyAccessor for dialog system.\n */\n public async run(context: TurnContext, accessor: StatePropertyAccessor) {\n const dialogSet = new DialogSet(accessor);\n dialogSet.add(this);\n\n const dialogContext = await dialogSet.createContext(context);\n this.ensureMsTeamsChannel(dialogContext);\n const results = await dialogContext.continueDialog();\n if (results && results.status === DialogTurnStatus.empty) {\n await dialogContext.beginDialog(this.id);\n } else if (\n results &&\n results.status === DialogTurnStatus.complete &&\n results.result instanceof Error\n ) {\n throw results.result;\n }\n }\n\n private getActivityText(activity: Activity): string {\n let text = activity.text;\n const removedMentionText = TurnContext.removeRecipientMention(activity);\n if (removedMentionText) {\n text = removedMentionText\n .toLowerCase()\n .replace(/\\n|\\r\\n/g, \"\")\n .trim();\n }\n\n return text;\n }\n\n private async commandRouteStep(stepContext: any) {\n const turnContext = stepContext.context as TurnContext;\n\n const text = this.getActivityText(turnContext.activity);\n\n const commandId = this.getMatchesCommandId(text);\n if (commandId) {\n return await stepContext.beginDialog(commandId);\n }\n\n const errorMsg = formatString(ErrorMessage.CannotFindCommand, turnContext.activity.text);\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.CannotFindCommand);\n }\n\n private async ssoStep(stepContext: any) {\n try {\n const turnContext = stepContext.context as TurnContext;\n\n const text = this.getActivityText(turnContext.activity);\n const message: CommandMessage = {\n text,\n };\n\n stepContext.options.commandMessage = message;\n\n return await stepContext.beginDialog(TEAMS_SSO_PROMPT_ID);\n } catch (error: unknown) {\n const errorMsg = formatString(ErrorMessage.FailedToRunSsoStep, (error as Error).message);\n internalLogger.error(errorMsg);\n return await stepContext.endDialog(new ErrorWithCode(errorMsg, ErrorCode.FailedToRunSsoStep));\n }\n }\n\n private async dedupStep(stepContext: any) {\n const tokenResponse = stepContext.result;\n if (!tokenResponse) {\n internalLogger.error(ErrorMessage.FailedToRetrieveSsoToken);\n return await stepContext.endDialog(\n new ErrorWithCode(ErrorMessage.FailedToRetrieveSsoToken, ErrorCode.FailedToRunSsoStep)\n );\n }\n\n try {\n // Only dedup after ssoStep to make sure that all Teams client would receive the login request\n if (tokenResponse && (await this.shouldDedup(stepContext.context))) {\n return Dialog.EndOfTurn;\n }\n return await stepContext.next({\n tokenResponse,\n message: stepContext.options.commandMessage,\n });\n } catch (error: unknown) {\n const errorMsg = formatString(ErrorMessage.FailedToRunDedupStep, (error as Error).message);\n internalLogger.error(errorMsg);\n return await stepContext.endDialog(\n new ErrorWithCode(errorMsg, ErrorCode.FailedToRunDedupStep)\n );\n }\n }\n\n /**\n * Called when the component is ending.\n *\n * @param context Context for the current turn of conversation.\n */\n protected async onEndDialog(context: TurnContext) {\n const conversationId = context.activity.conversation.id;\n const currentDedupKeys = this.dedupStorageKeys.filter((key) => key.indexOf(conversationId) > 0);\n await this.dedupStorage.delete(currentDedupKeys);\n this.dedupStorageKeys = this.dedupStorageKeys.filter((key) => key.indexOf(conversationId) < 0);\n }\n\n /**\n * If a user is signed into multiple Teams clients, the Bot might receive a \"signin/tokenExchange\" from each client.\n * Each token exchange request for a specific user login will have an identical activity.value.Id.\n * Only one of these token exchange requests should be processed by the bot. For a distributed bot in production,\n * this requires a distributed storage to ensure only one token exchange is processed.\n * @param context Context for the current turn of conversation.\n * @returns boolean value indicate whether the message should be removed\n */\n private async shouldDedup(context: TurnContext): Promise<boolean> {\n const storeItem = {\n eTag: context.activity.value.id,\n };\n\n const key = this.getStorageKey(context);\n const storeItems = { [key]: storeItem };\n\n try {\n await this.dedupStorage.write(storeItems);\n this.dedupStorageKeys.push(key);\n } catch (err: unknown) {\n if (err instanceof Error && err.message.indexOf(\"eTag conflict\")) {\n return true;\n }\n throw err;\n }\n return false;\n }\n\n private getStorageKey(context: TurnContext): string {\n if (!context || !context.activity || !context.activity.conversation) {\n throw new Error(\"Invalid context, can not get storage key!\");\n }\n const activity = context.activity;\n const channelId = activity.channelId;\n const conversationId = activity.conversation.id;\n if (activity.type !== ActivityTypes.Invoke || activity.name !== tokenExchangeOperationName) {\n throw new Error(\"TokenExchangeState can only be used with Invokes of signin/tokenExchange.\");\n }\n const value = activity.value;\n if (!value || !value.id) {\n throw new Error(\"Invalid signin/tokenExchange. Missing activity.value.id.\");\n }\n return `${channelId}/${conversationId}/${value.id as string}`;\n }\n\n private matchPattern(pattern: string | RegExp, text: string): boolean | RegExpMatchArray {\n if (text) {\n if (typeof pattern === \"string\") {\n const regExp = new RegExp(pattern, \"i\");\n return regExp.test(text);\n }\n\n if (pattern instanceof RegExp) {\n const matches = text.match(pattern);\n return matches ?? false;\n }\n }\n\n return false;\n }\n\n private isPatternMatched(patterns: TriggerPatterns, text: string): boolean {\n const expressions = Array.isArray(patterns) ? patterns : [patterns];\n\n for (const ex of expressions) {\n const matches = this.matchPattern(ex, text);\n return !!matches;\n }\n\n return false;\n }\n\n private getMatchesCommandId(text: string): string | undefined {\n for (const command of this.commandMapping) {\n const pattern: TriggerPatterns = command[1];\n\n if (this.isPatternMatched(pattern, text)) {\n return command[0];\n }\n }\n\n return undefined;\n }\n\n /**\n * Ensure bot is running in MS Teams since TeamsBotSsoPrompt is only supported in MS Teams channel.\n * @param dc dialog context\n * @throws {@link ErrorCode|ChannelNotSupported} if bot channel is not MS Teams\n * @internal\n */\n private ensureMsTeamsChannel(dc: DialogContext) {\n if (dc.context.activity.channelId != Channels.Msteams) {\n const errorMsg = formatString(\n ErrorMessage.OnlyMSTeamsChannelSupported,\n \"SSO execution dialog\"\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.ChannelNotSupported);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n BotState,\n ConversationState,\n MemoryStorage,\n SigninStateVerificationQuery,\n StatePropertyAccessor,\n TeamsActivityHandler,\n TurnContext,\n UserState,\n} from \"botbuilder\";\nimport { TeamsBotSsoPromptSettings } from \"../../bot/teamsBotSsoPrompt\";\nimport { TeamsFx } from \"../../core/teamsfx\";\nimport { IdentityType } from \"../../models/identityType\";\nimport {\n BotSsoConfig,\n BotSsoExecutionActivityHandler,\n BotSsoExecutionDialogHandler,\n TriggerPatterns,\n} from \"../interface\";\nimport { BotSsoExecutionDialog } from \"./botSsoExecutionDialog\";\nimport { OnBehalfOfCredentialAuthConfig } from \"../..\";\n\n/**\n * Default SSO execution activity handler\n */\nexport class DefaultBotSsoExecutionActivityHandler\n extends TeamsActivityHandler\n implements BotSsoExecutionActivityHandler\n{\n private ssoExecutionDialog: BotSsoExecutionDialog;\n private userState: BotState;\n private conversationState: BotState;\n private dialogState: StatePropertyAccessor;\n\n /**\n * Creates a new instance of the DefaultBotSsoExecutionActivityHandler.\n * @param ssoConfig configuration for SSO command bot\n *\n * @remarks\n * In the constructor, it uses BotSsoConfig parameter which from {@link ConversationBot} options to initialize {@link BotSsoExecutionDialog}.\n * It also need to register an event handler for the message event which trigger {@link BotSsoExecutionDialog} instance.\n */\n constructor(ssoConfig: BotSsoConfig) {\n super();\n const memoryStorage = new MemoryStorage();\n const userState = ssoConfig.dialog?.userState ?? new UserState(memoryStorage);\n const conversationState =\n ssoConfig.dialog?.conversationState ?? new ConversationState(memoryStorage);\n const dedupStorage = ssoConfig.dialog?.dedupStorage ?? memoryStorage;\n\n const { scopes, ...customConfig } = ssoConfig.aad;\n const settings: TeamsBotSsoPromptSettings = {\n scopes: scopes,\n timeout: ssoConfig.dialog?.ssoPromptConfig?.timeout,\n endOnInvalidMessage: ssoConfig.dialog?.ssoPromptConfig?.endOnInvalidMessage,\n };\n\n this.ssoExecutionDialog = new BotSsoExecutionDialog(\n dedupStorage,\n settings,\n customConfig as OnBehalfOfCredentialAuthConfig,\n customConfig.initiateLoginEndpoint!\n );\n\n this.conversationState = conversationState;\n this.dialogState = conversationState.createProperty(\"DialogState\");\n this.userState = userState;\n\n this.onMessage(async (context, next) => {\n await this.ssoExecutionDialog.run(context, this.dialogState);\n await next();\n });\n }\n\n /**\n * Add TeamsFxBotSsoCommandHandler instance to SSO execution dialog\n * @param handler {@link BotSsoExecutionDialogHandler} callback function\n * @param triggerPatterns The trigger pattern\n *\n * @remarks\n * This function is used to add SSO command to {@link BotSsoExecutionDialog} instance.\n */\n addCommand(handler: BotSsoExecutionDialogHandler, triggerPatterns: TriggerPatterns): void {\n this.ssoExecutionDialog.addCommand(handler, triggerPatterns);\n }\n\n /**\n * Called to initiate the event emission process.\n * @param context The context object for the current turn.\n */\n async run(context: TurnContext) {\n try {\n await super.run(context);\n } finally {\n await this.conversationState.saveChanges(context, false);\n await this.userState.saveChanges(context, false);\n }\n }\n\n /**\n * Receives invoke activities with Activity name of 'signin/verifyState'.\n * @param context A context object for this turn.\n * @param query Signin state (part of signin action auth flow) verification invoke query.\n * @returns A promise that represents the work queued.\n *\n * @remarks\n * It should trigger {@link BotSsoExecutionDialog} instance to handle signin process\n */\n async handleTeamsSigninVerifyState(context: TurnContext, query: SigninStateVerificationQuery) {\n await this.ssoExecutionDialog.run(context, this.dialogState);\n }\n\n /**\n * Receives invoke activities with Activity name of 'signin/tokenExchange'\n * @param context A context object for this turn.\n * @param query Signin state (part of signin action auth flow) verification invoke query\n * @returns A promise that represents the work queued.\n *\n * @remarks\n * It should trigger {@link BotSsoExecutionDialog} instance to handle signin process\n */\n async handleTeamsSigninTokenExchange(context: TurnContext, query: SigninStateVerificationQuery) {\n await this.ssoExecutionDialog.run(context, this.dialogState);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { BotFrameworkAdapter, TurnContext, WebRequest, WebResponse } from \"botbuilder\";\nimport { CardActionBot } from \"./cardAction\";\nimport { CommandBot } from \"./command\";\nimport { ConversationOptions, BotSsoExecutionActivityHandler } from \"./interface\";\nimport { NotificationBot } from \"./notification\";\nimport { DefaultBotSsoExecutionActivityHandler } from \"./sso/defaultBotSsoExecutionActivityHandler\";\n\n/**\n * Provide utilities for bot conversation, including:\n * - handle command and response.\n * - send notification to varies targets (e.g., member, group, channel).\n *\n * @example\n * For command and response, you can register your commands through the constructor, or use the `registerCommand` and `registerCommands` API to add commands later.\n *\n * ```typescript\n * // register through constructor\n * const conversationBot = new ConversationBot({\n * command: {\n * enabled: true,\n * commands: [ new HelloWorldCommandHandler() ],\n * },\n * });\n *\n * // register through `register*` API\n * conversationBot.command.registerCommand(new HelpCommandHandler());\n * ```\n *\n * For notification, you can enable notification at initialization, then send notifications at any time.\n *\n * ```typescript\n * // enable through constructor\n * const conversationBot = new ConversationBot({\n * notification: {\n * enabled: true,\n * },\n * });\n *\n * // get all bot installations and send message\n * for (const target of await conversationBot.notification.installations()) {\n * await target.sendMessage(\"Hello Notification\");\n * }\n *\n * // alternative - send message to all members\n * for (const target of await conversationBot.notification.installations()) {\n * for (const member of await target.members()) {\n * await member.sendMessage(\"Hello Notification\");\n * }\n * }\n * ```\n *\n * @remarks\n * Set `adapter` in {@link ConversationOptions} to use your own bot adapter.\n *\n * For command and response, ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.\n *\n * For notification, set `notification.storage` in {@link ConversationOptions} to use your own storage implementation.\n */\n\n/**\n * @deprecated Use `BotBuilderCloudAdapter.ConversationBot` instead.\n */\nexport class ConversationBot {\n /**\n * The bot adapter.\n */\n public readonly adapter: BotFrameworkAdapter;\n\n /**\n * The entrypoint of command and response.\n */\n public readonly command?: CommandBot;\n\n /**\n * The entrypoint of notification.\n */\n public readonly notification?: NotificationBot;\n\n /**\n * The action handler used for adaptive card universal actions.\n */\n public readonly cardAction?: CardActionBot;\n\n /**\n * Creates new instance of the `ConversationBot`.\n *\n * @remarks\n * It's recommended to create your own adapter and storage for production environment instead of the default one.\n *\n * @param options - initialize options\n */\n public constructor(options: ConversationOptions) {\n if (options.adapter) {\n this.adapter = options.adapter;\n } else {\n this.adapter = this.createDefaultAdapter(options.adapterConfig);\n }\n\n let ssoCommandActivityHandler: BotSsoExecutionActivityHandler | undefined;\n\n if (options?.ssoConfig) {\n if (options.ssoConfig.dialog?.CustomBotSsoExecutionActivityHandler) {\n ssoCommandActivityHandler =\n new options.ssoConfig.dialog.CustomBotSsoExecutionActivityHandler(options.ssoConfig);\n } else {\n ssoCommandActivityHandler = new DefaultBotSsoExecutionActivityHandler(options.ssoConfig);\n }\n }\n\n if (options.command?.enabled) {\n this.command = new CommandBot(\n this.adapter,\n options.command,\n ssoCommandActivityHandler,\n options.ssoConfig\n );\n }\n\n if (options.notification?.enabled) {\n this.notification = new NotificationBot(this.adapter, options.notification);\n }\n\n if (options.cardAction?.enabled) {\n this.cardAction = new CardActionBot(this.adapter, options.cardAction);\n }\n }\n\n private createDefaultAdapter(adapterConfig?: { [key: string]: unknown }): BotFrameworkAdapter {\n const adapter =\n adapterConfig === undefined\n ? new BotFrameworkAdapter({\n appId: process.env.BOT_ID,\n appPassword: process.env.BOT_PASSWORD,\n })\n : new BotFrameworkAdapter(adapterConfig);\n\n // the default error handler\n adapter.onTurnError = async (context, error) => {\n // This check writes out errors to console.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n console.error(`[onTurnError] unhandled error: ${error}`);\n\n // Send a trace activity, which will be displayed in Bot Framework Emulator\n await context.sendTraceActivity(\n \"OnTurnError Trace\",\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${error}`,\n \"https://www.botframework.com/schemas/error\",\n \"TurnError\"\n );\n\n // Send a message to the user\n await context.sendActivity(`The bot encountered unhandled error: ${error.message}`);\n await context.sendActivity(\"To continue to run this bot, please fix the bot source code.\");\n };\n\n return adapter;\n }\n\n /**\n * The request handler to integrate with web request.\n *\n * @param req - an Express or Restify style request object.\n * @param res - an Express or Restify style response object.\n * @param logic - the additional function to handle bot context.\n *\n * @example\n * For example, to use with Restify:\n * ``` typescript\n * // The default/empty behavior\n * server.post(\"api/messages\", conversationBot.requestHandler);\n *\n * // Or, add your own logic\n * server.post(\"api/messages\", async (req, res) => {\n * await conversationBot.requestHandler(req, res, async (context) => {\n * // your-own-context-logic\n * });\n * });\n * ```\n */\n public async requestHandler(\n req: WebRequest,\n res: WebResponse,\n logic?: (context: TurnContext) => Promise<any>\n ): Promise<void> {\n if (logic === undefined) {\n // create empty logic\n logic = async () => {};\n }\n\n await this.adapter.processActivity(req, res, logic);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n Activity,\n Attachment,\n CardAction,\n CardFactory,\n CardImage,\n HeroCard,\n O365ConnectorCard,\n ReceiptCard,\n ThumbnailCard,\n} from \"botbuilder\";\nimport { AdaptiveCards } from \"@microsoft/adaptivecards-tools\";\n\n/**\n * Provides utility method to build bot message with cards that supported in Teams.\n */\nexport class MessageBuilder {\n /**\n * Build a bot message activity attached with adaptive card.\n *\n * @param cardTemplate The adaptive card template.\n * @param data card data used to render the template.\n * @returns A bot message activity attached with an adaptive card.\n *\n * @example\n * ```javascript\n * const cardTemplate = {\n * type: \"AdaptiveCard\",\n * body: [\n * {\n * \"type\": \"TextBlock\",\n * \"text\": \"${title}\",\n * \"size\": \"Large\"\n * },\n * {\n * \"type\": \"TextBlock\",\n * \"text\": \"${description}\"\n * }],\n * $schema: \"http://adaptivecards.io/schemas/adaptive-card.json\",\n * version: \"1.4\"\n * };\n *\n * type CardData = {\n * title: string,\n * description: string\n * };\n * const card = MessageBuilder.attachAdaptiveCard<CardData>(\n * cardTemplate, {\n * title: \"sample card title\",\n * description: \"sample card description\"\n * });\n * ```\n */\n public static attachAdaptiveCard<TData extends object>(\n cardTemplate: unknown,\n data: TData\n ): Partial<Activity> {\n return {\n attachments: [CardFactory.adaptiveCard(AdaptiveCards.declare(cardTemplate).render(data))],\n };\n }\n\n /**\n * Build a bot message activity attached with an adaptive card.\n *\n * @param card The adaptive card content.\n * @returns A bot message activity attached with an adaptive card.\n */\n public static attachAdaptiveCardWithoutData(card: unknown): Partial<Activity> {\n return {\n attachments: [CardFactory.adaptiveCard(AdaptiveCards.declareWithoutData(card).render())],\n };\n }\n\n /**\n * Build a bot message activity attached with an hero card.\n *\n * @param title The card title.\n * @param images Optional. The array of images to include on the card.\n * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array\n * is converted to an `imBack` button with a title and value set to the value of the string.\n * @param other Optional. Any additional properties to include on the card.\n *\n * @returns A bot message activity attached with a hero card.\n *\n * @example\n * ```javascript\n * const message = MessageBuilder.attachHeroCard(\n * 'sample title',\n * ['https://example.com/sample.jpg'],\n * ['action']\n * );\n * ```\n */\n public static attachHeroCard(\n title: string,\n images?: (CardImage | string)[],\n buttons?: (CardAction | string)[],\n other?: Partial<HeroCard>\n ): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.heroCard(title, images, buttons, other));\n }\n\n /**\n * Returns an attachment for a sign-in card.\n *\n * @param title The title for the card's sign-in button.\n * @param url The URL of the sign-in page to use.\n * @param text Optional. Additional text to include on the card.\n *\n * @returns A bot message activity attached with a sign-in card.\n *\n * @remarks\n * For channels that don't natively support sign-in cards, an alternative message is rendered.\n */\n public static attachSigninCard(title: string, url: string, text?: string): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.signinCard(title, url, text));\n }\n\n /**\n * Build a bot message activity attached with an Office 365 connector card.\n *\n * @param card A description of the Office 365 connector card.\n * @returns A bot message activity attached with an Office 365 connector card.\n */\n public static attachO365ConnectorCard(card: O365ConnectorCard): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.o365ConnectorCard(card));\n }\n\n /**\n * Build a message activity attached with a receipt card.\n * @param card A description of the receipt card.\n * @returns A message activity attached with a receipt card.\n */\n public static AttachReceiptCard(card: ReceiptCard): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.receiptCard(card));\n }\n\n /**\n *\n * @param title The card title.\n * @param images Optional. The array of images to include on the card.\n * @param buttons Optional. The array of buttons to include on the card. Each `string` in the array\n * is converted to an `imBack` button with a title and value set to the value of the string.\n * @param other Optional. Any additional properties to include on the card.\n * @returns A message activity attached with a thumbnail card\n */\n public static attachThumbnailCard(\n title: string,\n images?: (CardImage | string)[],\n buttons?: (CardAction | string)[],\n other?: Partial<ThumbnailCard>\n ): Partial<Activity> {\n return MessageBuilder.attachContent(CardFactory.thumbnailCard(title, images, buttons, other));\n }\n\n /**\n * Add an attachement to a bot activity.\n * @param attachement The attachment object to attach.\n * @returns A message activity with an attachment.\n */\n public static attachContent(attachement: Attachment): Partial<Activity> {\n return {\n attachments: [attachement],\n };\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken } from \"@azure/identity\";\nimport { TurnContext, MessagingExtensionResponse, ActivityTypes } from \"botbuilder\";\nimport { parseJwt, getScopesArray, formatString } from \"../util/utils\";\nimport { MessageExtensionTokenResponse } from \"./teamsMsgExtTokenResponse\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport {\n AuthenticationConfiguration,\n OnBehalfOfCredentialAuthConfig,\n} from \"../models/configuration\";\nimport { IdentityType } from \"../models/identityType\";\nimport { internalLogger } from \"../util/logger\";\nimport { TeamsFx } from \"../core/teamsfx\";\nimport { OnBehalfOfUserCredential } from \"../credential/onBehalfOfUserCredential\";\n/**\n * Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions.\n * This method only work on MessageExtension with Query now.\n *\n * @param {OnBehalfOfCredentialAuthConfig} authConfig - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @returns SignIn link SilentAuth CardAction with 200 status code.\n */\nfunction getSignInResponseForMessageExtensionWithSilentAuthConfig(\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[]\n): any {\n const scopesArray = getScopesArray(scopes);\n const signInLink = `${initiateLoginEndpoint}?scope=${encodeURI(scopesArray.join(\" \"))}&clientId=${\n authConfig.clientId\n }&tenantId=${authConfig.tenantId}`;\n return {\n composeExtension: {\n type: \"silentAuth\",\n suggestedActions: {\n actions: [\n {\n type: \"openUrl\",\n value: signInLink,\n title: \"Message Extension OAuth\",\n },\n ],\n },\n },\n };\n}\n\n/**\n * Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions.\n * This method just a workaround for link unfurling now.\n *\n * @param {OnBehalfOfCredentialAuthConfig} authConfig - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @returns SignIn link Auth CardAction with 200 status code.\n */\nfunction getSignInResponseForMessageExtensionWithAuthConfig(\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[]\n): any {\n const scopesArray = getScopesArray(scopes);\n const signInLink = `${initiateLoginEndpoint}?scope=${encodeURI(scopesArray.join(\" \"))}&clientId=${\n authConfig.clientId\n }&tenantId=${authConfig.tenantId}`;\n return {\n composeExtension: {\n type: \"auth\",\n suggestedActions: {\n actions: [\n {\n type: \"openUrl\",\n value: signInLink,\n title: \"Message Extension OAuth\",\n },\n ],\n },\n },\n };\n}\n\n/**\n * Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions.\n * This method only work on MessageExtension with Query now.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth.\n * @param {string | string[]} scopes - The list of scopes for which the token will have access.\n *\n * @returns SignIn link CardAction with 200 status code.\n */\nfunction getSignInResponseForMessageExtension(teamsfx: TeamsFx, scopes: string | string[]): any {\n const scopesArray = getScopesArray(scopes);\n const signInLink = `${teamsfx.getConfig(\"initiateLoginEndpoint\")}?scope=${encodeURI(\n scopesArray.join(\" \")\n )}&clientId=${teamsfx.getConfig(\"clientId\")}&tenantId=${teamsfx.getConfig(\"tenantId\")}`;\n return {\n composeExtension: {\n type: \"silentAuth\",\n suggestedActions: {\n actions: [\n {\n type: \"openUrl\",\n value: signInLink,\n title: \"Message Extension OAuth\",\n },\n ],\n },\n },\n };\n}\n\n/**\n * execution in message extension with SSO token.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {OnBehalfOfCredentialAuthConfig} authConfig - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function executionWithTokenAndConfig(\n context: TurnContext,\n authConfig: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[],\n logic?: (token: MessageExtensionTokenResponse) => Promise<any>\n): Promise<MessagingExtensionResponse | void> {\n const valueObj = context.activity.value;\n if (!valueObj.authentication || !valueObj.authentication.token) {\n internalLogger.verbose(\"No AccessToken in request, return silentAuth for AccessToken\");\n return getSignInResponseForMessageExtensionWithSilentAuthConfig(\n authConfig,\n initiateLoginEndpoint,\n scopes\n );\n }\n try {\n const credential = new OnBehalfOfUserCredential(valueObj.authentication.token, authConfig);\n const token: AccessToken | null = await credential.getToken(scopes);\n const ssoTokenExpiration: number = parseJwt(valueObj.authentication.token).exp;\n const tokenRes: MessageExtensionTokenResponse = {\n ssoToken: valueObj.authentication.token,\n ssoTokenExpiration: new Date(ssoTokenExpiration * 1000).toISOString(),\n token: token!.token,\n expiration: token!.expiresOnTimestamp.toString(),\n connectionName: \"\",\n };\n if (logic) {\n return await logic(tokenRes);\n }\n } catch (err) {\n if (\n err instanceof ErrorWithCode &&\n err.code === ErrorCode.UiRequiredError &&\n context.activity.name === \"composeExtension/query\"\n ) {\n internalLogger.verbose(\"User not consent yet, return 412 to user consent first.\");\n const response = { status: 412 };\n await context.sendActivity({ value: response, type: ActivityTypes.InvokeResponse });\n return;\n } else if (\n err instanceof ErrorWithCode &&\n err.code === ErrorCode.UiRequiredError &&\n context.activity.name === \"composeExtension/queryLink\"\n ) {\n internalLogger.verbose(\"User not consent yet, return auth card for user login\");\n const response = getSignInResponseForMessageExtensionWithAuthConfig(\n authConfig,\n initiateLoginEndpoint,\n scopes\n );\n await context.sendActivity({\n value: { status: 200, body: response },\n type: ActivityTypes.InvokeResponse,\n });\n return;\n }\n throw err;\n }\n}\n\n/**\n * execution in message extension with SSO token.\n * @deprecated Use {@link executionWithTokenAndConfig} instead.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {AuthenticationConfiguration} config - User custom the message extension authentication configuration.\n * @param {string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function executionWithToken(\n context: TurnContext,\n config: AuthenticationConfiguration,\n scopes: string | string[],\n logic?: (token: MessageExtensionTokenResponse) => Promise<any>\n): Promise<MessagingExtensionResponse | void> {\n const valueObj = context.activity.value;\n if (!valueObj.authentication || !valueObj.authentication.token) {\n internalLogger.verbose(\"No AccessToken in request, return silentAuth for AccessToken\");\n return getSignInResponseForMessageExtension(new TeamsFx(IdentityType.User, config), scopes);\n }\n try {\n const teamsfx = new TeamsFx(IdentityType.User, config).setSsoToken(\n valueObj.authentication.token\n );\n const token: AccessToken | null = await teamsfx.getCredential().getToken(scopes);\n const ssoTokenExpiration: number = parseJwt(valueObj.authentication.token).exp;\n const tokenRes: MessageExtensionTokenResponse = {\n ssoToken: valueObj.authentication.token,\n ssoTokenExpiration: new Date(ssoTokenExpiration * 1000).toISOString(),\n token: token!.token,\n expiration: token!.expiresOnTimestamp.toString(),\n connectionName: \"\",\n };\n if (logic) {\n return await logic(tokenRes);\n }\n } catch (err) {\n if (err instanceof ErrorWithCode && err.code === ErrorCode.UiRequiredError) {\n internalLogger.verbose(\"User not consent yet, return 412 to user consent first.\");\n const response = { status: 412 };\n await context.sendActivity({ value: response, type: ActivityTypes.InvokeResponse });\n return;\n }\n throw err;\n }\n}\n\n// eslint-disable-next-line no-secrets/no-secrets\n/**\n * Users execute query in message extension with SSO or access token.\n * @deprecated Use {@link handleMessageExtensionQueryWithSSO} instead.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {AuthenticationConfiguration} config - User custom the message extension authentication configuration.\n * @param {string| string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when User invoke not response to message extension query.\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function handleMessageExtensionQueryWithToken(\n context: TurnContext,\n config: AuthenticationConfiguration | null,\n scopes: string | string[],\n logic: (token: MessageExtensionTokenResponse) => Promise<any>\n): Promise<MessagingExtensionResponse | void> {\n if (context.activity.name != \"composeExtension/query\") {\n internalLogger.error(ErrorMessage.OnlySupportInQueryActivity);\n throw new ErrorWithCode(\n formatString(ErrorMessage.OnlySupportInQueryActivity),\n ErrorCode.FailedOperation\n );\n }\n return await executionWithToken(context, config ?? {}, scopes, logic);\n}\n\n/**\n * Users execute query in message extension with SSO or access token.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {OnBehalfOfCredentialAuthConfig} config - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string| string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when User invoke not response to message extension query.\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function handleMessageExtensionQueryWithSSO(\n context: TurnContext,\n config: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[],\n logic: (token: MessageExtensionTokenResponse) => Promise<any>\n) {\n if (context.activity.name != \"composeExtension/query\") {\n internalLogger.error(ErrorMessage.OnlySupportInQueryActivity);\n throw new ErrorWithCode(\n formatString(ErrorMessage.OnlySupportInQueryActivity),\n ErrorCode.FailedOperation\n );\n }\n return await executionWithTokenAndConfig(\n context,\n config ?? {},\n initiateLoginEndpoint,\n scopes,\n logic\n );\n}\n\n/**\n * Users execute link query in message extension with SSO or access token.\n *\n * @param {TurnContext} context - The context object for the current turn.\n * @param {OnBehalfOfCredentialAuthConfig} config - User custom the message extension authentication configuration.\n * @param {initiateLoginEndpoint} initiateLoginEndpoint - Login page for Teams to redirect to.\n * @param {string| string[]} scopes - The list of scopes for which the token will have access.\n * @param {function} logic - Business logic when executing the link query in message extension with SSO or access token.\n *\n * @throws {@link ErrorCode|InternalError} when User invoke not response to message extension link query.\n * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.\n * @throws {@link ErrorCode|TokenExpiredError} when SSO token has already expired.\n * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.\n * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns A MessageExtension Response for the activity. If the logic not return any, return void instead.\n */\nexport async function handleMessageExtensionLinkQueryWithSSO(\n context: TurnContext,\n config: OnBehalfOfCredentialAuthConfig,\n initiateLoginEndpoint: string,\n scopes: string | string[],\n logic: (token: MessageExtensionTokenResponse) => Promise<any>\n) {\n if (context.activity.name != \"composeExtension/queryLink\") {\n internalLogger.error(ErrorMessage.OnlySupportInLinkQueryActivity);\n throw new ErrorWithCode(\n formatString(ErrorMessage.OnlySupportInLinkQueryActivity),\n ErrorCode.FailedOperation\n );\n }\n return await executionWithTokenAndConfig(\n context,\n config ?? {},\n initiateLoginEndpoint,\n scopes,\n logic\n );\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { CloudAdapter } from \"botbuilder\";\nimport { CardActionMiddleware } from \"../conversation/middlewares/cardActionMiddleware\";\nimport { CardActionOptions, TeamsFxAdaptiveCardActionHandler } from \"../conversation/interface\";\n\n/**\n * A card action bot to respond to adaptive card universal actions.\n */\nexport class CardActionBot {\n private readonly adapter: CloudAdapter;\n private middleware: CardActionMiddleware;\n\n /**\n * Create a new instance of the `CardActionBot`.\n *\n * @param adapter - The bound `CloudAdapter`.\n * @param options - The initialize options.\n */\n constructor(adapter: CloudAdapter, options?: CardActionOptions) {\n this.middleware = new CardActionMiddleware(options?.actions);\n this.adapter = adapter.use(this.middleware);\n }\n\n /**\n * Register a card action handler to the bot.\n *\n * @param actionHandler - A card action handler to be registered.\n */\n registerHandler(actionHandler: TeamsFxAdaptiveCardActionHandler) {\n if (actionHandler) {\n this.middleware.actionHandlers.push(actionHandler);\n }\n }\n\n /**\n * Register card action handlers to the bot.\n *\n * @param actionHandlers - A set of card action handlers to be registered.\n */\n registerHandlers(actionHandlers: TeamsFxAdaptiveCardActionHandler[]) {\n if (actionHandlers) {\n this.middleware.actionHandlers.push(...actionHandlers);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CloudAdapter } from \"botbuilder\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\nimport { internalLogger } from \"../util/logger\";\nimport {\n CommandOptions,\n BotSsoConfig,\n BotSsoExecutionActivityHandler,\n TeamsFxBotCommandHandler,\n TeamsFxBotSsoCommandHandler,\n} from \"../conversation/interface\";\nimport { CommandResponseMiddleware } from \"../conversation/middlewares/commandMiddleware\";\n\n/**\n * A command bot for receiving commands and sending responses in Teams.\n *\n * @remarks\n * Ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.\n */\nexport class CommandBot {\n private readonly adapter: CloudAdapter;\n private readonly middleware: CommandResponseMiddleware;\n private readonly ssoConfig: BotSsoConfig | undefined;\n\n // eslint-disable-next-line no-secrets/no-secrets\n /**\n * Create a new instance of the `CommandBot`.\n *\n * @param adapter - The bound `CloudAdapter`.\n * @param options - The initialize options\n * @param ssoCommandActivityHandler - SSO execution activity handler.\n * @param ssoConfig - SSO configuration for Bot SSO.\n */\n constructor(\n adapter: CloudAdapter,\n options?: CommandOptions,\n ssoCommandActivityHandler?: BotSsoExecutionActivityHandler,\n ssoConfig?: BotSsoConfig\n ) {\n this.ssoConfig = ssoConfig;\n\n this.middleware = new CommandResponseMiddleware(\n options?.commands,\n options?.ssoCommands,\n ssoCommandActivityHandler\n );\n this.adapter = adapter.use(this.middleware);\n }\n\n /**\n * Register a command into the command bot.\n *\n * @param command - The command to be registered.\n */\n public registerCommand(command: TeamsFxBotCommandHandler): void {\n if (command) {\n this.middleware.commandHandlers.push(command);\n }\n }\n\n /**\n * Register commands into the command bot.\n *\n * @param commands - The commands to be registered.\n */\n public registerCommands(commands: TeamsFxBotCommandHandler[]): void {\n if (commands) {\n this.middleware.commandHandlers.push(...commands);\n }\n }\n\n /**\n * Register a sso command into the command bot.\n *\n * @param ssoCommand - The sso command to be registered.\n */\n public registerSsoCommand(ssoCommand: TeamsFxBotSsoCommandHandler): void {\n this.validateSsoActivityHandler();\n this.middleware.addSsoCommand(ssoCommand);\n }\n\n /**\n * Register sso commands into the command bot.\n *\n * @param ssoCommands - The sso commands to be registered.\n */\n public registerSsoCommands(ssoCommands: TeamsFxBotSsoCommandHandler[]): void {\n if (ssoCommands.length > 0) {\n this.validateSsoActivityHandler();\n for (const ssoCommand of ssoCommands) {\n this.middleware.addSsoCommand(ssoCommand);\n }\n }\n }\n\n private validateSsoActivityHandler() {\n if (!this.middleware.ssoActivityHandler) {\n internalLogger.error(ErrorMessage.SsoActivityHandlerIsNull);\n throw new ErrorWithCode(\n ErrorMessage.SsoActivityHandlerIsNull,\n ErrorCode.SsoActivityHandlerIsUndefined\n );\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n CloudAdapter,\n CardFactory,\n ChannelInfo,\n ConversationParameters,\n ConversationReference,\n TeamDetails,\n TeamsChannelAccount,\n TeamsInfo,\n TurnContext,\n} from \"botbuilder\";\nimport type { ConnectorClient } from \"botframework-connector\";\nimport * as path from \"path\";\nimport {\n NotificationTarget,\n NotificationTargetType,\n MessageResponse,\n ConversationReferenceStore,\n PagedData,\n} from \"../conversation/interface\";\nimport { NotificationOptions } from \"./interface\";\nimport { NotificationMiddleware } from \"../conversation/middlewares/notificationMiddleware\";\nimport { DefaultConversationReferenceStore, LocalFileStorage } from \"../conversation/storage\";\nimport * as utils from \"../conversation/utils\";\n\n/**\n * Send a plain text message to a notification target.\n *\n * @param target - The notification target.\n * @param text - The plain text message.\n * @param onError - An optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending message.\n */\nexport function sendMessage(\n target: NotificationTarget,\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n): Promise<MessageResponse> {\n return target.sendMessage(text, onError);\n}\n\n/**\n * Send an adaptive card message to a notification target.\n *\n * @param target - The notification target.\n * @param card - The adaptive card raw JSON.\n * @param onError - An optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending adaptive card message.\n */\nexport function sendAdaptiveCard(\n target: NotificationTarget,\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n): Promise<MessageResponse> {\n return target.sendAdaptiveCard(card, onError);\n}\n\n/**\n * A {@link NotificationTarget} that represents a team channel.\n *\n * @remarks\n * It's recommended to get channels from {@link TeamsBotInstallation.channels()}.\n */\nexport class Channel implements NotificationTarget {\n /**\n * The parent {@link TeamsBotInstallation} where this channel is created from.\n */\n public readonly parent: TeamsBotInstallation;\n\n /**\n * Detailed channel information.\n */\n public readonly info: ChannelInfo;\n\n /**\n * Notification target type. For channel it's always \"Channel\".\n */\n public readonly type: NotificationTargetType = NotificationTargetType.Channel;\n\n /**\n * Constructor.\n *\n * @remarks\n * It's recommended to get channels from {@link TeamsBotInstallation.channels()}, instead of using this constructor.\n *\n * @param parent - The parent {@link TeamsBotInstallation} where this channel is created from.\n * @param info - Detailed channel information.\n */\n constructor(parent: TeamsBotInstallation, info: ChannelInfo) {\n this.parent = parent;\n this.info = info;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - The plain text message.\n * @param onError - An optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n conversation,\n async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - The adaptive card raw JSON.\n * @param onError - An optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n conversation,\n async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n }\n );\n return response;\n }\n\n /**\n * @internal\n */\n private newConversation(context: TurnContext): Promise<ConversationReference> {\n const reference = TurnContext.getConversationReference(context.activity);\n const channelConversation = utils.cloneConversation(reference);\n channelConversation.conversation.id = this.info.id || \"\";\n\n return Promise.resolve(channelConversation);\n }\n}\n\n/**\n * A {@link NotificationTarget} that represents a team member.\n *\n * @remarks\n * It's recommended to get members from {@link TeamsBotInstallation.members()}.\n */\nexport class Member implements NotificationTarget {\n /**\n * The parent {@link TeamsBotInstallation} where this member is created from.\n */\n public readonly parent: TeamsBotInstallation;\n\n /**\n * Detailed member account information.\n */\n public readonly account: TeamsChannelAccount;\n\n /**\n * Notification target type. For member it's always \"Person\".\n */\n public readonly type: NotificationTargetType = NotificationTargetType.Person;\n\n /**\n * Constructor.\n *\n * @remarks\n * It's recommended to get members from {@link TeamsBotInstallation.members()}, instead of using this constructor.\n *\n * @param parent - The parent {@link TeamsBotInstallation} where this member is created from.\n * @param account - Detailed member account information.\n */\n constructor(parent: TeamsBotInstallation, account: TeamsChannelAccount) {\n this.parent = parent;\n this.account = account;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - The plain text message.\n * @param onError - An optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n conversation,\n async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - The adaptive card raw JSON.\n * @param onError - An optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n this.parent.conversationReference,\n async (context) => {\n const conversation = await this.newConversation(context);\n await this.parent.adapter.continueConversationAsync(\n this.parent.botAppId,\n conversation,\n async (ctx: TurnContext) => {\n try {\n const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(ctx, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n }\n );\n return response;\n }\n\n /**\n * @internal\n */\n private async newConversation(context: TurnContext): Promise<ConversationReference> {\n const reference = TurnContext.getConversationReference(context.activity);\n const personalConversation = utils.cloneConversation(reference);\n\n const connectorClient: ConnectorClient = context.turnState.get(\n this.parent.adapter.ConnectorClientKey\n );\n const conversation = await connectorClient.conversations.createConversation({\n isGroup: false,\n tenantId: context.activity.conversation.tenantId,\n bot: context.activity.recipient,\n members: [this.account],\n channelData: {},\n } as ConversationParameters);\n personalConversation.conversation.id = conversation.id;\n\n return personalConversation;\n }\n}\n\n/**\n * A {@link NotificationTarget} that represents a bot installation. Teams Bot could be installed into\n * - Personal chat\n * - Group chat\n * - Team (by default the `General` channel)\n *\n * @remarks\n * It's recommended to get bot installations from {@link ConversationBot.installations()}.\n */\nexport class TeamsBotInstallation implements NotificationTarget {\n /**\n * The bound `CloudAdapter`.\n */\n public readonly adapter: CloudAdapter;\n\n /**\n * The bound `ConversationReference`.\n */\n public readonly conversationReference: Partial<ConversationReference>;\n\n /**\n * The bot app id.\n */\n public readonly botAppId: string;\n /**\n * Notification target type.\n *\n * @remarks\n * - \"Channel\" means bot is installed into a team and notification will be sent to its \"General\" channel.\n * - \"Group\" means bot is installed into a group chat.\n * - \"Person\" means bot is installed into a personal scope and notification will be sent to personal chat.\n */\n public readonly type?: NotificationTargetType;\n\n /**\n * Constructor\n *\n * @remarks\n * It's recommended to get bot installations from {@link ConversationBot.installations()}, instead of using this constructor.\n *\n * @param adapter - The bound `CloudAdapter`.\n * @param conversationReference - The bound `ConversationReference`.\n * @param botAppId - The bot app id.\n */\n constructor(\n adapter: CloudAdapter,\n conversationReference: Partial<ConversationReference>,\n botAppId: string\n ) {\n this.adapter = adapter;\n this.conversationReference = conversationReference;\n this.type = utils.getTargetType(conversationReference);\n this.botAppId = botAppId;\n }\n\n /**\n * Send a plain text message.\n *\n * @param text - The plain text message.\n * @param onError - An optional error handler that can catch exceptions during message sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending message.\n */\n public async sendMessage(\n text: string,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n try {\n const res = await context.sendActivity(text);\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(context, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - The adaptive card raw JSON.\n * @param onError - An optional error handler that can catch exceptions during adaptive card sending.\n * If not defined, error will be handled by `BotAdapter.onTurnError`.\n *\n * @returns The response of sending adaptive card message.\n */\n public async sendAdaptiveCard(\n card: unknown,\n onError?: (context: TurnContext, error: Error) => Promise<void>\n ): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n try {\n const res = await context.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\n } catch (error) {\n if (onError) {\n await onError(context, error as Error);\n } else {\n throw error;\n }\n }\n }\n );\n return response;\n }\n\n /**\n * Get channels from this bot installation.\n *\n * @returns An array of channels if bot is installed into a team, otherwise returns an empty array.\n */\n public async channels(): Promise<Channel[]> {\n const channels: Channel[] = [];\n if (this.type !== NotificationTargetType.Channel) {\n return channels;\n }\n\n let teamsChannels: ChannelInfo[] = [];\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n const teamId = utils.getTeamsBotInstallationId(context);\n if (teamId !== undefined) {\n teamsChannels = await TeamsInfo.getTeamChannels(context, teamId);\n }\n }\n );\n\n for (const channel of teamsChannels) {\n channels.push(new Channel(this, channel));\n }\n\n return channels;\n }\n\n /**\n * Gets a pagined list of members from this bot installation.\n *\n * @param pageSize - Suggested number of entries on a page.\n * @param continuationToken - A continuation token.\n * @returns An array of members from where the bot is installed.\n */\n public async getPagedMembers(\n pageSize?: number,\n continuationToken?: string\n ): Promise<PagedData<Member>> {\n let result: PagedData<Member> = {\n data: [],\n continuationToken: \"\",\n };\n\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n const pagedMembers = await TeamsInfo.getPagedMembers(context, pageSize, continuationToken);\n\n result = {\n data: pagedMembers.members.map((m) => new Member(this, m)),\n continuationToken: pagedMembers.continuationToken,\n };\n }\n );\n\n return result;\n }\n\n /**\n * Get members from this bot installation.\n *\n * @returns An array of members from where the bot is installed.\n *\n * @deprecated Use `getPagedMembers` instead.\n */\n public async members(): Promise<Member[]> {\n const members: Member[] = [];\n\n let continuationToken: string | undefined;\n do {\n const pagedData = await this.getPagedMembers(undefined, continuationToken);\n continuationToken = pagedData.continuationToken;\n members.push(...pagedData.data);\n } while (continuationToken);\n\n return members;\n }\n\n /**\n * Get team details from this bot installation\n *\n * @returns The team details if bot is installed into a team, otherwise returns `undefined`.\n */\n public async getTeamDetails(): Promise<TeamDetails | undefined> {\n if (this.type !== NotificationTargetType.Channel) {\n return undefined;\n }\n\n let teamDetails: TeamDetails | undefined;\n await this.adapter.continueConversationAsync(\n this.botAppId,\n this.conversationReference,\n async (context) => {\n const teamId = utils.getTeamsBotInstallationId(context);\n if (teamId !== undefined) {\n teamDetails = await TeamsInfo.getTeamDetails(context, teamId);\n }\n }\n );\n\n return teamDetails;\n }\n}\n\n/**\n * Provide utilities to send notification to varies targets (e.g., member, group, channel).\n */\nexport class NotificationBot {\n private readonly conversationReferenceStore: ConversationReferenceStore;\n private readonly adapter: CloudAdapter;\n private readonly botAppId: string;\n\n /**\n * Constructor of the notification bot.\n *\n * @remarks\n * To ensure accuracy, it's recommended to initialize before handling any message.\n *\n * @param adapter - The bound `CloudAdapter`\n * @param options - The initialize options\n */\n public constructor(adapter: CloudAdapter, options?: NotificationOptions) {\n if (options?.store) {\n this.conversationReferenceStore = options.store;\n } else {\n const storage =\n options?.storage ??\n new LocalFileStorage(\n path.resolve(process.env.RUNNING_ON_AZURE === \"1\" ? process.env.TEMP ?? \"./\" : \"./\")\n );\n\n this.conversationReferenceStore = new DefaultConversationReferenceStore(storage);\n }\n\n this.adapter = adapter.use(\n new NotificationMiddleware({\n conversationReferenceStore: this.conversationReferenceStore,\n })\n );\n this.botAppId = (options?.botAppId ?? process.env.BOT_ID) as string;\n }\n\n /**\n * Create a {@link TeamsBotInstallation} instance with conversation reference.\n *\n * @param conversationReference - The bound `ConversationReference`.\n * @returns - The {@link TeamsBotInstallation} instance or null.\n */\n public buildTeamsBotInstallation(\n conversationReference: Partial<ConversationReference>\n ): TeamsBotInstallation | null {\n if (!conversationReference) {\n throw new Error(\"conversationReference is required.\");\n }\n\n return new TeamsBotInstallation(this.adapter, conversationReference, this.botAppId);\n }\n\n /**\n * Validate the installation by getting paged memebers.\n *\n * @param conversationReference The bound `ConversationReference`.\n * @returns Returns false if recieves `BotNotInConversationRoster` error, otherwise returns true.\n */\n public async validateInstallation(\n conversationReference: Partial<ConversationReference>\n ): Promise<boolean> {\n let isValid = true;\n await this.adapter.continueConversationAsync(\n this.botAppId,\n conversationReference,\n async (context) => {\n try {\n // try get member to see if the installation is still valid\n await TeamsInfo.getPagedMembers(context, 1);\n } catch (error: any) {\n if ((error.code as string) === \"BotNotInConversationRoster\") {\n isValid = false;\n }\n }\n }\n );\n return isValid;\n }\n\n /**\n * Gets a pagined list of targets where the bot is installed.\n *\n * @remarks\n * The result is retrieving from the persisted storage.\n *\n * @param pageSize - Suggested number of entries on a page.\n * @param continuationToken - A continuation token.\n *\n * @returns An array of {@link TeamsBotInstallation} with paged data and continuation token.\n */\n public async getPagedInstallations(\n pageSize?: number,\n continuationToken?: string,\n validationEnabled = true\n ): Promise<PagedData<TeamsBotInstallation>> {\n if (this.conversationReferenceStore === undefined || this.adapter === undefined) {\n throw new Error(\"NotificationBot has not been initialized.\");\n }\n\n const references = await this.conversationReferenceStore.list(pageSize, continuationToken);\n const targets: TeamsBotInstallation[] = [];\n for (const reference of references.data) {\n // validate connection\n let valid;\n if (validationEnabled) {\n // try get member to see if the installation is still valid\n valid = await this.validateInstallation(reference);\n }\n\n if (!validationEnabled || (validationEnabled && valid)) {\n targets.push(new TeamsBotInstallation(this.adapter, reference, this.botAppId));\n } else {\n await this.conversationReferenceStore.remove(utils.getKey(reference), reference);\n }\n }\n\n return {\n data: targets,\n continuationToken: references.continuationToken,\n };\n }\n\n /**\n * Get all targets where the bot is installed.\n *\n * @remarks\n * The result is retrieving from the persisted storage.\n *\n * @returns An array of {@link TeamsBotInstallation}.\n *\n * @deprecated Use getPagedInstallations instead.\n */\n public async installations(): Promise<TeamsBotInstallation[]> {\n let continuationToken: string | undefined;\n const targets: TeamsBotInstallation[] = [];\n do {\n const result = await this.getPagedInstallations(undefined, continuationToken);\n continuationToken = result.continuationToken;\n targets.push(...result.data);\n } while (continuationToken);\n\n return targets;\n }\n\n /**\n * Return the first {@link Member} where predicate is true, and undefined otherwise.\n *\n * @param predicate - Find calls predicate once for each member of the installation,\n * until it finds one where predicate returns true. If such a member is found, find\n * immediately returns that member. Otherwise, find returns undefined.\n * @param scope - The scope to find members from the installations\n * (personal chat, group chat, Teams channel).\n *\n * @returns The first {@link Member} where predicate is true, and `undefined` otherwise.\n */\n public async findMember(\n predicate: (member: Member) => Promise<boolean>,\n scope?: SearchScope\n ): Promise<Member | undefined> {\n for (const target of await this.installations()) {\n if (this.matchSearchScope(target, scope)) {\n for (const member of await target.members()) {\n if (await predicate(member)) {\n return member;\n }\n }\n }\n }\n\n return;\n }\n\n /**\n * Return the first {@link Channel} where predicate is true, and undefined otherwise.\n * (Ensure the bot app is installed into the `General` channel, otherwise undefined will be returned.)\n *\n * @param predicate - Find calls predicate once for each channel of the installation,\n * until it finds one where predicate returns true. If such a channel is found, find\n * immediately returns that channel. Otherwise, find returns `undefined`.\n *\n * @returns The first {@link Channel} where predicate is true, and `undefined` otherwise.\n */\n public async findChannel(\n predicate: (channel: Channel, teamDetails: TeamDetails | undefined) => Promise<boolean>\n ): Promise<Channel | undefined> {\n for (const target of await this.installations()) {\n if (target.type === NotificationTargetType.Channel) {\n const teamDetails = await target.getTeamDetails();\n for (const channel of await target.channels()) {\n if (await predicate(channel, teamDetails)) {\n return channel;\n }\n }\n }\n }\n\n return;\n }\n\n /**\n * Return all {@link Member} where predicate is true, and empty array otherwise.\n *\n * @param predicate - Find calls predicate for each member of the installation.\n * @param scope - The scope to find members from the installations\n * (personal chat, group chat, Teams channel).\n *\n * @returns An array of {@link Member} where predicate is true, and empty array otherwise.\n */\n public async findAllMembers(\n predicate: (member: Member) => Promise<boolean>,\n scope?: SearchScope\n ): Promise<Member[]> {\n const members: Member[] = [];\n for (const target of await this.installations()) {\n if (this.matchSearchScope(target, scope)) {\n for (const member of await target.members()) {\n if (await predicate(member)) {\n members.push(member);\n }\n }\n }\n }\n\n return members;\n }\n\n /**\n * Return all {@link Channel} where predicate is true, and empty array otherwise.\n * (Ensure the bot app is installed into the `General` channel, otherwise empty array will be returned.)\n *\n * @param predicate - Find calls predicate for each channel of the installation.\n *\n * @returns An array of {@link Channel} where predicate is true, and empty array otherwise.\n */\n public async findAllChannels(\n predicate: (channel: Channel, teamDetails: TeamDetails | undefined) => Promise<boolean>\n ): Promise<Channel[]> {\n const channels: Channel[] = [];\n for (const target of await this.installations()) {\n if (target.type === NotificationTargetType.Channel) {\n const teamDetails = await target.getTeamDetails();\n for (const channel of await target.channels()) {\n if (await predicate(channel, teamDetails)) {\n channels.push(channel);\n }\n }\n }\n }\n\n return channels;\n }\n\n private matchSearchScope(target: NotificationTarget, scope?: SearchScope): boolean {\n scope = scope ?? SearchScope.All;\n\n return (\n (target.type === NotificationTargetType.Channel && (scope & SearchScope.Channel) !== 0) ||\n (target.type === NotificationTargetType.Group && (scope & SearchScope.Group) !== 0) ||\n (target.type === NotificationTargetType.Person && (scope & SearchScope.Person) !== 0)\n );\n }\n}\n\n/**\n * The search scope when calling {@link NotificationBot.findMember} and {@link NotificationBot.findAllMembers}.\n * The search scope is a flagged enum and it can be combined with `|`.\n * For example, to search from personal chat and group chat, use `SearchScope.Person | SearchScope.Group`.\n */\nexport enum SearchScope {\n /**\n * Search members from the installations in personal chat only.\n */\n Person = 1,\n\n /**\n * Search members from the installations in group chat only.\n */\n Group = 2,\n\n /**\n * Search members from the installations in Teams channel only.\n */\n Channel = 4,\n\n /**\n * Search members from all installations including personal chat, group chat and Teams channel.\n */\n All = Person | Group | Channel,\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n CloudAdapter,\n ConfigurationServiceClientCredentialFactory,\n ConfigurationBotFrameworkAuthentication,\n TurnContext,\n Request,\n Response,\n} from \"botbuilder\";\nimport { CardActionBot } from \"./cardAction\";\nimport { CommandBot } from \"./command\";\nimport { BotSsoExecutionActivityHandler } from \"../conversation/interface\";\nimport { ConversationOptions } from \"./interface\";\nimport { NotificationBot } from \"./notification\";\nimport { DefaultBotSsoExecutionActivityHandler } from \"../conversation/sso/defaultBotSsoExecutionActivityHandler\";\n\n/**\n * Provide utilities for bot conversation, including:\n * - handle command and response.\n * - send notification to varies targets (e.g., member, group, channel).\n *\n * @example\n * For command and response, you can register your commands through the constructor, or use the `registerCommand` and `registerCommands` API to add commands later.\n *\n * ```typescript\n * import { BotBuilderCloudAdapter } from \"@microsoft/teamsfx\";\n * import ConversationBot = BotBuilderCloudAdapter.ConversationBot;\n *\n * // register through constructor\n * const conversationBot = new ConversationBot({\n * command: {\n * enabled: true,\n * commands: [ new HelloWorldCommandHandler() ],\n * },\n * });\n *\n * // register through `register*` API\n * conversationBot.command.registerCommand(new HelpCommandHandler());\n * ```\n *\n * For notification, you can enable notification at initialization, then send notifications at any time.\n *\n * ```typescript\n * import { BotBuilderCloudAdapter } from \"@microsoft/teamsfx\";\n * import ConversationBot = BotBuilderCloudAdapter.ConversationBot;\n *\n * // enable through constructor\n * const conversationBot = new ConversationBot({\n * notification: {\n * enabled: true,\n * },\n * });\n *\n * // get all bot installations and send message\n * for (const target of await conversationBot.notification.installations()) {\n * await target.sendMessage(\"Hello Notification\");\n * }\n *\n * // alternative - send message to all members\n * for (const target of await conversationBot.notification.installations()) {\n * for (const member of await target.members()) {\n * await member.sendMessage(\"Hello Notification\");\n * }\n * }\n * ```\n *\n * @remarks\n * Set `adapter` in {@link ConversationOptions} to use your own bot adapter.\n *\n * For command and response, ensure each command should ONLY be registered with the command once, otherwise it'll cause unexpected behavior if you register the same command more than once.\n *\n * For notification, set `notification.storage` in {@link ConversationOptions} to use your own storage implementation.\n */\nexport class ConversationBot {\n /**\n * The bot adapter.\n */\n public readonly adapter: CloudAdapter;\n\n /**\n * The entrypoint of command and response.\n */\n public readonly command?: CommandBot;\n\n /**\n * The entrypoint of notification.\n */\n public readonly notification?: NotificationBot;\n\n /**\n * The action handler used for adaptive card universal actions.\n */\n public readonly cardAction?: CardActionBot;\n\n /**\n * Create new instance of the `ConversationBot`.\n *\n * @remarks\n * It's recommended to create your own adapter and storage for production environment instead of the default one.\n *\n * @param options - The initialize options.\n */\n public constructor(options: ConversationOptions) {\n if (options.adapter) {\n this.adapter = options.adapter;\n } else {\n this.adapter = this.createDefaultAdapter(options.adapterConfig);\n }\n\n let ssoCommandActivityHandler: BotSsoExecutionActivityHandler | undefined;\n\n if (options?.ssoConfig) {\n if (options.ssoConfig.dialog?.CustomBotSsoExecutionActivityHandler) {\n ssoCommandActivityHandler =\n new options.ssoConfig.dialog.CustomBotSsoExecutionActivityHandler(options.ssoConfig);\n } else {\n ssoCommandActivityHandler = new DefaultBotSsoExecutionActivityHandler(options.ssoConfig);\n }\n }\n\n if (options.command?.enabled) {\n this.command = new CommandBot(\n this.adapter,\n options.command,\n ssoCommandActivityHandler,\n options.ssoConfig\n );\n }\n\n if (options.notification?.enabled) {\n this.notification = new NotificationBot(this.adapter, options.notification);\n }\n\n if (options.cardAction?.enabled) {\n this.cardAction = new CardActionBot(this.adapter, options.cardAction);\n }\n }\n\n private createDefaultAdapter(adapterConfig?: { [key: string]: unknown }): CloudAdapter {\n const credentialsFactory =\n adapterConfig === undefined\n ? new ConfigurationServiceClientCredentialFactory({\n MicrosoftAppId: process.env.BOT_ID,\n MicrosoftAppPassword: process.env.BOT_PASSWORD,\n MicrosoftAppType: \"MultiTenant\",\n })\n : new ConfigurationServiceClientCredentialFactory(adapterConfig);\n const botFrameworkAuthentication = new ConfigurationBotFrameworkAuthentication(\n {},\n credentialsFactory\n );\n const adapter = new CloudAdapter(botFrameworkAuthentication);\n\n // the default error handler\n adapter.onTurnError = async (context, error) => {\n // This check writes out errors to console.\n console.error(`[onTurnError] unhandled error`, error);\n\n // Only send error message for user messages, not for other message types so the bot doesn't spam a channel or chat.\n if (context.activity.type === \"message\") {\n // Send a trace activity, which will be displayed in Bot Framework Emulator\n await context.sendTraceActivity(\n \"OnTurnError Trace\",\n error instanceof Error ? error.message : error,\n \"https://www.botframework.com/schemas/error\",\n \"TurnError\"\n );\n\n // Send a message to the user\n await context.sendActivity(`The bot encountered unhandled error: ${error.message}`);\n await context.sendActivity(\"To continue to run this bot, please fix the bot source code.\");\n }\n };\n\n return adapter;\n }\n\n /**\n * The request handler to integrate with web request.\n *\n * @param req - An incoming HTTP [Request](xref:botbuilder.Request).\n * @param res - The corresponding HTTP [Response](xref:botbuilder.Response).\n * @param logic - The additional function to handle bot context.\n *\n * @example\n * For example, to use with Restify:\n * ``` typescript\n * // The default/empty behavior\n * server.use(restify.plugins.bodyParser());\n * server.post(\"api/messages\", conversationBot.requestHandler);\n *\n * // Or, add your own logic\n * server.use(restify.plugins.bodyParser());\n * server.post(\"api/messages\", async (req, res) => {\n * await conversationBot.requestHandler(req, res, async (context) => {\n * // your-own-context-logic\n * });\n * });\n * ```\n */\n public async requestHandler(\n req: Request,\n res: Response,\n logic?: (context: TurnContext) => Promise<any>\n ): Promise<void> {\n if (logic === undefined) {\n // create empty logic\n logic = async () => {};\n }\n\n await this.adapter.process(req, res, logic);\n }\n}\n"],"names":["ErrorCode","LogLevel","jwt_decode","ConfidentialClientApplication","createHash","Client","ManagedIdentityCredential","IdentityType","Dialog","ActivityTypes","Channels","TeamsInfo","CardFactory","ActionTypes","MessageFactory","uuidv4","StatusCodes","verifyStateOperationName","tokenExchangeOperationName","axios","ApiKeyLocation","Agent","NotificationTargetType","AdaptiveCardResponse","InvokeResponseErrorCode","CardActionBot","TurnContext","CommandBot","path.resolve","fs.access","fs.readFile","fs.writeFile","sendMessage","sendAdaptiveCard","Channel","utils.cloneConversation","Member","TeamsBotInstallation","utils.getTargetType","utils.getTeamsBotInstallationId","NotificationBot","utils.getKey","SearchScope","ComponentDialog","WaterfallDialog","DialogSet","DialogTurnStatus","TeamsActivityHandler","MemoryStorage","UserState","ConversationState","ConversationBot","BotFrameworkAdapter","AdaptiveCards","ConfigurationServiceClientCredentialFactory","ConfigurationBotFrameworkAuthentication","CloudAdapter"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAEA;;;AAGYA;AAAZ,WAAY,SAAS;;;;IAInB,kDAAqC,CAAA;;;;IAKrC,0DAA6C,CAAA;;;;IAK7C,sDAAyC,CAAA;;;;IAKzC,4CAA+B,CAAA;;;;IAK/B,wDAA2C,CAAA;;;;IAK3C,kEAAqD,CAAA;;;;IAKrD,oEAAuD,CAAA;;;;IAKvD,oDAAuC,CAAA;;;;IAKvC,sDAAyC,CAAA;;;;IAKzC,0DAA6C,CAAA;;;;IAK7C,4EAA+D,CAAA;;;;IAK/D,wDAA2C,CAAA;;;;IAK3C,4CAA+B,CAAA;;;;IAK/B,gDAAmC,CAAA;;;;IAKnC,oDAAuC,CAAA;;;;IAKvC,0CAA6B,CAAA;;;;IAK7B,gDAAmC,CAAA;;;;IAKnC,gDAAmC,CAAA;;;;IAKnC,kEAAqD,CAAA;;;;IAKrD,8EAAiE,CAAA;AACnE,CAAC,EApGWA,iBAAS,KAATA,iBAAS,QAoGpB;AAED;;;MAGa,YAAY;;AACvB;AACgB,iCAAoB,GAAG,uCAAuC,CAAC;AAC/D,mCAAsB,GAAG,mCAAmC,CAAC;AAC7D,2CAA8B,GAAG,4CAA4C,CAAC;AAC9E,yCAA4B,GAC1C,2DAA2D,CAAC;AAC9C,iDAAoC,GAClD,8CAA8C,CAAC;AAEjD;AACgB,uCAA0B,GAAG,kCAAkC,CAAC;AAChE,sCAAyB,GAAG,+BAA+B,CAAC;AAE5E;AACgB,6CAAgC,GAC9C,uDAAuD,CAAC;AAE1D;AACgB,wCAA2B,GAAG,2CAA2C,CAAC;AAE1E,sCAAyB,GAAG,oCA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