@microsoft/teamsfx 0.4.1-rc.0 → 0.4.2-alpha.eb4575da.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm2017.js","sources":["../src/core/errors.ts","../src/models/configuration.ts","../src/util/logger.ts","../src/util/utils.ts","../src/core/configurationProvider.ts","../src/credential/m365TenantCredential.browser.ts","../src/credential/onBehalfOfUserCredential.browser.ts","../src/core/cache.browser.ts","../src/models/grantType.ts","../src/credential/teamsUserCredential.browser.ts","../src/core/msGraphAuthProvider.ts","../src/core/msGraphClientProvider.ts","../src/core/defaultTediousConnectionConfiguration.ts","../src/bot/teamsBotSsoPrompt.browser.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Error code to trace the error types.\n * @beta\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/**\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\n/**\n * Error class with code and message thrown by the SDK.\n *\n * @beta\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 * @beta\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 * Configuration for current environment.\n * @beta\n */\nexport interface Configuration {\n /**\n * Authentication related configuration.\n *\n * @readonly\n */\n readonly authentication?: AuthenticationConfiguration;\n\n /**\n * Configuration for resources.\n *\n * @readonly\n */\n readonly resources?: ResourceConfiguration[];\n}\n\n/**\n * Authentication related configuration.\n * @beta\n */\nexport interface AuthenticationConfiguration {\n /**\n * Hostname of AAD authority. Default value comes from M365_AUTHORITY_HOST environment variable.\n *\n * @readonly\n */\n readonly authorityHost?: string;\n\n /**\n * AAD tenant id, default value comes from M365_TENANT_ID environment variable.\n *\n * @readonly\n */\n readonly tenantId?: string;\n\n /**\n * The client (application) ID of an App Registration in the tenant, default value comes from M365_CLIENT_ID environment variable\n *\n * @readonly\n */\n readonly clientId?: string;\n\n /**\n * Secret string that the application uses when requesting a token. Only used in confidential client applications. Can be created in the Azure app registration portal. Default value comes from M365_CLIENT_SECRET environment variable\n *\n * @readonly\n */\n readonly clientSecret?: string;\n\n /**\n * The content of a PEM-encoded public/private key certificate.\n *\n * @readonly\n */\n readonly certificateContent?: string;\n\n /**\n * Endpoint of auth service provisioned by Teams Framework. Default value comes from SIMPLE_AUTH_ENDPOINT environment variable.\n *\n * @readonly\n */\n readonly simpleAuthEndpoint?: string;\n\n /**\n * Login page for Teams to redirect to. Default value comes from INITIATE_LOGIN_ENDPOINT environment variable.\n *\n * @readonly\n */\n readonly initiateLoginEndpoint?: string;\n\n /**\n * Application ID URI. Default value comes from M365_APPLICATION_ID_URI environment variable.\n */\n readonly applicationIdUri?: string;\n}\n\n/**\n * Configuration for resources.\n * @beta\n */\nexport interface ResourceConfiguration {\n /**\n * Resource type.\n *\n * @readonly\n */\n readonly type: ResourceType;\n\n /**\n * Resource name.\n *\n * @readonly\n */\n readonly name: string;\n\n /**\n * Config for the resource.\n *\n * @readonly\n */\n readonly properties: { [index: string]: any };\n}\n\n/**\n * Available resource type.\n * @beta\n */\nexport enum ResourceType {\n /**\n * SQL database.\n *\n */\n SQL,\n\n /**\n * Rest API.\n *\n */\n API,\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Interface for customized logger.\n * @beta\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 *\n * @beta\n */\nexport type LogFunction = (level: LogLevel, message: string) => void;\n\n/**\n * Log level.\n *\n * @beta\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 *\n * @beta\n */\nexport function setLogLevel(level: LogLevel): void {\n internalLogger.level = level;\n}\n\n/**\n * Get log level.\n *\n * @returns Log level\n *\n * @beta\n */\nexport function getLogLevel(): LogLevel | undefined {\n return internalLogger.level;\n}\n\nclass InternalLogger {\n public level?: LogLevel = undefined;\n\n public customLogger: Logger | undefined;\n public customLogFunction: LogFunction | undefined;\n private defaultLogger: Logger = {\n verbose: console.debug,\n info: console.info,\n warn: console.warn,\n error: console.error,\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 const logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;\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 *\n * @beta\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 *\n * @beta\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 } from \"../models/userinfo\";\nimport jwt_decode from \"jwt-decode\";\nimport { internalLogger } from \"./logger\";\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 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 * 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\n/**\n * @internal\n */\nexport const isNode =\n typeof process !== \"undefined\" &&\n !!process.version &&\n !!process.versions &&\n !!process.versions.node;\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AuthenticationConfiguration,\n Configuration,\n ResourceConfiguration,\n ResourceType,\n} from \"../models/configuration\";\nimport { internalLogger } from \"../util/logger\";\nimport { formatString, isNode } from \"../util/utils\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"./errors\";\n\n/**\n * Global configuration instance\n *\n */\nexport let config: Configuration;\n\n/**\n * Initialize configuration from environment variables or configuration object and set the global instance\n *\n * @param {Configuration} configuration - Optional configuration that overrides the default configuration values. The override depth is 1.\n *\n * @throws {@link ErrorCode|InvalidParameter} when configuration is not passed in browser environment\n *\n * @beta\n */\nexport function loadConfiguration(configuration?: Configuration): void {\n internalLogger.info(\"load configuration\");\n\n // browser environment\n if (!isNode) {\n if (!configuration) {\n const errorMsg = \"You are running the code in browser. Configuration must be passed in.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n config = configuration;\n return;\n }\n\n // node environment\n let newAuthentication: AuthenticationConfiguration;\n let newResources: ResourceConfiguration[] = [];\n const defaultResourceName = \"default\";\n\n if (configuration?.authentication) {\n newAuthentication = configuration.authentication;\n } else {\n newAuthentication = {\n authorityHost: process.env.M365_AUTHORITY_HOST,\n tenantId: process.env.M365_TENANT_ID,\n clientId: process.env.M365_CLIENT_ID,\n clientSecret: process.env.M365_CLIENT_SECRET,\n simpleAuthEndpoint: process.env.SIMPLE_AUTH_ENDPOINT,\n initiateLoginEndpoint: process.env.INITIATE_LOGIN_ENDPOINT,\n applicationIdUri: process.env.M365_APPLICATION_ID_URI,\n };\n }\n\n if (configuration?.resources) {\n newResources = configuration.resources;\n } else {\n newResources = [\n {\n // SQL resource\n type: ResourceType.SQL,\n name: defaultResourceName,\n properties: {\n sqlServerEndpoint: process.env.SQL_ENDPOINT,\n sqlUsername: process.env.SQL_USER_NAME,\n sqlPassword: process.env.SQL_PASSWORD,\n sqlDatabaseName: process.env.SQL_DATABASE_NAME,\n sqlIdentityId: process.env.IDENTITY_ID,\n },\n },\n {\n // API resource\n type: ResourceType.API,\n name: defaultResourceName,\n properties: {\n endpoint: process.env.API_ENDPOINT,\n },\n },\n ];\n }\n\n config = {\n authentication: newAuthentication,\n resources: newResources,\n };\n}\n\n/**\n * Get configuration for a specific resource.\n * @param {ResourceType} resourceType - The type of resource\n * @param {string} resourceName - The name of resource, default value is \"default\".\n *\n * @returns Resource configuration for target resource from global configuration instance.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when resource configuration with the specific type and name is not found\n *\n * @beta\n */\nexport function getResourceConfiguration(\n resourceType: ResourceType,\n resourceName = \"default\"\n): { [index: string]: any } {\n internalLogger.info(\n `Get resource configuration of ${ResourceType[resourceType]} from ${resourceName}`\n );\n const result: ResourceConfiguration | undefined = config.resources?.find(\n (item) => item.type === resourceType && item.name === resourceName\n );\n if (result) {\n return result.properties;\n }\n\n const errorMsg = formatString(\n ErrorMessage.MissingResourceConfiguration,\n ResourceType[resourceType],\n resourceName\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);\n}\n\n/**\n * Get configuration for authentication.\n *\n * @returns Authentication configuration from global configuration instance, the value may be undefined if no authentication config exists in current environment.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when global configuration does not exist\n *\n * @beta\n */\nexport function getAuthenticationConfiguration(): AuthenticationConfiguration | undefined {\n internalLogger.info(\"Get authentication configuration\");\n if (config) {\n return config.authentication;\n }\n const errorMsg =\n \"Please call loadConfiguration() first before calling getAuthenticationConfiguration().\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(\n formatString(ErrorMessage.ConfigurationNotExists, errorMsg),\n ErrorCode.InvalidConfiguration\n );\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/identity\";\nimport { formatString } from \"../util/utils\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\n\n/**\n * Represent Microsoft 365 tenant identity, and it is usually used when user is not involved.\n *\n * @remarks\n * Only works in in server side.\n *\n * @beta\n */\nexport class M365TenantCredential implements TokenCredential {\n /**\n * Constructor of M365TenantCredential.\n *\n * @remarks\n * Only works in in server side.\n * @beta\n */\n constructor() {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"M365TenantCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get access token for credential.\n *\n * @remarks\n * Only works in in server side.\n * @beta\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"M365TenantCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/identity\";\nimport { UserInfo } from \"../models/userinfo\";\nimport { formatString } from \"../util/utils\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\n\n/**\n * Represent on-behalf-of flow to get user identity, and it is designed to be used in Azure Function or Bot scenarios.\n *\n * @remarks\n * Can only be used in server side.\n *\n * @beta\n */\nexport class OnBehalfOfUserCredential implements TokenCredential {\n /**\n * Constructor of OnBehalfOfUserCredential\n *\n * @remarks\n * Can Only works in in server side.\n * @beta\n */\n constructor(ssoToken: string) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"OnBehalfOfUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get access token from credential.\n * @remarks\n * Can only be used in server side.\n * @beta\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"OnBehalfOfUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get basic user info from SSO token.\n * @remarks\n * Can only be used in server side.\n * @beta\n */\n public getUserInfo(): Promise<UserInfo> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"OnBehalfOfUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Configuration used in initialization.\n * @internal\n */\nclass Cache {\n public static get(key: string): string | null {\n return sessionStorage.getItem(key);\n }\n\n public static set(key: string, value: string): void {\n sessionStorage.setItem(key, value);\n }\n\n public static remove(key: string): void {\n sessionStorage.removeItem(key);\n }\n}\n\nexport { Cache };\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * @internal\n */\nexport enum GrantType {\n authCode = \"authorization_code\",\n ssoToken = \"sso_token\",\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 { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\nimport { Cache } from \"../core/cache.browser\";\nimport * as microsoftTeams from \"@microsoft/teams-js\";\nimport { getAuthenticationConfiguration } from \"../core/configurationProvider\";\nimport { AuthenticationConfiguration } from \"../models/configuration\";\nimport { AuthCodeResult } from \"../models/authCodeResult\";\nimport axios, { AxiosInstance } from \"axios\";\nimport { GrantType } from \"../models/grantType\";\nimport { AccessTokenResult } from \"../models/accessTokenResult\";\nimport { validateScopesType, getUserInfoFromSsoToken, parseJwt } from \"../util/utils\";\nimport { formatString } from \"../util/utils\";\nimport { internalLogger } from \"../util/logger\";\n\nconst accessTokenCacheKeyPrefix = \"accessToken\";\nconst separator = \"-\";\nconst tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;\nconst initializeTeamsSdkTimeoutInMillisecond = 5000;\nconst loginPageWidth = 600;\nconst loginPageHeight = 535;\nconst maxRetryCount = 3;\nconst retryTimeSpanInMillisecond = 3000;\n\n/**\n * Represent Teams current user's identity, and it is used within Teams tab application.\n *\n * @remarks\n * Can only be used within Teams.\n *\n * @beta\n */\nexport class TeamsUserCredential implements TokenCredential {\n private readonly config: AuthenticationConfiguration;\n private ssoToken: AccessToken | null;\n\n /**\n * Constructor of TeamsUserCredential.\n * Developer need to call loadConfiguration(config) before using this class.\n * \n * @example\n * ```typescript\n * const config = {\n * authentication: {\n * runtimeConnectorEndpoint: \"https://xxx.xxx.com\",\n * initiateLoginEndpoint: \"https://localhost:3000/auth-start.html\",\n * clientId: \"xxx\"\n * }\n * }\n loadConfiguration(config); // No default config from environment variables, developers must provide the config object.\n const credential = new TeamsUserCredential([\"https://graph.microsoft.com/User.Read\"]);\n * ```\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, initiate login endpoint or simple auth endpoint is not found in config.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n * \n * @beta\n */\n constructor() {\n internalLogger.info(\"Create teams user credential\");\n this.config = this.loadAndValidateConfig();\n this.ssoToken = null;\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 credential.login([\"https://graph.microsoft.com/User.Read\"]); // single scope using string array\n * await credential.login(\"https://graph.microsoft.com/User.Read\"); // single scopes using string\n * await credential.login([\"https://graph.microsoft.com/User.Read\", \"Calendars.Read\"]); // multiple scopes using string array\n * await credential.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|ServiceError} when simple auth server failed to exchange access token.\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 * @beta\n */\n public async login(scopes: string | string[]): Promise<void> {\n validateScopesType(scopes);\n const scopesStr = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n\n internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);\n\n return new Promise<void>((resolve, reject) => {\n microsoftTeams.initialize(() => {\n microsoftTeams.authentication.authenticate({\n url: `${this.config.initiateLoginEndpoint}?clientId=${\n this.config.clientId\n }&scope=${encodeURI(scopesStr)}`,\n width: loginPageWidth,\n height: loginPageHeight,\n successCallback: async (result?: string) => {\n if (!result) {\n const errorMsg = \"Get empty authentication result from Teams\";\n\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n return;\n }\n\n const authCodeResult: AuthCodeResult = JSON.parse(result);\n try {\n await this.exchangeAccessTokenFromSimpleAuthServer(scopesStr, authCodeResult);\n resolve();\n } catch (err) {\n reject(this.generateAuthServerError(err));\n }\n },\n failureCallback: (reason?: string) => {\n const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${reason}`;\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed));\n },\n });\n });\n });\n }\n\n /**\n * Get access token from credential.\n *\n * Important: Access tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice\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 get access token with unknown error.\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 nodeJS.\n *\n * @returns User access token of defined scopes.\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 * Throw error if get access token failed.\n *\n * @beta\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n validateScopesType(scopes);\n const ssoToken = await this.getSSOToken();\n\n const scopeStr = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n if (scopeStr === \"\") {\n internalLogger.info(\"Get SSO token\");\n\n return ssoToken;\n } else {\n internalLogger.info(\"Get access token with scopes: \" + scopeStr);\n const cachedKey = await this.getAccessTokenCacheKey(scopeStr);\n const cachedToken = this.getTokenCache(cachedKey);\n\n if (cachedToken) {\n if (!this.isAccessTokenNearExpired(cachedToken)) {\n internalLogger.verbose(\"Get access token from cache\");\n return cachedToken;\n } else {\n internalLogger.verbose(\"Cached access token is expired\");\n }\n } else {\n internalLogger.verbose(\"No cached access token\");\n }\n\n const accessToken = await this.getAndCacheAccessTokenFromSimpleAuthServer(scopeStr);\n return accessToken;\n }\n }\n\n /**\n * Get basic user info from SSO token\n *\n * @example\n * ```typescript\n * const currentUser = await credential.getUserInfo();\n * ```\n *\n * @throws {@link ErrorCode|InternalError} when SSO token from Teams client is not valid.\n * @throws {@link ErrorCode|InvalidParameter} when SSO token from Teams client is empty.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns Basic user info with user displayName, objectId and preferredUserName.\n *\n * @beta\n */\n public async getUserInfo(): Promise<UserInfo> {\n internalLogger.info(\"Get basic user info from SSO token\");\n const ssoToken = await this.getSSOToken();\n return getUserInfoFromSsoToken(ssoToken.token);\n }\n\n private async exchangeAccessTokenFromSimpleAuthServer(\n scopesStr: string,\n authCodeResult: AuthCodeResult\n ): Promise<void> {\n const axiosInstance: AxiosInstance = await this.getAxiosInstance();\n\n let retryCount = 0;\n while (true) {\n try {\n const response = await axiosInstance.post(\"/auth/token\", {\n scope: scopesStr,\n code: authCodeResult.code,\n code_verifier: authCodeResult.codeVerifier,\n redirect_uri: authCodeResult.redirectUri,\n grant_type: GrantType.authCode,\n });\n\n const tokenResult: AccessTokenResult = response.data;\n const key = await this.getAccessTokenCacheKey(scopesStr);\n // Important: tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice\n this.setTokenCache(key, {\n token: tokenResult.access_token,\n expiresOnTimestamp: tokenResult.expires_on,\n });\n return;\n } catch (err: any) {\n if (err.response?.data?.type && err.response.data.type === \"AadUiRequiredException\") {\n internalLogger.warn(\"Exchange access token failed, retry...\");\n if (retryCount < maxRetryCount) {\n await this.sleep(retryTimeSpanInMillisecond);\n retryCount++;\n continue;\n }\n }\n throw err;\n }\n }\n }\n\n /**\n * Get access token cache from authentication server\n * @returns Access token\n */\n private async getAndCacheAccessTokenFromSimpleAuthServer(\n scopesStr: string\n ): Promise<AccessToken> {\n try {\n internalLogger.verbose(\n \"Get access token from authentication server with scopes: \" + scopesStr\n );\n const axiosInstance: AxiosInstance = await this.getAxiosInstance();\n const response = await axiosInstance.post(\"/auth/token\", {\n scope: scopesStr,\n grant_type: GrantType.ssoToken,\n });\n\n const accessTokenResult: AccessTokenResult = response.data;\n const accessToken: AccessToken = {\n token: accessTokenResult.access_token,\n expiresOnTimestamp: accessTokenResult.expires_on,\n };\n const cacheKey = await this.getAccessTokenCacheKey(scopesStr);\n this.setTokenCache(cacheKey, accessToken);\n return accessToken;\n } catch (err) {\n throw this.generateAuthServerError(err);\n }\n }\n\n /**\n * Get SSO token using teams SDK\n * It will try to get SSO token from memory first, if SSO token doesn't exist or about to expired, then it will using teams SDK to get SSO token\n * @returns SSO token\n */\n private getSSOToken(): Promise<AccessToken> {\n return new Promise<AccessToken>((resolve, reject) => {\n if (this.ssoToken) {\n if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {\n internalLogger.verbose(\"Get SSO token from memory cache\");\n resolve(this.ssoToken);\n return;\n }\n }\n\n let initialized = false;\n microsoftTeams.initialize(() => {\n initialized = true;\n microsoftTeams.authentication.getAuthToken({\n successCallback: (token: string) => {\n if (!token) {\n const errorMsg = \"Get empty SSO token from Teams\";\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n return;\n }\n\n const tokenObject = parseJwt(token);\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 reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n return;\n }\n\n const ssoToken: AccessToken = {\n token,\n expiresOnTimestamp: tokenObject.exp * 1000,\n };\n\n this.ssoToken = ssoToken;\n resolve(ssoToken);\n },\n failureCallback: (errMessage: string) => {\n const errorMsg = \"Get SSO token failed with error: \" + errMessage;\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n },\n resources: [],\n });\n });\n\n // If the code not running in Teams, the initialize callback function would never trigger\n setTimeout(() => {\n if (!initialized) {\n const errorMsg =\n \"Initialize teams sdk timeout, maybe the code is not running inside Teams\";\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n }\n }, initializeTeamsSdkTimeoutInMillisecond);\n });\n }\n\n /**\n * Load and validate authentication configuration\n * @returns Authentication configuration\n */\n private loadAndValidateConfig(): AuthenticationConfiguration {\n internalLogger.verbose(\"Validate authentication configuration\");\n const config = getAuthenticationConfiguration();\n\n if (!config) {\n internalLogger.error(ErrorMessage.AuthenticationConfigurationNotExists);\n\n throw new ErrorWithCode(\n ErrorMessage.AuthenticationConfigurationNotExists,\n ErrorCode.InvalidConfiguration\n );\n }\n\n if (config.initiateLoginEndpoint && config.simpleAuthEndpoint && config.clientId) {\n return config;\n }\n\n const missingValues = [];\n if (!config.initiateLoginEndpoint) {\n missingValues.push(\"initiateLoginEndpoint\");\n }\n\n if (!config.simpleAuthEndpoint) {\n missingValues.push(\"simpleAuthEndpoint\");\n }\n\n if (!config.clientId) {\n missingValues.push(\"clientId\");\n }\n\n const errorMsg = formatString(\n ErrorMessage.InvalidConfiguration,\n missingValues.join(\", \"),\n \"undefined\"\n );\n\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);\n }\n\n /**\n * Get axios instance with sso token bearer header\n * @returns AxiosInstance\n */\n private async getAxiosInstance(): Promise<AxiosInstance> {\n const ssoToken = await this.getSSOToken();\n const axiosInstance: AxiosInstance = axios.create({\n baseURL: this.config.simpleAuthEndpoint,\n });\n\n axiosInstance.interceptors.request.use((config) => {\n config.headers!.Authorization = \"Bearer \" + ssoToken.token;\n return config;\n });\n\n return axiosInstance;\n }\n\n /**\n * Set access token to cache\n * @param key\n * @param token\n */\n private setTokenCache(key: string, token: AccessToken): void {\n Cache.set(key, JSON.stringify(token));\n }\n\n /**\n * Get access token from cache.\n * If there is no cache or cannot be parsed, then it will return null\n * @param key\n * @returns Access token or null\n */\n private getTokenCache(key: string): AccessToken | null {\n const value = Cache.get(key);\n if (value === null) {\n return null;\n }\n\n const accessToken: AccessToken | null = this.validateAndParseJson(value);\n return accessToken;\n }\n\n /**\n * Parses passed value as JSON access token, if value is not a valid json string JSON.parse() will throw an error.\n * @param jsonValue\n */\n private validateAndParseJson(jsonValue: string): AccessToken | null {\n try {\n const parsedJson = JSON.parse(jsonValue);\n /**\n * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object\n * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check\n * of the parsed value is necessary in order to be certain that the string represents a valid JSON object.\n *\n */\n return parsedJson && typeof parsedJson === \"object\" ? parsedJson : null;\n } catch (error) {\n return null;\n }\n }\n\n /**\n * Generate cache key\n * @param scopesStr\n * @returns Access token cache key, a key example: accessToken-userId-clientId-tenantId-scopes\n */\n private async getAccessTokenCacheKey(scopesStr: string): Promise<string> {\n const ssoToken = await this.getSSOToken();\n const ssoTokenObj = parseJwt(ssoToken.token);\n\n const clientId = this.config.clientId;\n const userObjectId = ssoTokenObj.oid;\n const tenantId = ssoTokenObj.tid;\n\n const key = [accessTokenCacheKeyPrefix, userObjectId, clientId, tenantId, scopesStr]\n .join(separator)\n .replace(/\" \"/g, \"_\");\n return key;\n }\n\n /**\n * Check whether the token is about to expire (within 5 minutes)\n * @returns Boolean value indicate whether the token is about to expire\n */\n private isAccessTokenNearExpired(token: AccessToken): boolean {\n const expireDate = new Date(token.expiresOnTimestamp);\n if (expireDate.getTime() - Date.now() > tokenRefreshTimeSpanInMillisecond) {\n return false;\n }\n return true;\n }\n\n private generateAuthServerError(err: any): Error {\n let errorMessage = err.message;\n if (err.response?.data?.type) {\n errorMessage = err.response.data.detail;\n if (err.response.data.type === \"AadUiRequiredException\") {\n const fullErrorMsg =\n \"Failed to get access token from authentication server, please login first: \" +\n errorMessage;\n internalLogger.warn(fullErrorMsg);\n return new ErrorWithCode(fullErrorMsg, ErrorCode.UiRequiredError);\n } else {\n const fullErrorMsg =\n \"Failed to get access token from authentication server: \" + errorMessage;\n internalLogger.error(fullErrorMsg);\n return new ErrorWithCode(fullErrorMsg, ErrorCode.ServiceError);\n }\n }\n\n const fullErrorMsg = \"Failed to get access token with error: \" + errorMessage;\n return new ErrorWithCode(fullErrorMsg, ErrorCode.InternalError);\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AuthenticationProvider } from \"@microsoft/microsoft-graph-client\";\nimport { TokenCredential } from \"@azure/identity\";\nimport { ErrorWithCode, ErrorCode } from \"./errors\";\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 *\n * @beta\n */\nexport class MsGraphAuthProvider implements AuthenticationProvider {\n private credential: TokenCredential;\n private scopes: string | string[];\n\n /**\n * Constructor of MsGraphAuthProvider.\n *\n * @param {TokenCredential} credential - Credential used to invoke Microsoft Graph APIs.\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 * @beta\n */\n constructor(credential: TokenCredential, scopes?: string | string[]) {\n this.credential = credential;\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.credential.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 { TokenCredential } from \"@azure/identity\";\nimport { Client } from \"@microsoft/microsoft-graph-client\";\nimport { MsGraphAuthProvider } from \"./msGraphAuthProvider\";\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 {TokenCredential} credential - token credential instance.\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 *\n * @beta\n */\nexport function createMicrosoftGraphClient(\n credential: TokenCredential,\n scopes?: string | string[]\n): Client {\n internalLogger.info(\"Create Microsoft Graph Client\");\n const authProvider = new MsGraphAuthProvider(credential, scopes);\n const graphClient = Client.initWithMiddleware({\n authProvider,\n });\n\n return graphClient;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { getResourceConfiguration } from \"./configurationProvider\";\nimport { ResourceType } from \"../models/configuration\";\nimport { AccessToken, ManagedIdentityCredential } from \"@azure/identity\";\nimport { ErrorWithCode, ErrorCode } from \"./errors\";\nimport { ConnectionConfig } from \"tedious\";\nimport { internalLogger } from \"../util/logger\";\n\n/**\n * SQL connection configuration instance.\n * @remarks\n * Only works in in server side.\n *\n * @beta\n *\n */\nexport class DefaultTediousConnectionConfiguration {\n /**\n * MSSQL default scope\n * https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi\n */\n private readonly defaultSQLScope: string = \"https://database.windows.net/\";\n\n /**\n * Generate connection configuration consumed by tedious.\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 *\n * @beta\n */\n public async getConfig(): Promise<ConnectionConfig> {\n internalLogger.info(\"Get SQL configuration\");\n const configuration = <SqlConfiguration>getResourceConfiguration(ResourceType.SQL);\n\n if (!configuration) {\n const errMsg = \"SQL resource configuration not exist\";\n internalLogger.error(errMsg);\n throw new ErrorWithCode(errMsg, ErrorCode.InvalidConfiguration);\n }\n\n try {\n this.isSQLConfigurationValid(configuration);\n } catch (err) {\n throw err;\n }\n\n if (!this.isMsiAuthentication()) {\n const configWithUPS = this.generateDefaultConfig(configuration);\n internalLogger.verbose(\"SQL configuration with username and password generated\");\n return configWithUPS;\n }\n\n try {\n const configWithToken = await this.generateTokenConfig(configuration);\n internalLogger.verbose(\"SQL configuration with MSI token generated\");\n return configWithToken;\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * Check SQL use MSI identity or username and password.\n *\n * @returns false - login with SQL MSI identity, true - login with username and password.\n * @internal\n */\n private isMsiAuthentication(): boolean {\n internalLogger.verbose(\n \"Check connection config using MSI access token or username and password\"\n );\n const configuration = <SqlConfiguration>getResourceConfiguration(ResourceType.SQL);\n if (configuration?.sqlUsername != null && configuration?.sqlPassword != null) {\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 * check configuration is an available configurations.\n * @param { SqlConfiguration } sqlConfig\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 */\n private isSQLConfigurationValid(sqlConfig: SqlConfiguration) {\n internalLogger.verbose(\"Check SQL configuration if valid\");\n if (!sqlConfig.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 (!(sqlConfig.sqlUsername && sqlConfig.sqlPassword) && !sqlConfig.sqlIdentityId) {\n const errMsg = `SQL configuration is not valid without ${\n sqlConfig.sqlIdentityId ? \"\" : \"identity id \"\n } ${sqlConfig.sqlUsername ? \"\" : \"SQL username \"} ${\n sqlConfig.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 * Generate tedious connection configuration with default authentication type.\n *\n * @param { SqlConfiguration } SQL configuration with username and password.\n *\n * @returns Tedious connection configuration with username and password.\n * @internal\n */\n private generateDefaultConfig(sqlConfig: SqlConfiguration): ConnectionConfig {\n internalLogger.verbose(\n `SQL server ${sqlConfig.sqlServerEndpoint}, user name ${sqlConfig.sqlUsername}, database name ${sqlConfig.sqlDatabaseName}`\n );\n\n const config = {\n server: sqlConfig.sqlServerEndpoint,\n authentication: {\n type: TediousAuthenticationType.default,\n options: {\n userName: sqlConfig.sqlUsername,\n password: sqlConfig.sqlPassword,\n },\n },\n options: {\n database: sqlConfig.sqlDatabaseName,\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 { SqlConfiguration } SQL configuration with AAD access token.\n *\n * @returns Tedious connection configuration with access token.\n * @internal\n */\n private async generateTokenConfig(sqlConfig: SqlConfiguration): Promise<ConnectionConfig> {\n internalLogger.verbose(\"Generate tedious config with MSI token\");\n\n let token: AccessToken | null;\n try {\n const credential = new ManagedIdentityCredential(sqlConfig.sqlIdentityId);\n token = await credential.getToken(this.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: sqlConfig.sqlServerEndpoint,\n authentication: {\n type: TediousAuthenticationType.MSI,\n options: {\n token: token.token,\n },\n },\n options: {\n database: sqlConfig.sqlDatabaseName,\n encrypt: true,\n },\n };\n internalLogger.verbose(\n `Generate token configuration success, server endpoint is ${sqlConfig.sqlServerEndpoint}, database name is ${sqlConfig.sqlDatabaseName}`\n );\n return config;\n }\n internalLogger.error(\n `Generate token configuration, server endpoint is ${sqlConfig.sqlServerEndpoint}, MSI token is not valid`\n );\n throw new ErrorWithCode(\"MSI token is not valid\", ErrorCode.InternalError);\n }\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\n/**\n * Configuration for SQL resource.\n * @internal\n */\ninterface SqlConfiguration {\n /**\n * SQL server endpoint.\n *\n * @readonly\n */\n readonly sqlServerEndpoint: string;\n\n /**\n * SQL server username.\n *\n * @readonly\n */\n readonly sqlUsername: string;\n\n /**\n * SQL server password.\n *\n * @readonly\n */\n readonly sqlPassword: string;\n\n /**\n * SQL server database name.\n *\n * @readonly\n */\n readonly sqlDatabaseName: string;\n\n /**\n * Managed identity id.\n *\n * @readonly\n */\n readonly sqlIdentityId: string;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { DialogContext, DialogTurnResult } from \"botbuilder-dialogs\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Settings used to configure an TeamsBotSsoPrompt instance.\n *\n * @remarks\n * Only works in in server side.\n *\n * @beta\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 * loadConfiguration();\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 *\n * @beta\n */\nexport class TeamsBotSsoPrompt {\n /**\n * Constructor of TeamsBotSsoPrompt.\n *\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 * @beta\n */\n constructor(dialogId: string, private settings: TeamsBotSsoPromptSettings) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"TeamsBotSsoPrompt\"),\n ErrorCode.RuntimeNotSupported\n );\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 * @beta\n */\n public async beginDialog(dc: DialogContext): Promise<DialogTurnResult> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"TeamsBotSsoPrompt\"),\n ErrorCode.RuntimeNotSupported\n );\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 * @beta\n */\n public async continueDialog(dc: DialogContext): Promise<DialogTurnResult> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"TeamsBotSsoPrompt\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n}\n"],"names":[],"mappings":";;;;;;AAAA;AACA;AAEA;;;;IAIY;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;AACrC,CAAC,EAvDW,SAAS,KAAT,SAAS,QAuDpB;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,GAA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;;;;;;;;;;;;;;;;IAkBM,MAAM,WAAW,CAAC,EAAiB;QACxC,MAAM,IAAI,aAAa,CACrB,YAAY,CAAC,YAAY,CAAC,0BAA0B,EAAE,mBAAmB,CAAC,EAC1E,SAAS,CAAC,mBAAmB,CAC9B,CAAC;KACH;;;;;;;;;;;;;;;;;;;IAoBM,MAAM,cAAc,CAAC,EAAiB;QAC3C,MAAM,IAAI,aAAa,CACrB,YAAY,CAAC,YAAY,CAAC,0BAA0B,EAAE,mBAAmB,CAAC,EAC1E,SAAS,CAAC,mBAAmB,CAC9B,CAAC;KACH;;;;;"}
1
+ {"version":3,"file":"index.esm2017.js","sources":["../src/core/errors.ts","../src/models/configuration.ts","../src/util/logger.ts","../src/util/utils.ts","../src/core/configurationProvider.ts","../src/credential/m365TenantCredential.browser.ts","../src/credential/onBehalfOfUserCredential.browser.ts","../src/credential/teamsUserCredential.browser.ts","../src/core/msGraphAuthProvider.ts","../src/core/msGraphClientProvider.ts","../src/core/defaultTediousConnectionConfiguration.browser.ts","../src/bot/teamsBotSsoPrompt.browser.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Error code to trace the error types.\n * @beta\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/**\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\n/**\n * Error class with code and message thrown by the SDK.\n *\n * @beta\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 * @beta\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 * Configuration for current environment.\n * @beta\n */\nexport interface Configuration {\n /**\n * Authentication related configuration.\n *\n * @readonly\n */\n readonly authentication?: AuthenticationConfiguration;\n\n /**\n * Configuration for resources.\n *\n * @readonly\n */\n readonly resources?: ResourceConfiguration[];\n}\n\n/**\n * Authentication related configuration.\n * @beta\n */\nexport interface AuthenticationConfiguration {\n /**\n * Hostname of AAD authority. Default value comes from M365_AUTHORITY_HOST environment variable.\n *\n * @readonly\n */\n readonly authorityHost?: string;\n\n /**\n * AAD tenant id, default value comes from M365_TENANT_ID environment variable.\n *\n * @readonly\n */\n readonly tenantId?: string;\n\n /**\n * The client (application) ID of an App Registration in the tenant, default value comes from M365_CLIENT_ID environment variable\n *\n * @readonly\n */\n readonly clientId?: string;\n\n /**\n * Secret string that the application uses when requesting a token. Only used in confidential client applications. Can be created in the Azure app registration portal. Default value comes from M365_CLIENT_SECRET environment variable\n *\n * @readonly\n */\n readonly clientSecret?: string;\n\n /**\n * The content of a PEM-encoded public/private key certificate.\n *\n * @readonly\n */\n readonly certificateContent?: string;\n\n /**\n * Endpoint of auth service provisioned by Teams Framework. Default value comes from SIMPLE_AUTH_ENDPOINT environment variable.\n *\n * @readonly\n */\n readonly simpleAuthEndpoint?: string;\n\n /**\n * Login page for Teams to redirect to. Default value comes from INITIATE_LOGIN_ENDPOINT environment variable.\n *\n * @readonly\n */\n readonly initiateLoginEndpoint?: string;\n\n /**\n * Application ID URI. Default value comes from M365_APPLICATION_ID_URI environment variable.\n */\n readonly applicationIdUri?: string;\n}\n\n/**\n * Configuration for resources.\n * @beta\n */\nexport interface ResourceConfiguration {\n /**\n * Resource type.\n *\n * @readonly\n */\n readonly type: ResourceType;\n\n /**\n * Resource name.\n *\n * @readonly\n */\n readonly name: string;\n\n /**\n * Config for the resource.\n *\n * @readonly\n */\n readonly properties: { [index: string]: any };\n}\n\n/**\n * Available resource type.\n * @beta\n */\nexport enum ResourceType {\n /**\n * SQL database.\n *\n */\n SQL,\n\n /**\n * Rest API.\n *\n */\n API,\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Interface for customized logger.\n * @beta\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 *\n * @beta\n */\nexport type LogFunction = (level: LogLevel, message: string) => void;\n\n/**\n * Log level.\n *\n * @beta\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 *\n * @beta\n */\nexport function setLogLevel(level: LogLevel): void {\n internalLogger.level = level;\n}\n\n/**\n * Get log level.\n *\n * @returns Log level\n *\n * @beta\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 *\n * @beta\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 *\n * @beta\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 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\n/**\n * @internal\n */\nexport const isNode =\n typeof process !== \"undefined\" &&\n !!process.version &&\n !!process.versions &&\n !!process.versions.node;\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AuthenticationConfiguration,\n Configuration,\n ResourceConfiguration,\n ResourceType,\n} from \"../models/configuration\";\nimport { internalLogger } from \"../util/logger\";\nimport { formatString, isNode } from \"../util/utils\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"./errors\";\n\n/**\n * Global configuration instance\n *\n */\nexport let config: Configuration;\n\n/**\n * Initialize configuration from environment variables or configuration object and set the global instance\n *\n * @param {Configuration} configuration - Optional configuration that overrides the default configuration values. The override depth is 1.\n *\n * @throws {@link ErrorCode|InvalidParameter} when configuration is not passed in browser environment\n *\n * @beta\n */\nexport function loadConfiguration(configuration?: Configuration): void {\n internalLogger.info(\"load configuration\");\n\n // browser environment\n if (!isNode) {\n if (!configuration) {\n const errorMsg = \"You are running the code in browser. Configuration must be passed in.\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);\n }\n config = configuration;\n return;\n }\n\n // node environment\n let newAuthentication: AuthenticationConfiguration;\n let newResources: ResourceConfiguration[] = [];\n const defaultResourceName = \"default\";\n\n if (configuration?.authentication) {\n newAuthentication = configuration.authentication;\n } else {\n newAuthentication = {\n authorityHost: process.env.M365_AUTHORITY_HOST,\n tenantId: process.env.M365_TENANT_ID,\n clientId: process.env.M365_CLIENT_ID,\n clientSecret: process.env.M365_CLIENT_SECRET,\n simpleAuthEndpoint: process.env.SIMPLE_AUTH_ENDPOINT,\n initiateLoginEndpoint: process.env.INITIATE_LOGIN_ENDPOINT,\n applicationIdUri: process.env.M365_APPLICATION_ID_URI,\n };\n }\n\n if (configuration?.resources) {\n newResources = configuration.resources;\n } else {\n newResources = [\n {\n // SQL resource\n type: ResourceType.SQL,\n name: defaultResourceName,\n properties: {\n sqlServerEndpoint: process.env.SQL_ENDPOINT,\n sqlUsername: process.env.SQL_USER_NAME,\n sqlPassword: process.env.SQL_PASSWORD,\n sqlDatabaseName: process.env.SQL_DATABASE_NAME,\n sqlIdentityId: process.env.IDENTITY_ID,\n },\n },\n {\n // API resource\n type: ResourceType.API,\n name: defaultResourceName,\n properties: {\n endpoint: process.env.API_ENDPOINT,\n },\n },\n ];\n }\n\n config = {\n authentication: newAuthentication,\n resources: newResources,\n };\n}\n\n/**\n * Get configuration for a specific resource.\n * @param {ResourceType} resourceType - The type of resource\n * @param {string} resourceName - The name of resource, default value is \"default\".\n *\n * @returns Resource configuration for target resource from global configuration instance.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when resource configuration with the specific type and name is not found\n *\n * @beta\n */\nexport function getResourceConfiguration(\n resourceType: ResourceType,\n resourceName = \"default\"\n): { [index: string]: any } {\n internalLogger.info(\n `Get resource configuration of ${ResourceType[resourceType]} from ${resourceName}`\n );\n const result: ResourceConfiguration | undefined = config.resources?.find(\n (item) => item.type === resourceType && item.name === resourceName\n );\n if (result) {\n return result.properties;\n }\n\n const errorMsg = formatString(\n ErrorMessage.MissingResourceConfiguration,\n ResourceType[resourceType],\n resourceName\n );\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);\n}\n\n/**\n * Get configuration for authentication.\n *\n * @returns Authentication configuration from global configuration instance, the value may be undefined if no authentication config exists in current environment.\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when global configuration does not exist\n *\n * @beta\n */\nexport function getAuthenticationConfiguration(): AuthenticationConfiguration | undefined {\n internalLogger.info(\"Get authentication configuration\");\n if (config) {\n return config.authentication;\n }\n const errorMsg =\n \"Please call loadConfiguration() first before calling getAuthenticationConfiguration().\";\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(\n formatString(ErrorMessage.ConfigurationNotExists, errorMsg),\n ErrorCode.InvalidConfiguration\n );\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/identity\";\nimport { formatString } from \"../util/utils\";\nimport { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\n\n/**\n * Represent Microsoft 365 tenant identity, and it is usually used when user is not involved.\n *\n * @remarks\n * Only works in in server side.\n *\n * @beta\n */\nexport class M365TenantCredential implements TokenCredential {\n /**\n * Constructor of M365TenantCredential.\n *\n * @remarks\n * Only works in in server side.\n * @beta\n */\n constructor() {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"M365TenantCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get access token for credential.\n *\n * @remarks\n * Only works in in server side.\n * @beta\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"M365TenantCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/identity\";\nimport { UserInfo } from \"../models/userinfo\";\nimport { formatString } from \"../util/utils\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\n\n/**\n * Represent on-behalf-of flow to get user identity, and it is designed to be used in Azure Function or Bot scenarios.\n *\n * @remarks\n * Can only be used in server side.\n *\n * @beta\n */\nexport class OnBehalfOfUserCredential implements TokenCredential {\n /**\n * Constructor of OnBehalfOfUserCredential\n *\n * @remarks\n * Can Only works in in server side.\n * @beta\n */\n constructor(ssoToken: string) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"OnBehalfOfUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get access token from credential.\n * @remarks\n * Can only be used in server side.\n * @beta\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"OnBehalfOfUserCredential\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Get basic user info from SSO token.\n * @remarks\n * Can only be used in server side.\n * @beta\n */\n public getUserInfo(): Promise<UserInfo> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"OnBehalfOfUserCredential\"),\n ErrorCode.RuntimeNotSupported\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 { ErrorCode, ErrorMessage, ErrorWithCode } from \"../core/errors\";\nimport * as microsoftTeams from \"@microsoft/teams-js\";\nimport { getAuthenticationConfiguration } from \"../core/configurationProvider\";\nimport { AuthenticationConfiguration } from \"../models/configuration\";\nimport {\n validateScopesType,\n getUserInfoFromSsoToken,\n parseJwt,\n getTenantIdAndLoginHintFromSsoToken,\n parseAccessTokenFromAuthCodeTokenResponse,\n} from \"../util/utils\";\nimport { formatString } from \"../util/utils\";\nimport { internalLogger } from \"../util/logger\";\nimport { PublicClientApplication } from \"@azure/msal-browser\";\n\nconst tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;\nconst initializeTeamsSdkTimeoutInMillisecond = 5000;\nconst loginPageWidth = 600;\nconst loginPageHeight = 535;\n\n/**\n * Represent Teams current user's identity, and it is used within Teams tab application.\n *\n * @remarks\n * Can only be used within Teams.\n *\n * @beta\n */\nexport class TeamsUserCredential implements TokenCredential {\n private readonly config: AuthenticationConfiguration;\n private ssoToken: AccessToken | null;\n private initialized: boolean;\n private msalInstance?: PublicClientApplication;\n private tid?: string;\n private loginHint?: string;\n\n /**\n * Constructor of TeamsUserCredential.\n * Developer need to call loadConfiguration(config) before using this class.\n * \n * @example\n * ```typescript\n * const config = {\n * authentication: {\n * initiateLoginEndpoint: \"https://localhost:3000/auth-start.html\",\n * clientId: \"xxx\"\n * }\n * }\n loadConfiguration(config); // No default config from environment variables, developers must provide the config object.\n const credential = new TeamsUserCredential([\"https://graph.microsoft.com/User.Read\"]);\n * ```\n *\n * @throws {@link ErrorCode|InvalidConfiguration} when client id, initiate login endpoint or simple auth endpoint is not found in config.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n * \n * @beta\n */\n constructor() {\n internalLogger.info(\"Create teams user credential\");\n this.config = this.loadAndValidateConfig();\n this.ssoToken = null;\n this.initialized = false;\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 credential.login([\"https://graph.microsoft.com/User.Read\"]); // single scope using string array\n * await credential.login(\"https://graph.microsoft.com/User.Read\"); // single scopes using string\n * await credential.login([\"https://graph.microsoft.com/User.Read\", \"Calendars.Read\"]); // multiple scopes using string array\n * await credential.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 * @beta\n */\n async login(scopes: string | string[]): Promise<AccessToken> {\n validateScopesType(scopes);\n const scopesStr = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n\n internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);\n\n if (!this.initialized) {\n await this.init();\n }\n\n return new Promise<AccessToken>((resolve, reject) => {\n microsoftTeams.initialize(() => {\n microsoftTeams.authentication.authenticate({\n url: `${this.config.initiateLoginEndpoint}?clientId=${\n this.config.clientId\n }&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,\n width: loginPageWidth,\n height: loginPageHeight,\n successCallback: async (result?: string) => {\n if (!result) {\n const errorMsg = \"Get empty authentication result from MSAL\";\n\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n return;\n }\n\n try {\n const accessToken = parseAccessTokenFromAuthCodeTokenResponse(result);\n resolve(accessToken);\n } catch (error: any) {\n reject(error);\n }\n },\n failureCallback: (reason?: string) => {\n const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${reason}`;\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.ConsentFailed));\n },\n });\n });\n });\n }\n\n /**\n * Get access token from credential.\n *\n * Important: Access tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice\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 get access token with unknown error.\n * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.\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 User access token of defined scopes.\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 * Throw error if get access token failed.\n *\n * @beta\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n validateScopesType(scopes);\n const ssoToken = await this.getSSOToken();\n\n const scopeStr = typeof scopes === \"string\" ? scopes : scopes.join(\" \");\n if (scopeStr === \"\") {\n internalLogger.info(\"Get SSO token\");\n\n return ssoToken;\n } else {\n internalLogger.info(\"Get access token with scopes: \" + scopeStr);\n\n if (!this.initialized) {\n await this.init();\n }\n\n let tokenResponse;\n const scopesArray = typeof scopes === \"string\" ? scopes.split(\" \") : scopes;\n const domain = window.location.origin;\n\n // First try to get Access Token from cache.\n try {\n const account = this.msalInstance!.getAccountByUsername(this.loginHint!);\n const scopesRequestForAcquireTokenSilent = {\n scopes: scopesArray,\n account: account ?? undefined,\n redirectUri: `${domain}/blank-auth-end.html`,\n };\n tokenResponse = await this.msalInstance!.acquireTokenSilent(\n scopesRequestForAcquireTokenSilent\n );\n } catch (error: any) {\n const acquireTokenSilentFailedMessage = `Failed to call acquireTokenSilent. Reason: ${error?.message}. `;\n internalLogger.verbose(acquireTokenSilentFailedMessage);\n }\n\n if (!tokenResponse) {\n // If fail to get Access Token from cache, try to get Access token by silent login.\n try {\n const scopesRequestForSsoSilent = {\n scopes: scopesArray,\n loginHint: this.loginHint,\n redirectUri: `${domain}/blank-auth-end.html`,\n };\n tokenResponse = await this.msalInstance!.ssoSilent(scopesRequestForSsoSilent);\n } catch (error: any) {\n const ssoSilentFailedMessage = `Failed to call ssoSilent. Reason: ${error?.message}. `;\n internalLogger.verbose(ssoSilentFailedMessage);\n }\n }\n\n if (!tokenResponse) {\n const errorMsg = `Failed to get access token cache silently, please login first: you need login first before get access token.`;\n internalLogger.error(errorMsg);\n throw new ErrorWithCode(errorMsg, ErrorCode.UiRequiredError);\n }\n\n const accessToken = parseAccessTokenFromAuthCodeTokenResponse(tokenResponse);\n return accessToken;\n }\n }\n\n /**\n * Get basic user info from SSO token\n *\n * @example\n * ```typescript\n * const currentUser = await credential.getUserInfo();\n * ```\n *\n * @throws {@link ErrorCode|InternalError} when SSO token from Teams client is not valid.\n * @throws {@link ErrorCode|InvalidParameter} when SSO token from Teams client is empty.\n * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.\n *\n * @returns Basic user info with user displayName, objectId and preferredUserName.\n *\n * @beta\n */\n public async getUserInfo(): Promise<UserInfo> {\n internalLogger.info(\"Get basic user info from SSO token\");\n const ssoToken = await this.getSSOToken();\n return getUserInfoFromSsoToken(ssoToken.token);\n }\n\n private async init(): Promise<void> {\n const ssoToken = await this.getSSOToken();\n const info = getTenantIdAndLoginHintFromSsoToken(ssoToken.token);\n this.loginHint = info.loginHint;\n this.tid = info.tid;\n\n const msalConfig = {\n auth: {\n clientId: this.config.clientId!,\n authority: `https://login.microsoftonline.com/${this.tid}`,\n },\n cache: {\n cacheLocation: \"sessionStorage\",\n },\n };\n\n this.msalInstance = new PublicClientApplication(msalConfig);\n this.initialized = true;\n }\n\n /**\n * Get SSO token using teams SDK\n * It will try to get SSO token from memory first, if SSO token doesn't exist or about to expired, then it will using teams SDK to get SSO token\n * @returns SSO token\n */\n private getSSOToken(): Promise<AccessToken> {\n return new Promise<AccessToken>((resolve, reject) => {\n if (this.ssoToken) {\n if (this.ssoToken.expiresOnTimestamp - Date.now() > tokenRefreshTimeSpanInMillisecond) {\n internalLogger.verbose(\"Get SSO token from memory cache\");\n resolve(this.ssoToken);\n return;\n }\n }\n\n let initialized = false;\n microsoftTeams.initialize(() => {\n initialized = true;\n microsoftTeams.authentication.getAuthToken({\n successCallback: (token: string) => {\n if (!token) {\n const errorMsg = \"Get empty SSO token from Teams\";\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n return;\n }\n\n const tokenObject = parseJwt(token);\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 reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n return;\n }\n\n const ssoToken: AccessToken = {\n token,\n expiresOnTimestamp: tokenObject.exp * 1000,\n };\n\n this.ssoToken = ssoToken;\n resolve(ssoToken);\n },\n failureCallback: (errMessage: string) => {\n const errorMsg = \"Get SSO token failed with error: \" + errMessage;\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n },\n resources: [],\n });\n });\n\n // If the code not running in Teams, the initialize callback function would never trigger\n setTimeout(() => {\n if (!initialized) {\n const errorMsg =\n \"Initialize teams sdk timeout, maybe the code is not running inside Teams\";\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n }\n }, initializeTeamsSdkTimeoutInMillisecond);\n });\n }\n\n /**\n * Load and validate authentication configuration\n * @returns Authentication configuration\n */\n private loadAndValidateConfig(): AuthenticationConfiguration {\n internalLogger.verbose(\"Validate authentication configuration\");\n const config = getAuthenticationConfiguration();\n\n if (!config) {\n internalLogger.error(ErrorMessage.AuthenticationConfigurationNotExists);\n\n throw new ErrorWithCode(\n ErrorMessage.AuthenticationConfigurationNotExists,\n ErrorCode.InvalidConfiguration\n );\n }\n\n if (config.initiateLoginEndpoint && config.clientId) {\n return config;\n }\n\n const missingValues = [];\n if (!config.initiateLoginEndpoint) {\n missingValues.push(\"initiateLoginEndpoint\");\n }\n\n if (!config.clientId) {\n missingValues.push(\"clientId\");\n }\n\n const errorMsg = formatString(\n ErrorMessage.InvalidConfiguration,\n missingValues.join(\", \"),\n \"undefined\"\n );\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 { AuthenticationProvider } from \"@microsoft/microsoft-graph-client\";\nimport { TokenCredential } from \"@azure/identity\";\nimport { ErrorWithCode, ErrorCode } from \"./errors\";\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 *\n * @beta\n */\nexport class MsGraphAuthProvider implements AuthenticationProvider {\n private credential: TokenCredential;\n private scopes: string | string[];\n\n /**\n * Constructor of MsGraphAuthProvider.\n *\n * @param {TokenCredential} credential - Credential used to invoke Microsoft Graph APIs.\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 * @beta\n */\n constructor(credential: TokenCredential, scopes?: string | string[]) {\n this.credential = credential;\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.credential.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 { TokenCredential } from \"@azure/identity\";\nimport { Client } from \"@microsoft/microsoft-graph-client\";\nimport { MsGraphAuthProvider } from \"./msGraphAuthProvider\";\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 {TokenCredential} credential - token credential instance.\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 *\n * @beta\n */\nexport function createMicrosoftGraphClient(\n credential: TokenCredential,\n scopes?: string | string[]\n): Client {\n internalLogger.info(\"Create Microsoft Graph Client\");\n const authProvider = new MsGraphAuthProvider(credential, scopes);\n const graphClient = Client.initWithMiddleware({\n authProvider,\n });\n\n return graphClient;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"./errors\";\nimport { ConnectionConfig } from \"tedious\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Generate connection configuration consumed by tedious.\n * @remarks\n * Only works in in server side.\n * @beta\n */\nexport class DefaultTediousConnectionConfiguration {\n constructor() {\n throw new ErrorWithCode(\n formatString(\n ErrorMessage.BrowserRuntimeNotSupported,\n \"DefaultTediousConnectionConfiguration\"\n ),\n ErrorCode.RuntimeNotSupported\n );\n }\n\n /**\n * Generate connection configuration consumed by tedious.\n * @remarks\n * Only works in in server side.\n * @beta\n */\n public async getConfig(): Promise<ConnectionConfig> {\n throw new ErrorWithCode(\n formatString(\n ErrorMessage.BrowserRuntimeNotSupported,\n \"DefaultTediousConnectionConfiguration\"\n ),\n ErrorCode.RuntimeNotSupported\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { DialogContext, DialogTurnResult } from \"botbuilder-dialogs\";\nimport { ErrorWithCode, ErrorCode, ErrorMessage } from \"../core/errors\";\nimport { formatString } from \"../util/utils\";\n\n/**\n * Settings used to configure an TeamsBotSsoPrompt instance.\n *\n * @remarks\n * Only works in in server side.\n *\n * @beta\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 * loadConfiguration();\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 *\n * @beta\n */\nexport class TeamsBotSsoPrompt {\n /**\n * Constructor of TeamsBotSsoPrompt.\n *\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 * @beta\n */\n constructor(dialogId: string, private settings: TeamsBotSsoPromptSettings) {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"TeamsBotSsoPrompt\"),\n ErrorCode.RuntimeNotSupported\n );\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 * @beta\n */\n public async beginDialog(dc: DialogContext): Promise<DialogTurnResult> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"TeamsBotSsoPrompt\"),\n ErrorCode.RuntimeNotSupported\n );\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 * @beta\n */\n public async continueDialog(dc: DialogContext): Promise<DialogTurnResult> {\n throw new ErrorWithCode(\n formatString(ErrorMessage.BrowserRuntimeNotSupported, \"TeamsBotSsoPrompt\"),\n ErrorCode.RuntimeNotSupported\n );\n }\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AAEA;;;;IAIY;AAAZ,WAAY,SAAS;;;;IAInB,kDAAqC,CAAA;;;;IAKrC,0DAA6C,CAAA;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M,MAAM,WAAW,CAAC,EAAiB;QACxC,MAAM,IAAI,aAAa,CACrB,YAAY,CAAC,YAAY,CAAC,0BAA0B,EAAE,mBAAmB,CAAC,EAC1E,SAAS,CAAC,mBAAmB,CAC9B,CAAC;KACH;;;;;;;;;;;;;;;;;;;IAoBM,MAAM,cAAc,CAAC,EAAiB;QAC3C,MAAM,IAAI,aAAa,CACrB,YAAY,CAAC,YAAY,CAAC,0BAA0B,EAAE,mBAAmB,CAAC,EAC1E,SAAS,CAAC,mBAAmB,CAC9B,CAAC;KACH;;;;;"}
@@ -171,7 +171,7 @@ function getLogLevel() {
171
171
  return internalLogger.level;
172
172
  }
173
173
  class InternalLogger {
174
- constructor() {
174
+ constructor(name, logLevel) {
175
175
  this.level = undefined;
176
176
  this.defaultLogger = {
177
177
  verbose: console.debug,
@@ -179,6 +179,8 @@ class InternalLogger {
179
179
  warn: console.warn,
180
180
  error: console.error,
181
181
  };
182
+ this.name = name;
183
+ this.level = logLevel;
182
184
  }
183
185
  error(message) {
184
186
  this.log(LogLevel.Error, (x) => x.error, message);
@@ -197,7 +199,13 @@ class InternalLogger {
197
199
  return;
198
200
  }
199
201
  const timestamp = new Date().toUTCString();
200
- const logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
202
+ let logHeader;
203
+ if (this.name) {
204
+ logHeader = `[${timestamp}] : @microsoft/teamsfx - ${this.name} : ${LogLevel[logLevel]} - `;
205
+ }
206
+ else {
207
+ logHeader = `[${timestamp}] : @microsoft/teamsfx : ${LogLevel[logLevel]} - `;
208
+ }
201
209
  const logMessage = `${logHeader}${message}`;
202
210
  if (this.level !== undefined && this.level <= logLevel) {
203
211
  if (this.customLogger) {