@microsoft/teamsfx 0.4.2-alpha.eb4575da.0 → 0.5.1-alpha.3194a88e.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,7 +45,6 @@ Please note that you need to load configuration before using any credentials.
45
45
  loadConfiguration({
46
46
  authentication: {
47
47
  initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL,
48
- simpleAuthEndpoint: process.env.REACT_APP_TEAMSFX_ENDPOINT,
49
48
  clientId: process.env.REACT_APP_CLIENT_ID,
50
49
  },
51
50
  });
@@ -67,7 +66,6 @@ Use the snippet below:
67
66
  loadConfiguration({
68
67
  authentication: {
69
68
  initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL,
70
- simpleAuthEndpoint: process.env.REACT_APP_TEAMSFX_ENDPOINT,
71
69
  clientId: process.env.REACT_APP_CLIENT_ID,
72
70
  },
73
71
  });
@@ -165,7 +163,6 @@ Use `TeamsUserCredential` and `createMicrosoftGraphClient`.
165
163
  loadConfiguration({
166
164
  authentication: {
167
165
  initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL,
168
- simpleAuthEndpoint: process.env.REACT_APP_TEAMSFX_ENDPOINT,
169
166
  clientId: process.env.REACT_APP_CLIENT_ID,
170
167
  },
171
168
  });
@@ -182,7 +179,6 @@ Use `axios` library to make HTTP request to Azure Function.
182
179
  loadConfiguration({
183
180
  authentication: {
184
181
  initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL,
185
- simpleAuthEndpoint: process.env.REACT_APP_TEAMSFX_ENDPOINT,
186
182
  clientId: process.env.REACT_APP_CLIENT_ID,
187
183
  },
188
184
  });
@@ -205,7 +201,10 @@ Apart from `tedious`, you can also compose connection config of other SQL librar
205
201
  ```ts
206
202
  loadConfiguration();
207
203
  const sqlConnectConfig = new DefaultTediousConnectionConfiguration();
204
+ // if there's only one SQL database
208
205
  const config = await sqlConnectConfig.getConfig();
206
+ // if there are multiple SQL databases
207
+ const config2 = await sqlConnectionConfig.getConfig("your database name");
209
208
  const connection = new Connection(config);
210
209
  connection.on("connect", (error) => {
211
210
  if (error) {
@@ -55,6 +55,10 @@ var ErrorCode;
55
55
  * Operation failed.
56
56
  */
57
57
  ErrorCode["FailedOperation"] = "FailedOperation";
58
+ /**
59
+ * Invalid response error.
60
+ */
61
+ ErrorCode["InvalidResponse"] = "InvalidResponse";
58
62
  })(ErrorCode || (ErrorCode = {}));
59
63
  /**
60
64
  * @internal
@@ -600,7 +604,6 @@ class OnBehalfOfUserCredential {
600
604
 
601
605
  // Copyright (c) Microsoft Corporation.
602
606
  const tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
603
- const initializeTeamsSdkTimeoutInMillisecond = 5000;
604
607
  const loginPageWidth = 600;
605
608
  const loginPageHeight = 535;
606
609
  /**
@@ -681,13 +684,29 @@ class TeamsUserCredential {
681
684
  reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
682
685
  return;
683
686
  }
687
+ let resultJson = {};
684
688
  try {
685
- const accessToken = parseAccessTokenFromAuthCodeTokenResponse(result);
686
- resolve(accessToken);
689
+ resultJson = JSON.parse(result);
687
690
  }
688
691
  catch (error) {
689
- reject(error);
692
+ // If can not parse result as Json, will throw error.
693
+ const failedToParseResult = "Failed to parse response to Json.";
694
+ internalLogger.error(failedToParseResult);
695
+ reject(new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse));
696
+ }
697
+ // If code exists in result, user may using previous auth-start and auth-end page.
698
+ if (resultJson.code) {
699
+ const helpLink = "https://aka.ms/teamsfx-auth-code-flow";
700
+ const usingPreviousAuthPage = "Found auth code in response. Auth code is not support for current version of SDK. " +
701
+ `Please refer to the help link for how to fix the issue: ${helpLink}.`;
702
+ internalLogger.error(usingPreviousAuthPage);
703
+ reject(new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse));
704
+ }
705
+ // If sessionStorage exists in result, set the values in current session storage.
706
+ if (resultJson.sessionStorage) {
707
+ this.setSessionStorage(resultJson.sessionStorage);
690
708
  }
709
+ resolve();
691
710
  },
692
711
  failureCallback: (reason) => {
693
712
  const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${reason}`;
