Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 398 lines 14.3 KB
Raw
1 /**
2 * @fileoverview Auth configs class for Composio SDK, used to manage authentication configurations.
3 *
4 * @author Musthaq Ahamad <musthaq@composio.dev>
5 * @date 2025-05-05
6 * @module AuthConfigs
7 */
8 import ComposioClient from '@composio/client';
9 import {
10 AuthConfigDeleteResponse,
11 AuthConfigUpdateResponse,
12 AuthConfigUpdateStatusResponse,
13 } from '@composio/client/resources/auth-configs';
14 import {
15 AuthConfigListParams,
16 AuthConfigListParamsSchema,
17 AuthConfigListResponse,
18 AuthConfigRetrieveResponse,
19 AuthConfigUpdateParams,
20 AuthConfigUpdateParamsSchema,
21 CreateAuthConfigParams,
22 CreateAuthConfigParamsSchema,
23 CreateAuthConfigResponse,
24 } from '../types/authConfigs.types';
25 import { ValidationError } from '../errors/ValidationErrors';
26 import { telemetry } from '../telemetry/Telemetry';
27 import {
28 transformAuthConfigListResponse,
29 transformAuthConfigRetrieveResponse,
30 transformCreateAuthConfigResponse,
31 } from '../utils/transformers/authConfigs';
32 import { ComposioRequestOptions } from '../types/requestOptions.types';
33 import { withCancellation } from '../utils/cancellation';
34 /**
35 * AuthConfigs class
36 *
37 * This class is used to manage authentication configurations in the Composio SDK.
38 * Auth configs are used to configure authentication providers and settings.
39 */
40 export class AuthConfigs {
41 private client: ComposioClient;
42
43 constructor(client: ComposioClient) {
44 this.client = client;
45 telemetry.instrument(this, 'AuthConfigs');
46 }
47
48 /**
49 * Lists authentication configurations based on provided filter criteria.
50 *
51 * This method retrieves auth configs from the Composio API, transforms them to the SDK format,
52 * and supports filtering by various parameters.
53 *
54 * @param {AuthConfigListParams} [query] - Optional query parameters for filtering auth configs
55 * @returns {Promise<AuthConfigListResponse>} A paginated list of auth configurations
56 * @throws {ValidationError} If the query parameters or response fail validation
57 *
58 * @example
59 * ```typescript
60 * // List all auth configs
61 * const allConfigs = await composio.authConfigs.list();
62 *
63 * // List auth configs for a specific toolkit
64 * const githubConfigs = await composio.authConfigs.list({
65 * toolkit: 'github'
66 * });
67 *
68 * // Search auth configs by name or id
69 * const searchedConfigs = await composio.authConfigs.list({
70 * search: 'github',
71 * showDisabled: true
72 * });
73 *
74 * // List Composio-managed auth configs
75 * const managedConfigs = await composio.authConfigs.list({
76 * isComposioManaged: true
77 * });
78 * ```
79 */
80 async list(
81 query?: AuthConfigListParams,
82 requestOptions?: ComposioRequestOptions
83 ): Promise<AuthConfigListResponse> {
84 const parsedQuery = query ? AuthConfigListParamsSchema.parse(query) : undefined;
85 const listParams = {
86 cursor: parsedQuery?.cursor,
87 is_composio_managed: parsedQuery?.isComposioManaged,
88 limit: parsedQuery?.limit,
89 search: parsedQuery?.search,
90 show_disabled: parsedQuery?.showDisabled,
91 toolkit_slug: parsedQuery?.toolkit,
92 };
93 const result = await withCancellation(
94 () => this.client.authConfigs.list(listParams, requestOptions),
95 requestOptions?.signal
96 );
97 return transformAuthConfigListResponse(result);
98 }
99
100 /**
101 * Create a new auth config
102 * @param {string} toolkit - Unique identifier of the toolkit
103 * @param {CreateAuthConfigParams} options - Options for creating a new auth config
104 * @returns {Promise<CreateAuthConfigResponse>} Created auth config
105 *
106 * @example
107 * // Use a specific Composio-managed app; omit managedAppId for the toolkit's default
108 * const { composioManagedAuth } = await composio.toolkits.get('slack');
109 * const slackAuthConfig = await authConfigs.create('slack', {
110 * type: AuthConfigTypes.COMPOSIO_MANAGED,
111 * managedAppId: composioManagedAuth?.find(app => !app.isDefault)?.managedAppId,
112 * });
113 *
114 * @example
115 * const authConfig = await authConfigs.create('my-toolkit', {
116 * type: AuthConfigTypes.CUSTOM,
117 * name: 'My Custom Auth Config',
118 * authScheme: AuthSchemeTypes.API_KEY,
119 * credentials: {
120 * apiKey: '1234567890',
121 * },
122 * });
123 *
124 * @link https://docs.composio.dev/reference/auth-configs/create-auth-config
125 */
126 async create(
127 toolkit: string,
128 options: CreateAuthConfigParams = { type: 'use_composio_managed_auth' },
129 requestOptions?: ComposioRequestOptions
130 ): Promise<CreateAuthConfigResponse> {
131 const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
132 if (parsedOptions.error) {
133 throw new ValidationError('Failed to parse auth config create options', {
134 cause: parsedOptions.error,
135 });
136 }
137 const createBody = {
138 toolkit: {
139 slug: toolkit,
140 },
141 auth_config:
142 parsedOptions.data.type === 'use_custom_auth'
143 ? {
144 type: parsedOptions.data.type,
145 name: parsedOptions.data.name,
146 authScheme: parsedOptions.data.authScheme,
147 credentials: parsedOptions.data.credentials,
148 is_enabled_for_tool_router: parsedOptions.data.isEnabledForToolRouter,
149 proxy_config: parsedOptions.data.proxyConfig
150 ? {
151 proxy_url: parsedOptions.data.proxyConfig.proxyUrl,
152 proxy_auth_key: parsedOptions.data.proxyConfig.proxyAuthKey,
153 }
154 : undefined,
155 tool_access_config: parsedOptions.data.toolAccessConfig
156 ? {
157 tools_for_connected_account_creation:
158 parsedOptions.data.toolAccessConfig.toolsForConnectedAccountCreation,
159 }
160 : undefined,
161 }
162 : {
163 type: parsedOptions.data.type,
164 credentials: parsedOptions.data.credentials,
165 name: parsedOptions.data.name,
166 is_enabled_for_tool_router: parsedOptions.data.isEnabledForToolRouter,
167 tool_access_config: parsedOptions.data.toolAccessConfig
168 ? {
169 tools_for_connected_account_creation:
170 parsedOptions.data.toolAccessConfig.toolsForConnectedAccountCreation,
171 }
172 : undefined,
173 managed_app_id: parsedOptions.data.managedAppId,
174 },
175 };
176 const result = await withCancellation(
177 () => this.client.authConfigs.create(createBody, requestOptions),
178 requestOptions?.signal
179 );
180 return transformCreateAuthConfigResponse(result);
181 }
182
183 /**
184 * Retrieves a specific authentication configuration by its ID.
185 *
186 * This method fetches detailed information about a single auth config
187 * and transforms the response to the SDK's standardized format.
188 *
189 * @param {string} nanoid - The unique identifier of the auth config to retrieve
190 * @returns {Promise<AuthConfigRetrieveResponse>} The auth config details
191 * @throws {Error} If the auth config cannot be found or an API error occurs
192 * @throws {ValidationError} If the response fails validation
193 *
194 * @example
195 * ```typescript
196 * // Get an auth config by ID
197 * const authConfig = await composio.authConfigs.get('auth_abc123');
198 * console.log(authConfig.name); // e.g., 'GitHub Auth'
199 * console.log(authConfig.toolkit.slug); // e.g., 'github'
200 * ```
201 */
202 async get(
203 nanoid: string,
204 requestOptions?: ComposioRequestOptions
205 ): Promise<AuthConfigRetrieveResponse> {
206 const result = await withCancellation(
207 () => this.client.authConfigs.retrieve(nanoid, requestOptions),
208 requestOptions?.signal
209 );
210 return transformAuthConfigRetrieveResponse(result);
211 }
212
213 /**
214 * Updates an existing authentication configuration.
215 *
216 * This method allows you to modify properties of an auth config such as credentials,
217 * scopes, or tool restrictions. The update type (custom or default) determines which
218 * fields can be updated.
219 *
220 * @param {string} nanoid - The unique identifier of the auth config to update
221 * @param {AuthConfigUpdateParams} data - The data to update, which can be either custom or default type
222 * @returns {Promise<AuthConfigUpdateResponse>} The updated auth config
223 * @throws {ValidationError} If the update parameters are invalid
224 * @throws {Error} If the auth config cannot be found or updated
225 *
226 * @example
227 * ```typescript
228 * // Update a custom auth config with new credentials
229 * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
230 * type: 'custom',
231 * credentials: {
232 * apiKey: 'new-api-key-value'
233 * }
234 * });
235 *
236 * // Update a default auth config with new scopes
237 * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
238 * type: 'default',
239 * scopes: ['read:user', 'repo']
240 * });
241 * ```
242 */
243 async update(
244 nanoid: string,
245 data: AuthConfigUpdateParams,
246 requestOptions?: ComposioRequestOptions
247 ): Promise<AuthConfigUpdateResponse> {
248 const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
249 if (parsedData.error) {
250 throw new ValidationError('Failed to parse auth config update data', {
251 cause: parsedData.error,
252 });
253 }
254 const updateBody =
255 parsedData.data.type === 'custom'
256 ? {
257 type: 'custom' as const,
258 credentials: parsedData.data.credentials,
259 is_enabled_for_tool_router: parsedData.data.isEnabledForToolRouter,
260 tool_access_config: {
261 tools_for_connected_account_creation:
262 parsedData.data.toolAccessConfig?.toolsForConnectedAccountCreation,
263 tools_available_for_execution:
264 parsedData.data.toolAccessConfig?.toolsAvailableForExecution ??
265 parsedData.data.restrictToFollowingTools,
266 },
267 }
268 : {
269 type: 'default' as const,
270 scopes: parsedData.data.scopes,
271 is_enabled_for_tool_router: parsedData.data.isEnabledForToolRouter,
272 tool_access_config: {
273 tools_for_connected_account_creation:
274 parsedData.data.toolAccessConfig?.toolsForConnectedAccountCreation,
275 tools_available_for_execution:
276 parsedData.data.toolAccessConfig?.toolsAvailableForExecution ??
277 parsedData.data.restrictToFollowingTools,
278 },
279 };
280 return withCancellation(
281 () => this.client.authConfigs.update(nanoid, updateBody, requestOptions),
282 requestOptions?.signal
283 );
284 }
285
286 /**
287 * Deletes an authentication configuration.
288 *
289 * This method permanently removes an auth config from the Composio platform.
290 * This action cannot be undone and will prevent any connected accounts that use
291 * this auth config from functioning.
292 *
293 * @param {string} nanoid - The unique identifier of the auth config to delete
294 * @returns {Promise<AuthConfigDeleteResponse>} The deletion response
295 * @throws {Error} If the auth config doesn't exist or cannot be deleted
296 *
297 * @example
298 * ```typescript
299 * // Delete an auth config
300 * await composio.authConfigs.delete('auth_abc123');
301 * ```
302 */
303 async delete(
304 nanoid: string,
305 requestOptions?: ComposioRequestOptions
306 ): Promise<AuthConfigDeleteResponse> {
307 return withCancellation(
308 () => this.client.authConfigs.delete(nanoid, undefined, requestOptions),
309 requestOptions?.signal
310 );
311 }
312
313 /**
314 * Updates the status of an authentication configuration.
315 *
316 * This method allows you to enable or disable an auth config. When disabled,
317 * the auth config cannot be used to create new connected accounts or authenticate
318 * with third-party services.
319 *
320 * @param {string} status - The status to set ('ENABLED' or 'DISABLED')
321 * @param {string} nanoid - The unique identifier of the auth config
322 * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
323 * @throws {Error} If the auth config cannot be found or the status cannot be updated
324 *
325 * @example
326 * ```typescript
327 * // Disable an auth config
328 * await composio.authConfigs.updateStatus('DISABLED', 'auth_abc123');
329 *
330 * // Enable an auth config
331 * await composio.authConfigs.updateStatus('ENABLED', 'auth_abc123');
332 * ```
333 */
334 async updateStatus(
335 status: 'ENABLED' | 'DISABLED',
336 nanoid: string,
337 requestOptions?: ComposioRequestOptions
338 ): Promise<AuthConfigUpdateStatusResponse> {
339 return withCancellation(
340 () => this.client.authConfigs.updateStatus(status, { nanoid }, requestOptions),
341 requestOptions?.signal
342 );
343 }
344
345 /**
346 * Enables an authentication configuration.
347 *
348 * This is a convenience method that calls updateStatus with 'ENABLED'.
349 * When enabled, the auth config can be used to create new connected accounts
350 * and authenticate with third-party services.
351 *
352 * @param {string} nanoid - The unique identifier of the auth config to enable
353 * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
354 * @throws {Error} If the auth config cannot be found or enabled
355 *
356 * @example
357 * ```typescript
358 * // Enable an auth config
359 * await composio.authConfigs.enable('auth_abc123');
360 * ```
361 */
362 async enable(
363 nanoid: string,
364 requestOptions?: ComposioRequestOptions
365 ): Promise<AuthConfigUpdateStatusResponse> {
366 return withCancellation(
367 () => this.client.authConfigs.updateStatus('ENABLED', { nanoid }, requestOptions),
368 requestOptions?.signal
369 );
370 }
371
372 /**
373 * Disables an authentication configuration.
374 *
375 * This is a convenience method that calls updateStatus with 'DISABLED'.
376 * When disabled, the auth config cannot be used to create new connected accounts
377 * or authenticate with third-party services, but existing connections may continue to work.
378 *
379 * @param {string} nanoid - The unique identifier of the auth config to disable
380 * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
381 * @throws {Error} If the auth config cannot be found or disabled
382 *
383 * @example
384 * ```typescript
385 * // Disable an auth config
386 * await composio.authConfigs.disable('auth_abc123');
387 * ```
388 */
389 async disable(
390 nanoid: string,
391 requestOptions?: ComposioRequestOptions
392 ): Promise<AuthConfigUpdateStatusResponse> {
393 return withCancellation(
394 () => this.client.authConfigs.updateStatus('DISABLED', { nanoid }, requestOptions),
395 requestOptions?.signal
396 );
397 }
398 }