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