@@ -838,47 +857,44 @@ class TeamsUserCredential {
838
857
  return;
839
858
  }
840
859
  }
841
- let initialized = false;
842
- microsoftTeams.initialize(() => {
843
- initialized = true;
844
- microsoftTeams.authentication.getAuthToken({
845
- successCallback: (token) => {
846
- if (!token) {
847
- const errorMsg = "Get empty SSO token from Teams";
848
- internalLogger.error(errorMsg);
849
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
850
- return;
851
- }
852
- const tokenObject = parseJwt(token);
853
- if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
854
- const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
860
+ if (this.checkInTeams()) {
861
+ microsoftTeams.initialize(() => {
862
+ microsoftTeams.authentication.getAuthToken({
863
+ successCallback: (token) => {
864
+ if (!token) {
865
+ const errorMsg = "Get empty SSO token from Teams";
866
+ internalLogger.error(errorMsg);
867
+ reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
868
+ return;
869
+ }
870
+ const tokenObject = parseJwt(token);
871
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
872
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
873
+ internalLogger.error(errorMsg);
874
+ reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
875
+ return;
876
+ }
877
+ const ssoToken = {
878
+ token,
879
+ expiresOnTimestamp: tokenObject.exp * 1000,
880
+ };
881
+ this.ssoToken = ssoToken;
882
+ resolve(ssoToken);
883
+ },
884
+ failureCallback: (errMessage) => {
885
+ const errorMsg = "Get SSO token failed with error: " + errMessage;
855
886
  internalLogger.error(errorMsg);
856
887
  reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
857
- return;
858
- }
859
- const ssoToken = {
860
- token,
861
- expiresOnTimestamp: tokenObject.exp * 1000,
862
- };
863
- this.ssoToken = ssoToken;
864
- resolve(ssoToken);
865
- },
866
- failureCallback: (errMessage) => {
867
- const errorMsg = "Get SSO token failed with error: " + errMessage;
868
- internalLogger.error(errorMsg);
869
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
870
- },
871
- resources: [],
888
+ },
889
+ resources: [],
890
+ });
872
891
  });
873
- });
874
- // If the code not running in Teams, the initialize callback function would never trigger
875
- setTimeout(() => {
876
- if (!initialized) {
877
- const errorMsg = "Initialize teams sdk timeout, maybe the code is not running inside Teams";
878
- internalLogger.error(errorMsg);
879
- reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
880
- }
881
- }, initializeTeamsSdkTimeoutInMillisecond);
892
+ }
893
+ else {
894
+ const errorMsg = "Initialize teams sdk failed due to not running inside Teams";
895
+ internalLogger.error(errorMsg);
896
+ reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
897
+ }
882
898
  });
883
899
  }
884
900
  /**
@@ -906,6 +922,31 @@ class TeamsUserCredential {
906
922
  internalLogger.error(errorMsg);
907
923
  throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
908
924
  }
925
+ setSessionStorage(sessionStorageValues) {
926
+ try {
927
+ const sessionStorageKeys = Object.keys(sessionStorageValues);
928
+ sessionStorageKeys.forEach((key) => {
929
+ sessionStorage.setItem(key, sessionStorageValues[key]);
930
+ });
931
+ }
932
+ catch (error) {
933
+ // Values in result.sessionStorage can not be set into session storage.
934
+ // Throw error since this may block user.
935
+ const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;
936
+ internalLogger.error(errorMessage);
937
+ throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
938
+ }
939
+ }
940
+ // Come from here: https://github.com/wictorwilen/msteams-react-base-component/blob/master/src/useTeams.ts
941
+ checkInTeams() {
942
+ if ((window.parent === window.self && window.nativeInterface) ||
943
+ window.navigator.userAgent.includes("Teams/") ||
944
+ window.name === "embedded-page-container" ||
945
+ window.name === "extension-tab-frame") {
946
+ return true;
947
+ }
948
+ return false;
949
+ }
909
950
  }
910
951
 
911
952
  // Copyright (c) Microsoft Corporation.
@@ -1047,7 +1088,7 @@ class DefaultTediousConnectionConfiguration {
1047
1088
  * Only works in in server side.
1048
1089
  * @beta
1049
1090
  */
