@microsoft/agents-hosting 0.5.12-g2d752e9b13 → 0.5.16-g6bdf69cc43

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.
Files changed (41) hide show
  1. package/dist/src/app/agentApplication.d.ts +186 -20
  2. package/dist/src/app/agentApplication.js +234 -32
  3. package/dist/src/app/agentApplication.js.map +1 -1
  4. package/dist/src/app/agentApplicationBuilder.d.ts +1 -1
  5. package/dist/src/app/agentApplicationOptions.d.ts +1 -1
  6. package/dist/src/app/appRoute.d.ts +5 -0
  7. package/dist/src/app/authorization.d.ts +293 -0
  8. package/dist/src/app/authorization.js +375 -0
  9. package/dist/src/app/authorization.js.map +1 -0
  10. package/dist/src/app/index.d.ts +1 -1
  11. package/dist/src/app/index.js +1 -1
  12. package/dist/src/app/index.js.map +1 -1
  13. package/dist/src/auth/index.d.ts +1 -0
  14. package/dist/src/auth/index.js +1 -0
  15. package/dist/src/auth/index.js.map +1 -1
  16. package/dist/src/auth/jwt-middleware.js.map +1 -1
  17. package/dist/src/auth/msalTokenCredential.d.ts +10 -0
  18. package/dist/src/auth/msalTokenCredential.js +19 -0
  19. package/dist/src/auth/msalTokenCredential.js.map +1 -0
  20. package/dist/src/auth/msalTokenProvider.d.ts +1 -0
  21. package/dist/src/auth/msalTokenProvider.js +15 -0
  22. package/dist/src/auth/msalTokenProvider.js.map +1 -1
  23. package/dist/src/oauth/oAuthFlow.d.ts +53 -9
  24. package/dist/src/oauth/oAuthFlow.js +164 -35
  25. package/dist/src/oauth/oAuthFlow.js.map +1 -1
  26. package/package.json +4 -3
  27. package/src/app/agentApplication.ts +247 -32
  28. package/src/app/agentApplicationBuilder.ts +1 -1
  29. package/src/app/agentApplicationOptions.ts +1 -1
  30. package/src/app/appRoute.ts +6 -0
  31. package/src/app/authorization.ts +418 -0
  32. package/src/app/index.ts +1 -1
  33. package/src/auth/index.ts +1 -0
  34. package/src/auth/jwt-middleware.ts +1 -1
  35. package/src/auth/msalTokenCredential.ts +14 -0
  36. package/src/auth/msalTokenProvider.ts +17 -1
  37. package/src/oauth/oAuthFlow.ts +196 -34
  38. package/dist/src/app/oauth/authorization.d.ts +0 -88
  39. package/dist/src/app/oauth/authorization.js +0 -134
  40. package/dist/src/app/oauth/authorization.js.map +0 -1
  41. package/src/app/oauth/authorization.ts +0 -160
