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