Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | /** |
| 2 | * @fileoverview Connected accounts class for Composio SDK, used to manage connected accounts of a user. |
| 3 | * |
| 4 | * @author Musthaq Ahamad <musthaq@composio.dev> |
| 5 | * @date 2025-05-05 |
| 6 | * @module ConnectedAccounts |
| 7 | */ |
| 8 | import ComposioClient, { BadRequestError, ConflictError } from '@composio/client'; |
| 9 | import type { APIPromise } from '@composio/client'; |
| 10 | import { |
| 11 | ConnectedAccountCreateResponse, |
| 12 | ConnectedAccountDeleteResponse, |
| 13 | ConnectedAccountRefreshParams, |
| 14 | ConnectedAccountRefreshResponse, |
| 15 | ConnectedAccountUpdateStatusParams, |
| 16 | ConnectedAccountUpdateStatusResponse, |
| 17 | ConnectedAccountPatchResponse, |
| 18 | ConnectedAccountListParams as ConnectedAccountListParamsRaw, |
| 19 | ConnectedAccountCreateParams as ConnectedAccountCreateParamsRaw, |
| 20 | } from '@composio/client/resources/connected-accounts'; |
| 21 | import { LinkCreateParams } from '@composio/client/resources/link'; |
| 22 | import { |
| 23 | CreateConnectedAccountOptions, |
| 24 | ConnectedAccountRetrieveResponse, |
| 25 | ConnectedAccountListParams, |
| 26 | ConnectedAccountListParamsSchema, |
| 27 | ConnectedAccountListResponse, |
| 28 | CreateConnectedAccountLinkOptions, |
| 29 | CreateConnectedAccountLinkOptionsSchema, |
| 30 | ConnectedAccountStatuses, |
| 31 | ConnectedAccountRefreshOptions, |
| 32 | ConnectedAccountRefreshOptionsSchema, |
| 33 | ConnectedAccountRevokeResponse, |
| 34 | ConnectedAccountCompleteAuthParams, |
| 35 | ConnectedAccountCompleteAuthParamsSchema, |
| 36 | ConnectedAccountCompleteAuthResponse, |
| 37 | UpdateConnectedAccountAclParams, |
| 38 | UpdateConnectedAccountParams, |
| 39 | UpdateConnectedAccountParamsSchema, |
| 40 | } from '../types/connectedAccounts.types'; |
| 41 | import { ConnectionRequest } from '../types/connectionRequest.types'; |
| 42 | import { createConnectionRequest } from './ConnectionRequest'; |
| 43 | import { |
| 44 | ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT, |
| 45 | serializeExperimentalForWire, |
| 46 | updateConnectedAccountAcl, |
| 47 | } from './Experimental'; |
| 48 | import { ValidationError } from '../errors/ValidationErrors'; |
| 49 | import { telemetry } from '../telemetry/Telemetry'; |
| 50 | import { |
| 51 | transformConnectedAccountListResponse, |
| 52 | transformConnectedAccountResponse, |
| 53 | transformConnectedAccountRevokeResponse, |
| 54 | transformConnectedAccountCompleteAuthResponse, |
| 55 | } from '../utils/transformers/connectedAccounts'; |
| 56 | import { |
| 57 | ComposioAclOnlyForSharedError, |
| 58 | ComposioConnectedAccountNotRevokableError, |
| 59 | ComposioConnectedAccountRevocationNotSupportedError, |
| 60 | ComposioFailedToCreateConnectedAccountLink, |
| 61 | ComposioLegacyConnectedAccountsEndpointRetiredError, |
| 62 | ComposioMultipleConnectedAccountsError, |
| 63 | } from '../errors'; |
| 64 | import logger from '../utils/logger'; |
| 65 | import { ConnectionData } from '../types/connectedAccountAuthStates.types'; |
| 66 | import { ComposioRequestOptions } from '../types/requestOptions.types'; |
| 67 | import { withCancellation } from '../utils/cancellation'; |
| 68 | import { ComposioRequestCancelledError } from '../errors/SDKErrors'; |
| 69 | |
| 70 | // One-time-per-process guard so long-running services don't spam the deprecation |
| 71 | // warning on every initiate() call. |
| 72 | let _legacyInitiateWarningEmitted = false; |
| 73 | |
| 74 | /** |
| 75 | * ConnectedAccounts class |
| 76 | * |
| 77 | * This class is used to manage connected accounts in the Composio SDK. |
| 78 | * Connected accounts are used to authenticate with third-party services. |
| 79 | */ |
| 80 | export class ConnectedAccounts { |
| 81 | private client: ComposioClient; |
| 82 | |
| 83 | constructor(client: ComposioClient) { |
| 84 | this.client = client; |
| 85 | telemetry.instrument(this, 'ConnectedAccounts'); |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Lists all connected accounts based on provided filter criteria. |
| 90 | * |
| 91 | * This method retrieves connected accounts from the Composio API with optional filtering. |
| 92 | * |
| 93 | * @param {ConnectedAccountListParams} [query] - Optional query parameters for filtering connected accounts |
| 94 | * @returns {Promise<ConnectedAccountListResponse>} A paginated list of connected accounts |
| 95 | * @throws {ValidationError} If the query fails validation against the expected schema |
| 96 | * @example |
| 97 | * ```typescript |
| 98 | * // List all connected accounts |
| 99 | * const allAccounts = await composio.connectedAccounts.list(); |
| 100 | * |
| 101 | * // List accounts for a specific user |
| 102 | * const userAccounts = await composio.connectedAccounts.list({ |
| 103 | * userIds: ['user123'] |
| 104 | * }); |
| 105 | * |
| 106 | * // List accounts for a specific toolkit |
| 107 | * const githubAccounts = await composio.connectedAccounts.list({ |
| 108 | * toolkitSlugs: ['github'] |
| 109 | * }); |
| 110 | * ``` |
| 111 | */ |
| 112 | async list( |
| 113 | query?: ConnectedAccountListParams, |
| 114 | requestOptions?: ComposioRequestOptions |
| 115 | ): Promise<ConnectedAccountListResponse> { |
| 116 | let rawQuery: ConnectedAccountListParamsRaw | undefined = undefined; |
| 117 | |
| 118 | if (query) { |
| 119 | const parsedQuery = ConnectedAccountListParamsSchema.safeParse(query); |
| 120 | if (!parsedQuery.success) { |
| 121 | throw new ValidationError('Failed to parse connected account list query', { |
| 122 | cause: parsedQuery.error, |
| 123 | }); |
| 124 | } |
| 125 | rawQuery = { |
| 126 | auth_config_ids: parsedQuery.data.authConfigIds, |
| 127 | cursor: parsedQuery.data.cursor?.toString(), |
| 128 | limit: parsedQuery.data.limit, |
| 129 | order_by: parsedQuery.data.orderBy, |
| 130 | statuses: parsedQuery.data.statuses, |
| 131 | toolkit_slugs: parsedQuery.data.toolkitSlugs, |
| 132 | user_ids: parsedQuery.data.userIds, |
| 133 | ...(parsedQuery.data.accountType !== undefined && { |
| 134 | account_type: parsedQuery.data.accountType, |
| 135 | }), |
| 136 | }; |
| 137 | } |
| 138 | |
| 139 | const result = await withCancellation( |
| 140 | () => this.client.connectedAccounts.list(rawQuery, requestOptions), |
| 141 | requestOptions?.signal |
| 142 | ); |
| 143 | return transformConnectedAccountListResponse(result); |
| 144 | } |
| 145 | |
| 146 | /** |
| 147 | * Compound function to create a new connected account. |
| 148 | * This function creates a new connected account and returns a connection request. |
| 149 | * Users can then wait for the connection to be established using the `waitForConnection` method. |
| 150 | * |
| 151 | * **Deprecated for Composio-managed OAuth (OAuth1, OAuth2, DCR_OAUTH).** |
| 152 | * The legacy `POST /api/v3/connected_accounts` endpoint that this method |
| 153 | * wraps is being retired for Composio-managed auth configs on redirectable |
| 154 | * schemes. The cutover is **2026-05-08** for new organizations and |
| 155 | * **2026-07-03** for all remaining organizations. After your org's cutover, |
| 156 | * this method will throw {@link ComposioLegacyConnectedAccountsEndpointRetiredError} |
| 157 | * for that specific combination. |
| 158 | * |
| 159 | * Use {@link ConnectedAccounts.link} for Composio-managed OAuth — it works for |
| 160 | * every redirectable scheme regardless of whether the auth config is |
| 161 | * Composio-managed or custom, and the return shape is the same. |
| 162 | * |
| 163 | * Custom auth configs (your own OAuth app) and non-OAuth schemes (API key, |
| 164 | * bearer token, basic auth) are unaffected and continue to work on |
| 165 | * `initiate()`. See https://docs.composio.dev/docs/changelog/2026/04/24 |
| 166 | * |
| 167 | * @param {string} userId - User ID of the connected account |
| 168 | * @param {string} authConfigId - Auth config ID of the connected account |
| 169 | * @param {CreateConnectedAccountOptions} options - Options for creating a new connected account |
| 170 | * @returns {Promise<ConnectionRequest>} Connection request object |
| 171 | * |
| 172 | * @example |
| 173 | * ```typescript |
| 174 | * // For OAuth2 authentication |
| 175 | * const connectionRequest = await composio.connectedAccounts.initiate( |
| 176 | * 'user_123', |
| 177 | * 'auth_config_123', |
| 178 | * { |
| 179 | * callbackUrl: 'https://your-app.com/callback', |
| 180 | * config: AuthScheme.OAuth2({ |
| 181 | * access_token: 'your_access_token', |
| 182 | * token_type: 'Bearer' |
| 183 | * }) |
| 184 | * } |
| 185 | * ); |
| 186 | * |
| 187 | * // For API Key authentication |
| 188 | * const connectionRequest = await composio.connectedAccounts.initiate( |
| 189 | * 'user_123', |
| 190 | * 'auth_config_123', |
| 191 | * { |
| 192 | * config: AuthScheme.ApiKey({ |
| 193 | * api_key: 'your_api_key' |
| 194 | * }) |
| 195 | * } |
| 196 | * ); |
| 197 | * |
| 198 | * // For Basic authentication |
| 199 | * const connectionRequest = await composio.connectedAccounts.initiate( |
| 200 | * 'user_123', |
| 201 | * 'auth_config_123', |
| 202 | * { |
| 203 | * config: AuthScheme.Basic({ |
| 204 | * username: 'your_username', |
| 205 | * password: 'your_password' |
| 206 | * }) |
| 207 | * } |
| 208 | * ); |
| 209 | * ``` |
| 210 | * |
| 211 | * @link https://docs.composio.dev/reference/connected-accounts/create-connected-account |
| 212 | */ |
| 213 | async initiate( |
| 214 | userId: string, |
| 215 | authConfigId: string, |
| 216 | options?: CreateConnectedAccountOptions, |
| 217 | requestOptions?: ComposioRequestOptions |
| 218 | ): Promise<ConnectionRequest> { |
| 219 | // Check if there are multiple connected accounts for the authConfig of the user |
| 220 | const connectedAccount = await this.list( |
| 221 | { |
| 222 | userIds: [userId], |
| 223 | authConfigIds: [authConfigId], |
| 224 | statuses: [ConnectedAccountStatuses.ACTIVE], |
| 225 | }, |
| 226 | requestOptions |
| 227 | ); |
| 228 | if (connectedAccount.items.length > 0 && !options?.allowMultiple) { |
| 229 | throw new ComposioMultipleConnectedAccountsError( |
| 230 | `Multiple connected accounts found for user ${userId} in auth config ${authConfigId}. Please use the allowMultiple option to allow multiple connected accounts.` |
| 231 | ); |
| 232 | } else if (connectedAccount.items.length > 0) { |
| 233 | logger.warn( |
| 234 | `[Warn:AllowMultiple] Multiple connected accounts found for user ${userId} in auth config ${authConfigId}` |
| 235 | ); |
| 236 | } |
| 237 | |
| 238 | const state: ConnectionData | undefined = options?.config ?? undefined; |
| 239 | // @TODO: Commenting this out. This is a temporary fix to allow api_key to be optional, in future ideally we should fix this from API side |
| 240 | |
| 241 | // if (options?.config) { |
| 242 | // const connectionDataParsed = ConnectionDataSchema.safeParse(options.config); |
| 243 | // if (!connectionDataParsed.success) { |
| 244 | // throw new ValidationError('Failed to parse connection data', { |
| 245 | // cause: connectionDataParsed.error, |
| 246 | // }); |
| 247 | // } |
| 248 | // state = connectionDataParsed.data; |
| 249 | // } |
| 250 | |
| 251 | const createParams: ConnectedAccountCreateParamsRaw = { |
| 252 | auth_config: { id: authConfigId }, |
| 253 | connection: { |
| 254 | callback_url: options?.callbackUrl, |
| 255 | user_id: userId, |
| 256 | state: state as NonNullable<ConnectedAccountCreateParamsRaw['connection']>['state'], |
| 257 | ...(options?.alias != null && { alias: options.alias }), |
| 258 | }, |
| 259 | }; |
| 260 | |
| 261 | let response: ConnectedAccountCreateResponse; |
| 262 | let httpResponse: Response | undefined; |
| 263 | try { |
| 264 | // Chain `.withResponse()` so we can read the SEC-339 `Deprecation` |
| 265 | // header (RFC 9745) the apollo retiring branch sets — that header is |
| 266 | // emitted only when the auth config is Composio-managed AND on a |
| 267 | // redirectable OAuth scheme, so it's the canonical signal that this |
| 268 | // caller needs to migrate. Custom auth configs and non-OAuth schemes |
| 269 | // never see the header, eliminating the false-positive warning that |
| 270 | // an `auth_scheme`-only check produced for `link()`-unaffected callers. |
| 271 | const apiCall: APIPromise<ConnectedAccountCreateResponse> = |
| 272 | this.client.connectedAccounts.create(createParams, requestOptions); |
| 273 | // Checked at runtime: test mocks may return a plain Promise. |
| 274 | if (typeof apiCall.withResponse === 'function') { |
| 275 | const resolved = await withCancellation( |
| 276 | () => apiCall.withResponse(), |
| 277 | requestOptions?.signal |
| 278 | ); |
| 279 | response = resolved.data; |
| 280 | httpResponse = resolved.response; |
| 281 | } else { |
| 282 | // Test mocks may return a plain Promise without `withResponse`. |
| 283 | // Fall back to a naked await; the deprecation gate below stays |
| 284 | // off in that case (no header to read). |
| 285 | response = await withCancellation(() => apiCall, requestOptions?.signal); |
| 286 | } |
| 287 | } catch (error) { |
| 288 | // Caller-initiated cancellation must surface as the typed error, |
| 289 | // not get remapped to the legacy-endpoint error below. |
| 290 | if (error instanceof ComposioRequestCancelledError) { |
| 291 | throw error; |
| 292 | } |
| 293 | // When the server has flipped this org to the retired path, the legacy |
| 294 | // endpoint returns 400 with a stable migration message. Surface it as |
| 295 | // a typed error so callers get an actionable hint instead of a generic |
| 296 | // BadRequestError. |
| 297 | if ( |
| 298 | error instanceof BadRequestError && |
| 299 | typeof error.message === 'string' && |
| 300 | error.message.includes('no longer supported') && |
| 301 | error.message.includes('/api/v3/connected_accounts/link') |
| 302 | ) { |
| 303 | throw new ComposioLegacyConnectedAccountsEndpointRetiredError(error.message, { |
| 304 | cause: error, |
| 305 | }); |
| 306 | } |
| 307 | throw error; |
| 308 | } |
| 309 | |
| 310 | // Warn once per process when apollo flags this response as on the |
| 311 | // retiring path. Header presence is a 1:1 signal — custom auth configs |
| 312 | // and non-OAuth schemes get a clean response and stay silent, fixing |
| 313 | // the false-positive that auth_scheme-based detection produced. |
| 314 | if (!_legacyInitiateWarningEmitted && httpResponse?.headers.get('Deprecation')) { |
| 315 | _legacyInitiateWarningEmitted = true; |
| 316 | logger.warn( |
| 317 | '[Deprecation] composio.connectedAccounts.initiate() will stop ' + |
| 318 | 'working for this auth config on or before 2026-07-03 (see Sunset ' + |
| 319 | 'header on the response). Switch to composio.connectedAccounts.link() — ' + |
| 320 | 'same return shape, same allowMultiple semantics. ' + |
| 321 | 'https://docs.composio.dev/docs/changelog/2026/04/24' |
| 322 | ); |
| 323 | } |
| 324 | |
| 325 | const redirectUrl = |
| 326 | typeof response.connectionData?.val?.redirectUrl === 'string' |
| 327 | ? response.connectionData.val.redirectUrl |
| 328 | : null; |
| 329 | |
| 330 | return createConnectionRequest( |
| 331 | this.client, |
| 332 | response.id, |
| 333 | response.connectionData.val.status, |
| 334 | redirectUrl |
| 335 | ); |
| 336 | } |
| 337 | |
| 338 | /** |
| 339 | * @description Create a Composio Connect Link for a user to connect their account to a given auth config. This method will return an external link which you can use the user to connect their account. |
| 340 | * |
| 341 | * @docs https://docs.composio.dev/reference/connected-accounts/create-connected-account#create-a-composio-connect-link |
| 342 | * |
| 343 | * @param userId {string} - The external user ID to create the connected account for. |
| 344 | * @param authConfigId {string} - The auth config ID to create the connected account for. |
| 345 | * @param options {CreateConnectedAccountLinkOptions} - Options for creating a new connected account link. |
| 346 | * @param options.callbackUrl {string} - The url to redirect the user to post connecting their account. |
| 347 | * @returns {ConnectionRequest} Connection request object |
| 348 | * |
| 349 | * @example |
| 350 | * ```typescript |
| 351 | * // create a connection request and redirect the user to the redirect url |
| 352 | * const connectionRequest = await composio.connectedAccounts.link('user_123', 'auth_config_123'); |
| 353 | * const redirectUrl = connectionRequest.redirectUrl; |
| 354 | * console.log(`Visit: ${redirectUrl} to authenticate your account`); |
| 355 | * |
| 356 | * // Wait for the connection to be established |
| 357 | * const connectedAccount = await connectionRequest.waitForConnection() |
| 358 | * ``` |
| 359 | * |
| 360 | * @example |
| 361 | * ```typescript |
| 362 | * // create a connection request and redirect the user to the redirect url |
| 363 | * const connectionRequest = await composio.connectedAccounts.link('user_123', 'auth_config_123', { |
| 364 | * callbackUrl: 'https://your-app.com/callback' |
| 365 | * }); |
| 366 | * const redirectUrl = connectionRequest.redirectUrl; |
| 367 | * console.log(`Visit: ${redirectUrl} to authenticate your account`); |
| 368 | * |
| 369 | * // Wait for the connection to be established |
| 370 | * const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionRequest.id); |
| 371 | * ``` |
| 372 | */ |
| 373 | async link( |
| 374 | userId: string, |
| 375 | authConfigId: string, |
| 376 | options?: CreateConnectedAccountLinkOptions, |
| 377 | requestOptions?: ComposioRequestOptions |
| 378 | ): Promise<ConnectionRequest> { |
| 379 | const parsedLinkOptions = CreateConnectedAccountLinkOptionsSchema.safeParse(options || {}); |
| 380 | if (!parsedLinkOptions.success) { |
| 381 | throw new ValidationError('Failed to parse create connected account link options', { |
| 382 | cause: parsedLinkOptions.error, |
| 383 | }); |
| 384 | } |
| 385 | |
| 386 | const opts = parsedLinkOptions.data; |
| 387 | |
| 388 | // Mirror initiate(): guard against silently creating extra connections on |
| 389 | // the same auth config unless the caller explicitly opts in. The preflight |
| 390 | // list call honors the caller's signal too — the whole composite is |
| 391 | // cancellable as a single unit. |
| 392 | const existing = await this.list( |
| 393 | { |
| 394 | userIds: [userId], |
| 395 | authConfigIds: [authConfigId], |
| 396 | statuses: [ConnectedAccountStatuses.ACTIVE], |
| 397 | }, |
| 398 | requestOptions |
| 399 | ); |
| 400 | if (existing.items.length > 0 && !opts.allowMultiple) { |
| 401 | throw new ComposioMultipleConnectedAccountsError( |
| 402 | `Multiple connected accounts found for user ${userId} in auth config ${authConfigId}. Please use the allowMultiple option to allow multiple connected accounts.` |
| 403 | ); |
| 404 | } else if (existing.items.length > 0) { |
| 405 | logger.warn( |
| 406 | `[Warn:AllowMultiple] Multiple connected accounts found for user ${userId} in auth config ${authConfigId}` |
| 407 | ); |
| 408 | } |
| 409 | |
| 410 | const experimentalWire = serializeExperimentalForWire(opts.experimental); |
| 411 | const body: LinkCreateParams = { |
| 412 | auth_config_id: authConfigId, |
| 413 | user_id: userId, |
| 414 | ...(opts.callbackUrl !== undefined && { callback_url: opts.callbackUrl }), |
| 415 | ...(opts.alias !== undefined && { alias: opts.alias }), |
| 416 | ...(experimentalWire !== undefined && { experimental: experimentalWire }), |
| 417 | }; |
| 418 | |
| 419 | try { |
| 420 | const response = await withCancellation( |
| 421 | () => this.client.link.create(body, requestOptions), |
| 422 | requestOptions?.signal |
| 423 | ); |
| 424 | |
| 425 | const connectionRequest = createConnectionRequest( |
| 426 | this.client, |
| 427 | response.connected_account_id, |
| 428 | ConnectedAccountStatuses.INITIATED, |
| 429 | response.redirect_url |
| 430 | ); |
| 431 | return connectionRequest; |
| 432 | } catch (error) { |
| 433 | // Caller-initiated cancellation must surface as the typed error, |
| 434 | // not get remapped to ComposioFailedToCreateConnectedAccountLink below. |
| 435 | if (error instanceof ComposioRequestCancelledError) { |
| 436 | throw error; |
| 437 | } |
| 438 | // The server rejects ACL on PRIVATE connections — surface that as a |
| 439 | // typed error so callers can `instanceof` instead of grepping messages. |
| 440 | if ( |
| 441 | error instanceof BadRequestError && |
| 442 | typeof error.message === 'string' && |
| 443 | error.message.includes(ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT) |
| 444 | ) { |
| 445 | throw new ComposioAclOnlyForSharedError(error.message, { cause: error }); |
| 446 | } |
| 447 | throw new ComposioFailedToCreateConnectedAccountLink( |
| 448 | 'Failed to create connected account link', |
| 449 | { |
| 450 | cause: error, |
| 451 | } |
| 452 | ); |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | /** |
| 457 | * Waits for a connection request to complete and become active. |
| 458 | * |
| 459 | * This method polls the Composio API, backing off from 1 second to 5 seconds between polls, |
| 460 | * to check the status of a connection until it either becomes active, enters a terminal error state, or times out. |
| 461 | * |
| 462 | * @param {string} connectedAccountId - The ID of the connected account to wait for |
| 463 | * @param {number} [timeout=60000] - Maximum time to wait in milliseconds (default: 60 seconds) |
| 464 | * @returns {Promise<ConnectedAccountRetrieveResponse>} The finalized connected account data |
| 465 | * @throws {ComposioConnectedAccountNotFoundError} If the connected account cannot be found |
| 466 | * @throws {ConnectionRequestFailedError} If the connection enters a failed, expired, or deleted state |
| 467 | * @throws {ConnectionRequestTimeoutError} If the connection does not complete within the timeout period |
| 468 | * |
| 469 | * @example |
| 470 | * ```typescript |
| 471 | * // Wait for a connection to complete with default timeout |
| 472 | * const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc'); |
| 473 | * |
| 474 | * // Wait with a custom timeout of 2 minutes |
| 475 | * const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc', 120000); |
| 476 | * ``` |
| 477 | */ |
| 478 | async waitForConnection( |
| 479 | connectedAccountId: string, |
| 480 | timeout: number = 60000 |
| 481 | ): Promise<ConnectedAccountRetrieveResponse> { |
| 482 | const connectionRequest = createConnectionRequest(this.client, connectedAccountId); |
| 483 | return connectionRequest.waitForConnection(timeout); |
| 484 | } |
| 485 | |
| 486 | /** |
| 487 | * Retrieves a specific connected account by its ID. |
| 488 | * |
| 489 | * This method fetches detailed information about a single connected account |
| 490 | * and transforms the response to the SDK's standardized format. |
| 491 | * |
| 492 | * @param {string} nanoid - The unique identifier of the connected account |
| 493 | * @returns {Promise<ConnectedAccountRetrieveResponse>} The connected account details |
| 494 | * @throws {Error} If the connected account cannot be found or an API error occurs |
| 495 | * |
| 496 | * @example |
| 497 | * ```typescript |
| 498 | * // Get a connected account by ID |
| 499 | * const account = await composio.connectedAccounts.get('conn_abc123'); |
| 500 | * console.log(account.status); // e.g., 'ACTIVE' |
| 501 | * console.log(account.toolkit.slug); // e.g., 'github' |
| 502 | * ``` |
| 503 | */ |
| 504 | async get( |
| 505 | nanoid: string, |
| 506 | requestOptions?: ComposioRequestOptions |
| 507 | ): Promise<ConnectedAccountRetrieveResponse> { |
| 508 | const response = await withCancellation( |
| 509 | () => this.client.connectedAccounts.retrieve(nanoid, requestOptions), |
| 510 | requestOptions?.signal |
| 511 | ); |
| 512 | return transformConnectedAccountResponse(response); |
| 513 | } |
| 514 | |
| 515 | /** |
| 516 | * Deletes a connected account. |
| 517 | * |
| 518 | * This method permanently removes a connected account from the Composio platform. |
| 519 | * This action cannot be undone and will revoke any access tokens associated with the account. |
| 520 | * |
| 521 | * @param {string} nanoid - The unique identifier of the connected account to delete |
| 522 | * @returns {Promise<ConnectedAccountDeleteResponse>} The deletion response |
| 523 | * @throws {Error} If the account doesn't exist or cannot be deleted |
| 524 | * |
| 525 | * @example |
| 526 | * ```typescript |
| 527 | * // Delete a connected account |
| 528 | * await composio.connectedAccounts.delete('conn_abc123'); |
| 529 | * ``` |
| 530 | */ |
| 531 | async delete( |
| 532 | nanoid: string, |
| 533 | requestOptions?: ComposioRequestOptions |
| 534 | ): Promise<ConnectedAccountDeleteResponse> { |
| 535 | return withCancellation( |
| 536 | () => this.client.connectedAccounts.delete(nanoid, undefined, requestOptions), |
| 537 | requestOptions?.signal |
| 538 | ); |
| 539 | } |
| 540 | |
| 541 | /** |
| 542 | * Refreshes a connected account's authentication credentials. |
| 543 | * |
| 544 | * This method attempts to refresh OAuth tokens or other credentials associated with |
| 545 | * the connected account. This is useful when a token has expired or is about to expire. |
| 546 | * |
| 547 | * @param {string} nanoid - The unique identifier of the connected account to refresh |
| 548 | * @returns {Promise<ConnectedAccountRefreshResponse>} The response containing the refreshed account details |
| 549 | * @throws {Error} If the account doesn't exist or credentials cannot be refreshed |
| 550 | * |
| 551 | * @example |
| 552 | * ```typescript |
| 553 | * // Refresh a connected account's credentials |
| 554 | * const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123'); |
| 555 | * ``` |
| 556 | * |
| 557 | * @deprecated The `POST /connected_accounts/{id}/refresh` endpoint is deprecated by the |
| 558 | * Composio API. Re-initiate authentication instead: `composio.connectedAccounts.link(userId, authConfigId)` |
| 559 | * for a fresh connection, or `session.authorize(toolkit)` from a session. Behaviour is unchanged |
| 560 | * while the endpoint remains available; do not generate new code against `refresh`. |
| 561 | */ |
| 562 | async refresh( |
| 563 | nanoid: string, |
| 564 | options?: ConnectedAccountRefreshOptions, |
| 565 | requestOptions?: ComposioRequestOptions |
| 566 | ): Promise<ConnectedAccountRefreshResponse> { |
| 567 | let params: ConnectedAccountRefreshParams | undefined = undefined; |
| 568 | |
| 569 | if (options) { |
| 570 | const parsedOptions = ConnectedAccountRefreshOptionsSchema.safeParse(options); |
| 571 | if (!parsedOptions.success) { |
| 572 | throw new ValidationError('Failed to parse connected account refresh options', { |
| 573 | cause: parsedOptions.error, |
| 574 | }); |
| 575 | } |
| 576 | |
| 577 | if (parsedOptions.data.validateCredentials !== undefined) { |
| 578 | logger.warn( |
| 579 | 'connectedAccounts.refresh(): the Composio API no longer accepts `validateCredentials`; the option is ignored.' |
| 580 | ); |
| 581 | } |
| 582 | |
| 583 | params = { |
| 584 | query_redirect_url: parsedOptions.data.redirectUrl, |
| 585 | }; |
| 586 | } |
| 587 | |
| 588 | return withCancellation( |
| 589 | () => this.client.connectedAccounts.refresh(nanoid, params, requestOptions), |
| 590 | requestOptions?.signal |
| 591 | ); |
| 592 | } |
| 593 | |
| 594 | /** |
| 595 | * Revoke a connected account at the upstream provider. |
| 596 | * |
| 597 | * Best-effort upstream revocation of the stored tokens/credentials; on |
| 598 | * success the connection status becomes `REVOKED`. Revoking an already |
| 599 | * revoked connection returns an empty `revokedTokens` list without an |
| 600 | * upstream call. |
| 601 | * |
| 602 | * @param {string} nanoid - The unique identifier of the connected account to revoke |
| 603 | * @returns {Promise<ConnectedAccountRevokeResponse>} Which tokens were revoked and the resulting status |
| 604 | * @throws {ComposioConnectedAccountRevocationNotSupportedError} If the toolkit does not support programmatic revocation (400) |
| 605 | * @throws {ComposioConnectedAccountNotRevokableError} If the connection is not in a revokable state (409) |
| 606 | * |
| 607 | * @example |
| 608 | * ```typescript |
| 609 | * const result = await composio.connectedAccounts.revoke('conn_abc123'); |
| 610 | * console.log(result.connectedAccount.status); // 'REVOKED' |
| 611 | * console.log(result.revokedTokens); // e.g. ['access_token', 'refresh_token'] |
| 612 | * ``` |
| 613 | */ |
| 614 | async revoke( |
| 615 | nanoid: string, |
| 616 | requestOptions?: ComposioRequestOptions |
| 617 | ): Promise<ConnectedAccountRevokeResponse> { |
| 618 | try { |
| 619 | const result = await withCancellation( |
| 620 | () => this.client.connectedAccounts.revoke(nanoid, requestOptions), |
| 621 | requestOptions?.signal |
| 622 | ); |
| 623 | return transformConnectedAccountRevokeResponse(result); |
| 624 | } catch (error) { |
| 625 | if (error instanceof BadRequestError) { |
| 626 | throw new ComposioConnectedAccountRevocationNotSupportedError( |
| 627 | `Connected account ${nanoid} cannot be revoked programmatically: ${error.message}`, |
| 628 | { cause: error, meta: { nanoid } } |
| 629 | ); |
| 630 | } |
| 631 | if (error instanceof ConflictError) { |
| 632 | throw new ComposioConnectedAccountNotRevokableError( |
| 633 | `Connected account ${nanoid} is not in a revokable state: ${error.message}`, |
| 634 | { cause: error, meta: { nanoid } } |
| 635 | ); |
| 636 | } |
| 637 | throw error; |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | /** |
| 642 | * Complete a deferred OAuth connection once you have verified the user's |
| 643 | * identity. |
| 644 | * |
| 645 | * When your project has an OAuth callback verifier configured, Composio |
| 646 | * does not activate a new OAuth connection by itself: it redirects to your |
| 647 | * verifier with a single-use session URI. After confirming who the user is, |
| 648 | * redeem that session URI here; Composio checks that your project owns the |
| 649 | * pending connection and that `userId` is its owner, completes the token |
| 650 | * exchange, and the connection becomes `ACTIVE`. |
| 651 | * |
| 652 | * The session URI is single-use: redeeming it twice, or after it expires, |
| 653 | * fails with a 404 from the API. |
| 654 | * |
| 655 | * @param {ConnectedAccountCompleteAuthParams} params - `userId` the connection was initiated for and the verifier's `sessionUri` |
| 656 | * @returns {Promise<ConnectedAccountCompleteAuthResponse>} The completed connection's ID and toolkit |
| 657 | * @throws {ValidationError} If the params fail validation |
| 658 | * |
| 659 | * @example |
| 660 | * ```typescript |
| 661 | * // In your verifier route, after authenticating the user: |
| 662 | * const { connectedAccountId, toolkitSlug } = await composio.connectedAccounts.completeAuth({ |
| 663 | * userId: 'user_123', |
| 664 | * sessionUri, // the session URI from the verifier redirect |
| 665 | * }); |
| 666 | * ``` |
| 667 | */ |
| 668 | async completeAuth( |
| 669 | params: ConnectedAccountCompleteAuthParams, |
| 670 | requestOptions?: ComposioRequestOptions |
| 671 | ): Promise<ConnectedAccountCompleteAuthResponse> { |
| 672 | const parsedParams = ConnectedAccountCompleteAuthParamsSchema.safeParse(params); |
| 673 | if (!parsedParams.success) { |
| 674 | throw new ValidationError('Failed to parse connected account completeAuth params', { |
| 675 | cause: parsedParams.error, |
| 676 | }); |
| 677 | } |
| 678 | const result = await withCancellation( |
| 679 | () => |
| 680 | this.client.connectedAccounts.completeAuth( |
| 681 | { |
| 682 | user_id: parsedParams.data.userId, |
| 683 | session_uri: parsedParams.data.sessionUri, |
| 684 | }, |
| 685 | requestOptions |
| 686 | ), |
| 687 | requestOptions?.signal |
| 688 | ); |
| 689 | return transformConnectedAccountCompleteAuthResponse(result); |
| 690 | } |
| 691 | |
| 692 | /** |
| 693 | * Update the status of a connected account |
| 694 | * @param {string} nanoid - Unique identifier of the connected account |
| 695 | * @param {ConnectedAccountUpdateStatusParams} params - Parameters for updating the status |
| 696 | * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details |
| 697 | * |
| 698 | * @example |
| 699 | * ```typescript |
| 700 | * // Enable a connected account |
| 701 | * const updatedAccount = await composio.connectedAccounts.updateStatus('conn_abc123', { |
| 702 | * enabled: true |
| 703 | * }); |
| 704 | * |
| 705 | * // Disable a connected account with a reason |
| 706 | * const disabledAccount = await composio.connectedAccounts.updateStatus('conn_abc123', { |
| 707 | * enabled: false, |
| 708 | * reason: 'Token expired' |
| 709 | * }); |
| 710 | * ``` |
| 711 | */ |
| 712 | async updateStatus( |
| 713 | nanoid: string, |
| 714 | params: ConnectedAccountUpdateStatusParams, |
| 715 | requestOptions?: ComposioRequestOptions |
| 716 | ): Promise<ConnectedAccountUpdateStatusResponse> { |
| 717 | return withCancellation( |
| 718 | () => this.client.connectedAccounts.updateStatus(nanoid, params, requestOptions), |
| 719 | requestOptions?.signal |
| 720 | ); |
| 721 | } |
| 722 | |
| 723 | /** |
| 724 | * Enable a connected account |
| 725 | * @param {string} nanoid - Unique identifier of the connected account |
| 726 | * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details |
| 727 | * |
| 728 | * @example |
| 729 | * ```typescript |
| 730 | * // Enable a previously disabled connected account |
| 731 | * const enabledAccount = await composio.connectedAccounts.enable('conn_abc123'); |
| 732 | * console.log(enabledAccount.isDisabled); // false |
| 733 | * ``` |
| 734 | */ |
| 735 | async enable( |
| 736 | nanoid: string, |
| 737 | requestOptions?: ComposioRequestOptions |
| 738 | ): Promise<ConnectedAccountUpdateStatusResponse> { |
| 739 | return withCancellation( |
| 740 | () => this.client.connectedAccounts.updateStatus(nanoid, { enabled: true }, requestOptions), |
| 741 | requestOptions?.signal |
| 742 | ); |
| 743 | } |
| 744 | |
| 745 | /** |
| 746 | * Disable a connected account |
| 747 | * @param {string} nanoid - Unique identifier of the connected account |
| 748 | * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details |
| 749 | * |
| 750 | * @example |
| 751 | * ```typescript |
| 752 | * // Disable a connected account |
| 753 | * const disabledAccount = await composio.connectedAccounts.disable('conn_abc123'); |
| 754 | * console.log(disabledAccount.isDisabled); // true |
| 755 | * |
| 756 | * // You can also use updateStatus with a reason |
| 757 | * // const disabledAccount = await composio.connectedAccounts.updateStatus('conn_abc123', { |
| 758 | * // enabled: false, |
| 759 | * // reason: 'No longer needed' |
| 760 | * // }); |
| 761 | * ``` |
| 762 | */ |
| 763 | async disable( |
| 764 | nanoid: string, |
| 765 | requestOptions?: ComposioRequestOptions |
| 766 | ): Promise<ConnectedAccountUpdateStatusResponse> { |
| 767 | return withCancellation( |
| 768 | () => this.client.connectedAccounts.updateStatus(nanoid, { enabled: false }, requestOptions), |
| 769 | requestOptions?.signal |
| 770 | ); |
| 771 | } |
| 772 | |
| 773 | /** |
| 774 | * Update the per-user ACL on a SHARED connected account. |
| 775 | * **Experimental — shape may change in future releases.** |
| 776 | * |
| 777 | * Only meaningful for SHARED connections — calling this on a PRIVATE |
| 778 | * connection raises `ComposioAclOnlyForSharedError` (400). ACL writes |
| 779 | * require the connection's creator or an API key. |
| 780 | * |
| 781 | * PATCH semantics: omit a field to leave it unchanged; pass an empty |
| 782 | * array to clear an allow/deny list. At least one field must be |
| 783 | * provided. |
| 784 | * |
| 785 | * @param {string} nanoid - The unique identifier of the connected account |
| 786 | * @param {UpdateConnectedAccountAclParams} params - The ACL fields to patch |
| 787 | * @returns {Promise<ConnectedAccountPatchResponse>} The PATCH response |
| 788 | * |
| 789 | * @example |
| 790 | * ```typescript |
| 791 | * // Allow every userId to use this SHARED connection |
| 792 | * await composio.connectedAccounts.updateAcl('ca_abc123', { allowAllUsers: true }); |
| 793 | * |
| 794 | * // Targeted allow list |
| 795 | * await composio.connectedAccounts.updateAcl('ca_abc123', { |
| 796 | * allowedUserIds: ['user_alice', 'user_bob'], |
| 797 | * }); |
| 798 | * |
| 799 | * // Clear the allow list (back to deny-by-default unless allowAllUsers is true) |
| 800 | * await composio.connectedAccounts.updateAcl('ca_abc123', { allowedUserIds: [] }); |
| 801 | * ``` |
| 802 | */ |
| 803 | async updateAcl( |
| 804 | nanoid: string, |
| 805 | params: UpdateConnectedAccountAclParams |
| 806 | ): Promise<ConnectedAccountPatchResponse> { |
| 807 | return updateConnectedAccountAcl(this.client, nanoid, params); |
| 808 | } |
| 809 | |
| 810 | /** |
| 811 | * Enable or disable a connected account. Accepts `{ enabled: boolean }`. |
| 812 | * |
| 813 | * Use `updateAcl()` for ACL writes on SHARED connections. |
| 814 | * |
| 815 | * @param {string} nanoid - The unique identifier of the connected account |
| 816 | * @param {UpdateConnectedAccountParams} params - The update parameters |
| 817 | * @returns {Promise<ConnectedAccountUpdateStatusResponse>} The update response |
| 818 | * |
| 819 | * @example |
| 820 | * ```typescript |
| 821 | * // Disable an account |
| 822 | * await composio.connectedAccounts.update('ca_abc123', { enabled: false }); |
| 823 | * ``` |
| 824 | */ |
| 825 | async update( |
| 826 | nanoid: string, |
| 827 | params: UpdateConnectedAccountParams, |
| 828 | requestOptions?: ComposioRequestOptions |
| 829 | ): Promise<ConnectedAccountUpdateStatusResponse> { |
| 830 | const parsedParams = UpdateConnectedAccountParamsSchema.safeParse(params); |
| 831 | if (!parsedParams.success) { |
| 832 | throw new ValidationError('Failed to parse connected account update params', { |
| 833 | cause: parsedParams.error, |
| 834 | }); |
| 835 | } |
| 836 | |
| 837 | return withCancellation( |
| 838 | () => this.client.connectedAccounts.updateStatus(nanoid, parsedParams.data, requestOptions), |
| 839 | requestOptions?.signal |
| 840 | ); |
| 841 | } |
| 842 | } |