@@ -0,0 +1,418 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { TurnContext } from '../turnContext'
7
+ import { debug } from '../logger'
8
+ import { TurnState } from './turnState'
9
+ import { Storage } from '../storage'
10
+ import { OAuthFlow, TokenResponse } from '../oauth'
11
+ import { AuthConfiguration, MsalTokenProvider } from '../auth'
12
+ import jwt, { JwtPayload } from 'jsonwebtoken'
13
+ import { Activity } from '@microsoft/agents-activity'
14
+
15
+ const logger = debug('agents:authorization')
16
+
17
+ /**
18
+ * Interface representing the state of a sign-in process.
19
+ * @interface SignInState
20
+ */
21
+ export interface SignInState {
22
+ /** Optional activity to continue with after sign-in completion. */
23
+ continuationActivity?: Activity,
24
+ /** Identifier of the auth handler being used. */
25
+ handlerId?: string,
26
+ /** Whether the sign-in process has been completed. */
27
+ completed?: boolean
28
+ }
29
+
30
+ /**
31
+ * Interface defining an authorization handler for OAuth flows.
32
+ * @interface AuthHandler
33
+ */
34
+ export interface AuthHandler {
35
+ /** Connection name for the auth provider. */
36
+ name?: string,
37
+ /** The OAuth flow implementation. */
38
+ flow?: OAuthFlow,
39
+ /** Title to display on auth cards/UI. */
40
+ title?: string,
41
+ /** Text to display on auth cards/UI. */
42
+ text?: string,
43
+ }
44
+
45
+ /**
46
+ * Options for configuring user authorization.
47
+ * Contains settings to configure OAuth connections.
48
+ * @interface AuthorizationHandlers
49
+ */
50
+ export interface AuthorizationHandlers extends Record<string, AuthHandler> {}
51
+
52
+ /**
53
+ * Class responsible for managing authorization and OAuth flows.
54
+ * Handles multiple OAuth providers and manages the complete authentication lifecycle.
55
+ *
56
+ * @remarks
57
+ * The Authorization class provides a centralized way to handle OAuth authentication
58
+ * flows within the agent application. It supports multiple authentication handlers,
59
+ * token exchange, on-behalf-of flows, and provides event handlers for success/failure scenarios.
60
+ *
61
+ * Key features:
62
+ * - Multiple OAuth provider support
63
+ * - Token caching and exchange
64
+ * - On-behalf-of (OBO) token flows
65
+ * - Sign-in success/failure event handling
66
+ * - Automatic configuration from environment variables
67
+ *
68
+ * Example usage:
69
+ * ```typescript
70
+ * const auth = new Authorization(storage, {
71
+ * 'microsoft': {
72
+ * name: 'Microsoft',
73
+ * title: 'Sign in with Microsoft',
74
+ * text: 'Please sign in'
75
+ * }
76
+ * });
77
+ *
78
+ * auth.onSignInSuccess(async (context, state) => {
79
+ * await context.sendActivity('Welcome! You are now signed in.');
80
+ * });
81
+ * ```
82
+ */
83
+ export class Authorization {
84
+ /**
85
+ * Dictionary of configured authentication handlers.
86
+ * @public
87
+ */
88
+ authHandlers: AuthorizationHandlers
89
+
90
+ /**
91
+ * Creates a new instance of Authorization.
92
+ *
93
+ * @param storage - The storage system to use for state management.
94
+ * @param authHandlers - Configuration for OAuth providers.
95
+ * @throws {Error} If storage is null/undefined or no auth handlers are provided.
96
+ *
97
+ * @remarks
98
+ * The constructor initializes all configured auth handlers and sets up OAuth flows.
99
+ * It automatically configures handler properties from environment variables if not provided:
100
+ * - Connection name: {handlerId}_connectionName
101
+ * - Connection title: {handlerId}_connectionTitle
102
+ * - Connection text: {handlerId}_connectionText
103
+ *
104
+ * Example usage:
105
+ * ```typescript
106
+ * const auth = new Authorization(storage, {
107
+ * 'microsoft': {
108
+ * name: 'Microsoft',
109
+ * title: 'Sign in with Microsoft'
110
+ * },
111
+ * 'google': {
112
+ * // Will use GOOGLE_connectionName from env vars
113
+ * }
114
+ * });
115
+ * ```
116
+ */
117
+ constructor (private storage: Storage, authHandlers: AuthorizationHandlers) {
118
+ if (storage === undefined || storage === null) {
119
+ throw new Error('Storage is required for UserAuthorization')
120
+ }
121
+ if (authHandlers === undefined || Object.keys(authHandlers).length === 0) {
122
+ throw new Error('The authorization does not have any auth handlers')
123
+ }
124
+ this.authHandlers = authHandlers
125
+ for (const ah in this.authHandlers) {
126
+ if (this.authHandlers![ah].name === undefined && process.env[ah + '_connectionName'] === undefined) {
127
+ throw new Error(`AuthHandler name ${ah}_connectionName not set in autorization and not found in env vars.`)
128
+ }
129
+ const currentAuthHandler = this.authHandlers![ah]
130
+ currentAuthHandler.name = currentAuthHandler.name ?? process.env[ah + '_connectionName'] as string
131
+ currentAuthHandler.title = currentAuthHandler.title ?? process.env[ah + '_connectionTitle'] as string
132
+ currentAuthHandler.text = currentAuthHandler.text ?? process.env[ah + '_connectionText'] as string
133
+ currentAuthHandler.flow = new OAuthFlow(this.storage, currentAuthHandler.name, null!, currentAuthHandler.title, currentAuthHandler.text)
134
+ }
135
+ logger.info('Authorization handlers configured with', Object.keys(this.authHandlers).length, 'handlers')
136
+ }
137
+
138
+ /**
139
+ * Gets the token for a specific auth handler.
140
+ *
141
+ * @param context - The context object for the current turn.
142
+ * @param authHandlerId - ID of the auth handler to use.
143
+ * @returns A promise that resolves to the token response from the OAuth provider.
144
+ * @throws {Error} If the auth handler is not configured.
145
+ * @public
146
+ *
147
+ * @remarks
148
+ * This method retrieves an existing token for the specified auth handler.
149
+ * The token may be cached and will be retrieved from the OAuth provider if needed.
150
+ *
151
+ * Example usage:
152
+ * ```typescript
153
+ * const tokenResponse = await auth.getToken(context, 'microsoft');
154
+ * if (tokenResponse.token) {
155
+ * console.log('User is authenticated');
156
+ * }
157
+ * ```
158
+ */
159
+ public async getToken (context: TurnContext, authHandlerId: string): Promise<TokenResponse> {
160
+ logger.info('getToken from user token service for authHandlerId:', authHandlerId)
161
+ const authHandler = this.getAuthHandlerOrThrow(authHandlerId)
162
+ return await authHandler.flow?.getUserToken(context)!
163
+ }
164
+
165
+ /**
166
+ * Gets the auth handler by ID or throws an error if not found.
167
+ *
168
+ * @param authHandlerId - ID of the auth handler to retrieve.
169
+ * @returns The auth handler instance.
170
+ * @throws {Error} If the auth handler with the specified ID is not configured.
171
+ * @private
172
+ */
173
+ private getAuthHandlerOrThrow (authHandlerId: string): AuthHandler {
174
+ if (!Object.prototype.hasOwnProperty.call(this.authHandlers, authHandlerId)) {
175
+ throw new Error(`AuthHandler with ID ${authHandlerId} not configured`)
176
+ }
177
+ return this.authHandlers[authHandlerId]
178
+ }
179
+
180
+ /**
181
+ * Exchanges a token for a new token with different scopes.
182
+ *
183
+ * @param context - The context object for the current turn.
184
+ * @param scopes - Array of scopes to request for the new token.
185
+ * @param authHandlerId - ID of the auth handler to use.
186
+ * @returns A promise that resolves to the exchanged token response.
187
+ * @throws {Error} If the auth handler is not configured.
188
+ * @public
189
+ *
190
+ * @remarks
191
+ * This method handles token exchange scenarios, particularly for on-behalf-of (OBO) flows.
192
+ * It checks if the current token is exchangeable (e.g., has audience starting with 'api://')
193
+ * and performs the appropriate token exchange using MSAL.
194
+ *
195
+ * Example usage:
196
+ * ```typescript
197
+ * const exchangedToken = await auth.exchangeToken(
198
+ * context,
199
+ * ['https://graph.microsoft.com/.default'],
200
+ * 'microsoft'
201
+ * );
202
+ * ```
203
+ */
204
+ public async exchangeToken (context: TurnContext, scopes: string[], authHandlerId: string): Promise<TokenResponse> {
205
+ logger.info('getToken from user token service for authHandlerId:', authHandlerId)
206
+ const authHandler = this.getAuthHandlerOrThrow(authHandlerId)
207
+ const tokenResponse = await authHandler.flow?.getUserToken(context)!
208
+ if (this.isExchangeable(tokenResponse.token)) {
209
+ return await this.handleObo(context, tokenResponse.token!, scopes)
210
+ }
211
+ return tokenResponse
212
+ }
213
+
214
+ /**
215
+ * Checks if a token is exchangeable for an on-behalf-of flow.
216
+ *
217
+ * @param token - The token to check.
218
+ * @returns True if the token is exchangeable, false otherwise.
219
+ * @private
220
+ */
221
+ private isExchangeable (token: string | undefined): boolean {
222
+ if (!token || typeof token !== 'string') {
223
+ return false
224
+ }
225
+ const payload = jwt.decode(token) as JwtPayload
226
+ return payload?.aud?.indexOf('api://') === 0
227
+ }
228
+
229
+ /**
230
+ * Handles on-behalf-of token exchange using MSAL.
231
+ *
232
+ * @param context - The context object for the current turn.
233
+ * @param token - The token to exchange.
234
+ * @param scopes - Array of scopes to request for the new token.
235
+ * @returns A promise that resolves to the exchanged token response.
236
+ * @private
237
+ */
238
+ private async handleObo (context: TurnContext, token: string, scopes: string[]): Promise<TokenResponse> {
239
+ const msalTokenProvider = new MsalTokenProvider()
240
+ const authConfig: AuthConfiguration = context.adapter.authConfig
241
+ const newToken = await msalTokenProvider.acquireTokenOnBehalfOf(authConfig, scopes, token)
242
+ return { token: newToken }
243
+ }
244
+
245
+ /**
246
+ * Begins or continues an OAuth flow.
247
+ *
248
+ * @param context - The context object for the current turn.
249
+ * @param state - The state object for the current turn.
250
+ * @param authHandlerId - ID of the auth handler to use.
251
+ * @returns A promise that resolves to the token response from the OAuth provider.
252
+ * @throws {Error} If the auth handler is not configured.
253
+ * @public
254
+ *
255
+ * @remarks
256
+ * This method manages the complete OAuth authentication flow:
257
+ * - If no flow is active, it begins a new OAuth flow and shows the sign-in card
258
+ * - If a flow is active, it continues the flow and processes the authentication response
259
+ * - Handles success/failure callbacks and updates the sign-in state accordingly
260
+ *
261
+ * The method automatically manages the sign-in state and continuation activities,
262
+ * allowing the conversation to resume after successful authentication.
263
+ *
264
+ * Example usage:
265
+ * ```typescript
266
+ * const tokenResponse = await auth.beginOrContinueFlow(context, state, 'microsoft');
267
+ * if (tokenResponse && tokenResponse.token) {
268
+ * // User is now authenticated
269
+ * await context.sendActivity('Authentication successful!');
270
+ * }
271
+ * ```
272
+ */
273
+ public async beginOrContinueFlow (context: TurnContext, state: TurnState, authHandlerId: string, secRoute: boolean = true) : Promise<TokenResponse> {
274
+ const authHandler = this.getAuthHandlerOrThrow(authHandlerId)
275
+ logger.info('beginOrContinueFlow for authHandlerId:', authHandlerId)
276
+ const signInState: SignInState | undefined = state.getValue('user.__SIGNIN_STATE_') || { continuationActivity: undefined, handlerId: undefined, completed: false }
277
+ const flow = authHandler.flow!
278
+ let tokenResponse: TokenResponse | undefined
279
+ tokenResponse = await authHandler.flow?.getUserToken(context)
280
+
281
+ if (tokenResponse?.token && tokenResponse.token.length > 0) {
282
+ delete authHandler.flow?.state.eTag
283
+ authHandler.flow!.state.flowStarted = false
284
+ await authHandler.flow?.setFlowState(context, authHandler.flow.state)
285
+ if (secRoute) {
286
+ return tokenResponse!
287
+ }
288
+ }
289
+
290
+ if (flow.state === null || flow.state?.flowStarted === false || flow.state?.flowStarted === undefined) {
291
+ tokenResponse = await flow.beginFlow(context)
292
+ if (secRoute && tokenResponse?.token === undefined) {
293
+ signInState!.continuationActivity = context.activity
294
+ signInState!.handlerId = authHandlerId
295
+ state.setValue('user.__SIGNIN_STATE_', signInState)
296
+ }
297
+ } else {
298
+ tokenResponse = await flow.continueFlow(context)
299
+ if (tokenResponse && tokenResponse.token) {
300
+ if (this._signInSuccessHandler) {
301
+ await this._signInSuccessHandler(context, state, authHandlerId)
302
+ }
303
+ if (secRoute) {
304
+ state.deleteValue('user.__SIGNIN_STATE_')
305
+ }
306
+ } else {
307
+ logger.warn('Failed to complete OAuth flow, no token received')
308
+ if (this._signInFailureHandler) {
309
+ await this._signInFailureHandler(context, state, authHandlerId, 'Failed to complete the OAuth flow')
310
+ }
311
+ // signInState!.completed = false
312
+ // state.setValue('user.__SIGNIN_STATE_', signInState)
313
+ }
314
+ }
315
+ return tokenResponse!
316
+ }
317
+
318
+ /**
319
+ * Signs out the current user.
320
+ *
321
+ * @param context - The context object for the current turn.
322
+ * @param state - The state object for the current turn.
323
+ * @param authHandlerId - Optional ID of the auth handler to use for sign out. If not provided, signs out from all handlers.
324
+ * @returns A promise that resolves when sign out is complete.
325
+ * @throws {Error} If the specified auth handler is not configured.
326
+ * @public
327
+ *
328
+ * @remarks
329
+ * This method clears the user's token and resets the authentication state.
330
+ * If no specific authHandlerId is provided, it signs out from all configured handlers.
331
+ * This ensures complete cleanup of authentication state across all providers.
332
+ *
333
+ * Example usage:
334
+ * ```typescript
335
+ * // Sign out from specific handler
336
+ * await auth.signOut(context, state, 'microsoft');
337
+ *
338
+ * // Sign out from all handlers
339
+ * await auth.signOut(context, state);
340
+ * ```
341
+ */
342
+ async signOut (context: TurnContext, state: TurnState, authHandlerId?: string) : Promise<void> {
343
+ logger.info('signOut for authHandlerId:', authHandlerId)
344
+ if (authHandlerId === undefined) { // aw
345
+ for (const ah in this.authHandlers) {
346
+ const flow = this.authHandlers[ah].flow
347
+ await flow?.signOut(context)
348
+ }
349
+ } else {
350
+ const authHandler = this.getAuthHandlerOrThrow(authHandlerId)
351
+ await authHandler.flow?.signOut(context)
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Private handler for successful sign-in events.
357
+ * @private
358
+ */
359
+ _signInSuccessHandler: ((context: TurnContext, state: TurnState, authHandlerId?: string) => Promise<void>) | null = null
360
+
361
+ /**
362
+ * Sets a handler to be called when sign-in is successfully completed.
363
+ *
364
+ * @param handler - The handler function to call on successful sign-in.
365
+ * @public
366
+ *
367
+ * @remarks
368
+ * This method allows you to register a callback that will be invoked whenever
369
+ * a user successfully completes the authentication process. The handler receives
370
+ * the turn context, state, and the ID of the auth handler that was used.
371
+ *
372
+ * Example usage:
373
+ * ```typescript
374
+ * auth.onSignInSuccess(async (context, state, authHandlerId) => {
375
+ * await context.sendActivity(`Welcome! You signed in using ${authHandlerId}.`);
376
+ * // Perform any post-authentication setup
377
+ * });
378
+ * ```
379
+ */
380
+ public onSignInSuccess (handler: (context: TurnContext, state: TurnState, authHandlerId?: string) => Promise<void>) {
381
+ this._signInSuccessHandler = handler
382
+ }
383
+
384
+ /**
385
+ * Private handler for failed sign-in events.
386
+ * @private
387
+ */
388
+ _signInFailureHandler: ((context: TurnContext, state: TurnState, authHandlerId?: string, errorMessage?: string) => Promise<void>) | null = null
389
+
390
+ /**
391
+ * Sets a handler to be called when sign-in fails.
392
+ *
393
+ * @param handler - The handler function to call on sign-in failure.
394
+ * @public
395
+ *
396
+ * @remarks
397
+ * This method allows you to register a callback that will be invoked whenever
398
+ * a user's authentication attempt fails. The handler receives the turn context,
399
+ * state, auth handler ID, and an optional error message describing the failure.
400
+ *
401
+ * Common failure scenarios include:
402
+ * - User cancels the authentication process
403
+ * - Invalid credentials or expired tokens
404
+ * - Network connectivity issues
405
+ * - OAuth provider errors
406
+ *
407
+ * Example usage:
408
+ * ```typescript
409
+ * auth.onSignInFailure(async (context, state, authHandlerId, errorMessage) => {
410
+ * await context.sendActivity(`Sign-in failed: ${errorMessage || 'Unknown error'}`);
411
+ * await context.sendActivity('Please try signing in again.');
412
+ * });
413
+ * ```
414
+ */
415
+ public onSignInFailure (handler: (context: TurnContext, state: TurnState, authHandlerId?: string, errorMessage?: string) => Promise<void>) {
416
+ this._signInFailureHandler = handler
417
+ }
418
+ }
package/src/app/index.ts CHANGED
@@ -3,7 +3,7 @@ export * from './agentApplicationBuilder'
3
3
  export * from './agentApplicationOptions'
4
4
  export * from './appRoute'
5
5
  export * from './attachmentDownloader'
6
- export * from './oauth/authorization'
6
+ export * from './authorization'
7
7
  export * from './conversationUpdateEvents'
8
8
  export * from './routeHandler'
9
9
  export * from './routeSelector'
package/src/auth/index.ts CHANGED
@@ -2,3 +2,4 @@ export * from './authConfiguration'
2
2
  export * from './authProvider'
3
3
  export * from './msalTokenProvider'
4
4
  export * from './request'
5
+ export * from './msalTokenCredential'
@@ -43,7 +43,7 @@ const verifyToken = async (raw: string, config: AuthConfiguration): Promise<JwtP
43
43
 
44
44
  return await new Promise((resolve, reject) => {
45
45
  const verifyOptions: jwt.VerifyOptions = {
46
- issuer: config.issuers,
46
+ issuer: config.issuers as [string, ...string[]],
47
47
  audience: [config.clientId!, 'https://api.botframework.com'],
48
48
  ignoreExpiration: false,
49
49
  algorithms: ['RS256'],
@@ -0,0 +1,14 @@
1
+ import { GetTokenOptions, TokenCredential } from '@azure/core-auth'
2
+ import { AuthConfiguration, MsalTokenProvider } from './'
3
+
4
+ export class MsalTokenCredential implements TokenCredential {
5
+ constructor (private authConfig: AuthConfiguration) {}
6
+ public async getToken (scopes: string[], options?: GetTokenOptions) {
7
+ const scope = scopes[0].substring(0, scopes[0].lastIndexOf('/'))
8
+ const token = await new MsalTokenProvider().getAccessToken(this.authConfig, scope)
9
+ return {
10
+ token,
11
+ expiresOnTimestamp: Date.now() + 10000
12
+ }
13
+ }
14
+ }
@@ -25,7 +25,7 @@ export class MsalTokenProvider implements AuthProvider {
25
25
  * @param scope The scope for the token.
26
26
  * @returns A promise that resolves to the access token.
27
27
  */
28
- async getAccessToken (authConfig: AuthConfiguration, scope: string): Promise<string> {
28
+ public async getAccessToken (authConfig: AuthConfiguration, scope: string): Promise<string> {
29
29
  if (!authConfig.clientId && process.env.NODE_ENV !== 'production') {
30
30
  return ''
31
31
  }
@@ -51,6 +51,22 @@ export class MsalTokenProvider implements AuthProvider {
51
51
  return token
52
52
  }
53
53
 
54
+ public async acquireTokenOnBehalfOf (authConfig: AuthConfiguration, scopes: string[], oboAssertion: string): Promise<string> {
55
+ const cca = new ConfidentialClientApplication({
56
+ auth: {
57
+ clientId: authConfig.clientId as string,
58
+ authority: `https://login.microsoftonline.com/${authConfig.tenantId || 'botframework.com'}`,
59
+ clientSecret: authConfig.clientSecret
60
+ },
61
+ system: this.sysOptions
62
+ })
63
+ const token = await cca.acquireTokenOnBehalfOf({
64
+ oboAssertion,
65
+ scopes
66
+ })
67
+ return token?.accessToken as string
68
+ }
69
+
54
70
  private readonly sysOptions: NodeSystemOptions = {
55
71
  loggerOptions: {
56
72
  logLevel: LogLevel.Trace,