1050
- async getConfig() {
1091
+ async getConfig(databaseName) {
1051
1092
  throw new ErrorWithCode(formatString(ErrorMessage.BrowserRuntimeNotSupported, "DefaultTediousConnectionConfiguration"), ErrorCode.RuntimeNotSupported);
1052
1093
  }
1053
1094
  }
@@ -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/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,CAA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ACH;;;;;;;;;;;;;;;;;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 * Invalid response error.\n */\n InvalidResponse = \"InvalidResponse\",\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 formatString,\n getTenantIdAndLoginHintFromSsoToken,\n parseAccessTokenFromAuthCodeTokenResponse,\n} from \"../util/utils\";\nimport { internalLogger } from \"../util/logger\";\nimport { PublicClientApplication } from \"@azure/msal-browser\";\n\nconst tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;\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<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 if (!this.initialized) {\n await this.init();\n }\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)}&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 let resultJson: any = {};\n try {\n resultJson = JSON.parse(result);\n } catch (error) {\n // If can not parse result as Json, will throw error.\n const failedToParseResult = \"Failed to parse response to Json.\";\n internalLogger.error(failedToParseResult);\n reject(new ErrorWithCode(failedToParseResult, ErrorCode.InvalidResponse));\n }\n\n // If code exists in result, user may using previous auth-start and auth-end page.\n if (resultJson.code) {\n const helpLink = \"https://aka.ms/teamsfx-auth-code-flow\";\n const usingPreviousAuthPage =\n \"Found auth code in response. Auth code is not support for current version of SDK. \" +\n `Please refer to the help link for how to fix the issue: ${helpLink}.`;\n internalLogger.error(usingPreviousAuthPage);\n reject(new ErrorWithCode(usingPreviousAuthPage, ErrorCode.InvalidResponse));\n }\n\n // If sessionStorage exists in result, set the values in current session storage.\n if (resultJson.sessionStorage) {\n this.setSessionStorage(resultJson.sessionStorage);\n }\n\n resolve();\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 if (this.checkInTeams()) {\n microsoftTeams.initialize(() => {\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 =\n \"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 } else {\n const errorMsg = \"Initialize teams sdk failed due to not running inside Teams\";\n internalLogger.error(errorMsg);\n reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));\n }\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 private setSessionStorage(sessionStorageValues: any): void {\n try {\n const sessionStorageKeys = Object.keys(sessionStorageValues);\n sessionStorageKeys.forEach((key) => {\n sessionStorage.setItem(key, sessionStorageValues[key]);\n });\n } catch (error: any) {\n // Values in result.sessionStorage can not be set into session storage.\n // Throw error since this may block user.\n const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;\n internalLogger.error(errorMessage);\n throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);\n }\n }\n\n // Come from here: https://github.com/wictorwilen/msteams-react-base-component/blob/master/src/useTeams.ts\n private checkInTeams(): boolean {\n if (\n (window.parent === window.self && (window as any).nativeInterface) ||\n window.navigator.userAgent.includes(\"Teams/\") ||\n window.name === \"embedded-page-container\" ||\n window.name === \"extension-tab-frame\"\n ) {\n return true;\n }\n return false;\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(databaseName?: string): 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;;;;IAK7C,sDAAyC,CAAA;;;;IAKzC,4CAA+B,CAAA;;;;IAK/B,wDAA2C,CAAA;;;;IAK3C,wDAA2C,CAAA;;;;IAK3C,4CAA+B,CAAA;;;;IAK/B,gDAAmC,CAAA;;;;IAKnC,oDAAuC,CAAA;;;;IAKvC,0CAA6B,CAAA;;;;IAK7B,gDAAmC,CAAA;;;;IAKnC,gDAAmC,CAAA;AACrC,CAAC,EA5DW,SAAS,KAAT,SAAS,QA4DpB;AAED;;;MAGa,YAAY;;AACvB;AACgB,iCAAoB,GAAG,uCAAuC,CAAC;AAC/D,mCAAsB,GAAG,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