import { AccessToken } from '@azure/identity'; import { AuthenticationProvider } from '@microsoft/microsoft-graph-client'; import { Client } from '@microsoft/microsoft-graph-client'; import { ConnectionConfig } from 'tedious'; import { Dialog } from 'botbuilder-dialogs'; import { DialogContext } from 'botbuilder-dialogs'; import { DialogTurnResult } from 'botbuilder-dialogs'; import { GetTokenOptions } from '@azure/identity'; import { TokenCredential } from '@azure/identity'; import { TokenResponse } from 'botframework-schema'; /** * Authentication related configuration. * @beta */ export declare interface AuthenticationConfiguration { /** * Hostname of AAD authority. Default value comes from M365_AUTHORITY_HOST environment variable. * * @readonly */ readonly authorityHost?: string; /** * AAD tenant id, default value comes from M365_TENANT_ID environment variable. * * @readonly */ readonly tenantId?: string; /** * The client (application) ID of an App Registration in the tenant, default value comes from M365_CLIENT_ID environment variable * * @readonly */ readonly clientId?: string; /** * 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 * * @readonly */ readonly clientSecret?: string; /** * Endpoint of auth service provisioned by Teams App Framework toolkit. Default value comes from SIMPLE_AUTH_ENDPOINT environment variable. * * @readonly */ readonly simpleAuthEndpoint?: string; /** * Login page for Teams to redirect to. Default value comes from INITIATE_LOGIN_ENDPOINT environment variable. * * @readonly */ readonly initiateLoginEndpoint?: string; /** * Application ID URI. Default value comes from M365_APPLICATION_ID_URI environment variable. */ readonly applicationIdUri?: string; } /** * configuration for current environment. * @beta */ export declare interface Configuration { /** * Authentication related configuration. * * @readonly */ readonly authentication?: AuthenticationConfiguration; /** * Configuration for resources. * * @readonly */ readonly resources?: ResourceConfiguration[]; } /** * Get Microsoft graph client, will throw {@link ErrorWithCode} if get GraphClient failed. * * @example * Get Microsoft graph client by TokenCredential * ```typescript * // Sso token example (Azure Function) * const ssoToken = "YOUR_TOKEN_STRING"; * const options = {"AAD_APP_ID", "AAD_APP_SECRET"}; * const credential = new OnBehalfOfAADUserCredential(ssoToken, options); * const graphClient = await createMicrosoftGraphClient(credential); * const profile = await graphClient.api("/me").get(); * * // TeamsBotSsoPrompt example (Bot Application) * const requiredScopes = ["User.Read"]; * const config: Configuration = { * loginUrl: loginUrl, * clientId: clientId, * clientSecret: clientSecret, * tenantId: tenantId * }; * const prompt = new TeamsBotSsoPrompt(dialogId, { * config: config * scopes: '["User.Read"], * }); * this.addDialog(prompt); * * const oboCredential = new OnBehalfOfAADUserCredential( * getUserId(dialogContext), * { * clientId: "AAD_APP_ID", * clientSecret: "AAD_APP_SECRET" * }); * try { * const graphClient = await createMicrosoftGraphClient(credential); * const profile = await graphClient.api("/me").get(); * } catch (e) { * dialogContext.beginDialog(dialogId); * return Dialog.endOfTurn(); * } * ``` * * @param {TokenCredential} credential - token credential instance * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`. * * @returns Graph client with specified access. * * @beta */ export declare function createMicrosoftGraphClient(credential: TokenCredential, scopes?: string | string[]): Client; /** * SQL connection configuration instance. * * @beta * */ export declare class DefaultTediousConnectionConfiguration { /** * MSSQL default scope * https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi */ private readonly defaultSQLScope; /** * Generate connection configuration consumed by tedious. * * @beta * @returns return configuration items to the user for tedious to connection to the SQL. * @throws {InvalidConfiguration} if sql config resource configuration is invalid */ getConfig(): Promise; /** * Check SQL use MSI identity or username and password. * * @returns { boolean } false - login with SQL MSI identity, true - login with username and password. * @internal */ private isMsiAuthentication; /** * check configuration is an available configurations. * @param { SqlConfiguration } sqlConfig * * @returns {boolean} true - sql configuration has a valid SQL endpoints, SQL username with password or identity ID. * false - configuration is not valid. * @internal */ private isSQLConfigurationValid; /** * Generate tedious connection configuration with default authentication type. * * @param { SqlConfiguration } sqlConfig sql configuration with username and password. * * @returns tedious connection configuration with username and password. * @internal */ private generateDefaultConfig; /** * Generate tedious connection configuration with azure-active-directory-access-token authentication type. * * @param { SqlConfiguration } sqlConfig sql configuration with AAD access token. * * @returns tedious connection configuration with access token. * @internal */ private generateTokenConfig; } /** * Error code to help debugging. * @beta */ export declare enum ErrorCode { /** * Invalid parameter error. */ InvalidParameter = "InvalidParameter", /** * Invalid configuration. */ InvalidConfiguration = "InvalidConfiguration", /** * Internal error. */ InternalError = "InternalError", /** * Channel is not supported error. */ ChannelNotSupported = "ChannelNotSupported", /** * Runtime is not supported. */ RuntimeNotSupported = "RuntimeNotSupported", /** * User failed to finish the AAD consent flow. */ ConsentFailed = "ConsentFailed", /** * The user or administrator has not consented to use the application. */ UiRequiredError = "UiRequiredError", /** * Token is not within its valid time range. */ TokenExpiredError = "TokenExpiredError", /** * Call service (AAD or simple authentication server) failed */ ServiceError = "ServiceError", /** * operation failed error. */ FailedOperation = "FailedOperation" } /** * Error class with code and message thrown by the SDK library. * * @beta */ export declare class ErrorWithCode extends Error { /** * error code * * @readonly */ code: string | undefined; /** * Constructor of ErrorWithCode * * @param {string} message - error message * @param {ErrorCode} code - error code */ constructor(message?: string, code?: ErrorCode); } /** * Gets configuration for authentication. * * @beta * * @returns AuthenticationConfiguration from global configuration instance, the value may be undefined if no authentication config exists in current environment. * @throws {InvalidConfiguration} if global configuration does not exist */ export declare function getAuthenticationConfiguration(): AuthenticationConfiguration | undefined; /** * Get log level. * * @returns log level * * @beta */ export declare function getLogLevel(): LogLevel; /** * Gets configuration for a specific resource. * * @beta * * @param {ResourceType} resourceType - The type of resource * @param {string} resourceName - The name of resource, default value is "default". * * @returns ResourceConfiguration for target resource from global configuration instance. * @throws {InvalidConfiguration} if resource configuration with the specific type and name is not found */ export declare function getResourceConfiguration(resourceType: ResourceType, resourceName?: string): { [index: string]: any; }; export { GetTokenOptions } /** * Initialize configuration from environment variables and set the global instance * * @beta * * @param {Configuration} configuration - Optional configuration that overrides the default configuration values. The override depth is 1. * @throws {InvalidParameter} if configuration is not passed in when in browser environment */ export declare function loadConfiguration(configuration?: Configuration): void; /** * Log function for customized logging. */ export declare type LogFunction = (level: LogLevel, message: string) => void; /** * Interface for customized logger. * @beta */ export declare interface Logger { /** * Writes to error level logging or lower. */ error(message: string): void; /** * Writes to warning level logging or lower. */ warn(message: string): void; /** * Writes to info level logging or lower. */ info(message: string): void; /** * Writes to verbose level logging. */ verbose(message: string): void; } /** * logging level. * * @beta */ export declare enum LogLevel { /** * Show verbose, information, warning and error message. */ Verbose = 0, /** * Show information, warning and error message. */ Info = 1, /** * Show warning and error message. */ Warn = 2, /** * Show error message. */ Error = 3 } /** * Used when user is not involved. * * @remarks * Can only be used in server side code. * * @beta */ export declare class M365TenantCredential implements TokenCredential { private readonly clientSecretCredential; /** * Constructor of ApplicationCredential * * @throws {InvalidConfiguration} */ constructor(); /** * Get access token for credential * * @param {string | string[]} scopes - The list of scopes for which the token will have access. Should in the format of {resource uri}/.default. * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make. * * @throws {ServiceError} * @throws {InternalError} */ getToken(scopes: string | string[], options?: GetTokenOptions): Promise; /** * Load and validate authentication configuration * @returns Authentication configuration */ private loadAndValidateConfig; } /** * Microsoft Graph auth provider for Teams App Framework * * @beta */ export declare class MsGraphAuthProvider implements AuthenticationProvider { private credential; private scopes; /** * Constructor * * @param {TokenCredential} credential - Credential used to invoke Microsoft Graph APIs. * @param {string | string[]} scopes - Required scope in token when invoking Microsoft Graph APIs. * * @returns An instance of MsGraphAuthProvider. * * @beta */ constructor(credential: TokenCredential, scopes?: string | string[]); /** * Get access token for Microsoft Graph API requests * * @returns access token from the credential * */ getAccessToken(): Promise; } /** * Exchange access token using the OBO flow with SSO token. * * @remarks * Can only be used in server side. * * @beta */ export declare class OnBehalfOfUserCredential implements TokenCredential { private msalClient; private ssoToken; /** * Constructor of OnBehalfOfUserCredential * * @param {string} ssoToken - User token provided by Teams SSO feature. * @throws {InvalidConfiguration} if client id, client secret or authority host is not found in config. * */ constructor(ssoToken: string); /** * Get access token from credential * * @example * ```typescript * await credential.getToken([]) // Get user single sign-on token * await credential.getToken("") // Get user single sign-on token * await credential.getToken(["User.Read"]) // Get Graph access token * await credential.getToken("User.Read") // Get Graph access token * await credential.getToken(["User.Read", "Application.Read.All"]) // Get Graph access token for multiple scopes * await credential.getToken("User.Read Application.Read.All") // Get Graph access token for multiple scopes. Scopes is split by space in one string * ``` * @param {string | string[]} scopes - The list of scopes for which the token will have access. * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make. * @returns {AccessToken} Return access token with expected scopes. * Return SSO token if scopes is empty string or empty array. * * @throws {InternalError} if fail to acquire access token on behalf of user * * @remarks * If error occurs during OBO flow, it will throw exception. * * @beta */ getToken(scopes: string | string[], options?: GetTokenOptions): Promise; /** * Get the user info from access token, will throw {@link ErrorWithCode} if token is invalid. * * @example * ```typescript * const currentUser = await credential.getUserInfo(); * ``` * * @returns Return UserInfo for current user. * */ getUserInfo(): Promise; private generateAuthServerError; } /** * Configuration for resources. * @beta */ export declare interface ResourceConfiguration { /** * Resource type. * * @readonly */ readonly type: ResourceType; /** * Resource name. * * @readonly */ readonly name: string; /** * Config for the resource. * * @readonly */ readonly properties: { [index: string]: any; }; } /** * Available resource type. * @beta */ export declare enum ResourceType { /** * SQL database. * */ SQL = 0, /** * Rest API. * */ API = 1 } /** * Update custom log function. Use the function if it's set. Priority is lower than setLogger. * * @param {LogFunction} logFunction - custom log function. If it's undefined, custom log function will be cleared. * * @beta */ export declare function setLogFunction(logFunction?: LogFunction): void; /** * Update custom logger. Use the output function if it's set. Priority is higher than setLogFunction. * * @param {Logger} logger - custom logger. If it's undefined, custom logger will be cleared. * * @beta */ export declare function setLogger(logger?: Logger): void; /** * Update log level helper. * * @param { LogLevel } level - log level in configuration * * @beta */ export declare function setLogLevel(level: LogLevel): void; /** * Creates a new prompt that leverage Teams Single Sign On (SSO) support for bot to automatically sign in user and * help rechieve oauth token, asks the user to consent if needed. * * @remarks * The prompt will attempt to retrieve the users current token of the desired scopes and store it in * the token store. * * User will be automatically signed in leveraging Teams support of Bot Single Sign On(SSO): * https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots * * @example * When used with your bots `DialogSet` you can simply add a new instance of the prompt as a named * dialog using `DialogSet.add()`. You can then start the prompt from a waterfall step using either * `DialogContext.beginDialog()` or `DialogContext.prompt()`. The user will be prompted to signin as * needed and their access token will be passed as an argument to the callers next waterfall step: * * ```JavaScript * const { ConversationState, MemoryStorage } = require('botbuilder'); * const { DialogSet, WaterfallDialog } = require('botbuilder-dialogs'); * const { TeamsBotSsoPrompt } = require('@microsoft/teamsfx'); * * const convoState = new ConversationState(new MemoryStorage()); * const dialogState = convoState.createProperty('dialogState'); * const dialogs = new DialogSet(dialogState); * * loadConfiguration(); * dialogs.add(new TeamsBotSsoPrompt('TeamsBotSsoPrompt', { * scopes: ["User.Read"], * })); * * dialogs.add(new WaterfallDialog('taskNeedingLogin', [ * async (step) => { * return await step.beginDialog('TeamsBotSsoPrompt'); * }, * async (step) => { * const token = step.result; * if (token) { * * // ... continue with task needing access token ... * * } else { * await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`); * return await step.endDialog(); * } * } * ])); * ``` * * @beta */ export declare class TeamsBotSsoPrompt extends Dialog { private settings; /** * Create a new TeamsBotSsoPrompt instance. * * @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`. * @param settings Settings used to configure the prompt. * * @beta */ constructor(dialogId: string, settings: TeamsBotSsoPromptSettings); /** * Called when a prompt dialog is pushed onto the dialog stack and is being activated. * * @param dc The DialogContext for the current turn of the conversation. * @returns A `Promise` representing the asynchronous operation. * @throws {InvalidParameter} if timeout property in teams bot sso prompt settings is not number or is not positive. * @throws {ChannelNotSupported} if bot channel is not MS Teams * * @remarks * If the task is successful, the result indicates whether the prompt is still * active after the turn has been processed by the prompt. * * @beta */ beginDialog(dc: DialogContext): Promise; /** * Called when a prompt dialog is the active dialog and the user replied with a new activity. * @param dc The DialogContext for the current turn of the conversation. * @returns A `Promise` representing the asynchronous operation. * @throws {ChannelNotSupported} if bot channel is not MS Teams * * @remarks * If the task is successful, the result indicates whether the dialog is still * active after the turn has been processed by the dialog. * The prompt generally continues to receive the user's replies until it accepts the * user's reply as valid input for the prompt. * * @beta */ continueDialog(dc: DialogContext): Promise; /** * Ensure bot is running in MS Teams since TeamsBotSsoPrompt is only supported in MS Teams channel. * @param dc dialog context * @throws {ChannelNotSupported} if bot channel is not MS Teams * @internal */ private ensureMsTeamsChannel; /** * Send OAuthCard that tells Teams to obtain an authentication token for the bot application. * For details see https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/auth-aad-sso-bots. * * @internal */ private sendOAuthCardAsync; /** * Get sign in resource. * * @throws {InvalidConfiguration} if client id, tenant id or initiate login endpoint is not found in config. * * @internal */ private getSignInResource; /** * @internal */ private recognizeToken; /** * @internal */ private getTokenExchangeInvokeResponse; /** * @internal */ private isTeamsVerificationInvoke; /** * @internal */ private isTokenExchangeRequestInvoke; /** * @internal */ private isTokenExchangeRequest; } /** * Settings used to configure an TeamsBotSsoPrompt instance. * * @beta */ export declare interface TeamsBotSsoPromptSettings { /** * The array of strings that declare the desired permissions and the resources requested. */ scopes: string[]; /** * (Optional) number of milliseconds the prompt will wait for the user to authenticate. * Defaults to a value `900,000` (15 minutes.) */ timeout?: number; /** * (Optional) value indicating whether the TeamsBotSsoPrompt should end upon receiving an * invalid message. Generally the TeamsBotSsoPrompt will end the auth flow when receives user * message not related to the auth flow. Setting the flag to false ignores the user's message instead. * Defaults to value `true` */ endOnInvalidMessage?: boolean; } /** * Token response provided by Teams Bot SSO prompt * @beta */ export declare interface TeamsBotSsoPromptTokenResponse extends TokenResponse { /** * SSO token for user */ ssoToken: string; /** * Expire time of SSO token */ ssoTokenExpiration: string; } /** * Used within Teams client applications. * * @remarks * User can interactively login and consent within Teams. * * @beta */ export declare class TeamsUserCredential implements TokenCredential { /** * Constructor of TeamsUserCredential * * @param {Configuration} config * @throws {RuntimeNotSupported} if runtime is nodeJS * */ constructor(); /** * Popup login page to get user's access token, will throw {@link ErrorWithCode} if failed. * * @remarks Only works in Teams client app. User will be redirected to the authorization page to login and consent. * * @example * ```typescript * await credential.login(["User.Read"]); * ``` * @param scopes - The array of Microsoft Token scope of access. Default value is `[.default]`. Scopes provide a way to manage permissions to protected resources. * @throws {RuntimeNotSupported} if runtime is nodeJS * */ login(scopes: string | string[]): Promise; /** * Get access token from credential * * @example * ```typescript * await credential.getToken([]) // Get SSO token * await credential.getToken("") // Get SSO token * await credential.getToken(["User.Read"]) // Get Graph access token * await credential.getToken("User.Read") // Get Graph access token * await credential.getToken(["User.Read", "Application.Read.All"]) // Get Graph access token for multiple scopes * await credential.getToken([".default"]) // Get Graph access token with default scope * await credential.getToken(".default") // Get Graph access token with default scope * await credential.getToken(["https://outlook.office.com/mail.read"]) // Get Outlook access token * ``` * * @param {string | string[]} scopes - The list of scopes for which the token will have access. * @param {GetTokenOptions} options - The options used to configure any requests this TokenCredential implementation might make. * * @returns user access token of defined scopes. * If scopes is empty string or array, it returns SSO token. * If scopes is non-empty, it returns access token for target scope. * Throw error if get access token failed. * @throws {RuntimeNotSupported} if runtime is nodeJS * */ getToken(scopes: string | string[], options?: GetTokenOptions): Promise; /** * Get the user info from access token, will throw {@link ErrorWithCode} if token is invalid. * * @example * Get basic user info from SSO token * ```typescript * const currentUser = await credential.getUserInfo(); * ``` * * @returns UserInfo with user displayName, objectId and preferredUserName. * @throws {RuntimeNotSupported} if runtime is nodeJS * */ getUserInfo(): Promise; } export { TokenCredential } /** * UserInfo with user displayName, objectId and preferredUserName. * * @beta */ export declare interface UserInfo { /** * User Display Name. * * @readonly */ displayName: string; /** * User unique reference within the Azure Active Directory domain. * * @readonly */ objectId: string; /** * Usually be the email address. * * @readonly */ preferredUserName: string; } export { }