Skip to content

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

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

jkomyno408e7d080f9b
diff --git a/ts/examples/triggers/src/subscribe.ts b/ts/examples/triggers/src/subscribe.ts
new file mode 100644
index 000000000..d1ee4645d
--- /dev/null
+++ b/ts/examples/triggers/src/subscribe.ts
@@ -0,0 +1,21 @@
+import { Composio } from '@composio/core';
+
+// Initialize Composio client
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+});
+
+// Subscribe to triggers with optional filters
+// Replace 'ti_ollBPgfhgmMK' with your actual trigger ID
+const sub = await composio.triggers.subscribe(
+ metadata => {
+ console.log('Received trigger event:');
+ console.dir(metadata, { depth: 3 });
+ },
+ { triggerId: 'ti_ollBPgfhgmMK' }
+);
+
+console.log('Subscribed to triggers. Waiting for events...');
+
+// Keep the process alive forever
+process.stdin.resume();
diff --git a/ts/packages/core/src/models/Triggers.ts b/ts/packages/core/src/models/Triggers.ts
index 8b333e42f..1ad6274e5 100644
--- a/ts/packages/core/src/models/Triggers.ts
+++ b/ts/packages/core/src/models/Triggers.ts
@@ -433,10 +433,9 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
logger.debug('🔄 Subscribing to triggers with filters: ', JSON.stringify(filters, null, 2));
await this.pusherService.subscribe((_data: Record<string, unknown>) => {
logger.debug('Received raw trigger data', JSON.stringify(_data, null, 2));
- // @TODO: This is a temporary fix to get the trigger data
- // ideally we should have a type for the trigger data
- const data = _data as TriggerData;
- const parsedData = transformIncomingTriggerPayload(data);
+
+ // Parse using unified method that handles V1/V2/V3 and legacy formats
+ const parsedData = this.parsePusherPayload(_data);
if (this.shouldSendTriggerAfterFilters(parsedFilters.data, parsedData)) {
try {
@@ -450,6 +449,70 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
});
}
+ /**
+ * Parses incoming Pusher payload, supporting V1, V2, V3, and legacy TriggerData formats.
+ * This method reuses the same schemas and normalizers used for HTTP webhooks.
+ * @private
+ */
+ private parsePusherPayload(data: Record<string, unknown>): IncomingTriggerPayload {
+ // Try V3 format first (has 'composio.trigger.message' type)
+ const v3Result = WebhookPayloadV3Schema.safeParse(data);
+ if (v3Result.success) {
+ logger.debug('Parsed Pusher payload as V3 format');
+ return this.normalizeV3Payload(v3Result.data);
+ }
+
+ // Try V2 format (has 'type', 'timestamp', 'log_id', and 'data')
+ const v2Result = WebhookPayloadV2Schema.safeParse(data);
+ if (v2Result.success) {
+ logger.debug('Parsed Pusher payload as V2 format');
+ return this.normalizeV2Payload(v2Result.data);
+ }
+
+ // Try V1 format (has 'trigger_name', 'connection_id', 'trigger_id', 'payload', 'log_id')
+ const v1Result = WebhookPayloadV1Schema.safeParse(data);
+ if (v1Result.success) {
+ logger.debug('Parsed Pusher payload as V1 format');
+ return this.normalizeV1Payload(v1Result.data);
+ }
+
+ // Try legacy TriggerData format (for backwards compatibility)
+ const legacyData = data as TriggerData;
+ if (legacyData.metadata?.nanoId && legacyData.appName) {
+ logger.debug('Parsed Pusher payload as legacy TriggerData format');
+ return transformIncomingTriggerPayload(legacyData);
+ }
+
+ // Fallback: log warning and return a minimal payload with available data
+ logger.warn('Unknown Pusher payload format. Payload keys: ' + Object.keys(data).join(', '));
+
+ // Return a minimal payload structure to avoid breaking the subscription
+ return {
+ id: (data.id as string) || (data.trigger_id as string) || 'unknown',
+ uuid: (data.uuid as string) || (data.id as string) || 'unknown',
+ triggerSlug: (data.triggerSlug as string) || (data.trigger_name as string) || 'UNKNOWN',
+ toolkitSlug: (data.toolkitSlug as string) || (data.appName as string) || 'UNKNOWN',
+ userId: (data.userId as string) || '',
+ payload: (data.payload as Record<string, unknown>) || data,
+ originalPayload: (data.originalPayload as Record<string, unknown>) || data,
+ metadata: {
+ id: (data.id as string) || 'unknown',
+ uuid: (data.uuid as string) || 'unknown',
+ toolkitSlug: (data.toolkitSlug as string) || 'UNKNOWN',
+ triggerSlug: (data.triggerSlug as string) || 'UNKNOWN',
+ triggerConfig: {},
+ connectedAccount: {
+ id: '',
+ uuid: '',
+ authConfigId: '',
+ authConfigUUID: '',
+ userId: '',
+ status: 'ACTIVE',
+ },
+ },
+ };
+ }
+
/**
* Unsubscribe from all the triggers
*
@@ -519,6 +582,28 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
// Validate input parameters
const parsedParams = VerifyWebhookParamsSchema.safeParse(params);
if (!parsedParams.success) {
+ // Extract missing required parameters for a more helpful error message
+ const missingParams = parsedParams.error.issues
+ .filter(issue => issue.code === 'invalid_type' && issue.received === 'undefined')
+ .map(issue => {
+ const paramName = issue.path[0] as string;
+ const headerMap: Record<string, string> = {
+ id: 'webhook-id',
+ timestamp: 'webhook-timestamp',
+ signature: 'webhook-signature',
+ };
+ const headerName = headerMap[paramName];
+ return headerName ? `'${paramName}' (from '${headerName}' header)` : `'${paramName}'`;
+ });
+
+ if (missingParams.length > 0) {
+ throw new ValidationError(
+ `Missing required parameters: ${missingParams.join(', ')}. ` +
+ `Extract these values from the HTTP request headers and body.`,
+ { cause: parsedParams.error }
+ );
+ }
+
throw new ValidationError('Invalid parameters passed to verifyWebhook', {
cause: parsedParams.error,
});
diff --git a/ts/packages/core/src/types/triggers.types.ts b/ts/packages/core/src/types/triggers.types.ts
index 30c2d9e4f..73db1667d 100644
--- a/ts/packages/core/src/types/triggers.types.ts
+++ b/ts/packages/core/src/types/triggers.types.ts
@@ -268,21 +268,42 @@ export const VerifyWebhookParamsSchema = z.object({
* The webhook message ID from the 'webhook-id' header.
* Format: 'msg_xxx'
*/
- id: z.string(),
+ id: z.string({
+ required_error: "Missing 'id' parameter. Pass the value of the 'webhook-id' HTTP header.",
+ invalid_type_error: "Invalid 'id' parameter. Expected string from 'webhook-id' HTTP header.",
+ }),
/** The raw webhook payload as a string (request body) */
- payload: z.string(),
+ payload: z.string({
+ required_error:
+ "Missing 'payload' parameter. Pass the raw request body as a string (do not parse it).",
+ invalid_type_error: "Invalid 'payload' parameter. Expected string (raw request body).",
+ }),
/** The webhook secret used to sign the payload (from Composio dashboard) */
- secret: z.string(),
+ secret: z.string({
+ required_error:
+ "Missing 'secret' parameter. Get your webhook secret from the Composio dashboard.",
+ invalid_type_error: "Invalid 'secret' parameter. Expected string.",
+ }),
/**
* The signature from the 'webhook-signature' header.
* Format: 'v1,base64EncodedSignature'
*/
- signature: z.string(),
+ signature: z.string({
+ required_error:
+ "Missing 'signature' parameter. Pass the value of the 'webhook-signature' HTTP header.",
+ invalid_type_error:
+ "Invalid 'signature' parameter. Expected string from 'webhook-signature' HTTP header.",
+ }),
/**
* The webhook timestamp from the 'webhook-timestamp' header.
* This is the Unix timestamp in seconds when the webhook was sent.
*/
- timestamp: z.string(),
+ timestamp: z.string({
+ required_error:
+ "Missing 'timestamp' parameter. Pass the value of the 'webhook-timestamp' HTTP header.",
+ invalid_type_error:
+ "Invalid 'timestamp' parameter. Expected string from 'webhook-timestamp' HTTP header.",
+ }),
/**
* Maximum allowed age of the webhook in seconds.
* If the webhook timestamp is older than this, verification will fail.
diff --git a/ts/packages/core/test/fixtures/webhook/README.md b/ts/packages/core/test/fixtures/webhook/README.md
new file mode 100644
index 000000000..b7a0654a5
--- /dev/null
+++ b/ts/packages/core/test/fixtures/webhook/README.md
@@ -0,0 +1,105 @@
+# Webhook Verification Test Fixtures
+
+This directory contains sanitized webhook fixtures for testing the `verifyWebhook` function.
+These fixtures use deterministic test secrets so the tests can verify both the structure
+and the signature verification algorithm.
+
+## Fixture Format
+
+Each fixture file contains:
+
+```json
+{
+ "description": "Human-readable description of this fixture",
+ "capturedAt": "ISO 8601 timestamp when this was captured",
+ "headers": {
+ "webhook-id": "msg_xxx",
+ "webhook-timestamp": "1234567890",
+ "webhook-signature": "v1,base64_signature"
+ },
+ "payload": "{...raw JSON payload string...}",
+ "testSecret": "deterministic-test-secret",
+ "expectedResult": {
+ "version": "V1|V2|V3",
+ "triggerSlug": "GITHUB_PUSH_EVENT"
+ }
+}
+```
+
+## Why Sanitized Fixtures?
+
+Real webhook secrets should **never** be committed to version control. Instead:
+
+1. We capture real webhooks to preserve exact JSON structure and whitespace
+2. Replace sensitive IDs with sanitized placeholders (e.g., `msg_SANITIZED_001`)
+3. Re-sign the payload with a known test secret
+4. The test validates both structure correctness and algorithm correctness
+
+## How to Capture New Fixtures
+
+### 1. Start the Webhook Server
+
+```bash
+cd ts/examples/triggers
+pnpm webhook
+```
+
+### 2. Expose Locally with ngrok or telebit
+
+```bash
+ngrok http 3000
+# OR
+telebit http 3000
+```
+
+### 3. Configure Webhook URL in Composio Dashboard
+
+Set the webhook URL to your public URL (e.g., `https://abc123.ngrok.io/webhook`).
+
+### 4. Trigger an Event
+
+Perform an action that triggers the webhook (e.g., push to a GitHub repo).
+
+### 5. Capture the Raw Request
+
+The webhook server logs the raw headers and payload. Copy them.
+
+### 6. Sanitize and Re-sign
+
+Use this script to create a sanitized fixture:
+
+```typescript
+import * as crypto from 'node:crypto';
+
+const testSecret = 'test-webhook-secret-for-fixtures';
+
+// Your captured data (sanitize IDs first!)
+const webhookId = 'msg_SANITIZED_001';
+const webhookTimestamp = '1738150200';
+const payload = '{"id":"evt-SANITIZED",...}';
+
+// Compute new signature with test secret
+const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
+const signature = crypto.createHmac('sha256', testSecret).update(toSign, 'utf8').digest('base64');
+
+console.log(`v1,${signature}`);
+```
+
+### 7. Create the Fixture File
+
+Save as `v3-<description>.json` (or v1/v2 depending on version).
+
+## Golden Signatures
+
+The `golden-signatures.json` file contains contract test cases that verify
+the signature algorithm produces consistent output. These should never change
+unless the algorithm itself changes.
+
+## Testing
+
+The fixtures are loaded by `verifyWebhook.integration.test.ts` and used to:
+
+1. Verify signature validation works with real-world payload structure
+2. Test version detection (V1, V2, V3)
+3. Ensure payload normalization produces expected output
+4. Contract test that algorithm hasn't changed (golden signatures)
diff --git a/ts/packages/core/test/fixtures/webhook/golden-signatures.json b/ts/packages/core/test/fixtures/webhook/golden-signatures.json
new file mode 100644
index 000000000..88e658d79
--- /dev/null
+++ b/ts/packages/core/test/fixtures/webhook/golden-signatures.json
@@ -0,0 +1,47 @@
+{
+ "description": "Golden signature test cases - DO NOT MODIFY unless algorithm changes",
+ "algorithm": "HMAC-SHA256",
+ "format": "v1,base64(HMAC-SHA256(id.timestamp.payload, secret))",
+ "testCases": [
+ {
+ "name": "simple payload",
+ "id": "msg_test_001",
+ "timestamp": "1700000000",
+ "payload": "{\"test\":\"data\"}",
+ "secret": "test-secret",
+ "expectedSignature": "v1,4Fay6rvxXDEbH+4oA1fYP2BR/Bwzn3/7ONj40iJQagY="
+ },
+ {
+ "name": "unicode payload",
+ "id": "msg_test_002",
+ "timestamp": "1700000001",
+ "payload": "{\"message\":\"Hello World\"}",
+ "secret": "unicode-secret-key",
+ "expectedSignature": "v1,ICmAFUlesRqIFA44bU6Wlce5GszoHjG+w7nurcu5EWc="
+ },
+ {
+ "name": "complex nested payload",
+ "id": "msg_test_003",
+ "timestamp": "1700000002",
+ "payload": "{\"nested\":{\"array\":[1,2,3],\"object\":{\"key\":\"value\"}}}",
+ "secret": "complex-secret",
+ "expectedSignature": "v1,Vx/pw0yOiRRoxdfifaZ3zBKt4B3KkRKFVr6gLQNJs9Q="
+ },
+ {
+ "name": "empty data object",
+ "id": "msg_test_004",
+ "timestamp": "1700000003",
+ "payload": "{\"data\":{}}",
+ "secret": "empty-data-secret",
+ "expectedSignature": "v1,IbLtu+G65OH8Gw7ZFqy38ru+Jrg96yWfueYMMdaFYs0="
+ },
+ {
+ "name": "special characters in secret",
+ "id": "msg_test_005",
+ "timestamp": "1700000004",
+ "payload": "{\"test\":true}",
+ "secret": "secret!@#$%^&*()",
+ "expectedSignature": "v1,kUvMXJ0rouLoROxY70WIzV+zLQGpSRuCXv8evLTPjXg="
+ }
+ ]
+}
diff --git a/ts/packages/core/test/fixtures/webhook/v1-github-push.json b/ts/packages/core/test/fixtures/webhook/v1-github-push.json
new file mode 100644
index 000000000..1c2aab681
--- /dev/null
+++ b/ts/packages/core/test/fixtures/webhook/v1-github-push.json
@@ -0,0 +1,16 @@
+{
+ "description": "V1 GitHub push webhook - legacy format sanitized",
+ "capturedAt": "2026-01-29T10:30:00Z",
+ "headers": {
+ "webhook-id": "msg_fixture_v1_001",
+ "webhook-timestamp": "1738150200",
+ "webhook-signature": "v1,A/VFbvOJ8JAzXZweWvc+IHaBie19NVKUpQKbeobt5xo="
+ },
+ "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\"}",
+ "testSecret": "test-webhook-secret-for-fixtures",
+ "expectedResult": {
+ "version": "V1",
+ "triggerSlug": "GITHUB_PUSH_EVENT",
+ "triggerId": "trigger_fixture_001"
+ }
+}
diff --git a/ts/packages/core/test/fixtures/webhook/v2-github-push.json b/ts/packages/core/test/fixtures/webhook/v2-github-push.json
new file mode 100644
index 000000000..4384263cc
--- /dev/null
+++ b/ts/packages/core/test/fixtures/webhook/v2-github-push.json
@@ -0,0 +1,16 @@
+{
+ "description": "V2 GitHub push webhook - sanitized real-world structure",
+ "capturedAt": "2026-01-29T10:30:00Z",
+ "headers": {
+ "webhook-id": "msg_fixture_v2_001",
+ "webhook-timestamp": "1738150200",
+ "webhook-signature": "v1,a/mTZohEnMvzupLGWsiDLhTctk+hgx3Q2r1ACjybkhk="
+ },
+ "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\"}}}",
+ "testSecret": "test-webhook-secret-for-fixtures",
+ "expectedResult": {
+ "version": "V2",
+ "triggerSlug": "GITHUB_PUSH_EVENT",
+ "userId": "user_fixture_002"
+ }
+}
diff --git a/ts/packages/core/test/fixtures/webhook/v3-github-push.json b/ts/packages/core/test/fixtures/webhook/v3-github-push.json
new file mode 100644
index 000000000..a9e3f15ab
--- /dev/null
+++ b/ts/packages/core/test/fixtures/webhook/v3-github-push.json
@@ -0,0 +1,17 @@
+{
+ "description": "V3 GitHub push webhook - sanitized real-world structure",
+ "capturedAt": "2026-01-29T10:30:00Z",
+ "headers": {
+ "webhook-id": "msg_fixture_v3_001",
+ "webhook-timestamp": "1738150200",
+ "webhook-signature": "v1,GqTsMaDtroeNNR7rDDzEGVTtHfFtIDknXhmkCXss7cA="
+ },
+ "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\"}]}}",
+ "testSecret": "test-webhook-secret-for-fixtures",
+ "expectedResult": {
+ "version": "V3",
+ "triggerSlug": "GITHUB_PUSH_EVENT",
+ "userId": "user_fixture_001",
+ "connectedAccountId": "ca_fixture_001"
+ }
+}
diff --git a/ts/packages/core/test/models/triggers.test.ts b/ts/packages/core/test/models/triggers.test.ts
index d8b70fac8..4edcb2df7 100644
--- a/ts/packages/core/test/models/triggers.test.ts
+++ b/ts/packages/core/test/models/triggers.test.ts
@@ -978,4 +978,214 @@ describe('Triggers', () => {
expect(callback2).toHaveBeenCalledTimes(1);
});
});
+
+ describe('parsePusherPayload (V1/V2/V3 format support)', () => {
+ const mockCallback = vi.fn();
+
+ // V1 mock payload matching WebhookPayloadV1Schema
+ const mockV1Payload = {
+ trigger_name: 'GMAIL_NEW_GMAIL_MESSAGE',
+ connection_id: 'conn-123',
+ trigger_id: 'trigger-456',
+ payload: { subject: 'Test email', from: '[email protected]' },
+ log_id: 'log-789',
+ };
+
+ // V2 mock payload matching WebhookPayloadV2Schema
+ const mockV2Payload = {
+ type: 'GMAIL_NEW_GMAIL_MESSAGE',
+ timestamp: '2026-01-28T12:00:00Z',
+ log_id: 'log-789',
+ data: {
+ connection_id: 'conn-uuid',
+ connection_nano_id: 'conn-123',
+ trigger_nano_id: 'trigger-456',
+ trigger_id: 'trigger-uuid',
+ user_id: 'user-789',
+ subject: 'Test email',
+ },
+ };
+
+ // V3 mock payload matching WebhookPayloadV3Schema
+ const mockV3Payload = {
+ id: 'msg-123',
+ timestamp: '2026-01-28T12:00:00Z',
+ type: 'composio.trigger.message',
+ metadata: {
+ log_id: 'log-789',
+ trigger_slug: 'GMAIL_NEW_GMAIL_MESSAGE',
+ trigger_id: 'trigger-456',
+ connected_account_id: 'conn-123',
+ auth_config_id: 'auth-456',
+ user_id: 'user-789',
+ },
+ data: { subject: 'Test email', from: '[email protected]' },
+ };
+
+ beforeEach(() => {
+ mockCallback.mockClear();
+ vi.mocked(logger.debug).mockClear();
+ vi.mocked(logger.warn).mockClear();
+ });
+
+ it('should parse V3 Pusher payload', async () => {
+ await triggers.subscribe(mockCallback);
+ const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
+ const filterCallback = subscribeCall[0];
+
+ filterCallback(mockV3Payload);
+
+ expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'trigger-456',
+ triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
+ userId: 'user-789',
+ toolkitSlug: 'GMAIL',
+ payload: { subject: 'Test email', from: '[email protected]' },
+ metadata: expect.objectContaining({
+ id: 'trigger-456',
+ triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
+ connectedAccount: expect.objectContaining({
+ id: 'conn-123',
+ userId: 'user-789',
+ authConfigId: 'auth-456',
+ }),
+ }),
+ })
+ );
+ expect(logger.debug).toHaveBeenCalledWith('Parsed Pusher payload as V3 format');
+ });
+
+ it('should parse V2 Pusher payload', async () => {
+ await triggers.subscribe(mockCallback);
+ const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
+ const filterCallback = subscribeCall[0];
+
+ filterCallback(mockV2Payload);
+
+ expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'trigger-456',
+ uuid: 'trigger-uuid',
+ triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
+ userId: 'user-789',
+ toolkitSlug: 'GMAIL',
+ metadata: expect.objectContaining({
+ id: 'trigger-456',
+ uuid: 'trigger-uuid',
+ connectedAccount: expect.objectContaining({
+ id: 'conn-123',
+ uuid: 'conn-uuid',
+ userId: 'user-789',
+ }),
+ }),
+ })
+ );
+ expect(logger.debug).toHaveBeenCalledWith('Parsed Pusher payload as V2 format');
+ });
+
+ it('should parse V1 Pusher payload', async () => {
+ await triggers.subscribe(mockCallback);
+ const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
+ const filterCallback = subscribeCall[0];
+
+ filterCallback(mockV1Payload);
+
+ expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'trigger-456',
+ triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
+ toolkitSlug: 'GMAIL',
+ payload: { subject: 'Test email', from: '[email protected]' },
+ metadata: expect.objectContaining({
+ id: 'trigger-456',
+ triggerSlug: 'GMAIL_NEW_GMAIL_MESSAGE',
+ connectedAccount: expect.objectContaining({
+ id: 'conn-123',
+ }),
+ }),
+ })
+ );
+ expect(logger.debug).toHaveBeenCalledWith('Parsed Pusher payload as V1 format');
+ });
+
+ it('should parse legacy TriggerData payload for backwards compatibility', async () => {
+ await triggers.subscribe(mockCallback);
+ const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
+ const filterCallback = subscribeCall[0];
+
+ filterCallback(mockTriggerData);
+
+ expect(mockCallback).toHaveBeenCalledTimes(1);
+ expect(mockCallback).toHaveBeenCalledWith(mockIncomingTriggerPayload);
+ expect(logger.debug).toHaveBeenCalledWith(
+ 'Parsed Pusher payload as legacy TriggerData format'
+ );
+ });
+
+ it('should log warning for unknown payload format and attempt legacy transformation', async () => {
+ const unknownPayload = {
+ someField: 'value',
+ anotherField: 123,
+ };
+
+ await triggers.subscribe(mockCallback);
+ const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
+ const filterCallback = subscribeCall[0];
+
+ // This should not throw, but should log a warning
+ expect(() => filterCallback(unknownPayload)).not.toThrow();
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining('Unknown Pusher payload format')
+ );
+ });
+
+ it('should filter V3 payloads correctly by triggerId', async () => {
+ const filters = { triggerId: 'trigger-456' };
+ await triggers.subscribe(mockCallback, filters);
+ const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
+ const filterCallback = subscribeCall[0];
+
+ filterCallback(mockV3Payload);
+
+ expect(mockCallback).toHaveBeenCalledTimes(1);
+ });
+
+ it('should filter V3 payloads correctly and reject non-matching triggerId', async () => {
+ const filters = { triggerId: 'wrong-trigger-id' };
+ await triggers.subscribe(mockCallback, filters);
+ const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
+ const filterCallback = subscribeCall[0];
+
+ filterCallback(mockV3Payload);
+
+ expect(mockCallback).not.toHaveBeenCalled();
+ });
+
+ it('should filter V2 payloads by toolkit', async () => {
+ const filters = { toolkits: ['GMAIL'] };
+ await triggers.subscribe(mockCallback, filters);
+ const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
+ const filterCallback = subscribeCall[0];
+
+ filterCallback(mockV2Payload);
+
+ expect(mockCallback).toHaveBeenCalledTimes(1);
+ });
+
+ it('should filter V1 payloads by triggerSlug', async () => {
+ const filters = { triggerSlug: ['GMAIL_NEW_GMAIL_MESSAGE'] };
+ await triggers.subscribe(mockCallback, filters);
+ const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
+ const filterCallback = subscribeCall[0];
+
+ filterCallback(mockV1Payload);
+
+ expect(mockCallback).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/ts/packages/core/test/models/verifyWebhook.integration.test.ts b/ts/packages/core/test/models/verifyWebhook.integration.test.ts
new file mode 100644
index 000000000..a6135abec
--- /dev/null
+++ b/ts/packages/core/test/models/verifyWebhook.integration.test.ts
@@ -0,0 +1,394 @@
+import * as crypto from 'node:crypto';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Triggers } from '../../src/models/Triggers';
+import ComposioClient from '@composio/client';
+import { WebhookVersions } from '../../src/types/triggers.types';
+
+// Mock dependencies
+vi.mock('../../src/utils/logger');
+vi.mock('../../src/telemetry/Telemetry', () => ({
+ telemetry: {
+ instrument: vi.fn(),
+ },
+}));
+vi.mock('../../src/services/pusher/Pusher');
+
+// Create mock client
+const createMockClient = () => ({
+ baseURL: 'https://api.composio.dev',
+ apiKey: 'test-api-key',
+ triggerInstances: {
+ listActive: vi.fn(),
+ upsert: vi.fn(),
+ manage: {
+ delete: vi.fn(),
+ update: vi.fn(),
+ },
+ },
+ triggersTypes: {
+ list: vi.fn(),
+ retrieve: vi.fn(),
+ retrieveEnum: vi.fn(),
+ },
+ connectedAccounts: {
+ list: vi.fn(),
+ },
+});
+
+/**
+ * Fixture type definition
+ */
+interface WebhookFixture {
+ description: string;
+ capturedAt: string;
+ headers: {
+ 'webhook-id': string;
+ 'webhook-timestamp': string;
+ 'webhook-signature': string;
+ };
+ payload: string;
+ testSecret: string;
+ expectedResult: {
+ version: string;
+ triggerSlug: string;
+ userId?: string;
+ connectedAccountId?: string;
+ triggerId?: string;
+ };
+}
+
+/**
+ * Golden signature test case
+ */
+interface GoldenSignatureTestCase {
+ name: string;
+ id: string;
+ timestamp: string;
+ payload: string;
+ secret: string;
+ expectedSignature: string;
+}
+
+interface GoldenSignatures {
+ description: string;
+ algorithm: string;
+ format: string;
+ testCases: GoldenSignatureTestCase[];
+}
+
+/**
+ * Load all webhook fixtures from the fixtures directory
+ */
+function loadFixtures(): WebhookFixture[] {
+ const fixturesDir = path.join(__dirname, '../fixtures/webhook');
+ const fixtureFiles = fs
+ .readdirSync(fixturesDir)
+ .filter(f => f.startsWith('v') && f.endsWith('.json') && !f.includes('golden'));
+
+ return fixtureFiles.map(file => {
+ const content = fs.readFileSync(path.join(fixturesDir, file), 'utf-8');
+ return JSON.parse(content) as WebhookFixture;
+ });
+}
+
+/**
+ * Load golden signatures for contract testing
+ */
+function loadGoldenSignatures(): GoldenSignatures {
+ const fixturesDir = path.join(__dirname, '../fixtures/webhook');
+ const content = fs.readFileSync(path.join(fixturesDir, 'golden-signatures.json'), 'utf-8');
+ return JSON.parse(content) as GoldenSignatures;
+}
+
+/**
+ * Compute signature using the documented algorithm
+ */
+function computeSignature(id: string, timestamp: string, payload: string, secret: string): string {
+ const toSign = `${id}.${timestamp}.${payload}`;
+ const signature = crypto.createHmac('sha256', secret).update(toSign, 'utf8').digest('base64');
+ return `v1,${signature}`;
+}
+
+describe('Triggers.verifyWebhook - Integration Tests', () => {
+ let triggers: Triggers<any>;
+ let mockClient: ReturnType<typeof createMockClient>;
+ const fixtures = loadFixtures();
+ const goldenSignatures = loadGoldenSignatures();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockClient = createMockClient();
+ triggers = new Triggers(mockClient as unknown as ComposioClient);
+ });
+
+ describe('fixture-based verification', () => {
+ it.each(fixtures)('verifies $description', async fixture => {
+ const result = await triggers.verifyWebhook({
+ payload: fixture.payload,
+ signature: fixture.headers['webhook-signature'],
+ id: fixture.headers['webhook-id'],
+ timestamp: fixture.headers['webhook-timestamp'],
+ secret: fixture.testSecret,
+ tolerance: 0, // Disable timestamp validation for fixtures
+ });
+
+ expect(result.version).toBe(fixture.expectedResult.version);
+ expect(result.payload.triggerSlug).toBe(fixture.expectedResult.triggerSlug);
+
+ if (fixture.expectedResult.userId) {
+ expect(result.payload.userId).toBe(fixture.expectedResult.userId);
+ }
+
+ if (fixture.expectedResult.connectedAccountId) {
+ expect(result.payload.metadata.connectedAccount.id).toBe(
+ fixture.expectedResult.connectedAccountId
+ );
+ }
+
+ if (fixture.expectedResult.triggerId) {
+ expect(result.payload.id).toBe(fixture.expectedResult.triggerId);
+ }
+ });
+
+ it('detects correct version for V3 payload', async () => {
+ const v3Fixture = fixtures.find(f => f.expectedResult.version === 'V3');
+ if (!v3Fixture) {
+ throw new Error('V3 fixture not found');
+ }
+
+ const result = await triggers.verifyWebhook({
+ payload: v3Fixture.payload,
+ signature: v3Fixture.headers['webhook-signature'],
+ id: v3Fixture.headers['webhook-id'],
+ timestamp: v3Fixture.headers['webhook-timestamp'],
+ secret: v3Fixture.testSecret,
+ tolerance: 0,
+ });
+
+ expect(result.version).toBe(WebhookVersions.V3);
+ expect(result.rawPayload).toHaveProperty('type', 'composio.trigger.message');
+ expect(result.rawPayload).toHaveProperty('metadata');
+ });
+
+ it('detects correct version for V2 payload', async () => {
+ const v2Fixture = fixtures.find(f => f.expectedResult.version === 'V2');
+ if (!v2Fixture) {
+ throw new Error('V2 fixture not found');
+ }
+
+ const result = await triggers.verifyWebhook({
+ payload: v2Fixture.payload,
+ signature: v2Fixture.headers['webhook-signature'],
+ id: v2Fixture.headers['webhook-id'],
+ timestamp: v2Fixture.headers['webhook-timestamp'],
+ secret: v2Fixture.testSecret,
+ tolerance: 0,
+ });
+
+ expect(result.version).toBe(WebhookVersions.V2);
+ expect(result.rawPayload).toHaveProperty('type');
+ expect(result.rawPayload).toHaveProperty('data');
+ });
+
+ it('detects correct version for V1 payload', async () => {
+ const v1Fixture = fixtures.find(f => f.expectedResult.version === 'V1');
+ if (!v1Fixture) {
+ throw new Error('V1 fixture not found');
+ }
+
+ const result = await triggers.verifyWebhook({
+ payload: v1Fixture.payload,
+ signature: v1Fixture.headers['webhook-signature'],
+ id: v1Fixture.headers['webhook-id'],
+ timestamp: v1Fixture.headers['webhook-timestamp'],
+ secret: v1Fixture.testSecret,
+ tolerance: 0,
+ });
+
+ expect(result.version).toBe(WebhookVersions.V1);
+ expect(result.rawPayload).toHaveProperty('trigger_name');
+ expect(result.rawPayload).toHaveProperty('connection_id');
+ });
+ });
+
+ describe('golden signature contract tests', () => {
+ it.each(goldenSignatures.testCases)(
+ 'produces identical signature for: $name',
+ async testCase => {
+ const computed = computeSignature(
+ testCase.id,
+ testCase.timestamp,
+ testCase.payload,
+ testCase.secret
+ );
+ expect(computed).toBe(testCase.expectedSignature);
+ }
+ );
+
+ it('algorithm matches documented format', () => {
+ expect(goldenSignatures.algorithm).toBe('HMAC-SHA256');
+ expect(goldenSignatures.format).toBe('v1,base64(HMAC-SHA256(id.timestamp.payload, secret))');
+ });
+ });
+
+ describe('signature algorithm validation', () => {
+ it('computes signature using id.timestamp.payload format', async () => {
+ const fixture = fixtures[0];
+ const expectedSignature = computeSignature(
+ fixture.headers['webhook-id'],
+ fixture.headers['webhook-timestamp'],
+ fixture.payload,
+ fixture.testSecret
+ );
+
+ expect(expectedSignature).toBe(fixture.headers['webhook-signature']);
+ });
+
+ it('rejects signature computed with wrong format (payload only)', async () => {
+ const fixture = fixtures[0];
+ // Wrong format: just payload
+ const wrongSignature =
+ 'v1,' +
+ crypto
+ .createHmac('sha256', fixture.testSecret)
+ .update(fixture.payload, 'utf8')
+ .digest('base64');
+
+ await expect(
+ triggers.verifyWebhook({
+ payload: fixture.payload,
+ signature: wrongSignature,
+ id: fixture.headers['webhook-id'],
+ timestamp: fixture.headers['webhook-timestamp'],
+ secret: fixture.testSecret,
+ tolerance: 0,
+ })
+ ).rejects.toThrow('The signature provided is invalid');
+ });
+
+ it('rejects signature computed with wrong format (timestamp.payload)', async () => {
+ const fixture = fixtures[0];
+ // Wrong format: timestamp.payload (missing id)
+ const toSign = `${fixture.headers['webhook-timestamp']}.${fixture.payload}`;
+ const wrongSignature =
+ 'v1,' +
+ crypto.createHmac('sha256', fixture.testSecret).update(toSign, 'utf8').digest('base64');
+
+ await expect(
+ triggers.verifyWebhook({
+ payload: fixture.payload,
+ signature: wrongSignature,
+ id: fixture.headers['webhook-id'],
+ timestamp: fixture.headers['webhook-timestamp'],
+ secret: fixture.testSecret,
+ tolerance: 0,
+ })
+ ).rejects.toThrow('The signature provided is invalid');
+ });
+ });
+
+ describe('payload structure validation', () => {
+ it('preserves exact JSON structure from fixture', async () => {
+ const v3Fixture = fixtures.find(f => f.expectedResult.version === 'V3');
+ if (!v3Fixture) throw new Error('V3 fixture not found');
+
+ const result = await triggers.verifyWebhook({
+ payload: v3Fixture.payload,
+ signature: v3Fixture.headers['webhook-signature'],
+ id: v3Fixture.headers['webhook-id'],
+ timestamp: v3Fixture.headers['webhook-timestamp'],
+ secret: v3Fixture.testSecret,
+ tolerance: 0,
+ });
+
+ const parsedPayload = JSON.parse(v3Fixture.payload);
+ expect(result.rawPayload).toEqual(parsedPayload);
+ });
+
+ it('normalizes V3 payload to IncomingTriggerPayload format', async () => {
+ const v3Fixture = fixtures.find(f => f.expectedResult.version === 'V3');
+ if (!v3Fixture) throw new Error('V3 fixture not found');
+
+ const result = await triggers.verifyWebhook({
+ payload: v3Fixture.payload,
+ signature: v3Fixture.headers['webhook-signature'],
+ id: v3Fixture.headers['webhook-id'],
+ timestamp: v3Fixture.headers['webhook-timestamp'],
+ secret: v3Fixture.testSecret,
+ tolerance: 0,
+ });
+
+ // Verify normalized payload has expected structure
+ expect(result.payload).toHaveProperty('id');
+ expect(result.payload).toHaveProperty('uuid');
+ expect(result.payload).toHaveProperty('triggerSlug');
+ expect(result.payload).toHaveProperty('toolkitSlug');
+ expect(result.payload).toHaveProperty('userId');
+ expect(result.payload).toHaveProperty('payload');
+ expect(result.payload).toHaveProperty('metadata');
+ expect(result.payload.metadata).toHaveProperty('connectedAccount');
+ });
+ });
+
+ describe('whitespace sensitivity', () => {
+ it('fails verification if whitespace in payload changes', async () => {
+ const fixture = fixtures[0];
+ // Add extra whitespace to payload
+ const modifiedPayload = fixture.payload.replace('{', '{ ');
+
+ await expect(
+ triggers.verifyWebhook({
+ payload: modifiedPayload,
+ signature: fixture.headers['webhook-signature'],
+ id: fixture.headers['webhook-id'],
+ timestamp: fixture.headers['webhook-timestamp'],
+ secret: fixture.testSecret,
+ tolerance: 0,
+ })
+ ).rejects.toThrow();
+ });
+
+ it('fails verification if payload is re-serialized', async () => {
+ const fixture = fixtures[0];
+ // Parse and re-serialize - may change whitespace/key order
+ const reserialized = JSON.stringify(JSON.parse(fixture.payload));
+
+ // Only test if re-serialization actually changed the payload
+ if (reserialized !== fixture.payload) {
+ await expect(
+ triggers.verifyWebhook({
+ payload: reserialized,
+ signature: fixture.headers['webhook-signature'],
+ id: fixture.headers['webhook-id'],
+ timestamp: fixture.headers['webhook-timestamp'],
+ secret: fixture.testSecret,
+ tolerance: 0,
+ })
+ ).rejects.toThrow();
+ }
+ });
+ });
+
+ describe('cross-fixture consistency', () => {
+ it('all fixtures use the same test secret', () => {
+ const secrets = new Set(fixtures.map(f => f.testSecret));
+ expect(secrets.size).toBe(1);
+ expect(secrets.has('test-webhook-secret-for-fixtures')).toBe(true);
+ });
+
+ it('all fixtures have unique webhook IDs', () => {
+ const ids = fixtures.map(f => f.headers['webhook-id']);
+ const uniqueIds = new Set(ids);
+ expect(uniqueIds.size).toBe(fixtures.length);
+ });
+
+ it('fixtures cover all supported versions', () => {
+ const versions = new Set(fixtures.map(f => f.expectedResult.version));
+ expect(versions.has('V1')).toBe(true);
+ expect(versions.has('V2')).toBe(true);
+ expect(versions.has('V3')).toBe(true);
+ });
+ });
+});