Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 04:45 UTC
| 1 | import ComposioClient, { APIError } from '@composio/client'; |
| 2 | import type { TriggerInstanceUpsertParams as ClientTriggerInstanceUpsertParams } from '@composio/client/resources/trigger-instances'; |
| 3 | import { TriggersTypeRetrieveEnumResponse } from '@composio/client/resources/triggers-types'; |
| 4 | import { |
| 5 | TriggerInstanceUpsertResponse, |
| 6 | TriggerInstanceUpsertParamsSchema, |
| 7 | TriggerInstanceUpsertParams, |
| 8 | TriggerInstanceListActiveParams, |
| 9 | TriggerInstanceListActiveParamsSchema, |
| 10 | TriggerInstanceListActiveResponse, |
| 11 | TriggerSubscribeParams, |
| 12 | TriggerInstanceManageUpdateParams, |
| 13 | TriggerInstanceManageUpdateResponse, |
| 14 | TriggerInstanceManageDeleteResponse, |
| 15 | TriggerSubscribeParamSchema, |
| 16 | IncomingTriggerPayload, |
| 17 | TriggerData, |
| 18 | TriggersTypeListParams, |
| 19 | TriggersTypeListResponse, |
| 20 | TriggersTypeListParamsSchema, |
| 21 | TriggersTypeRetrieveResponse, |
| 22 | VerifyWebhookParams, |
| 23 | VerifyWebhookParamsSchema, |
| 24 | VerifyWebhookResult, |
| 25 | ParseWebhookOptions, |
| 26 | WebhookRequestLike, |
| 27 | WebhookPayload, |
| 28 | WebhookPayloadV1Schema, |
| 29 | WebhookPayloadV2Schema, |
| 30 | WebhookPayloadV3Schema, |
| 31 | WebhookTriggerPayloadV3Schema, |
| 32 | WebhookVersion, |
| 33 | WebhookVersions, |
| 34 | SetWebhookSubscriptionParams, |
| 35 | WebhookSubscription, |
| 36 | } from '../types/triggers.types'; |
| 37 | import { upsertWebhookSubscription } from './Webhooks'; |
| 38 | import logger from '../utils/logger'; |
| 39 | import { telemetry } from '../telemetry/Telemetry'; |
| 40 | import { ValidationError } from '../errors'; |
| 41 | import { PusherService } from '../services/pusher/Pusher'; |
| 42 | import { |
| 43 | ComposioTriggerTypeNotFoundError, |
| 44 | ComposioWebhookPayloadError, |
| 45 | ComposioWebhookSignatureVerificationError, |
| 46 | } from '../errors/TriggerErrors'; |
| 47 | import { transform } from '../utils/transform'; |
| 48 | import { |
| 49 | transformIncomingTriggerPayload, |
| 50 | transformTriggerInstanceListActiveResponse, |
| 51 | transformTriggerTypeListResponse, |
| 52 | transformTriggerTypeRetrieveResponse, |
| 53 | } from '../utils/transformers/triggers'; |
| 54 | import { ToolkitVersionParam } from '../types/tool.types'; |
| 55 | import type { ComposioConfig } from '../composio'; |
| 56 | import type { BaseComposioProvider } from '../provider/BaseProvider'; |
| 57 | import { hmacSha256Base64, timingSafeEqual } from '../utils/crypto'; |
| 58 | import { CONFIG_DEFAULTS } from '../utils/config-defaults'; |
| 59 | import { ComposioRequestOptions } from '../types/requestOptions.types'; |
| 60 | import { withCancellation } from '../utils/cancellation'; |
| 61 | import { invokeUserCallback } from '../utils/userCallback'; |
| 62 | |
| 63 | /** |
| 64 | * Safely converts a value to a string, returning the default if the value is null, undefined, or empty. |
| 65 | * This prevents runtime crashes when calling string methods like `.toLowerCase()` on non-string values. |
| 66 | * @private |
| 67 | */ |
| 68 | const toStringOrDefault = (value: unknown, defaultValue: string): string => { |
| 69 | if (value === null || value === undefined) { |
| 70 | return defaultValue; |
| 71 | } |
| 72 | const str = String(value); |
| 73 | return str.length > 0 ? str : defaultValue; |
| 74 | }; |
| 75 | |
| 76 | /** |
| 77 | * The signature header names Composio sends with every webhook delivery. |
| 78 | * @private |
| 79 | */ |
| 80 | const WEBHOOK_HEADERS = { |
| 81 | id: 'webhook-id', |
| 82 | timestamp: 'webhook-timestamp', |
| 83 | signature: 'webhook-signature', |
| 84 | } as const; |
| 85 | |
| 86 | /** |
| 87 | * Returns true if the value is a Fetch API `Request`. |
| 88 | * @private |
| 89 | */ |
| 90 | const isFetchRequest = (request: WebhookRequestLike): request is Request => |
| 91 | typeof Request !== 'undefined' && request instanceof Request; |
| 92 | |
| 93 | /** |
| 94 | * Reads a single header value case-insensitively from either a `Headers` |
| 95 | * instance or a plain record (where values may be `string | string[]`). |
| 96 | * Returns `undefined` when the header is missing. |
| 97 | * @private |
| 98 | */ |
| 99 | const getHeader = (headers: unknown, name: string): string | undefined => { |
| 100 | if (typeof Headers !== 'undefined' && headers instanceof Headers) { |
| 101 | return headers.get(name) ?? undefined; |
| 102 | } |
| 103 | |
| 104 | if (headers === null || typeof headers !== 'object') { |
| 105 | return undefined; |
| 106 | } |
| 107 | |
| 108 | // Plain record: match the header name case-insensitively. |
| 109 | const target = name.toLowerCase(); |
| 110 | for (const [key, value] of Object.entries(headers as Record<string, unknown>)) { |
| 111 | if (key.toLowerCase() !== target) { |
| 112 | continue; |
| 113 | } |
| 114 | if (Array.isArray(value)) { |
| 115 | const first = value.find((item): item is string => typeof item === 'string'); |
| 116 | return first; |
| 117 | } |
| 118 | return typeof value === 'string' ? value : undefined; |
| 119 | } |
| 120 | return undefined; |
| 121 | }; |
| 122 | |
| 123 | /** |
| 124 | * Coerces an object request body (string, Buffer/Uint8Array, or already-parsed |
| 125 | * value) into the raw string form expected by signature verification. |
| 126 | * @private |
| 127 | */ |
| 128 | const bodyToString = (body: unknown): string => { |
| 129 | if (typeof body === 'string') { |
| 130 | return body; |
| 131 | } |
| 132 | if (body instanceof Uint8Array) { |
| 133 | return new TextDecoder().decode(body); |
| 134 | } |
| 135 | if (body === null || body === undefined) { |
| 136 | return ''; |
| 137 | } |
| 138 | // Already-parsed object (e.g. Next.js Pages Router with the JSON body parser). |
| 139 | // Note: re-stringifying cannot reproduce the exact bytes Composio signed, so |
| 140 | // signature verification on a pre-parsed body is best-effort only. |
| 141 | if (typeof body === 'object') { |
| 142 | return JSON.stringify(body); |
| 143 | } |
| 144 | return String(body); |
| 145 | }; |
| 146 | |
| 147 | /** |
| 148 | * Trigger (Instance) class |
| 149 | * /api/v3/trigger_instances |
| 150 | * |
| 151 | */ |
| 152 | export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, unknown>> { |
| 153 | private client: ComposioClient; |
| 154 | private pusherService: PusherService; |
| 155 | private toolkitVersions: ToolkitVersionParam; |
| 156 | |
| 157 | constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) { |
| 158 | this.client = client; |
| 159 | this.pusherService = new PusherService(client, { |
| 160 | apiKey: config?.apiKey, |
| 161 | userApiKey: config?.userApiKey, |
| 162 | orgApiKey: config?.orgApiKey, |
| 163 | defaultHeaders: config?.defaultHeaders, |
| 164 | }); |
| 165 | this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions; |
| 166 | telemetry.instrument(this, 'Triggers'); |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Create or update the project webhook subscription used for webhook delivery. |
| 171 | * |
| 172 | * If a subscription already exists, the first subscription is updated. Otherwise a new |
| 173 | * subscription is created. By default this subscribes to V3 trigger message events. |
| 174 | * |
| 175 | * @example |
| 176 | * ```ts |
| 177 | * await composio.triggers.setWebhookSubscription({ |
| 178 | * webhookUrl: `${APP_URL}/webhooks/composio`, |
| 179 | * }); |
| 180 | * ``` |
| 181 | */ |
| 182 | async setWebhookSubscription(params: SetWebhookSubscriptionParams): Promise<WebhookSubscription> { |
| 183 | return upsertWebhookSubscription(this.client, params); |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Fetch list of all the active triggers |
| 188 | * |
| 189 | * @param {TriggerInstanceListActiveParams} query - The query parameters to filter the trigger instances |
| 190 | * @returns {Promise<TriggerInstanceListActiveResponse>} List of trigger instances |
| 191 | * |
| 192 | * @throws {ValidationError} If the parameters are invalid |
| 193 | * @throws {Error} If the client is not authenticated |
| 194 | * |
| 195 | * @example |
| 196 | * ```ts |
| 197 | * const triggers = await triggers.listActive({ |
| 198 | * authConfigIds: ['123'], |
| 199 | * connectedAccountIds: ['456'], |
| 200 | * }); |
| 201 | * ``` |
| 202 | */ |
| 203 | async listActive( |
| 204 | query?: TriggerInstanceListActiveParams, |
| 205 | requestOptions?: ComposioRequestOptions |
| 206 | ): Promise<TriggerInstanceListActiveResponse> { |
| 207 | // Validate the parameters if provided |
| 208 | |
| 209 | const parsedParams = TriggerInstanceListActiveParamsSchema.safeParse(query ?? {}); |
| 210 | |
| 211 | if (!parsedParams.success) { |
| 212 | throw new ValidationError(`Invalid parameters passed to list triggers`, { |
| 213 | cause: parsedParams.error, |
| 214 | }); |
| 215 | } |
| 216 | |
| 217 | const listParams = query |
| 218 | ? { |
| 219 | auth_config_ids: parsedParams.data.authConfigIds, |
| 220 | connected_account_ids: parsedParams.data.connectedAccountIds, |
| 221 | cursor: parsedParams.data.cursor, |
| 222 | limit: parsedParams.data.limit, |
| 223 | show_disabled: parsedParams.data.showDisabled, |
| 224 | trigger_ids: parsedParams.data.triggerIds, |
| 225 | trigger_names: parsedParams.data.triggerNames, |
| 226 | } |
| 227 | : undefined; |
| 228 | const result = await withCancellation( |
| 229 | () => this.client.triggerInstances.listActive(listParams, requestOptions), |
| 230 | requestOptions?.signal |
| 231 | ); |
| 232 | return transformTriggerInstanceListActiveResponse(result); |
| 233 | } |
| 234 | |
| 235 | /** |
| 236 | * Create a new trigger instance for a user |
| 237 | * If the connected account id is not provided, the first connected account for the user and toolkit will be used |
| 238 | * |
| 239 | * For a trigger that supports both webhook and polling, `body.type` picks one; omit it to let Composio choose. |
| 240 | * `body.pollingInterval` sets the minutes between polls and wins over `triggerConfig.interval`. |
| 241 | * |
| 242 | * @param {string} userId - The user id of the trigger instance |
| 243 | * @param {string} slug - The slug of the trigger instance |
| 244 | * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance |
| 245 | * @returns {Promise<TriggerInstanceUpsertResponse>} The trigger instance, with the type it uses, why it polls |
| 246 | * when it fell back from a webhook, and its polling interval |
| 247 | */ |
| 248 | async create( |
| 249 | userId: string, |
| 250 | slug: string, |
| 251 | body?: TriggerInstanceUpsertParams, |
| 252 | requestOptions?: ComposioRequestOptions |
| 253 | ): Promise<TriggerInstanceUpsertResponse> { |
| 254 | if (!userId?.trim()) { |
| 255 | throw new ValidationError(`A non-empty userId is required to create a trigger`); |
| 256 | } |
| 257 | |
| 258 | const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body ?? {}); |
| 259 | |
| 260 | if (!parsedBody.success) { |
| 261 | throw new ValidationError(`Invalid parameters passed to create trigger`, { |
| 262 | cause: parsedBody.error, |
| 263 | }); |
| 264 | } |
| 265 | |
| 266 | // Validate the trigger slug up-front so callers get a clear client-side |
| 267 | // `ComposioTriggerTypeNotFoundError`. The Python SDK mirrors this behavior. |
| 268 | try { |
| 269 | await this.getType(slug, requestOptions); |
| 270 | } catch (error) { |
| 271 | // The trigger types endpoint returns 400 (not 404) for an unknown slug. |
| 272 | if (error instanceof APIError && (error.status === 400 || error.status === 404)) { |
| 273 | throw new ComposioTriggerTypeNotFoundError(`Trigger type ${slug} not found`, { |
| 274 | cause: error, |
| 275 | possibleFixes: [ |
| 276 | `Please check the trigger slug`, |
| 277 | `Please check the provided version of toolkit has the trigger`, |
| 278 | `Visit the toolkit page to see the available triggers`, |
| 279 | ], |
| 280 | }); |
| 281 | } |
| 282 | throw error; |
| 283 | } |
| 284 | |
| 285 | // Pass `user_id` straight through: when `connected_account_id` is omitted the |
| 286 | // backend resolves the first active connection for this user and the |
| 287 | // trigger's toolkit, mirroring tool execution. When 2FA is enabled and |
| 288 | // `connected_account_id` is pinned, the backend validates that `user_id` |
| 289 | // owns it. |
| 290 | const upsertParams: ClientTriggerInstanceUpsertParams = { |
| 291 | connected_account_id: parsedBody.data.connectedAccountId, |
| 292 | trigger_config: parsedBody.data.triggerConfig, |
| 293 | type: parsedBody.data.type, |
| 294 | polling_interval: parsedBody.data.pollingInterval, |
| 295 | toolkit_versions: this.toolkitVersions, |
| 296 | user_id: userId, |
| 297 | }; |
| 298 | const result = await withCancellation( |
| 299 | () => this.client.triggerInstances.upsert(slug, upsertParams, requestOptions), |
| 300 | requestOptions?.signal |
| 301 | ); |
| 302 | |
| 303 | return { |
| 304 | triggerId: result.trigger_id, |
| 305 | type: result.type, |
| 306 | fallbackReason: result.fallback_reason, |
| 307 | pollingInterval: result.polling_interval, |
| 308 | }; |
| 309 | } |
| 310 | |
| 311 | /** |
| 312 | * Update an existing trigger instance |
| 313 | * |
| 314 | * @param {string} triggerId - The Id of the trigger instance |
| 315 | * @param {TriggerInstanceManageUpdateParams} body - The parameters to update the trigger instance |
| 316 | * @returns {Promise<TriggerInstanceManageUpdateResponse>} The updated trigger instance response |
| 317 | */ |
| 318 | async update( |
| 319 | triggerId: string, |
| 320 | body: TriggerInstanceManageUpdateParams, |
| 321 | requestOptions?: ComposioRequestOptions |
| 322 | ): Promise<TriggerInstanceManageUpdateResponse> { |
| 323 | return withCancellation( |
| 324 | () => this.client.triggerInstances.manage.update(triggerId, body, requestOptions), |
| 325 | requestOptions?.signal |
| 326 | ); |
| 327 | } |
| 328 | |
| 329 | /** |
| 330 | * Delete a trigger instance |
| 331 | * |
| 332 | * @param {string} triggerId - The slug of the trigger instance |
| 333 | * @returns |
| 334 | */ |
| 335 | async delete( |
| 336 | triggerId: string, |
| 337 | requestOptions?: ComposioRequestOptions |
| 338 | ): Promise<TriggerInstanceManageDeleteResponse> { |
| 339 | const result = await withCancellation( |
| 340 | () => this.client.triggerInstances.manage.delete(triggerId, requestOptions), |
| 341 | requestOptions?.signal |
| 342 | ); |
| 343 | return { |
| 344 | triggerId: result.trigger_id, |
| 345 | }; |
| 346 | } |
| 347 | |
| 348 | /** |
| 349 | * Disable a trigger instance |
| 350 | * |
| 351 | * @param {string} triggerId - The id of the trigger instance |
| 352 | * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance |
| 353 | */ |
| 354 | async disable(triggerId: string, requestOptions?: ComposioRequestOptions) { |
| 355 | const body = { status: 'disable' as const }; |
| 356 | return withCancellation( |
| 357 | () => this.client.triggerInstances.manage.update(triggerId, body, requestOptions), |
| 358 | requestOptions?.signal |
| 359 | ); |
| 360 | } |
| 361 | |
| 362 | /** |
| 363 | * Enable a trigger instance |
| 364 | * |
| 365 | * @param {string} triggerId - The id of the trigger instance |
| 366 | * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance |
| 367 | */ |
| 368 | async enable(triggerId: string, requestOptions?: ComposioRequestOptions) { |
| 369 | const body = { status: 'enable' as const }; |
| 370 | return withCancellation( |
| 371 | () => this.client.triggerInstances.manage.update(triggerId, body, requestOptions), |
| 372 | requestOptions?.signal |
| 373 | ); |
| 374 | } |
| 375 | |
| 376 | /** |
| 377 | * @TODO Learn about trigger types |
| 378 | */ |
| 379 | /** |
| 380 | * List all the trigger types |
| 381 | * |
| 382 | * @param {TriggersTypeListParams} query - The query parameters to filter the trigger types |
| 383 | * @param {RequestOptions} options - Request options |
| 384 | * @returns {Promise<TriggersTypeListResponse>} The list of trigger types |
| 385 | */ |
| 386 | async listTypes( |
| 387 | query?: TriggersTypeListParams, |
| 388 | requestOptions?: ComposioRequestOptions |
| 389 | ): Promise<TriggersTypeListResponse> { |
| 390 | const parsedQuery = transform(query ?? {}) |
| 391 | .with(TriggersTypeListParamsSchema) |
| 392 | .using(raw => raw); |
| 393 | |
| 394 | const listParams = { |
| 395 | cursor: parsedQuery.cursor, |
| 396 | limit: parsedQuery.limit, |
| 397 | toolkit_slugs: parsedQuery.toolkits, |
| 398 | toolkit_versions: this.toolkitVersions, |
| 399 | }; |
| 400 | const result = await withCancellation( |
| 401 | () => this.client.triggersTypes.list(listParams, requestOptions), |
| 402 | requestOptions?.signal |
| 403 | ); |
| 404 | |
| 405 | return transformTriggerTypeListResponse(result); |
| 406 | } |
| 407 | |
| 408 | /** |
| 409 | * Retrieve a trigger type by its slug for the provided version of the app |
| 410 | * Use the global toolkit versions param when initializing composio to pass a toolkitversion |
| 411 | * |
| 412 | * @param {string} slug - The slug of the trigger type |
| 413 | * @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object |
| 414 | */ |
| 415 | async getType( |
| 416 | slug: string, |
| 417 | requestOptions?: ComposioRequestOptions |
| 418 | ): Promise<TriggersTypeRetrieveResponse> { |
| 419 | const retrieveParams = { |
| 420 | // if the version is provided override the global version |
| 421 | toolkit_versions: this.toolkitVersions, |
| 422 | }; |
| 423 | const result = await withCancellation( |
| 424 | () => this.client.triggersTypes.retrieve(slug, retrieveParams, requestOptions), |
| 425 | requestOptions?.signal |
| 426 | ); |
| 427 | return transformTriggerTypeRetrieveResponse(result); |
| 428 | } |
| 429 | |
| 430 | /** |
| 431 | * Fetches the list of all the available trigger enums |
| 432 | * |
| 433 | * This method is used by the CLI where filters are not required. |
| 434 | * @returns |
| 435 | */ |
| 436 | async listEnum( |
| 437 | requestOptions?: ComposioRequestOptions |
| 438 | ): Promise<TriggersTypeRetrieveEnumResponse> { |
| 439 | return withCancellation( |
| 440 | () => this.client.triggersTypes.retrieveEnum(requestOptions), |
| 441 | requestOptions?.signal |
| 442 | ); |
| 443 | } |
| 444 | |
| 445 | /** |
| 446 | * Applies compound filters to the trigger data |
| 447 | * @param data data to apply filters to |
| 448 | * @returns True if the trigger data matches the filters, false otherwise |
| 449 | */ |
| 450 | private shouldSendTriggerAfterFilters( |
| 451 | filters: TriggerSubscribeParams, |
| 452 | data: IncomingTriggerPayload |
| 453 | ): boolean { |
| 454 | // Check if toolkits filter is provided and matches. |
| 455 | // Payloads don't carry the toolkit slug, so `data.toolkitSlug` is the trigger slug's |
| 456 | // first `_` segment, which is wrong for toolkits whose slug contains an underscore |
| 457 | // (`ONE_DRIVE_FILE_CREATED_TRIGGER` gives `ONE`). Trigger slugs start with |
| 458 | // `<TOOLKIT>_`, so a filter also matches on that prefix. |
| 459 | const toolkitSlug = data.toolkitSlug.toLowerCase(); |
| 460 | const triggerSlug = data.triggerSlug.toLowerCase(); |
| 461 | if ( |
| 462 | filters.toolkits?.length && |
| 463 | !filters.toolkits |
| 464 | .map(toolkit => toolkit.toLowerCase()) |
| 465 | .some(toolkit => toolkit === toolkitSlug || triggerSlug.startsWith(`${toolkit}_`)) |
| 466 | ) { |
| 467 | logger.debug( |
| 468 | 'Trigger does not match toolkits filter', |
| 469 | JSON.stringify(filters.toolkits, null, 2) |
| 470 | ); |
| 471 | return false; |
| 472 | } |
| 473 | |
| 474 | // Check if triggerId filter matches |
| 475 | if (filters.triggerId && filters.triggerId !== data.id) { |
| 476 | logger.debug( |
| 477 | 'Trigger does not match triggerId filter', |
| 478 | JSON.stringify(filters.triggerId, null, 2) |
| 479 | ); |
| 480 | return false; |
| 481 | } |
| 482 | |
| 483 | // Check if connectedAccountId filter matches |
| 484 | if ( |
| 485 | filters.connectedAccountId && |
| 486 | filters.connectedAccountId !== data.metadata.connectedAccount.id |
| 487 | ) { |
| 488 | logger.debug( |
| 489 | 'Trigger does not match connectedAccountId filter', |
| 490 | JSON.stringify(filters.connectedAccountId, null, 2) |
| 491 | ); |
| 492 | return false; |
| 493 | } |
| 494 | |
| 495 | // Check if authConfigId filter matches. |
| 496 | // Only V3 trigger payloads (and the legacy TriggerData shape) carry an auth config id; |
| 497 | // V1/V2 payloads and non-trigger V3 events normalize it to '', so this filter drops |
| 498 | // those events entirely. This mirrors the Python SDK's `auth_config_id` filter. |
| 499 | if ( |
| 500 | filters.authConfigId && |
| 501 | filters.authConfigId !== data.metadata.connectedAccount.authConfigId |
| 502 | ) { |
| 503 | logger.debug( |
| 504 | 'Trigger does not match authConfigId filter', |
| 505 | JSON.stringify(filters.authConfigId, null, 2) |
| 506 | ); |
| 507 | return false; |
| 508 | } |
| 509 | |
| 510 | // Check if triggerName filter matches |
| 511 | if ( |
| 512 | filters.triggerSlug?.length && |
| 513 | !filters.triggerSlug |
| 514 | .map(triggerSlug => triggerSlug.toLowerCase()) |
| 515 | .includes(data.triggerSlug.toLowerCase()) |
| 516 | ) { |
| 517 | logger.debug( |
| 518 | 'Trigger does not match triggerSlug filter', |
| 519 | JSON.stringify(filters.triggerSlug, null, 2) |
| 520 | ); |
| 521 | return false; |
| 522 | } |
| 523 | |
| 524 | // Check if triggerData filter matches |
| 525 | if (filters.triggerData && filters.triggerData !== data.metadata.triggerData) { |
| 526 | logger.debug( |
| 527 | 'Trigger does not match triggerData filter', |
| 528 | JSON.stringify(filters.triggerData, null, 2) |
| 529 | ); |
| 530 | return false; |
| 531 | } |
| 532 | |
| 533 | // Check if userId (clientUniqueUserId) filter matches |
| 534 | if (filters.userId && filters.userId !== data.metadata.connectedAccount.userId) { |
| 535 | logger.debug('Trigger does not match userId filter', JSON.stringify(filters.userId, null, 2)); |
| 536 | return false; |
| 537 | } |
| 538 | |
| 539 | logger.debug('Trigger matches all filters', JSON.stringify(filters, null, 2)); |
| 540 | // If all filters pass or no filters were provided, return true |
| 541 | return true; |
| 542 | } |
| 543 | |
| 544 | /** |
| 545 | * Subscribe to all the triggers |
| 546 | * |
| 547 | * @param fn - The function to call when a trigger is received. It may be `async`. Errors |
| 548 | * thrown from — or promises rejected by — the function are contained and logged. |
| 549 | * @param filters - The filters to apply to the triggers |
| 550 | * @param onSubscriptionError - Optional callback invoked with the raw Pusher payload when |
| 551 | * the underlying subscription fails (for example on auth or permission rejection). The |
| 552 | * subscribe promise still resolves; this is the only programmatic signal of the failure. |
| 553 | * Errors thrown from — or promises rejected by — the callback are contained and logged. |
| 554 | * |
| 555 | * @example |
| 556 | * ```ts |
| 557 | * |
| 558 | * triggers.subscribe((data) => { |
| 559 | * console.log(data); |
| 560 | * }, ); |
| 561 | * ``` |
| 562 | */ |
| 563 | async subscribe( |
| 564 | fn: (_data: IncomingTriggerPayload) => void, |
| 565 | filters: TriggerSubscribeParams = {}, |
| 566 | onSubscriptionError?: (data: Record<string, unknown>) => void |
| 567 | ) { |
| 568 | if (!fn) throw new Error('Function is required for trigger subscription'); |
| 569 | |
| 570 | const parsedFilters = TriggerSubscribeParamSchema.safeParse(filters); |
| 571 | |
| 572 | if (!parsedFilters.success) { |
| 573 | throw new ValidationError(`Invalid parameters passed to subscribe to triggers`, { |
| 574 | cause: parsedFilters.error, |
| 575 | }); |
| 576 | } |
| 577 | |
| 578 | logger.debug('🔄 Subscribing to triggers with filters: ', JSON.stringify(filters, null, 2)); |
| 579 | await this.pusherService.subscribe((_data: Record<string, unknown>) => { |
| 580 | logger.debug('Received raw trigger data', JSON.stringify(_data, null, 2)); |
| 581 | |
| 582 | // Parse using unified method that handles V1/V2/V3 and legacy formats |
| 583 | const parsedData = this.parsePusherPayload(_data); |
| 584 | |
| 585 | if (this.shouldSendTriggerAfterFilters(parsedFilters.data, parsedData)) { |
| 586 | invokeUserCallback('❌ Error in trigger callback:', () => fn(parsedData)); |
| 587 | } else { |
| 588 | logger.debug('Trigger does not match filters', JSON.stringify(parsedFilters.data, null, 2)); |
| 589 | } |
| 590 | }, onSubscriptionError); |
| 591 | } |
| 592 | |
| 593 | /** |
| 594 | * Tries to parse data as V1, V2, or V3 webhook payload format. |
| 595 | * Returns the parsed result with version info, or null if no format matches. |
| 596 | * Also returns any schema validation errors for debugging purposes. |
| 597 | * @private |
| 598 | */ |
| 599 | private tryParseVersionedPayload(data: unknown): |
| 600 | | { |
| 601 | ok: true; |
| 602 | version: WebhookVersion; |
| 603 | rawPayload: WebhookPayload; |
| 604 | normalizedPayload: IncomingTriggerPayload; |
| 605 | } |
| 606 | | { |
| 607 | ok: false; |
| 608 | v1Error: string; |
| 609 | v2Error: string; |
| 610 | v3Error: string; |
| 611 | } { |
| 612 | // Try V3 first (has 'composio.trigger.message' type) |
| 613 | const v3Result = WebhookPayloadV3Schema.safeParse(data); |
| 614 | if (v3Result.success) { |
| 615 | return { |
| 616 | ok: true, |
| 617 | version: WebhookVersions.V3, |
| 618 | rawPayload: v3Result.data, |
| 619 | normalizedPayload: this.normalizeV3Payload(v3Result.data), |
| 620 | }; |
| 621 | } |
| 622 | |
| 623 | // Try V2 (has 'type', 'timestamp', 'log_id', and 'data') |
| 624 | const v2Result = WebhookPayloadV2Schema.safeParse(data); |
| 625 | if (v2Result.success) { |
| 626 | return { |
| 627 | ok: true, |
| 628 | version: WebhookVersions.V2, |
| 629 | rawPayload: v2Result.data, |
| 630 | normalizedPayload: this.normalizeV2Payload(v2Result.data), |
| 631 | }; |
| 632 | } |
| 633 | |
| 634 | // Try V1 (has 'trigger_name', 'connection_id', 'trigger_id', 'payload', 'log_id') |
| 635 | const v1Result = WebhookPayloadV1Schema.safeParse(data); |
| 636 | if (v1Result.success) { |
| 637 | return { |
| 638 | ok: true, |
| 639 | version: WebhookVersions.V1, |
| 640 | rawPayload: v1Result.data, |
| 641 | normalizedPayload: this.normalizeV1Payload(v1Result.data), |
| 642 | }; |
| 643 | } |
| 644 | |
| 645 | return { |
| 646 | ok: false, |
| 647 | v1Error: v1Result.error.message, |
| 648 | v2Error: v2Result.error.message, |
| 649 | v3Error: v3Result.error.message, |
| 650 | }; |
| 651 | } |
| 652 | |
| 653 | /** |
| 654 | * Parses incoming Pusher payload, supporting V1, V2, V3, and legacy TriggerData formats. |
| 655 | * @private |
| 656 | */ |
| 657 | private parsePusherPayload(data: Record<string, unknown>): IncomingTriggerPayload { |
| 658 | // Try V1/V2/V3 formats |
| 659 | const versionedResult = this.tryParseVersionedPayload(data); |
| 660 | if (versionedResult.ok) { |
| 661 | logger.debug(`Parsed Pusher payload as ${versionedResult.version} format`); |
| 662 | return versionedResult.normalizedPayload; |
| 663 | } |
| 664 | |
| 665 | // Try legacy TriggerData format (for backwards compatibility) |
| 666 | const legacyData = data as TriggerData; |
| 667 | if (legacyData.metadata?.nanoId && legacyData.appName) { |
| 668 | logger.debug('Parsed Pusher payload as legacy TriggerData format'); |
| 669 | return transformIncomingTriggerPayload(legacyData); |
| 670 | } |
| 671 | |
| 672 | // Fallback: log warning and return a minimal payload with available data |
| 673 | logger.warn('Unknown Pusher payload format. Payload keys: ' + Object.keys(data).join(', ')); |
| 674 | |
| 675 | // Return a minimal payload structure to avoid breaking the subscription |
| 676 | // Use toStringOrDefault to safely convert values and prevent crashes when |
| 677 | // non-string values are passed (e.g., numbers, objects) and .toLowerCase() is called later |
| 678 | const id = toStringOrDefault(data.id, toStringOrDefault(data.trigger_id, 'unknown')); |
| 679 | const uuid = toStringOrDefault(data.uuid, toStringOrDefault(data.id, 'unknown')); |
| 680 | const triggerSlug = toStringOrDefault( |
| 681 | data.triggerSlug, |
| 682 | toStringOrDefault(data.trigger_name, 'UNKNOWN') |
| 683 | ); |
| 684 | const toolkitSlug = toStringOrDefault( |
| 685 | data.toolkitSlug, |
| 686 | toStringOrDefault(data.appName, 'UNKNOWN') |
| 687 | ); |
| 688 | const userId = toStringOrDefault(data.userId, ''); |
| 689 | |
| 690 | return { |
| 691 | id, |
| 692 | uuid, |
| 693 | triggerSlug, |
| 694 | toolkitSlug, |
| 695 | userId, |
| 696 | payload: (data.payload as Record<string, unknown>) || data, |
| 697 | originalPayload: (data.originalPayload as Record<string, unknown>) || data, |
| 698 | metadata: { |
| 699 | id, |
| 700 | uuid, |
| 701 | triggerSlug, |
| 702 | toolkitSlug, |
| 703 | triggerConfig: {}, |
| 704 | connectedAccount: { |
| 705 | id: '', |
| 706 | uuid: '', |
| 707 | authConfigId: '', |
| 708 | authConfigUUID: '', |
| 709 | userId: '', |
| 710 | status: 'ACTIVE', |
| 711 | }, |
| 712 | }, |
| 713 | }; |
| 714 | } |
| 715 | |
| 716 | /** |
| 717 | * Unsubscribe from all the triggers |
| 718 | * |
| 719 | * Ends every subscription made with {@link subscribe} on this instance, including one that is |
| 720 | * still connecting, and closes the realtime connection so that a script can exit. A later |
| 721 | * `subscribe()` opens a new connection. |
| 722 | * |
| 723 | * @returns {Promise<void>} |
| 724 | * |
| 725 | * @example |
| 726 | * ```ts |
| 727 | * composio.trigger.subscribe((data) => { |
| 728 | * console.log(data); |
| 729 | * }); |
| 730 | * |
| 731 | * await triggers.unsubscribe(); |
| 732 | * ``` |
| 733 | */ |
| 734 | async unsubscribe() { |
| 735 | await this.pusherService.unsubscribe(); |
| 736 | } |
| 737 | |
| 738 | /** |
| 739 | * Parse an incoming webhook HTTP request into a typed, normalized trigger payload. |
| 740 | * |
| 741 | * Dump the incoming request in and get back the parsed Composio trigger event. |
| 742 | * When `verifySecret` is provided, the request signature is verified before the |
| 743 | * payload is returned (delegating to {@link verifyWebhook}); without it, the body |
| 744 | * is parsed without verification. |
| 745 | * |
| 746 | * The `request` may be either a Fetch API `Request` (Next.js App Router, Hono, |
| 747 | * Remix) or a plain `{ body, headers }` object (Express with `express.raw`, |
| 748 | * Next.js Pages Router `req`). The signature headers (`webhook-id`, |
| 749 | * `webhook-timestamp`, `webhook-signature`) are read case-insensitively. |
| 750 | * |
| 751 | * @param {WebhookRequestLike} request - The incoming webhook HTTP request |
| 752 | * @param {ParseWebhookOptions} [options] - Parse options |
| 753 | * @param {string} [options.verifySecret] - Webhook secret; when set, the signature is verified |
| 754 | * @param {number} [options.tolerance=300] - Max webhook age in seconds (only used when verifying) |
| 755 | * @returns {Promise<VerifyWebhookResult>} The parsed (and optionally verified) webhook payload |
| 756 | * |
| 757 | * @throws {ValidationError} If `verifySecret` is set but the signature headers are missing |
| 758 | * @throws {ComposioWebhookSignatureVerificationError} If signature verification fails |
| 759 | * @throws {ComposioWebhookPayloadError} If the payload cannot be parsed |
| 760 | * |
| 761 | * @example |
| 762 | * ```ts |
| 763 | * // Express with express.raw (verify the signature) |
| 764 | * app.post('/webhooks/composio', express.raw({ type: 'application/json' }), async (req, res) => { |
| 765 | * try { |
| 766 | * const result = await composio.triggers.parse(req, { |
| 767 | * verifySecret: process.env.COMPOSIO_WEBHOOK_SECRET, |
| 768 | * }); |
| 769 | * console.log('Trigger:', result.payload.triggerSlug); |
| 770 | * console.log('Event data:', result.payload.payload); |
| 771 | * res.sendStatus(200); |
| 772 | * } catch (error) { |
| 773 | * res.sendStatus(401); |
| 774 | * } |
| 775 | * }); |
| 776 | * |
| 777 | * // Express without verifying (parse only) |
| 778 | * app.post('/webhooks/composio', express.raw({ type: 'application/json' }), async (req, res) => { |
| 779 | * const result = await composio.triggers.parse(req); |
| 780 | * console.log('Trigger:', result.payload.triggerSlug); |
| 781 | * res.sendStatus(200); |
| 782 | * }); |
| 783 | * ``` |
| 784 | * |
| 785 | * @example |
| 786 | * ```ts |
| 787 | * // Next.js App Router (Request) — verify the signature |
| 788 | * export async function POST(request: Request) { |
| 789 | * try { |
| 790 | * const result = await composio.triggers.parse(request, { |
| 791 | * verifySecret: process.env.COMPOSIO_WEBHOOK_SECRET, |
| 792 | * }); |
| 793 | * console.log('Trigger:', result.payload.triggerSlug); |
| 794 | * console.log('Event data:', result.payload.payload); |
| 795 | * return new Response('OK', { status: 200 }); |
| 796 | * } catch (error) { |
| 797 | * return new Response('Unauthorized', { status: 401 }); |
| 798 | * } |
| 799 | * } |
| 800 | * |
| 801 | * // Next.js App Router — parse only (no verification) |
| 802 | * export async function POST(request: Request) { |
| 803 | * const result = await composio.triggers.parse(request); |
| 804 | * console.log('Trigger:', result.payload.triggerSlug); |
| 805 | * return new Response('OK', { status: 200 }); |
| 806 | * } |
| 807 | * ``` |
| 808 | */ |
| 809 | async parse( |
| 810 | request: WebhookRequestLike, |
| 811 | options?: ParseWebhookOptions |
| 812 | ): Promise<VerifyWebhookResult> { |
| 813 | // Extract the raw body and signature headers from either request shape. |
| 814 | let body: string; |
| 815 | let headers: unknown; |
| 816 | if (isFetchRequest(request)) { |
| 817 | body = await request.text(); |
| 818 | headers = request.headers; |
| 819 | } else { |
| 820 | body = bodyToString(request.body); |
| 821 | headers = request.headers; |
| 822 | } |
| 823 | |
| 824 | const verifySecret = options?.verifySecret; |
| 825 | |
| 826 | // Distinguish "caller omitted verifySecret" (explicit opt-out) from |
| 827 | // "caller passed verifySecret but it resolved to empty" (almost always an |
| 828 | // unset COMPOSIO_WEBHOOK_SECRET). The latter must fail loudly rather than |
| 829 | // silently skip verification and accept forged events. |
| 830 | const optedOutOfVerification = options === undefined || !('verifySecret' in options); |
| 831 | |
| 832 | if (optedOutOfVerification) { |
| 833 | // No secret requested: parse without verifying the signature. |
| 834 | const { version, rawPayload, normalizedPayload } = this.parseWebhookPayload(body); |
| 835 | return { |
| 836 | version, |
| 837 | payload: normalizedPayload, |
| 838 | rawPayload, |
| 839 | }; |
| 840 | } |
| 841 | |
| 842 | if (!verifySecret) { |
| 843 | throw new ValidationError( |
| 844 | `Cannot verify webhook: 'verifySecret' was provided but is empty — your ` + |
| 845 | `COMPOSIO_WEBHOOK_SECRET is likely unset. Set the secret, or omit 'verifySecret' ` + |
| 846 | `entirely to parse without verification.` |
| 847 | ); |
| 848 | } |
| 849 | |
| 850 | // Secret provided: signature headers are required to verify. |
| 851 | const id = getHeader(headers, WEBHOOK_HEADERS.id); |
| 852 | const timestamp = getHeader(headers, WEBHOOK_HEADERS.timestamp); |
| 853 | const signature = getHeader(headers, WEBHOOK_HEADERS.signature); |
| 854 | |
| 855 | if (!id || !timestamp || !signature) { |
| 856 | const missing = [ |
| 857 | !id ? `'${WEBHOOK_HEADERS.id}'` : undefined, |
| 858 | !timestamp ? `'${WEBHOOK_HEADERS.timestamp}'` : undefined, |
| 859 | !signature ? `'${WEBHOOK_HEADERS.signature}'` : undefined, |
| 860 | ].filter((header): header is string => header !== undefined); |
| 861 | |
| 862 | throw new ValidationError( |
| 863 | `Cannot verify webhook: missing signature header(s) ${missing.join(', ')}. ` + |
| 864 | `Pass the raw, unparsed request body and ensure the Composio signature headers ` + |
| 865 | `(${WEBHOOK_HEADERS.id}, ${WEBHOOK_HEADERS.timestamp}, ${WEBHOOK_HEADERS.signature}) ` + |
| 866 | `are forwarded to triggers.parse(). To parse without verifying, omit 'verifySecret'.` |
| 867 | ); |
| 868 | } |
| 869 | |
| 870 | return this.verifyWebhook({ |
| 871 | payload: body, |
| 872 | signature, |
| 873 | id, |
| 874 | timestamp, |
| 875 | secret: verifySecret, |
| 876 | tolerance: options?.tolerance, |
| 877 | }); |
| 878 | } |
| 879 | |
| 880 | /** |
| 881 | * Verify an incoming webhook payload and signature. |
| 882 | * |
| 883 | * This method validates that the webhook request is authentic by: |
| 884 | * 1. Verifying the HMAC-SHA256 signature matches the payload using the correct signing format |
| 885 | * 2. Optionally checking that the webhook timestamp is within the tolerance window |
| 886 | * |
| 887 | * The signature is computed as: `HMAC-SHA256(${webhookId}.${webhookTimestamp}.${payload}, secret)` |
| 888 | * and is expected in the format: `v1,base64EncodedSignature` |
| 889 | * |
| 890 | * @param {VerifyWebhookParams} params - The verification parameters |
| 891 | * @param {string} params.payload - The raw webhook payload as a string (request body) |
| 892 | * @param {string} params.signature - The signature from the 'webhook-signature' header |
| 893 | * @param {string} params.secret - The webhook secret used to sign the payload |
| 894 | * @param {string} params.webhookId - The webhook ID from the 'webhook-id' header |
| 895 | * @param {string} params.webhookTimestamp - The timestamp from the 'webhook-timestamp' header (Unix seconds) |
| 896 | * @param {number} [params.tolerance=300] - Maximum allowed age of the webhook in seconds (default: 5 minutes). Set to 0 to disable timestamp validation. |
| 897 | * @returns {VerifyWebhookResult} The verified and parsed webhook payload with version information |
| 898 | * |
| 899 | * @throws {ValidationError} If the parameters are invalid |
| 900 | * @throws {ComposioWebhookSignatureVerificationError} If the signature verification fails |
| 901 | * @throws {ComposioWebhookPayloadError} If the payload cannot be parsed or is invalid |
| 902 | * |
| 903 | * @example |
| 904 | * ```ts |
| 905 | * // In an Express.js webhook handler |
| 906 | * app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => { |
| 907 | * try { |
| 908 | * const result = await composio.triggers.verifyWebhook({ |
| 909 | * payload: req.body.toString(), |
| 910 | * signature: req.headers['webhook-signature'] as string, |
| 911 | * webhookId: req.headers['webhook-id'] as string, |
| 912 | * webhookTimestamp: req.headers['webhook-timestamp'] as string, |
| 913 | * secret: process.env.COMPOSIO_WEBHOOK_SECRET!, |
| 914 | * }); |
| 915 | * |
| 916 | * // Process the verified payload |
| 917 | * console.log('Webhook version:', result.version); |
| 918 | * console.log('Received trigger:', result.payload.triggerSlug); |
| 919 | * res.status(200).send('OK'); |
| 920 | * } catch (error) { |
| 921 | * console.error('Webhook verification failed:', error); |
| 922 | * res.status(401).send('Unauthorized'); |
| 923 | * } |
| 924 | * }); |
| 925 | * ``` |
| 926 | */ |
| 927 | async verifyWebhook(params: VerifyWebhookParams): Promise<VerifyWebhookResult> { |
| 928 | // Validate input parameters |
| 929 | const parsedParams = VerifyWebhookParamsSchema.safeParse(params); |
| 930 | if (!parsedParams.success) { |
| 931 | // Extract missing required parameters for a more helpful error message |
| 932 | const missingParams = parsedParams.error.issues |
| 933 | .filter(issue => issue.code === 'invalid_type' && issue.received === 'undefined') |
| 934 | .map(issue => { |
| 935 | const paramName = issue.path[0] as string; |
| 936 | const headerMap: Record<string, string> = { |
| 937 | id: 'webhook-id', |
| 938 | timestamp: 'webhook-timestamp', |
| 939 | signature: 'webhook-signature', |
| 940 | }; |
| 941 | const headerName = headerMap[paramName]; |
| 942 | return headerName ? `'${paramName}' (from '${headerName}' header)` : `'${paramName}'`; |
| 943 | }); |
| 944 | |
| 945 | if (missingParams.length > 0) { |
| 946 | throw new ValidationError( |
| 947 | `Missing required parameters: ${missingParams.join(', ')}. ` + |
| 948 | `Extract these values from the HTTP request headers and body.`, |
| 949 | { cause: parsedParams.error } |
| 950 | ); |
| 951 | } |
| 952 | |
| 953 | throw new ValidationError('Invalid parameters passed to verifyWebhook', { |
| 954 | cause: parsedParams.error, |
| 955 | }); |
| 956 | } |
| 957 | |
| 958 | const { |
| 959 | payload, |
| 960 | signature, |
| 961 | secret, |
| 962 | id: webhookId, |
| 963 | timestamp: webhookTimestamp, |
| 964 | tolerance, |
| 965 | } = parsedParams.data; |
| 966 | |
| 967 | // Validate timestamp if tolerance is set |
| 968 | if (tolerance > 0) { |
| 969 | this.validateWebhookTimestamp(webhookTimestamp, tolerance); |
| 970 | } |
| 971 | |
| 972 | // Verify signature using the correct format: msgId.timestamp.payload |
| 973 | await this.verifyWebhookSignature(webhookId, webhookTimestamp, payload, signature, secret); |
| 974 | |
| 975 | // Parse the payload and detect version |
| 976 | const { version, rawPayload, normalizedPayload } = this.parseWebhookPayload(payload); |
| 977 | |
| 978 | return { |
| 979 | version, |
| 980 | payload: normalizedPayload, |
| 981 | rawPayload, |
| 982 | }; |
| 983 | } |
| 984 | |
| 985 | /** |
| 986 | * Parses the webhook payload and detects its version (V1, V2, or V3) |
| 987 | * @private |
| 988 | */ |
| 989 | private parseWebhookPayload(payload: string): { |
| 990 | version: WebhookVersion; |
| 991 | rawPayload: WebhookPayload; |
| 992 | normalizedPayload: IncomingTriggerPayload; |
| 993 | } { |
| 994 | let jsonPayload: unknown; |
| 995 | try { |
| 996 | jsonPayload = JSON.parse(payload); |
| 997 | } catch (error) { |
| 998 | throw new ComposioWebhookPayloadError('Failed to parse webhook payload as JSON', { |
| 999 | cause: error, |
| 1000 | }); |
| 1001 | } |
| 1002 | |
| 1003 | // Try V1/V2/V3 formats using shared parsing logic |
| 1004 | const result = this.tryParseVersionedPayload(jsonPayload); |
| 1005 | if (result.ok) { |
| 1006 | const { ok, ...rest } = result; |
| 1007 | return rest; |
| 1008 | } |
| 1009 | |
| 1010 | const { v1Error, v2Error, v3Error } = result; |
| 1011 | |
| 1012 | // None of the schemas matched |
| 1013 | throw new ComposioWebhookPayloadError( |
| 1014 | 'Webhook payload does not match any known version (V1, V2, or V3). ' + |
| 1015 | 'Please ensure you are using a supported webhook payload format.', |
| 1016 | { |
| 1017 | cause: { |
| 1018 | v1Error, |
| 1019 | v2Error, |
| 1020 | v3Error, |
| 1021 | }, |
| 1022 | } |
| 1023 | ); |
| 1024 | } |
| 1025 | |
| 1026 | /** |
| 1027 | * Normalizes a V1 webhook payload to IncomingTriggerPayload format |
| 1028 | * @private |
| 1029 | */ |
| 1030 | private normalizeV1Payload( |
| 1031 | payload: import('../types/triggers.types').WebhookPayloadV1 |
| 1032 | ): IncomingTriggerPayload { |
| 1033 | // V1 has limited information, so we use what's available |
| 1034 | // and mark unknown fields appropriately |
| 1035 | const triggerName = payload.trigger_name; |
| 1036 | const toolkitSlug = triggerName.split('_')[0]?.toUpperCase() || 'UNKNOWN'; |
| 1037 | |
| 1038 | return { |
| 1039 | id: payload.trigger_id, |
| 1040 | uuid: payload.trigger_id, // V1 doesn't have UUID, use trigger_id |
| 1041 | triggerSlug: triggerName, |
| 1042 | toolkitSlug, |
| 1043 | userId: '', // V1 doesn't provide userId |
| 1044 | payload: payload.payload, |
| 1045 | originalPayload: payload.payload, |
| 1046 | metadata: { |
| 1047 | id: payload.trigger_id, |
| 1048 | uuid: payload.trigger_id, |
| 1049 | toolkitSlug, |
| 1050 | triggerSlug: triggerName, |
| 1051 | triggerConfig: {}, |
| 1052 | connectedAccount: { |
| 1053 | id: payload.connection_id, |
| 1054 | uuid: payload.connection_id, |
| 1055 | authConfigId: '', |
| 1056 | authConfigUUID: '', |
| 1057 | userId: '', |
| 1058 | status: 'ACTIVE', |
| 1059 | }, |
| 1060 | }, |
| 1061 | }; |
| 1062 | } |
| 1063 | |
| 1064 | /** |
| 1065 | * Normalizes a V2 webhook payload to IncomingTriggerPayload format |
| 1066 | * @private |
| 1067 | */ |
| 1068 | private normalizeV2Payload( |
| 1069 | payload: import('../types/triggers.types').WebhookPayloadV2 |
| 1070 | ): IncomingTriggerPayload { |
| 1071 | const triggerSlug = payload.type.toUpperCase(); |
| 1072 | const toolkitSlug = triggerSlug.split('_')[0] || 'UNKNOWN'; |
| 1073 | |
| 1074 | // Extract data fields |
| 1075 | const { connection_id, connection_nano_id, trigger_nano_id, trigger_id, user_id, ...restData } = |
| 1076 | payload.data; |
| 1077 | |
| 1078 | return { |
| 1079 | id: trigger_nano_id, |
| 1080 | uuid: trigger_id, |
| 1081 | triggerSlug, |
| 1082 | toolkitSlug, |
| 1083 | userId: user_id, |
| 1084 | payload: restData, |
| 1085 | originalPayload: restData, |
| 1086 | metadata: { |
| 1087 | id: trigger_nano_id, |
| 1088 | uuid: trigger_id, |
| 1089 | toolkitSlug, |
| 1090 | triggerSlug, |
| 1091 | triggerConfig: {}, |
| 1092 | connectedAccount: { |
| 1093 | id: connection_nano_id, |
| 1094 | uuid: connection_id, |
| 1095 | authConfigId: '', |
| 1096 | authConfigUUID: '', |
| 1097 | userId: user_id, |
| 1098 | status: 'ACTIVE', |
| 1099 | }, |
| 1100 | }, |
| 1101 | }; |
| 1102 | } |
| 1103 | |
| 1104 | /** |
| 1105 | * Normalizes a V3 webhook payload to IncomingTriggerPayload format |
| 1106 | * @private |
| 1107 | */ |
| 1108 | private normalizeV3Payload( |
| 1109 | payload: import('../types/triggers.types').WebhookPayloadV3 |
| 1110 | ): IncomingTriggerPayload { |
| 1111 | // Check if this is a trigger event with trigger-specific metadata |
| 1112 | const triggerResult = WebhookTriggerPayloadV3Schema.safeParse(payload); |
| 1113 | if (triggerResult.success) { |
| 1114 | const triggerSlug = triggerResult.data.metadata.trigger_slug; |
| 1115 | const toolkitSlug = triggerSlug.split('_')[0]?.toUpperCase() || 'UNKNOWN'; |
| 1116 | |
| 1117 | return { |
| 1118 | id: triggerResult.data.metadata.trigger_id, |
| 1119 | uuid: triggerResult.data.metadata.trigger_id, |
| 1120 | triggerSlug, |
| 1121 | toolkitSlug, |
| 1122 | userId: triggerResult.data.metadata.user_id, |
| 1123 | payload: payload.data, |
| 1124 | originalPayload: payload.data, |
| 1125 | metadata: { |
| 1126 | id: triggerResult.data.metadata.trigger_id, |
| 1127 | uuid: triggerResult.data.metadata.trigger_id, |
| 1128 | toolkitSlug, |
| 1129 | triggerSlug, |
| 1130 | triggerConfig: {}, |
| 1131 | connectedAccount: { |
| 1132 | id: triggerResult.data.metadata.connected_account_id, |
| 1133 | uuid: triggerResult.data.metadata.connected_account_id, |
| 1134 | authConfigId: triggerResult.data.metadata.auth_config_id, |
| 1135 | authConfigUUID: triggerResult.data.metadata.auth_config_id, |
| 1136 | userId: triggerResult.data.metadata.user_id, |
| 1137 | status: 'ACTIVE', |
| 1138 | }, |
| 1139 | }, |
| 1140 | }; |
| 1141 | } |
| 1142 | |
| 1143 | // Non-trigger V3 event (e.g., connection expired) |
| 1144 | // Return a minimal payload; callers should use specific schemas |
| 1145 | // (e.g., ConnectionExpiredEventSchema) on rawPayload for type-safe access |
| 1146 | return { |
| 1147 | id: payload.id, |
| 1148 | uuid: payload.id, |
| 1149 | triggerSlug: payload.type, |
| 1150 | toolkitSlug: 'COMPOSIO', |
| 1151 | userId: '', |
| 1152 | payload: payload.data, |
| 1153 | originalPayload: payload as unknown as Record<string, unknown>, |
| 1154 | metadata: { |
| 1155 | id: payload.id, |
| 1156 | uuid: payload.id, |
| 1157 | toolkitSlug: 'COMPOSIO', |
| 1158 | triggerSlug: payload.type, |
| 1159 | triggerConfig: {}, |
| 1160 | connectedAccount: { |
| 1161 | id: '', |
| 1162 | uuid: '', |
| 1163 | authConfigId: '', |
| 1164 | authConfigUUID: '', |
| 1165 | userId: '', |
| 1166 | status: 'ACTIVE', |
| 1167 | }, |
| 1168 | }, |
| 1169 | }; |
| 1170 | } |
| 1171 | |
| 1172 | /** |
| 1173 | * Verifies the HMAC-SHA256 signature of a webhook payload. |
| 1174 | * The signature format used by Composio is: `v1,base64EncodedSignature` |
| 1175 | * The signing input is: `${msgId}.${timestamp}.${payload}` |
| 1176 | * @private |
| 1177 | */ |
| 1178 | private async verifyWebhookSignature( |
| 1179 | webhookId: string, |
| 1180 | webhookTimestamp: string, |
| 1181 | payload: string, |
| 1182 | signature: string, |
| 1183 | secret: string |
| 1184 | ): Promise<void> { |
| 1185 | if (payload.length === 0) { |
| 1186 | throw new ComposioWebhookSignatureVerificationError('No webhook payload was provided.'); |
| 1187 | } |
| 1188 | |
| 1189 | if (signature.length === 0) { |
| 1190 | throw new ComposioWebhookSignatureVerificationError( |
| 1191 | "No signature header value was provided. Please pass the value of the 'webhook-signature' header." |
| 1192 | ); |
| 1193 | } |
| 1194 | |
| 1195 | if (secret.length === 0) { |
| 1196 | throw new ComposioWebhookSignatureVerificationError( |
| 1197 | 'No webhook secret was provided. You can find your webhook secret in your Composio dashboard.' |
| 1198 | ); |
| 1199 | } |
| 1200 | |
| 1201 | if (webhookId.length === 0) { |
| 1202 | throw new ComposioWebhookSignatureVerificationError( |
| 1203 | "No webhook ID was provided. Please pass the value of the 'webhook-id' header." |
| 1204 | ); |
| 1205 | } |
| 1206 | |
| 1207 | if (webhookTimestamp.length === 0) { |
| 1208 | throw new ComposioWebhookSignatureVerificationError( |
| 1209 | "No webhook timestamp was provided. Please pass the value of the 'webhook-timestamp' header." |
| 1210 | ); |
| 1211 | } |
| 1212 | |
| 1213 | // Parse signature - may have multiple signatures prefixed with version (e.g., "v1,base64sig") |
| 1214 | const signatures = signature.split(' '); |
| 1215 | const v1Signatures: string[] = []; |
| 1216 | |
| 1217 | for (const sig of signatures) { |
| 1218 | const [version, value] = sig.split(','); |
| 1219 | if (version === 'v1' && value) { |
| 1220 | v1Signatures.push(value); |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | if (v1Signatures.length === 0) { |
| 1225 | throw new ComposioWebhookSignatureVerificationError( |
| 1226 | 'No valid v1 signature found in the webhook-signature header. ' + |
| 1227 | "Expected format: 'v1,base64EncodedSignature'" |
| 1228 | ); |
| 1229 | } |
| 1230 | |
| 1231 | // Compute expected signature: HMAC-SHA256(msgId.timestamp.payload, secret) -> base64 |
| 1232 | const toSign = `${webhookId}.${webhookTimestamp}.${payload}`; |
| 1233 | const expectedSignature = await hmacSha256Base64(secret, toSign); |
| 1234 | |
| 1235 | // Check if any of the provided signatures match |
| 1236 | let isValid = false; |
| 1237 | for (const providedSignature of v1Signatures) { |
| 1238 | if (timingSafeEqual(providedSignature, expectedSignature)) { |
| 1239 | isValid = true; |
| 1240 | break; |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | if (!isValid) { |
| 1245 | throw new ComposioWebhookSignatureVerificationError( |
| 1246 | 'The signature provided is invalid. Please ensure you are using the correct webhook secret.' |
| 1247 | ); |
| 1248 | } |
| 1249 | } |
| 1250 | |
| 1251 | /** |
| 1252 | * Validates that the webhook timestamp is within the allowed tolerance |
| 1253 | * @private |
| 1254 | */ |
| 1255 | private validateWebhookTimestamp(webhookTimestamp: string, tolerance: number): void { |
| 1256 | const timestampSeconds = parseInt(webhookTimestamp, 10); |
| 1257 | |
| 1258 | if (Number.isNaN(timestampSeconds)) { |
| 1259 | throw new ComposioWebhookPayloadError( |
| 1260 | `Invalid webhook timestamp: ${webhookTimestamp}. Expected Unix timestamp in seconds.` |
| 1261 | ); |
| 1262 | } |
| 1263 | |
| 1264 | const webhookTimeMs = timestampSeconds * 1000; |
| 1265 | const currentTime = Date.now(); |
| 1266 | const timeDifference = Math.abs(currentTime - webhookTimeMs); |
| 1267 | |
| 1268 | if (timeDifference > tolerance * 1000) { |
| 1269 | throw new ComposioWebhookSignatureVerificationError( |
| 1270 | `The webhook timestamp is outside the allowed tolerance. ` + |
| 1271 | `The webhook was sent ${Math.round(timeDifference / 1000)} seconds ago, ` + |
| 1272 | `but the maximum allowed age is ${tolerance} seconds.` |
| 1273 | ); |
| 1274 | } |
| 1275 | } |
| 1276 | } |