@microsoft/teamsfx 1.1.2-alpha.efe3d972e.0 → 1.1.2-rc-hotfix.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.esm2017.js +3 -73
- package/dist/index.esm2017.js.map +1 -1
- package/dist/index.esm2017.mjs +102 -379
- package/dist/index.esm2017.mjs.map +1 -1
- package/dist/index.esm5.js +3 -73
- package/dist/index.esm5.js.map +1 -1
- package/dist/index.node.cjs.js +104 -387
- package/dist/index.node.cjs.js.map +1 -1
- package/package.json +3 -4
- package/types/teamsfx.d.ts +0 -201
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm2017.mjs","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/conversation.ts","../src/conversation/messageBuilder.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 * 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 // 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}\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 = jwt_decode(token) as SSOTokenInfoBase;\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;\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;\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","import { ConfidentialClientApplication, NodeAuthOptions } from \"@azure/msal-node\";\nimport { AuthenticationConfiguration } 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: AuthenticationConfiguration\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 { 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 {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 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;\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(config: AuthenticationConfiguration): AuthenticationConfiguration {\n internalLogger.verbose(\"Validate authentication configuration\");\n\n if (config.clientId && (config.clientSecret || config.certificateContent) && config.tenantId) {\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 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 { AuthenticationConfiguration } 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 {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 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;\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(\"AADSTS500133\") >= 0) {\n const fullErrorMsg =\n \"Failed to get access token from AAD server, sso token expired: \" + 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 { AuthenticationConfiguration } 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: 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 * @remarks\n * Can only be used within Teams.\n */\n public async login(scopes: string | string[]): Promise<void> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get access token from credential.\n * @remarks\n * Can only be used within Teams.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get basic user info from SSO token\n * @remarks\n * Can only be used within Teams.\n */\n public getUserInfo(): Promise<UserInfo> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\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\";\n\nconst defaultScope = \"https://graph.microsoft.com/.default\";\n\n/**\n * Microsoft Graph auth provider for Teams Framework\n */\nexport class MsGraphAuthProvider implements AuthenticationProvider {\n private teamsfx: TeamsFxConfiguration;\n private scopes: string | string[];\n\n /**\n * Constructor of MsGraphAuthProvider.\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 * @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 this.teamsfx = teamsfx;\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}'`);\n const accessToken = await this.teamsfx.getCredential().getToken(this.scopes);\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\";\n\n/**\n * Get Microsoft graph client.\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","// 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 * @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}`\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}`\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\";\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 /**\n * Constructor of TeamsBotSsoPrompt.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n * @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.\n * @param 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 private teamsfx: TeamsFx,\n dialogId: string,\n private settings: TeamsBotSsoPromptSettings\n ) {\n super(dialogId);\n validateScopesType(settings.scopes);\n this.loadAndValidateConfig();\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() {\n if (this.teamsfx.getIdentityType() !== IdentityType.User) {\n const errorMsg = formatString(\n ErrorMessage.IdentityTypeNotSupported,\n this.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 (!this.teamsfx.hasConfig(\"initiateLoginEndpoint\")) {\n missingConfigurations.push(\"initiateLoginEndpoint\");\n }\n\n if (!this.teamsfx.hasConfig(\"clientId\")) {\n missingConfigurations.push(\"clientId\");\n }\n\n if (!this.teamsfx.hasConfig(\"tenantId\")) {\n missingConfigurations.push(\"tenantId\");\n }\n\n if (!this.teamsfx.hasConfig(\"applicationIdUri\")) {\n missingConfigurations.push(\"applicationIdUri\");\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\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: \" + 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.teamsfx.getConfig(\"initiateLoginEndpoint\")}?scope=${encodeURI(\n this.settings.scopes.join(\" \")\n )}&clientId=${this.teamsfx.getConfig(\"clientId\")}&tenantId=${this.teamsfx.getConfig(\n \"tenantId\"\n )}&loginHint=${loginHint}`;\n\n internalLogger.verbose(\"Sign in link: \" + signInLink);\n\n const tokenExchangeResource: TokenExchangeResource = {\n id: uuidv4(),\n uri: this.teamsfx.getConfig(\"applicationIdUri\").replace(/\\/$/, \"\") + \"/access_as_user\",\n };\n\n internalLogger.verbose(\"Token exchange resource uri: \" + tokenExchangeResource.uri);\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 this.teamsfx.setSsoToken(ssoToken);\n const credential = this.teamsfx.getCredential();\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 } 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(config);\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 async AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n if (config.headers && config.headers[\"Authorization\"]) {\n throw new ErrorWithCode(\n ErrorMessage.AuthorizationHeaderAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n );\n }\n if (config.auth) {\n throw new ErrorWithCode(\n ErrorMessage.BasicCredentialAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n );\n }\n\n config.auth = {\n username: this.userName,\n password: this.password,\n };\n\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 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 async 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 throw new ErrorWithCode(\n formatString(ErrorMessage.DuplicateApiKeyInHeader, this.keyName),\n ErrorCode.AuthorizationInfoAlreadyExists\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 throw new ErrorWithCode(\n formatString(ErrorMessage.DuplicateApiKeyInQueryParam, this.keyName),\n ErrorCode.AuthorizationInfoAlreadyExists\n );\n }\n config.params[this.keyName] = this.keyValue;\n break;\n }\n\n return 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 async 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 throw new ErrorWithCode(\n formatString(ErrorMessage.DuplicateHttpsOptionProperty, property),\n ErrorCode.InvalidParameter\n );\n }\n }\n Object.assign(config.httpsAgent.options, this.certOption);\n }\n return 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\";\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 */\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(identityType?: IdentityType, customConfig?: Record<string, string>) {\n this.identityType = identityType ?? IdentityType.User;\n this.configuration = new Map<string, string>();\n this.loadFromEnv();\n if (customConfig) {\n for (const key of Object.keys(customConfig)) {\n const value = customConfig[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 * @returns UserInfo object.\n */\n public async getUserInfo(): 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 *\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[]): 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 { BotFrameworkAdapter } from \"botbuilder\";\nimport { Activity, InvokeResponse, TurnContext } from \"botbuilder-core\";\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 *\n * @returns the response of sending message.\n */\n sendMessage(text: string): Promise<MessageResponse>;\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n *\n * @returns the response of sending adaptive card message.\n */\n sendAdaptiveCard(card: unknown): Promise<MessageResponse>;\n}\n\n/**\n * Interface for a storage provider that stores and retrieves notification target references.\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 */\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 * 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 * 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/**\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 * @remark 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 * Options to initialize {@link ConversationBot}\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 * 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","import { IAdaptiveCard } from \"adaptivecards\";\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 {@link 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: IAdaptiveCard = {\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 {InvokeResponse} 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 {InvokeResponse} An InvokeResponse object.\n */\n public static adaptiveCard(card: IAdaptiveCard): 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 {InvokeResponse} 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 {InvokeResponse} 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 */\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 { CommandMessage, TeamsFxBotCommandHandler, TriggerPatterns } from \"../interface\";\n\n/**\n * @internal\n */\nexport class CommandResponseMiddleware implements Middleware {\n public readonly commandHandlers: TeamsFxBotCommandHandler[] = [];\n\n constructor(handlers?: TeamsFxBotCommandHandler[]) {\n if (handlers && handlers.length > 0) {\n this.commandHandlers.push(...handlers);\n }\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\n const message: CommandMessage = {\n text: commandText,\n };\n\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 message.matches = Array.isArray(matchResult) ? matchResult : void 0;\n const response = await handler.handleCommandReceived(context, message);\n\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 break;\n }\n }\n }\n\n await next();\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 as string, \"i\");\n return regExp.test(text);\n }\n\n if (pattern instanceof RegExp) {\n const matches = text.match(pattern as RegExp);\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 { CommandOptions, TeamsFxBotCommandHandler } 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 */\nexport class CommandBot {\n private readonly adapter: BotFrameworkAdapter;\n private readonly middleware: CommandResponseMiddleware;\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(adapter: BotFrameworkAdapter, options?: CommandOptions) {\n this.middleware = new CommandResponseMiddleware(options?.commands);\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 registered.\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 command to registered.\n */\n public registerCommands(commands: TeamsFxBotCommandHandler[]): void {\n if (commands) {\n this.middleware.commandHandlers.push(...commands);\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 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 return context.activity?.channelData?.team?.id ?? context.activity.conversation.id;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Activity, Middleware, TurnContext } from \"botbuilder\";\nimport { ConversationReferenceStore } from \"../storage\";\nimport { cloneConversation } from \"../utils\";\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.set(reference);\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.delete(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 if (!(await this.conversationReferenceStore.check(reference))) {\n await this.conversationReferenceStore.set(reference);\n }\n } else if (conversationType === \"channel\") {\n const teamId = context.activity?.channelData?.team?.id;\n if (teamId !== undefined) {\n const teamReference = cloneConversation(reference);\n teamReference.conversation.id = teamId;\n if (!(await this.conversationReferenceStore.check(teamReference))) {\n await this.conversationReferenceStore.set(teamReference);\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 { NotificationTargetStorage } from \"./interface\";\n\n/**\n * @internal\n */\nexport class LocalFileStorage implements NotificationTargetStorage {\n private readonly localFileName = \".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 ConversationReferenceStore {\n private readonly storage: NotificationTargetStorage;\n\n constructor(storage: NotificationTargetStorage) {\n this.storage = storage;\n }\n\n async check(reference: Partial<ConversationReference>): Promise<boolean> {\n const ref = await this.storage.read(this.getKey(reference));\n return ref !== undefined;\n }\n\n getAll(): Promise<Partial<ConversationReference>[]> {\n return this.storage.list();\n }\n\n set(reference: Partial<ConversationReference>): Promise<void> {\n return this.storage.write(this.getKey(reference), reference);\n }\n\n delete(reference: Partial<ConversationReference>): Promise<void> {\n return this.storage.delete(this.getKey(reference));\n }\n\n private getKey(reference: Partial<ConversationReference>): string {\n return `_${reference.conversation?.tenantId}_${reference.conversation?.id}`;\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 TeamsChannelAccount,\n TeamsInfo,\n TurnContext,\n} from \"botbuilder\";\nimport { 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 { ConversationReferenceStore, 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 * @returns the response of sending message.\n */\nexport function sendMessage(target: NotificationTarget, text: string): Promise<MessageResponse> {\n return target.sendMessage(text);\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 * @returns the response of sending adaptive card message.\n */\nexport function sendAdaptiveCard(\n target: NotificationTarget,\n card: unknown\n): Promise<MessageResponse> {\n return target.sendAdaptiveCard(card);\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 * @returns the response of sending message.\n */\n public async sendMessage(text: string): 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 const res = await ctx.sendActivity(text);\n response.id = res?.id;\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 * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(card: unknown): 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 const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\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 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 * @returns the response of sending message.\n */\n public async sendMessage(text: string): 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 const res = await ctx.sendActivity(text);\n response.id = res?.id;\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 * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(card: unknown): 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 const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\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 `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 * @returns the response of sending message.\n */\n public async sendMessage(text: string): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n const res = await context.sendActivity(text);\n response.id = res?.id;\n });\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(card: unknown): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n const res = await context.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\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 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 const channels: Channel[] = [];\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/**\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: 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 ConversationReferenceStore(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 references = await this.conversationReferenceStore.getAll();\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.delete(reference);\n }\n }\n\n return targets;\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 } from \"./interface\";\nimport { NotificationBot } from \"./notification\";\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 */\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 if (options.command?.enabled) {\n this.command = new CommandBot(this.adapter, options.command);\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 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 `${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"],"names":["uuidv4","utils.cloneConversation","utils.getTargetType","utils.getTeamsBotInstallationId"],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AAEA;;;IAGY;AAAZ,WAAY,SAAS;;;;IAInB,kDAAqC,CAAA;;;;IAKrC,0DAA6C,CAAA;;;;IAK7C,sDAAyC,CAAA;;;;IAKzC,4CAA+B,CAAA;;;;IAK/B,wDAA2C,CAAA;;;;IAK3C,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,EAtEW,SAAS,KAAT,SAAS,QAsEpB;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,G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AE,IAAI,CAAC,CAAC,CAAC;KAC/E;;;;;;;IAQM,OAAO,uBAAuB,CAAC,IAAuB;QAC3D,OAAO,cAAc,CAAC,aAAa,CAAC,WAAW,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC;KAC1E;;;;;;IAOM,OAAO,iBAAiB,CAAC,IAAiB;QAC/C,OAAO,cAAc,CAAC,aAAa,CAAC,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;KACpE;;;;;;;;;;IAWM,OAAO,mBAAmB,CAC/B,KAAa,EACb,MAA+B,EAC/B,OAAiC,EACjC,KAA8B;QAE9B,OAAO,cAAc,CAAC,aAAa,CAAC,WAAW,CAAC,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;KAC/F;;;;;;IAOM,OAAO,aAAa,CAAC,WAAuB;QACjD,OAAO;YACL,WAAW,EAAE,CAAC,WAAW,CAAC;SAC3B,CAAC;KACH;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.esm2017.mjs","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/utils.ts","../src/conversation/middleware.ts","../src/conversation/command.ts","../src/conversation/storage.ts","../src/conversation/notification.ts","../src/conversation/conversation.ts","../src/conversation/messageBuilder.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 * 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 // 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}\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 = jwt_decode(token) as SSOTokenInfoBase;\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;\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;\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","import { ConfidentialClientApplication, NodeAuthOptions } from \"@azure/msal-node\";\nimport { AuthenticationConfiguration } 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: AuthenticationConfiguration\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 { 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 {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 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;\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(config: AuthenticationConfiguration): AuthenticationConfiguration {\n internalLogger.verbose(\"Validate authentication configuration\");\n\n if (config.clientId && (config.clientSecret || config.certificateContent) && config.tenantId) {\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 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 { AuthenticationConfiguration } 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 {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 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;\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(\"AADSTS500133\") >= 0) {\n const fullErrorMsg =\n \"Failed to get access token from AAD server, sso token expired: \" + 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 { AuthenticationConfiguration } 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: 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 * @remarks\n * Can only be used within Teams.\n */\n public async login(scopes: string | string[]): Promise<void> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get access token from credential.\n * @remarks\n * Can only be used within Teams.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get basic user info from SSO token\n * @remarks\n * Can only be used within Teams.\n */\n public getUserInfo(): Promise<UserInfo> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.NodejsRuntimeNotSupported, \"TeamsUserCredential\"),\n ErrorCode.RuntimeNotSupported\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\";\n\nconst defaultScope = \"https://graph.microsoft.com/.default\";\n\n/**\n * Microsoft Graph auth provider for Teams Framework\n */\nexport class MsGraphAuthProvider implements AuthenticationProvider {\n private teamsfx: TeamsFxConfiguration;\n private scopes: string | string[];\n\n /**\n * Constructor of MsGraphAuthProvider.\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 * @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 this.teamsfx = teamsfx;\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}'`);\n const accessToken = await this.teamsfx.getCredential().getToken(this.scopes);\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\";\n\n/**\n * Get Microsoft graph client.\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","// 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 * @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}`\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}`\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\";\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 /**\n * Constructor of TeamsBotSsoPrompt.\n *\n * @param {TeamsFx} teamsfx - Used to provide configuration and auth\n * @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.\n * @param 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 private teamsfx: TeamsFx,\n dialogId: string,\n private settings: TeamsBotSsoPromptSettings\n ) {\n super(dialogId);\n validateScopesType(settings.scopes);\n this.loadAndValidateConfig();\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() {\n if (this.teamsfx.getIdentityType() !== IdentityType.User) {\n const errorMsg = formatString(\n ErrorMessage.IdentityTypeNotSupported,\n this.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 (!this.teamsfx.hasConfig(\"initiateLoginEndpoint\")) {\n missingConfigurations.push(\"initiateLoginEndpoint\");\n }\n\n if (!this.teamsfx.hasConfig(\"clientId\")) {\n missingConfigurations.push(\"clientId\");\n }\n\n if (!this.teamsfx.hasConfig(\"tenantId\")) {\n missingConfigurations.push(\"tenantId\");\n }\n\n if (!this.teamsfx.hasConfig(\"applicationIdUri\")) {\n missingConfigurations.push(\"applicationIdUri\");\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\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: \" + 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.teamsfx.getConfig(\"initiateLoginEndpoint\")}?scope=${encodeURI(\n this.settings.scopes.join(\" \")\n )}&clientId=${this.teamsfx.getConfig(\"clientId\")}&tenantId=${this.teamsfx.getConfig(\n \"tenantId\"\n )}&loginHint=${loginHint}`;\n\n internalLogger.verbose(\"Sign in link: \" + signInLink);\n\n const tokenExchangeResource: TokenExchangeResource = {\n id: uuidv4(),\n uri: this.teamsfx.getConfig(\"applicationIdUri\").replace(/\\/$/, \"\") + \"/access_as_user\",\n };\n\n internalLogger.verbose(\"Token exchange resource uri: \" + tokenExchangeResource.uri);\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 this.teamsfx.setSsoToken(ssoToken);\n const credential = this.teamsfx.getCredential();\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 } 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(config);\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 async AddAuthenticationInfo(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {\n if (config.headers && config.headers[\"Authorization\"]) {\n throw new ErrorWithCode(\n ErrorMessage.AuthorizationHeaderAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n );\n }\n if (config.auth) {\n throw new ErrorWithCode(\n ErrorMessage.BasicCredentialAlreadyExists,\n ErrorCode.AuthorizationInfoAlreadyExists\n );\n }\n\n config.auth = {\n username: this.userName,\n password: this.password,\n };\n\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 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 async 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 throw new ErrorWithCode(\n formatString(ErrorMessage.DuplicateApiKeyInHeader, this.keyName),\n ErrorCode.AuthorizationInfoAlreadyExists\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 throw new ErrorWithCode(\n formatString(ErrorMessage.DuplicateApiKeyInQueryParam, this.keyName),\n ErrorCode.AuthorizationInfoAlreadyExists\n );\n }\n config.params[this.keyName] = this.keyValue;\n break;\n }\n\n return 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 async 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 throw new ErrorWithCode(\n formatString(ErrorMessage.DuplicateHttpsOptionProperty, property),\n ErrorCode.InvalidParameter\n );\n }\n }\n Object.assign(config.httpsAgent.options, this.certOption);\n }\n return 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\";\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 */\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(identityType?: IdentityType, customConfig?: Record<string, string>) {\n this.identityType = identityType ?? IdentityType.User;\n this.configuration = new Map<string, string>();\n this.loadFromEnv();\n if (customConfig) {\n for (const key of Object.keys(customConfig)) {\n const value = customConfig[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 * @returns UserInfo object.\n */\n public async getUserInfo(): 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 *\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[]): 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 { BotFrameworkAdapter } from \"botbuilder\";\nimport { Activity, TurnContext } from \"botbuilder-core\";\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 *\n * @returns the response of sending message.\n */\n sendMessage(text: string): Promise<MessageResponse>;\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n *\n * @returns the response of sending adaptive card message.\n */\n sendAdaptiveCard(card: unknown): Promise<MessageResponse>;\n}\n\n/**\n * Interface for a storage provider that stores and retrieves notification target references.\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 */\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 * 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 * 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/**\n * Options to initialize {@link ConversationBot}\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 * 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","// 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 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 return context.activity?.channelData?.team?.id ?? context.activity.conversation.id;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Activity, ActivityTypes, Middleware, TurnContext } from \"botbuilder\";\nimport { CommandMessage, TeamsFxBotCommandHandler, TriggerPatterns } from \"./interface\";\nimport { ConversationReferenceStore } from \"./storage\";\nimport { cloneConversation } from \"./utils\";\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.set(reference);\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.delete(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 if (!(await this.conversationReferenceStore.check(reference))) {\n await this.conversationReferenceStore.set(reference);\n }\n } else if (conversationType === \"channel\") {\n const teamId = context.activity?.channelData?.team?.id;\n if (teamId !== undefined) {\n const teamReference = cloneConversation(reference);\n teamReference.conversation.id = teamId;\n if (!(await this.conversationReferenceStore.check(teamReference))) {\n await this.conversationReferenceStore.set(teamReference);\n }\n }\n }\n }\n}\n\nexport class CommandResponseMiddleware implements Middleware {\n public readonly commandHandlers: TeamsFxBotCommandHandler[] = [];\n\n constructor(handlers?: TeamsFxBotCommandHandler[]) {\n if (handlers && handlers.length > 0) {\n this.commandHandlers.push(...handlers);\n }\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\n const message: CommandMessage = {\n text: commandText,\n };\n\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 message.matches = Array.isArray(matchResult) ? matchResult : void 0;\n const response = await handler.handleCommandReceived(context, message);\n\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 }\n\n await next();\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 as string, \"i\");\n return regExp.test(text);\n }\n\n if (pattern instanceof RegExp) {\n const matches = text.match(pattern as RegExp);\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 { CommandOptions, TeamsFxBotCommandHandler } from \"./interface\";\nimport { CommandResponseMiddleware } from \"./middleware\";\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: BotFrameworkAdapter;\n private readonly middleware: CommandResponseMiddleware;\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(adapter: BotFrameworkAdapter, options?: CommandOptions) {\n this.middleware = new CommandResponseMiddleware(options?.commands);\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 registered.\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 command to registered.\n */\n public registerCommands(commands: TeamsFxBotCommandHandler[]): void {\n if (commands) {\n this.middleware.commandHandlers.push(...commands);\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 { NotificationTargetStorage } from \"./interface\";\n\n/**\n * @internal\n */\nexport class LocalFileStorage implements NotificationTargetStorage {\n private readonly localFileName = \".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 ConversationReferenceStore {\n private readonly storage: NotificationTargetStorage;\n\n constructor(storage: NotificationTargetStorage) {\n this.storage = storage;\n }\n\n async check(reference: Partial<ConversationReference>): Promise<boolean> {\n const ref = await this.storage.read(this.getKey(reference));\n return ref !== undefined;\n }\n\n getAll(): Promise<Partial<ConversationReference>[]> {\n return this.storage.list();\n }\n\n set(reference: Partial<ConversationReference>): Promise<void> {\n return this.storage.write(this.getKey(reference), reference);\n }\n\n delete(reference: Partial<ConversationReference>): Promise<void> {\n return this.storage.delete(this.getKey(reference));\n }\n\n private getKey(reference: Partial<ConversationReference>): string {\n return `_${reference.conversation?.tenantId}_${reference.conversation?.id}`;\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 TeamsChannelAccount,\n TeamsInfo,\n TurnContext,\n} from \"botbuilder\";\nimport { ConnectorClient } from \"botframework-connector\";\nimport * as path from \"path\";\nimport {\n NotificationTarget,\n NotificationTargetType,\n NotificationOptions,\n MessageResponse,\n} from \"./interface\";\nimport { NotificationMiddleware } from \"./middleware\";\nimport { ConversationReferenceStore, 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 * @returns the response of sending message.\n */\nexport function sendMessage(target: NotificationTarget, text: string): Promise<MessageResponse> {\n return target.sendMessage(text);\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 * @returns the response of sending adaptive card message.\n */\nexport function sendAdaptiveCard(\n target: NotificationTarget,\n card: unknown\n): Promise<MessageResponse> {\n return target.sendAdaptiveCard(card);\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 * @returns the response of sending message.\n */\n public async sendMessage(text: string): 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 const res = await ctx.sendActivity(text);\n response.id = res?.id;\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 * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(card: unknown): 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 const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\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 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 * @returns the response of sending message.\n */\n public async sendMessage(text: string): 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 const res = await ctx.sendActivity(text);\n response.id = res?.id;\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 * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(card: unknown): 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 const res = await ctx.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\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 `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 * @returns the response of sending message.\n */\n public async sendMessage(text: string): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n const res = await context.sendActivity(text);\n response.id = res?.id;\n });\n return response;\n }\n\n /**\n * Send an adaptive card message.\n *\n * @param card - the adaptive card raw JSON.\n * @returns the response of sending adaptive card message.\n */\n public async sendAdaptiveCard(card: unknown): Promise<MessageResponse> {\n const response: MessageResponse = {};\n await this.adapter.continueConversation(this.conversationReference, async (context) => {\n const res = await context.sendActivity({\n attachments: [CardFactory.adaptiveCard(card)],\n });\n response.id = res?.id;\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 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 const channels: Channel[] = [];\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/**\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: 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 ConversationReferenceStore(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 references = await this.conversationReferenceStore.getAll();\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.delete(reference);\n }\n }\n\n return targets;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { BotFrameworkAdapter, TurnContext, WebRequest, WebResponse } from \"botbuilder\";\nimport { CommandBot } from \"./command\";\nimport { ConversationOptions } from \"./interface\";\nimport { NotificationBot } from \"./notification\";\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 */\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 * 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 if (options.command?.enabled) {\n this.command = new CommandBot(this.adapter, options.command);\n }\n\n if (options.notification?.enabled) {\n this.notification = new NotificationBot(this.adapter, options.notification);\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 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 `${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"],"names":["uuidv4","utils.cloneConversation","utils.getTargetType","utils.getTeamsBotInstallationId"],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AAEA;;;IAGY;AAAZ,WAAY,SAAS;;;;IAInB,kDAAqC,CAAA;;;;IAKrC,0DAA6C,CAAA;;;;IAK7C,sDAAyC,CAAA;;;;IAKzC,4CAA+B,CAAA;;;;IAK/B,wDAA2C,CAAA;;;;IAK3C,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,EAtEW,SAAS,KAAT,SAAS,QAsEpB;AAED;;;MAGa,YAAY;;AACvB;AACgB,iCAAoB,GAAG,uCAAuC,CAAC;AAC/D,mCAAsB,GAAG,mCAAmC,CAAC;AAC7D,2CAA8B,GAAG,4CAA4C,CAAC;AAC9E,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