@devries-cameron20 / composio Mirror · read-only / commits / 408e7d080
Fork 0

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 22, 12:00 UTC

fix(ts/core): webhook subscription with v1, v2, v3 response schemas

jkomyno committed Jan 29, 2026 at 04:05 UTC 408e7d080f9badac424b8a9d777f93aa81db8c11
10 files changed +941 -9
ts/examples/triggers/src/subscribe.ts new
+21
@@ -0,0 +1,21 @@
1 +import { Composio } from '@composio/core';
2 +
3 +// Initialize Composio client
4 +const composio = new Composio({
5 + apiKey: process.env.COMPOSIO_API_KEY,
6 +});
7 +
8 +// Subscribe to triggers with optional filters
9 +// Replace 'ti_ollBPgfhgmMK' with your actual trigger ID
10 +const sub = await composio.triggers.subscribe(
11 + metadata => {
12 + console.log('Received trigger event:');
13 + console.dir(metadata, { depth: 3 });
14 + },
15 + { triggerId: 'ti_ollBPgfhgmMK' }
16 +);
17 +
18 +console.log('Subscribed to triggers. Waiting for events...');
19 +
20 +// Keep the process alive forever
21 +process.stdin.resume();
ts/packages/core/src/models/Triggers.ts
+89 -4
@@ -433,10 +433,9 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
433 logger.debug('🔄 Subscribing to triggers with filters: ', JSON.stringify(filters, null, 2));
434 await this.pusherService.subscribe((_data: Record<string, unknown>) => {
435 logger.debug('Received raw trigger data', JSON.stringify(_data, null, 2));
436 - // @TODO: This is a temporary fix to get the trigger data
437 - // ideally we should have a type for the trigger data
438 - const data = _data as TriggerData;
439 - const parsedData = transformIncomingTriggerPayload(data);
436 +
437 + // Parse using unified method that handles V1/V2/V3 and legacy formats
438 + const parsedData = this.parsePusherPayload(_data);
439
440 if (this.shouldSendTriggerAfterFilters(parsedFilters.data, parsedData)) {
441 try {
@@ -450,6 +449,70 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
449 });
450 }
451
452 + /**
453 + * Parses incoming Pusher payload, supporting V1, V2, V3, and legacy TriggerData formats.
454 + * This method reuses the same schemas and normalizers used for HTTP webhooks.
455 + * @private
456 + */
457 + private parsePusherPayload(data: Record<string, unknown>): IncomingTriggerPayload {
458 + // Try V3 format first (has 'composio.trigger.message' type)
459 + const v3Result = WebhookPayloadV3Schema.safeParse(data);
460 + if (v3Result.success) {
461 + logger.debug('Parsed Pusher payload as V3 format');
462 + return this.normalizeV3Payload(v3Result.data);
463 + }
464 +
465 + // Try V2 format (has 'type', 'timestamp', 'log_id', and 'data')
466 + const v2Result = WebhookPayloadV2Schema.safeParse(data);
467 + if (v2Result.success) {
468 + logger.debug('Parsed Pusher payload as V2 format');
469 + return this.normalizeV2Payload(v2Result.data);
470 + }
471 +
472 + // Try V1 format (has 'trigger_name', 'connection_id', 'trigger_id', 'payload', 'log_id')
473 + const v1Result = WebhookPayloadV1Schema.safeParse(data);
474 + if (v1Result.success) {
475 + logger.debug('Parsed Pusher payload as V1 format');
476 + return this.normalizeV1Payload(v1Result.data);
477 + }
478 +
479 + // Try legacy TriggerData format (for backwards compatibility)
480 + const legacyData = data as TriggerData;
481 + if (legacyData.metadata?.nanoId && legacyData.appName) {
482 + logger.debug('Parsed Pusher payload as legacy TriggerData format');
483 + return transformIncomingTriggerPayload(legacyData);
484 + }
485 +
486 + // Fallback: log warning and return a minimal payload with available data
487 + logger.warn('Unknown Pusher payload format. Payload keys: ' + Object.keys(data).join(', '));
488 +
489 + // Return a minimal payload structure to avoid breaking the subscription
490 + return {
491 + id: (data.id as string) || (data.trigger_id as string) || 'unknown',
492 + uuid: (data.uuid as string) || (data.id as string) || 'unknown',
493 + triggerSlug: (data.triggerSlug as string) || (data.trigger_name as string) || 'UNKNOWN',
494 + toolkitSlug: (data.toolkitSlug as string) || (data.appName as string) || 'UNKNOWN',
495 + userId: (data.userId as string) || '',
496 + payload: (data.payload as Record<string, unknown>) || data,
497 + originalPayload: (data.originalPayload as Record<string, unknown>) || data,
498 + metadata: {
499 + id: (data.id as string) || 'unknown',
500 + uuid: (data.uuid as string) || 'unknown',
501 + toolkitSlug: (data.toolkitSlug as string) || 'UNKNOWN',
502 + triggerSlug: (data.triggerSlug as string) || 'UNKNOWN',
503 + triggerConfig: {},
504 + connectedAccount: {
505 + id: '',
506 + uuid: '',
507 + authConfigId: '',
508 + authConfigUUID: '',
509 + userId: '',
510 + status: 'ACTIVE',
511 + },
512 + },
513 + };
514 + }
515 +
516 /**
517 * Unsubscribe from all the triggers
518 *
@@ -519,6 +582,28 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
582 // Validate input parameters
583 const parsedParams = VerifyWebhookParamsSchema.safeParse(params);
584 if (!parsedParams.success) {
585 + // Extract missing required parameters for a more helpful error message
586 + const missingParams = parsedParams.error.issues
587 + .filter(issue => issue.code === 'invalid_type' && issue.received === 'undefined')
588 + .map(issue => {
589 + const paramName = issue.path[0] as string;
590 + const headerMap: Record<string, string> = {
591 + id: 'webhook-id',
592 + timestamp: 'webhook-timestamp',
593 + signature: 'webhook-signature',
594 + };
595 + const headerName = headerMap[paramName];
596 + return headerName ? `'${paramName}' (from '${headerName}' header)` : `'${paramName}'`;
597 + });
598 +
599 + if (missingParams.length > 0) {
600 + throw new ValidationError(
601 + `Missing required parameters: ${missingParams.join(', ')}. ` +
602 + `Extract these values from the HTTP request headers and body.`,
603 + { cause: parsedParams.error }
604 + );
605 + }
606 +
607 throw new ValidationError('Invalid parameters passed to verifyWebhook', {
608 cause: parsedParams.error,
609 });
ts/packages/core/src/types/triggers.types.ts
+26 -5
@@ -268,21 +268,42 @@ export const VerifyWebhookParamsSchema = z.object({
268 * The webhook message ID from the 'webhook-id' header.
269 * Format: 'msg_xxx'
270 */
271 - id: z.string(),
271 + id: z.string({
272 + required_error: "Missing 'id' parameter. Pass the value of the 'webhook-id' HTTP header.",
273 + invalid_type_error: "Invalid 'id' parameter. Expected string from 'webhook-id' HTTP header.",
274 + }),
275 /** The raw webhook payload as a string (request body) */
273 - payload: z.string(),
276 + payload: z.string({
277 + required_error:
278 + "Missing 'payload' parameter. Pass the raw request body as a string (do not parse it).",
279 + invalid_type_error: "Invalid 'payload' parameter. Expected string (raw request body).",
280 + }),
281 /** The webhook secret used to sign the payload (from Composio dashboard) */
275 - secret: z.string(),
282 + secret: z.string({
283 + required_error:
284 + "Missing 'secret' parameter. Get your webhook secret from the Composio dashboard.",
285 + invalid_type_error: "Invalid 'secret' parameter. Expected string.",
286 + }),
287 /**
288 * The signature from the 'webhook-signature' header.
289 * Format: 'v1,base64EncodedSignature'
290 */
280 - signature: z.string(),
291 + signature: z.string({
292 + required_error:
293 + "Missing 'signature' parameter. Pass the value of the 'webhook-signature' HTTP header.",
294 + invalid_type_error:
295 + "Invalid 'signature' parameter. Expected string from 'webhook-signature' HTTP header.",
296 + }),
297 /**
298 * The webhook timestamp from the 'webhook-timestamp' header.
299 * This is the Unix timestamp in seconds when the webhook was sent.
300 */
285 - timestamp: z.string(),
301 + timestamp: z.string({
302 + required_error:
303 + "Missing 'timestamp' parameter. Pass the value of the 'webhook-timestamp' HTTP header.",
304 + invalid_type_error:
305 + "Invalid 'timestamp' parameter. Expected string from 'webhook-timestamp' HTTP header.",
306 + }),
307 /**
308 * Maximum allowed age of the webhook in seconds.
309 * If the webhook timestamp is older than this, verification will fail.
ts/packages/core/test/fixtures/webhook/README.md new
+105
@@ -0,0 +1,105 @@
1 +# Webhook Verification Test Fixtures
2 +
3 +This directory contains sanitized webhook fixtures for testing the `verifyWebhook` function.
4 +These fixtures use deterministic test secrets so the tests can verify both the structure
5 +and the signature verification algorithm.
6 +
7 +## Fixture Format
8 +
9 +Each fixture file contains:
10 +
11 +```json
12 +{
13 + "description": "Human-readable description of this fixture",
14 + "capturedAt": "ISO 8601 timestamp when this was captured",
15 + "headers": {
16 + "webhook-id": "msg_xxx",
17 + "webhook-timestamp": "1234567890",
18 + "webhook-signature": "v1,base64_signature"
19 + },
20 + "payload": "{...raw JSON payload string...}",
21 + "testSecret": "deterministic-test-secret",
22 + "expectedResult": {
23 + "version": "V1|V2|V3",
24 + "triggerSlug": "GITHUB_PUSH_EVENT"
25 + }
26 +}
27 +```
28 +
29 +## Why Sanitized Fixtures?
30 +
31 +Real webhook secrets should **never** be committed to version control. Instead:
32 +
33 +1. We capture real webhooks to preserve exact JSON structure and whitespace
34 +2. Replace sensitive IDs with sanitized placeholders (e.g., `msg_SANITIZED_001`)
35 +3. Re-sign the payload with a known test secret
36 +4. The test validates both structure correctness and algorithm correctness
37 +
38 +## How to Capture New Fixtures
39 +
40 +### 1. Start the Webhook Server
41 +
42 +```bash
43 +cd ts/examples/triggers
44 +pnpm webhook
45 +```
46 +
47 +### 2. Expose Locally with ngrok or telebit
48 +
49 +```bash
50 +ngrok http 3000
51 +# OR
52 +telebit http 3000
53 +```
54 +
55 +### 3. Configure Webhook URL in Composio Dashboard
56 +
57 +Set the webhook URL to your public URL (e.g., `https://abc123.ngrok.io/webhook`).
58 +
59 +### 4. Trigger an Event
60 +
61 +Perform an action that triggers the webhook (e.g., push to a GitHub repo).
62 +
63 +### 5. Capture the Raw Request
64 +
65 +The webhook server logs the raw headers and payload. Copy them.
66 +
67 +### 6. Sanitize and Re-sign
68 +
69 +Use this script to create a sanitized fixture:
70 +
71 +```typescript
72 +import * as crypto from 'node:crypto';
73 +
74 +const testSecret = 'test-webhook-secret-for-fixtures';
75 +
76 +// Your captured data (sanitize IDs first!)
77 +const webhookId = 'msg_SANITIZED_001';
78 +const webhookTimestamp = '1738150200';
79 +const payload = '{"id":"evt-SANITIZED",...}';
80 +
81 +// Compute new signature with test secret
82 +const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
83 +const signature = crypto.createHmac('sha256', testSecret).update(toSign, 'utf8').digest('base64');
84 +
85 +console.log(`v1,${signature}`);
86 +```
87 +
88 +### 7. Create the Fixture File
89 +
90 +Save as `v3-<description>.json` (or v1/v2 depending on version).
91 +
92 +## Golden Signatures
93 +
94 +The `golden-signatures.json` file contains contract test cases that verify
95 +the signature algorithm produces consistent output. These should never change
96 +unless the algorithm itself changes.
97 +
98 +## Testing
99 +
100 +The fixtures are loaded by `verifyWebhook.integration.test.ts` and used to:
101 +
102 +1. Verify signature validation works with real-world payload structure
103 +2. Test version detection (V1, V2, V3)
104 +3. Ensure payload normalization produces expected output
105 +4. Contract test that algorithm hasn't changed (golden signatures)
ts/packages/core/test/fixtures/webhook/golden-signatures.json new
+47
@@ -0,0 +1,47 @@
1 +{
2 + "description": "Golden signature test cases - DO NOT MODIFY unless algorithm changes",
3 + "algorithm": "HMAC-SHA256",
4 + "format": "v1,base64(HMAC-SHA256(id.timestamp.payload, secret))",
5 + "testCases": [
6 + {
7 + "name": "simple payload",
8 + "id": "msg_test_001",
9 + "timestamp": "1700000000",
10 + "payload": "{\"test\":\"data\"}",
11 + "secret": "test-secret",
12 + "expectedSignature": "v1,4Fay6rvxXDEbH+4oA1fYP2BR/Bwzn3/7ONj40iJQagY="
13 + },
14 + {
15 + "name": "unicode payload",
16 + "id": "msg_test_002",
17 + "timestamp": "1700000001",
18 + "payload": "{\"message\":\"Hello World\"}",
19 + "secret": "unicode-secret-key",
20 + "expectedSignature": "v1,ICmAFUlesRqIFA44bU6Wlce5GszoHjG+w7nurcu5EWc="
21 + },
22 + {
23 + "name": "complex nested payload",
24 + "id": "msg_test_003",
25 + "timestamp": "1700000002",
26 + "payload": "{\"nested\":{\"array\":[1,2,3],\"object\":{\"key\":\"value\"}}}",
27 + "secret": "complex-secret",
28 + "expectedSignature": "v1,Vx/pw0yOiRRoxdfifaZ3zBKt4B3KkRKFVr6gLQNJs9Q="
29 + },
30 + {
31 + "name": "empty data object",
32 + "id": "msg_test_004",
33 + "timestamp": "1700000003",
34 + "payload": "{\"data\":{}}",
35 + "secret": "empty-data-secret",
36 + "expectedSignature": "v1,IbLtu+G65OH8Gw7ZFqy38ru+Jrg96yWfueYMMdaFYs0="
37 + },
38 + {
39 + "name": "special characters in secret",
40 + "id": "msg_test_005",
41 + "timestamp": "1700000004",
42 + "payload": "{\"test\":true}",
43 + "secret": "secret!@#$%^&*()",
44 + "expectedSignature": "v1,kUvMXJ0rouLoROxY70WIzV+zLQGpSRuCXv8evLTPjXg="
45 + }
46 + ]
47 +}
ts/packages/core/test/fixtures/webhook/v1-github-push.json new
+16
@@ -0,0 +1,16 @@
1 +{
2 + "description": "V1 GitHub push webhook - legacy format sanitized",
3 + "capturedAt": "2026-01-29T10:30:00Z",
4 + "headers": {
5 + "webhook-id": "msg_fixture_v1_001",
6 + "webhook-timestamp": "1738150200",
7 + "webhook-signature": "v1,A/VFbvOJ8JAzXZweWvc+IHaBie19NVKUpQKbeobt5xo="
8 + },
9 + "payload": "{\"trigger_name\":\"GITHUB_PUSH_EVENT\",\"connection_id\":\"conn_fixture_001\",\"trigger_id\":\"trigger_fixture_001\",\"payload\":{\"ref\":\"refs/heads/main\",\"commits\":[{\"id\":\"def456\",\"message\":\"Legacy commit\"}]},\"log_id\":\"log_fixture_003\"}",
10 + "testSecret": "test-webhook-secret-for-fixtures",
11 + "expectedResult": {
12 + "version": "V1",
13 + "triggerSlug": "GITHUB_PUSH_EVENT",
14 + "triggerId": "trigger_fixture_001"
15 + }
16 +}
ts/packages/core/test/fixtures/webhook/v2-github-push.json new
+16
@@ -0,0 +1,16 @@
1 +{
2 + "description": "V2 GitHub push webhook - sanitized real-world structure",
3 + "capturedAt": "2026-01-29T10:30:00Z",
4 + "headers": {
5 + "webhook-id": "msg_fixture_v2_001",
6 + "webhook-timestamp": "1738150200",
7 + "webhook-signature": "v1,a/mTZohEnMvzupLGWsiDLhTctk+hgx3Q2r1ACjybkhk="
8 + },
9 + "payload": "{\"type\":\"github_push_event\",\"timestamp\":\"2026-01-29T10:30:00Z\",\"log_id\":\"log_fixture_002\",\"data\":{\"connection_id\":\"conn_uuid_fixture_002\",\"connection_nano_id\":\"ca_fixture_002\",\"trigger_nano_id\":\"ti_fixture_002\",\"trigger_id\":\"trigger_uuid_fixture_002\",\"user_id\":\"user_fixture_002\",\"ref\":\"refs/heads/main\",\"repository\":{\"name\":\"test-repo\"}}}",
10 + "testSecret": "test-webhook-secret-for-fixtures",
11 + "expectedResult": {
12 + "version": "V2",
13 + "triggerSlug": "GITHUB_PUSH_EVENT",
14 + "userId": "user_fixture_002"
15 + }
16 +}
ts/packages/core/test/fixtures/webhook/v3-github-push.json new
+17
@@ -0,0 +1,17 @@
1 +{
2 + "description": "V3 GitHub push webhook - sanitized real-world structure",
3 + "capturedAt": "2026-01-29T10:30:00Z",
4 + "headers": {
5 + "webhook-id": "msg_fixture_v3_001",
6 + "webhook-timestamp": "1738150200",
7 + "webhook-signature": "v1,GqTsMaDtroeNNR7rDDzEGVTtHfFtIDknXhmkCXss7cA="
8 + },
9 + "payload": "{\"id\":\"evt_fixture_v3_001\",\"timestamp\":\"2026-01-29T10:30:00Z\",\"type\":\"composio.trigger.message\",\"metadata\":{\"log_id\":\"log_fixture_001\",\"trigger_slug\":\"GITHUB_PUSH_EVENT\",\"trigger_id\":\"ti_fixture_001\",\"connected_account_id\":\"ca_fixture_001\",\"auth_config_id\":\"ac_fixture_001\",\"user_id\":\"user_fixture_001\"},\"data\":{\"ref\":\"refs/heads/main\",\"repository\":{\"name\":\"test-repo\",\"full_name\":\"user/test-repo\"},\"pusher\":{\"name\":\"test-user\"},\"commits\":[{\"id\":\"abc123\",\"message\":\"Test commit\"}]}}",
10 + "testSecret": "test-webhook-secret-for-fixtures",
11 + "expectedResult": {
12 + "version": "V3",
13 + "triggerSlug": "GITHUB_PUSH_EVENT",
14 + "userId": "user_fixture_001",
15 + "connectedAccountId": "ca_fixture_001"
16 + }
17 +}
ts/packages/core/test/models/triggers.test.ts
+210
@@ -978,4 +978,214 @@ describe('Triggers', () => {
978 expect(callback2).toHaveBeenCalledTimes(1);
979 });
980 });
981 +
982 + describe('parsePusherPayload (V1/V2/V3 format support)', () => {
983 + const mockCallback = vi.fn();
984 +
985 + // V1 mock payload matching WebhookPayloadV1Schema
986 + const mockV1Payload = {
987 + trigger_name: 'GMAIL_NEW_GMAIL_MESSAGE',
988 + connection_id: 'conn-123',
989 + trigger_id: 'trigger-456',
990 + payload: { subject: 'Test email', from: 'test@example.com' },
991 + log_id: 'log-789',
992 + };
993 +
994 + // V2 mock payload matching WebhookPayloadV2Schema
995 + const mockV2Payload = {
996 + type: 'GMAIL_NEW_GMAIL_MESSAGE',
997 + timestamp: '2026-01-28T12:00:00Z',
998 + log_id: 'log-789',
999 + data: {
1000 + connection_id: 'conn-uuid',
1001 + connection_nano_id: 'conn-123',
1002 + trigger_nano_id: 'trigger-456',
1003 + trigger_id: 'trigger-uuid',
1004 + user_id: 'user-789',
1005 + subject: 'Test email',
1006 + from: 'test@example.com',
1007 + },
1008 + };
1009 +
1010 + // V3 mock payload matching WebhookPayloadV3Schema
1011 + const mockV3Payload = {
1012 + id: 'msg-123',
1013 + timestamp: '2026-01-28T12:00:00Z',
1014 + type: 'composio.trigger.message',
1015 + metadata: {
1016 + log_id: 'log-789',
1017 + trigger_slug: 'GMAIL_NEW_GMAIL_MESSAGE',
1018 + trigger_id: 'trigger-456',
1019 + connected_account_id: 'conn-123',
1020 + auth_config_id: 'auth-456',
1021 + user_id: 'user-789',
1022 + },
1023 + data: { subject: 'Test email', from: 'test@example.com' },
1024 + };
1025 +
1026 + beforeEach(() => {
1027 + mockCallback.mockClear();
1028 + vi.mocked(logger.debug).mockClear();
1029 + vi.mocked(logger.warn).mockClear();
1030 + });
1031 +
1032 + it('should parse V3 Pusher payload', async () => {
1033 + await triggers.subscribe(mockCallback);
1034 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1035 + const filterCallback = subscribeCall[0];
1036 +
1037 + filterCallback(mockV3Payload);
1038 +
1039 + expect(mockCallback).toHaveBeenCalledTimes(1);
1040 + expect(mockCallback).toHaveBeenCalledWith(
1041 + expect.objectContaining({
1042 + id: 'trigger-456',
1043 + triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
1044 + userId: 'user-789',
1045 + toolkitSlug: 'GMAIL',
1046 + payload: { subject: 'Test email', from: 'test@example.com' },
1047 + metadata: expect.objectContaining({
1048 + id: 'trigger-456',
1049 + triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
1050 + connectedAccount: expect.objectContaining({
1051 + id: 'conn-123',
1052 + userId: 'user-789',
1053 + authConfigId: 'auth-456',
1054 + }),
1055 + }),
1056 + })
1057 + );
1058 + expect(logger.debug).toHaveBeenCalledWith('Parsed Pusher payload as V3 format');
1059 + });
1060 +
1061 + it('should parse V2 Pusher payload', async () => {
1062 + await triggers.subscribe(mockCallback);
1063 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1064 + const filterCallback = subscribeCall[0];
1065 +
1066 + filterCallback(mockV2Payload);
1067 +
1068 + expect(mockCallback).toHaveBeenCalledTimes(1);
1069 + expect(mockCallback).toHaveBeenCalledWith(
1070 + expect.objectContaining({
1071 + id: 'trigger-456',
1072 + uuid: 'trigger-uuid',
1073 + triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
1074 + userId: 'user-789',
1075 + toolkitSlug: 'GMAIL',
1076 + metadata: expect.objectContaining({
1077 + id: 'trigger-456',
1078 + uuid: 'trigger-uuid',
1079 + connectedAccount: expect.objectContaining({
1080 + id: 'conn-123',
1081 + uuid: 'conn-uuid',
1082 + userId: 'user-789',
1083 + }),
1084 + }),
1085 + })
1086 + );
1087 + expect(logger.debug).toHaveBeenCalledWith('Parsed Pusher payload as V2 format');
1088 + });
1089 +
1090 + it('should parse V1 Pusher payload', async () => {
1091 + await triggers.subscribe(mockCallback);
1092 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1093 + const filterCallback = subscribeCall[0];
1094 +
1095 + filterCallback(mockV1Payload);
1096 +
1097 + expect(mockCallback).toHaveBeenCalledTimes(1);
1098 + expect(mockCallback).toHaveBeenCalledWith(
1099 + expect.objectContaining({
1100 + id: 'trigger-456',
1101 + triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
1102 + toolkitSlug: 'GMAIL',
1103 + payload: { subject: 'Test email', from: 'test@example.com' },
1104 + metadata: expect.objectContaining({
1105 + id: 'trigger-456',
1106 + triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
1107 + connectedAccount: expect.objectContaining({
1108 + id: 'conn-123',
1109 + }),
1110 + }),
1111 + })
1112 + );
1113 + expect(logger.debug).toHaveBeenCalledWith('Parsed Pusher payload as V1 format');
1114 + });
1115 +
1116 + it('should parse legacy TriggerData payload for backwards compatibility', async () => {
1117 + await triggers.subscribe(mockCallback);
1118 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1119 + const filterCallback = subscribeCall[0];
1120 +
1121 + filterCallback(mockTriggerData);
1122 +
1123 + expect(mockCallback).toHaveBeenCalledTimes(1);
1124 + expect(mockCallback).toHaveBeenCalledWith(mockIncomingTriggerPayload);
1125 + expect(logger.debug).toHaveBeenCalledWith(
1126 + 'Parsed Pusher payload as legacy TriggerData format'
1127 + );
1128 + });
1129 +
1130 + it('should log warning for unknown payload format and attempt legacy transformation', async () => {
1131 + const unknownPayload = {
1132 + someField: 'value',
1133 + anotherField: 123,
1134 + };
1135 +
1136 + await triggers.subscribe(mockCallback);
1137 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1138 + const filterCallback = subscribeCall[0];
1139 +
1140 + // This should not throw, but should log a warning
1141 + expect(() => filterCallback(unknownPayload)).not.toThrow();
1142 + expect(logger.warn).toHaveBeenCalledWith(
1143 + expect.stringContaining('Unknown Pusher payload format')
1144 + );
1145 + });
1146 +
1147 + it('should filter V3 payloads correctly by triggerId', async () => {
1148 + const filters = { triggerId: 'trigger-456' };
1149 + await triggers.subscribe(mockCallback, filters);
1150 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1151 + const filterCallback = subscribeCall[0];
1152 +
1153 + filterCallback(mockV3Payload);
1154 +
1155 + expect(mockCallback).toHaveBeenCalledTimes(1);
1156 + });
1157 +
1158 + it('should filter V3 payloads correctly and reject non-matching triggerId', async () => {
1159 + const filters = { triggerId: 'wrong-trigger-id' };
1160 + await triggers.subscribe(mockCallback, filters);
1161 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1162 + const filterCallback = subscribeCall[0];
1163 +
1164 + filterCallback(mockV3Payload);
1165 +
1166 + expect(mockCallback).not.toHaveBeenCalled();
1167 + });
1168 +
1169 + it('should filter V2 payloads by toolkit', async () => {
1170 + const filters = { toolkits: ['GMAIL'] };
1171 + await triggers.subscribe(mockCallback, filters);
1172 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1173 + const filterCallback = subscribeCall[0];
1174 +
1175 + filterCallback(mockV2Payload);
1176 +
1177 + expect(mockCallback).toHaveBeenCalledTimes(1);
1178 + });
1179 +
1180 + it('should filter V1 payloads by triggerSlug', async () => {
1181 + const filters = { triggerSlug: ['GMAIL_NEW_GMAIL_MESSAGE'] };
1182 + await triggers.subscribe(mockCallback, filters);
1183 + const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
1184 + const filterCallback = subscribeCall[0];
1185 +
1186 + filterCallback(mockV1Payload);
1187 +
1188 + expect(mockCallback).toHaveBeenCalledTimes(1);
1189 + });
1190 + });
1191 });
ts/packages/core/test/models/verifyWebhook.integration.test.ts new
+394
@@ -0,0 +1,394 @@
1 +import * as crypto from 'node:crypto';
2 +import * as fs from 'node:fs';
3 +import * as path from 'node:path';
4 +import { describe, it, expect, vi, beforeEach } from 'vitest';
5 +import { Triggers } from '../../src/models/Triggers';
6 +import ComposioClient from '@composio/client';
7 +import { WebhookVersions } from '../../src/types/triggers.types';
8 +
9 +// Mock dependencies
10 +vi.mock('../../src/utils/logger');
11 +vi.mock('../../src/telemetry/Telemetry', () => ({
12 + telemetry: {
13 + instrument: vi.fn(),
14 + },
15 +}));
16 +vi.mock('../../src/services/pusher/Pusher');
17 +
18 +// Create mock client
19 +const createMockClient = () => ({
20 + baseURL: 'https://api.composio.dev',
21 + apiKey: 'test-api-key',
22 + triggerInstances: {
23 + listActive: vi.fn(),
24 + upsert: vi.fn(),
25 + manage: {
26 + delete: vi.fn(),
27 + update: vi.fn(),
28 + },
29 + },
30 + triggersTypes: {
31 + list: vi.fn(),
32 + retrieve: vi.fn(),
33 + retrieveEnum: vi.fn(),
34 + },
35 + connectedAccounts: {
36 + list: vi.fn(),
37 + },
38 +});
39 +
40 +/**
41 + * Fixture type definition
42 + */
43 +interface WebhookFixture {
44 + description: string;
45 + capturedAt: string;
46 + headers: {
47 + 'webhook-id': string;
48 + 'webhook-timestamp': string;
49 + 'webhook-signature': string;
50 + };
51 + payload: string;
52 + testSecret: string;
53 + expectedResult: {
54 + version: string;
55 + triggerSlug: string;
56 + userId?: string;
57 + connectedAccountId?: string;
58 + triggerId?: string;
59 + };
60 +}
61 +
62 +/**
63 + * Golden signature test case
64 + */
65 +interface GoldenSignatureTestCase {
66 + name: string;
67 + id: string;
68 + timestamp: string;
69 + payload: string;
70 + secret: string;
71 + expectedSignature: string;
72 +}
73 +
74 +interface GoldenSignatures {
75 + description: string;
76 + algorithm: string;
77 + format: string;
78 + testCases: GoldenSignatureTestCase[];
79 +}
80 +
81 +/**
82 + * Load all webhook fixtures from the fixtures directory
83 + */
84 +function loadFixtures(): WebhookFixture[] {
85 + const fixturesDir = path.join(__dirname, '../fixtures/webhook');
86 + const fixtureFiles = fs
87 + .readdirSync(fixturesDir)
88 + .filter(f => f.startsWith('v') && f.endsWith('.json') && !f.includes('golden'));
89 +
90 + return fixtureFiles.map(file => {
91 + const content = fs.readFileSync(path.join(fixturesDir, file), 'utf-8');
92 + return JSON.parse(content) as WebhookFixture;
93 + });
94 +}
95 +
96 +/**
97 + * Load golden signatures for contract testing
98 + */
99 +function loadGoldenSignatures(): GoldenSignatures {
100 + const fixturesDir = path.join(__dirname, '../fixtures/webhook');
101 + const content = fs.readFileSync(path.join(fixturesDir, 'golden-signatures.json'), 'utf-8');
102 + return JSON.parse(content) as GoldenSignatures;
103 +}
104 +
105 +/**
106 + * Compute signature using the documented algorithm
107 + */
108 +function computeSignature(id: string, timestamp: string, payload: string, secret: string): string {
109 + const toSign = `${id}.${timestamp}.${payload}`;
110 + const signature = crypto.createHmac('sha256', secret).update(toSign, 'utf8').digest('base64');
111 + return `v1,${signature}`;
112 +}
113 +
114 +describe('Triggers.verifyWebhook - Integration Tests', () => {
115 + let triggers: Triggers<any>;
116 + let mockClient: ReturnType<typeof createMockClient>;
117 + const fixtures = loadFixtures();
118 + const goldenSignatures = loadGoldenSignatures();
119 +
120 + beforeEach(() => {
121 + vi.clearAllMocks();
122 + mockClient = createMockClient();
123 + triggers = new Triggers(mockClient as unknown as ComposioClient);
124 + });
125 +
126 + describe('fixture-based verification', () => {
127 + it.each(fixtures)('verifies $description', async fixture => {
128 + const result = await triggers.verifyWebhook({
129 + payload: fixture.payload,
130 + signature: fixture.headers['webhook-signature'],
131 + id: fixture.headers['webhook-id'],
132 + timestamp: fixture.headers['webhook-timestamp'],
133 + secret: fixture.testSecret,
134 + tolerance: 0, // Disable timestamp validation for fixtures
135 + });
136 +
137 + expect(result.version).toBe(fixture.expectedResult.version);
138 + expect(result.payload.triggerSlug).toBe(fixture.expectedResult.triggerSlug);
139 +
140 + if (fixture.expectedResult.userId) {
141 + expect(result.payload.userId).toBe(fixture.expectedResult.userId);
142 + }
143 +
144 + if (fixture.expectedResult.connectedAccountId) {
145 + expect(result.payload.metadata.connectedAccount.id).toBe(
146 + fixture.expectedResult.connectedAccountId
147 + );
148 + }
149 +
150 + if (fixture.expectedResult.triggerId) {
151 + expect(result.payload.id).toBe(fixture.expectedResult.triggerId);
152 + }
153 + });
154 +
155 + it('detects correct version for V3 payload', async () => {
156 + const v3Fixture = fixtures.find(f => f.expectedResult.version === 'V3');
157 + if (!v3Fixture) {
158 + throw new Error('V3 fixture not found');
159 + }
160 +
161 + const result = await triggers.verifyWebhook({
162 + payload: v3Fixture.payload,
163 + signature: v3Fixture.headers['webhook-signature'],
164 + id: v3Fixture.headers['webhook-id'],
165 + timestamp: v3Fixture.headers['webhook-timestamp'],
166 + secret: v3Fixture.testSecret,
167 + tolerance: 0,
168 + });
169 +
170 + expect(result.version).toBe(WebhookVersions.V3);
171 + expect(result.rawPayload).toHaveProperty('type', 'composio.trigger.message');
172 + expect(result.rawPayload).toHaveProperty('metadata');
173 + });
174 +
175 + it('detects correct version for V2 payload', async () => {
176 + const v2Fixture = fixtures.find(f => f.expectedResult.version === 'V2');
177 + if (!v2Fixture) {
178 + throw new Error('V2 fixture not found');
179 + }
180 +
181 + const result = await triggers.verifyWebhook({
182 + payload: v2Fixture.payload,
183 + signature: v2Fixture.headers['webhook-signature'],
184 + id: v2Fixture.headers['webhook-id'],
185 + timestamp: v2Fixture.headers['webhook-timestamp'],
186 + secret: v2Fixture.testSecret,
187 + tolerance: 0,
188 + });
189 +
190 + expect(result.version).toBe(WebhookVersions.V2);
191 + expect(result.rawPayload).toHaveProperty('type');
192 + expect(result.rawPayload).toHaveProperty('data');
193 + });
194 +
195 + it('detects correct version for V1 payload', async () => {
196 + const v1Fixture = fixtures.find(f => f.expectedResult.version === 'V1');
197 + if (!v1Fixture) {
198 + throw new Error('V1 fixture not found');
199 + }
200 +
201 + const result = await triggers.verifyWebhook({
202 + payload: v1Fixture.payload,
203 + signature: v1Fixture.headers['webhook-signature'],
204 + id: v1Fixture.headers['webhook-id'],
205 + timestamp: v1Fixture.headers['webhook-timestamp'],
206 + secret: v1Fixture.testSecret,
207 + tolerance: 0,
208 + });
209 +
210 + expect(result.version).toBe(WebhookVersions.V1);
211 + expect(result.rawPayload).toHaveProperty('trigger_name');
212 + expect(result.rawPayload).toHaveProperty('connection_id');
213 + });
214 + });
215 +
216 + describe('golden signature contract tests', () => {
217 + it.each(goldenSignatures.testCases)(
218 + 'produces identical signature for: $name',
219 + async testCase => {
220 + const computed = computeSignature(
221 + testCase.id,
222 + testCase.timestamp,
223 + testCase.payload,
224 + testCase.secret
225 + );
226 + expect(computed).toBe(testCase.expectedSignature);
227 + }
228 + );
229 +
230 + it('algorithm matches documented format', () => {
231 + expect(goldenSignatures.algorithm).toBe('HMAC-SHA256');
232 + expect(goldenSignatures.format).toBe('v1,base64(HMAC-SHA256(id.timestamp.payload, secret))');
233 + });
234 + });
235 +
236 + describe('signature algorithm validation', () => {
237 + it('computes signature using id.timestamp.payload format', async () => {
238 + const fixture = fixtures[0];
239 + const expectedSignature = computeSignature(
240 + fixture.headers['webhook-id'],
241 + fixture.headers['webhook-timestamp'],
242 + fixture.payload,
243 + fixture.testSecret
244 + );
245 +
246 + expect(expectedSignature).toBe(fixture.headers['webhook-signature']);
247 + });
248 +
249 + it('rejects signature computed with wrong format (payload only)', async () => {
250 + const fixture = fixtures[0];
251 + // Wrong format: just payload
252 + const wrongSignature =
253 + 'v1,' +
254 + crypto
255 + .createHmac('sha256', fixture.testSecret)
256 + .update(fixture.payload, 'utf8')
257 + .digest('base64');
258 +
259 + await expect(
260 + triggers.verifyWebhook({
261 + payload: fixture.payload,
262 + signature: wrongSignature,
263 + id: fixture.headers['webhook-id'],
264 + timestamp: fixture.headers['webhook-timestamp'],
265 + secret: fixture.testSecret,
266 + tolerance: 0,
267 + })
268 + ).rejects.toThrow('The signature provided is invalid');
269 + });
270 +
271 + it('rejects signature computed with wrong format (timestamp.payload)', async () => {
272 + const fixture = fixtures[0];
273 + // Wrong format: timestamp.payload (missing id)
274 + const toSign = `${fixture.headers['webhook-timestamp']}.${fixture.payload}`;
275 + const wrongSignature =
276 + 'v1,' +
277 + crypto.createHmac('sha256', fixture.testSecret).update(toSign, 'utf8').digest('base64');
278 +
279 + await expect(
280 + triggers.verifyWebhook({
281 + payload: fixture.payload,
282 + signature: wrongSignature,
283 + id: fixture.headers['webhook-id'],
284 + timestamp: fixture.headers['webhook-timestamp'],
285 + secret: fixture.testSecret,
286 + tolerance: 0,
287 + })
288 + ).rejects.toThrow('The signature provided is invalid');
289 + });
290 + });
291 +
292 + describe('payload structure validation', () => {
293 + it('preserves exact JSON structure from fixture', async () => {
294 + const v3Fixture = fixtures.find(f => f.expectedResult.version === 'V3');
295 + if (!v3Fixture) throw new Error('V3 fixture not found');
296 +
297 + const result = await triggers.verifyWebhook({
298 + payload: v3Fixture.payload,
299 + signature: v3Fixture.headers['webhook-signature'],
300 + id: v3Fixture.headers['webhook-id'],
301 + timestamp: v3Fixture.headers['webhook-timestamp'],
302 + secret: v3Fixture.testSecret,
303 + tolerance: 0,
304 + });
305 +
306 + const parsedPayload = JSON.parse(v3Fixture.payload);
307 + expect(result.rawPayload).toEqual(parsedPayload);
308 + });
309 +
310 + it('normalizes V3 payload to IncomingTriggerPayload format', async () => {
311 + const v3Fixture = fixtures.find(f => f.expectedResult.version === 'V3');
312 + if (!v3Fixture) throw new Error('V3 fixture not found');
313 +
314 + const result = await triggers.verifyWebhook({
315 + payload: v3Fixture.payload,
316 + signature: v3Fixture.headers['webhook-signature'],
317 + id: v3Fixture.headers['webhook-id'],
318 + timestamp: v3Fixture.headers['webhook-timestamp'],
319 + secret: v3Fixture.testSecret,
320 + tolerance: 0,
321 + });
322 +
323 + // Verify normalized payload has expected structure
324 + expect(result.payload).toHaveProperty('id');
325 + expect(result.payload).toHaveProperty('uuid');
326 + expect(result.payload).toHaveProperty('triggerSlug');
327 + expect(result.payload).toHaveProperty('toolkitSlug');
328 + expect(result.payload).toHaveProperty('userId');
329 + expect(result.payload).toHaveProperty('payload');
330 + expect(result.payload).toHaveProperty('metadata');
331 + expect(result.payload.metadata).toHaveProperty('connectedAccount');
332 + });
333 + });
334 +
335 + describe('whitespace sensitivity', () => {
336 + it('fails verification if whitespace in payload changes', async () => {
337 + const fixture = fixtures[0];
338 + // Add extra whitespace to payload
339 + const modifiedPayload = fixture.payload.replace('{', '{ ');
340 +
341 + await expect(
342 + triggers.verifyWebhook({
343 + payload: modifiedPayload,
344 + signature: fixture.headers['webhook-signature'],
345 + id: fixture.headers['webhook-id'],
346 + timestamp: fixture.headers['webhook-timestamp'],
347 + secret: fixture.testSecret,
348 + tolerance: 0,
349 + })
350 + ).rejects.toThrow();
351 + });
352 +
353 + it('fails verification if payload is re-serialized', async () => {
354 + const fixture = fixtures[0];
355 + // Parse and re-serialize - may change whitespace/key order
356 + const reserialized = JSON.stringify(JSON.parse(fixture.payload));
357 +
358 + // Only test if re-serialization actually changed the payload
359 + if (reserialized !== fixture.payload) {
360 + await expect(
361 + triggers.verifyWebhook({
362 + payload: reserialized,
363 + signature: fixture.headers['webhook-signature'],
364 + id: fixture.headers['webhook-id'],
365 + timestamp: fixture.headers['webhook-timestamp'],
366 + secret: fixture.testSecret,
367 + tolerance: 0,
368 + })
369 + ).rejects.toThrow();
370 + }
371 + });
372 + });
373 +
374 + describe('cross-fixture consistency', () => {
375 + it('all fixtures use the same test secret', () => {
376 + const secrets = new Set(fixtures.map(f => f.testSecret));
377 + expect(secrets.size).toBe(1);
378 + expect(secrets.has('test-webhook-secret-for-fixtures')).toBe(true);
379 + });
380 +
381 + it('all fixtures have unique webhook IDs', () => {
382 + const ids = fixtures.map(f => f.headers['webhook-id']);
383 + const uniqueIds = new Set(ids);
384 + expect(uniqueIds.size).toBe(fixtures.length);
385 + });
386 +
387 + it('fixtures cover all supported versions', () => {
388 + const versions = new Set(fixtures.map(f => f.expectedResult.version));
389 + expect(versions.has('V1')).toBe(true);
390 + expect(versions.has('V2')).toBe(true);
391 + expect(versions.has('V3')).toBe(true);
392 + });
393 + });
394 +});