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.

feat(core): add `composio.triggers.verifyWebhook()` (#2251)

Alberto Schiabel2ff5ff4f2d1e
diff --git a/python/composio/core/models/triggers.py b/python/composio/core/models/triggers.py
index 04b724828..be4be9ff1 100644
--- a/python/composio/core/models/triggers.py
+++ b/python/composio/core/models/triggers.py
@@ -1,12 +1,15 @@
from __future__ import annotations
import functools
+import hashlib
+import hmac
import json
import time
import traceback
import typing as t
import uuid
from concurrent.futures import ThreadPoolExecutor
+from datetime import datetime, timezone
from unittest import mock
from composio_client.types import TriggersTypeRetrieveResponse
@@ -802,3 +805,190 @@ class Triggers(Resource):
:return: The trigger subscription handler.
"""
return _SubcriptionBuilder(client=self._client).connect(timeout=timeout)
+
+ def verify_webhook(
+ self,
+ payload: str,
+ signature: str,
+ secret: str,
+ tolerance: int = 300,
+ ) -> TriggerEvent:
+ """
+ Verify an incoming webhook payload and signature.
+
+ This method validates that the webhook request is authentic by:
+ 1. Verifying the HMAC-SHA256 signature matches the payload
+ 2. Optionally checking that the webhook timestamp is within the tolerance window
+
+ :param payload: The raw webhook payload as a string (request body)
+ :param signature: The signature from the webhook header (e.g., 'x-composio-signature')
+ :param secret: The webhook secret used to sign the payload
+ :param tolerance: Maximum allowed age of the webhook in seconds (default: 300 = 5 minutes).
+ Set to 0 to disable timestamp validation.
+ :return: The verified and parsed webhook payload as a TriggerEvent
+ :raises WebhookSignatureVerificationError: If the signature verification fails
+ :raises WebhookPayloadError: If the payload cannot be parsed or is invalid
+
+ Example:
+ # In a Flask webhook handler
+ @app.route('/webhook', methods=['POST'])
+ def webhook():
+ try:
+ event = composio.triggers.verify_webhook(
+ payload=request.get_data(as_text=True),
+ signature=request.headers.get('x-composio-signature', ''),
+ secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
+ )
+
+ # Process the verified payload
+ print(f"Received trigger: {event['trigger_slug']}")
+ return 'OK', 200
+ except WebhookSignatureVerificationError:
+ return 'Unauthorized', 401
+ """
+ # Verify signature
+ self._verify_webhook_signature(payload, signature, secret)
+
+ # Parse and validate payload
+ try:
+ data = t.cast(_TriggerData, json.loads(payload))
+ except json.JSONDecodeError as e:
+ raise exceptions.WebhookPayloadError(
+ f"Failed to parse webhook payload as JSON: {e}"
+ ) from e
+
+ # Transform to TriggerEvent format
+ event = self._transform_trigger_data(data)
+
+ # Validate timestamp if tolerance is set
+ if tolerance > 0:
+ self._validate_webhook_timestamp(data, tolerance)
+
+ return event
+
+ def _verify_webhook_signature(
+ self, payload: str, signature: str, secret: str
+ ) -> None:
+ """
+ Verify the HMAC-SHA256 signature of a webhook payload.
+
+ :param payload: The raw webhook payload
+ :param signature: The signature to verify
+ :param secret: The webhook secret
+ :raises WebhookSignatureVerificationError: If verification fails
+ """
+ if not payload:
+ raise exceptions.WebhookSignatureVerificationError(
+ "No webhook payload was provided."
+ )
+
+ if not signature:
+ raise exceptions.WebhookSignatureVerificationError(
+ "No signature header value was provided. "
+ "Please pass the value of the webhook signature header."
+ )
+
+ if not secret:
+ raise exceptions.WebhookSignatureVerificationError(
+ "No webhook secret was provided. "
+ "You can find your webhook secret in your Composio dashboard."
+ )
+
+ expected_signature = hmac.new(
+ key=secret.encode("utf-8"),
+ msg=payload.encode("utf-8"),
+ digestmod=hashlib.sha256,
+ ).hexdigest()
+
+ # Use timing-safe comparison to prevent timing attacks
+ if not hmac.compare_digest(signature, expected_signature):
+ raise exceptions.WebhookSignatureVerificationError(
+ "The signature provided is invalid."
+ )
+
+ def _validate_webhook_timestamp(self, data: _TriggerData, tolerance: int) -> None:
+ """
+ Validate that the webhook timestamp is within the allowed tolerance.
+
+ :param data: The parsed trigger data
+ :param tolerance: Maximum allowed age in seconds
+ :raises WebhookSignatureVerificationError: If timestamp is outside tolerance
+ :raises WebhookPayloadError: If timestamp format is invalid
+ """
+ # Check for timestamp in various locations
+ timestamp_str: t.Optional[str] = None
+
+ # Check root level
+ if "timestamp" in data: # type: ignore
+ timestamp_str = data.get("timestamp") # type: ignore
+ elif "webhookTimestamp" in data: # type: ignore
+ timestamp_str = data.get("webhookTimestamp") # type: ignore
+ # Check metadata level
+ elif "metadata" in data and "timestamp" in data["metadata"]: # type: ignore
+ timestamp_str = data["metadata"].get("timestamp") # type: ignore
+
+ if timestamp_str is None:
+ # If no timestamp is present, skip validation for backwards compatibility
+ return
+
+ try:
+ # Parse ISO 8601 timestamp
+ webhook_time = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00"))
+ # Ensure timezone-aware comparison
+ if webhook_time.tzinfo is None:
+ webhook_time = webhook_time.replace(tzinfo=timezone.utc)
+ except (ValueError, AttributeError) as e:
+ raise exceptions.WebhookPayloadError(
+ f"Invalid timestamp in webhook payload: {timestamp_str}. "
+ "Expected ISO 8601 format."
+ ) from e
+
+ current_time = datetime.now(timezone.utc)
+ time_difference = abs((current_time - webhook_time).total_seconds())
+
+ if time_difference > tolerance:
+ raise exceptions.WebhookSignatureVerificationError(
+ f"The webhook timestamp is outside the allowed tolerance. "
+ f"The webhook was sent {int(time_difference)} seconds ago, "
+ f"but the maximum allowed age is {tolerance} seconds."
+ )
+
+ def _transform_trigger_data(self, data: _TriggerData) -> TriggerEvent:
+ """
+ Transform raw trigger data to TriggerEvent format.
+
+ :param data: The raw trigger data
+ :return: The transformed TriggerEvent
+ """
+ return t.cast(
+ TriggerEvent,
+ {
+ "id": data["metadata"]["nanoId"],
+ "uuid": data["metadata"]["id"],
+ "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
+ "toolkit_slug": data["appName"],
+ "trigger_slug": data["metadata"]["triggerName"],
+ "metadata": {
+ "id": data["metadata"]["nanoId"],
+ "uuid": data["metadata"]["id"],
+ "toolkit_slug": data["appName"],
+ "trigger_slug": data["metadata"]["triggerName"],
+ "trigger_data": data["metadata"].get("triggerData"),
+ "trigger_config": data["metadata"]["triggerConfig"],
+ "connected_account": {
+ "id": data["metadata"]["connection"]["connectedAccountNanoId"],
+ "uuid": data["metadata"]["connection"]["id"],
+ "auth_config_id": data["metadata"]["connection"][
+ "authConfigNanoId"
+ ],
+ "auth_config_uuid": data["metadata"]["connection"][
+ "integrationId"
+ ],
+ "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
+ "status": data["metadata"]["connection"]["status"],
+ },
+ },
+ "payload": data.get("payload"),
+ "original_payload": data.get("originalPayload"),
+ },
+ )
diff --git a/python/composio/exceptions.py b/python/composio/exceptions.py
index 4c5d5525b..a944ca0df 100644
--- a/python/composio/exceptions.py
+++ b/python/composio/exceptions.py
@@ -176,6 +176,18 @@ class TriggerError(ToolkitError):
pass
+class WebhookSignatureVerificationError(TriggerError):
+ """Raised when webhook signature verification fails."""
+
+ pass
+
+
+class WebhookPayloadError(TriggerError):
+ """Raised when webhook payload is invalid."""
+
+ pass
+
+
class ActionError(ToolkitError):
pass
diff --git a/python/tests/test_triggers.py b/python/tests/test_triggers.py
index 4a4053423..c622d726d 100644
--- a/python/tests/test_triggers.py
+++ b/python/tests/test_triggers.py
@@ -1,6 +1,10 @@
"""Tests for Triggers class."""
+import hashlib
+import hmac
+import json
import pytest
+from datetime import datetime, timedelta, timezone
from unittest.mock import Mock, patch
from composio_client import omit
from composio.core.models.triggers import Triggers
@@ -423,3 +427,442 @@ class TestTriggers:
mock_builder.connect.assert_called_once_with(timeout=15.0)
assert result == mock_subscription
+
+
+class TestVerifyWebhook:
+ """Test cases for verify_webhook method."""
+
+ @pytest.fixture
+ def mock_client(self):
+ """Create a mock HTTP client."""
+ client = Mock()
+ client.triggers_types = Mock()
+ client.trigger_instances = Mock()
+ client.trigger_instances.manage = Mock()
+ client.connected_accounts = Mock()
+ return client
+
+ @pytest.fixture
+ def triggers(self, mock_client):
+ """Create a Triggers instance."""
+ return Triggers(client=mock_client)
+
+ @pytest.fixture
+ def test_secret(self):
+ """Test webhook secret."""
+ return "test-webhook-secret-12345"
+
+ @pytest.fixture
+ def mock_trigger_data(self):
+ """Create mock trigger data matching _TriggerData structure."""
+ return {
+ "appName": "github",
+ "clientId": 123,
+ "payload": {"action": "push", "repository": "test-repo"},
+ "originalPayload": {"action": "push", "repository": "test-repo"},
+ "metadata": {
+ "id": "trigger-123",
+ "nanoId": "trigger-123-nano",
+ "triggerName": "GITHUB_COMMIT_EVENT",
+ "triggerData": '{"action":"push"}',
+ "triggerConfig": {"webhook_url": "https://example.com/webhook"},
+ "connection": {
+ "id": "conn-123",
+ "connectedAccountNanoId": "conn-123-nano",
+ "integrationId": "github-integration",
+ "authConfigNanoId": "auth-123",
+ "clientUniqueUserId": "user-456",
+ "status": "ACTIVE",
+ },
+ },
+ }
+
+ def create_signature(self, payload: str, secret: str) -> str:
+ """Helper to create a valid HMAC-SHA256 signature."""
+ return hmac.new(
+ key=secret.encode("utf-8"),
+ msg=payload.encode("utf-8"),
+ digestmod=hashlib.sha256,
+ ).hexdigest()
+
+ # Successful verification tests
+
+ def test_verify_webhook_valid_payload_and_signature(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test successful webhook verification."""
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ )
+
+ assert result["id"] == "trigger-123-nano"
+ assert result["uuid"] == "trigger-123"
+ assert result["trigger_slug"] == "GITHUB_COMMIT_EVENT"
+ assert result["toolkit_slug"] == "github"
+ assert result["user_id"] == "user-456"
+
+ def test_verify_webhook_with_tolerance_zero(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test webhook verification with tolerance set to 0 (skip timestamp validation)."""
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ tolerance=0,
+ )
+
+ assert result["trigger_slug"] == "GITHUB_COMMIT_EVENT"
+
+ def test_verify_webhook_with_custom_tolerance(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test webhook verification with custom tolerance."""
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ tolerance=600, # 10 minutes
+ )
+
+ assert result is not None
+
+ def test_verify_webhook_transforms_payload_correctly(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that payload is correctly transformed to TriggerEvent format."""
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ )
+
+ # Verify transformation
+ assert result["metadata"]["connected_account"]["id"] == "conn-123-nano"
+ assert result["metadata"]["connected_account"]["uuid"] == "conn-123"
+ assert result["metadata"]["connected_account"]["auth_config_id"] == "auth-123"
+ assert (
+ result["metadata"]["connected_account"]["auth_config_uuid"]
+ == "github-integration"
+ )
+ assert result["metadata"]["connected_account"]["user_id"] == "user-456"
+ assert result["metadata"]["connected_account"]["status"] == "ACTIVE"
+
+ # Signature verification error tests
+
+ def test_verify_webhook_empty_payload_raises_error(self, triggers, test_secret):
+ """Test that empty payload raises WebhookSignatureVerificationError."""
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ triggers.verify_webhook(
+ payload="",
+ signature="some-signature",
+ secret=test_secret,
+ )
+
+ assert "No webhook payload was provided" in str(exc_info.value)
+
+ def test_verify_webhook_empty_signature_raises_error(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that empty signature raises WebhookSignatureVerificationError."""
+ payload = json.dumps(mock_trigger_data)
+
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ triggers.verify_webhook(
+ payload=payload,
+ signature="",
+ secret=test_secret,
+ )
+
+ assert "No signature header value was provided" in str(exc_info.value)
+
+ def test_verify_webhook_empty_secret_raises_error(
+ self, triggers, mock_trigger_data
+ ):
+ """Test that empty secret raises WebhookSignatureVerificationError."""
+ payload = json.dumps(mock_trigger_data)
+
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ triggers.verify_webhook(
+ payload=payload,
+ signature="some-signature",
+ secret="",
+ )
+
+ assert "No webhook secret was provided" in str(exc_info.value)
+
+ def test_verify_webhook_invalid_signature_raises_error(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that invalid signature raises WebhookSignatureVerificationError."""
+ payload = json.dumps(mock_trigger_data)
+
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ triggers.verify_webhook(
+ payload=payload,
+ signature="invalid-signature",
+ secret=test_secret,
+ )
+
+ assert "The signature provided is invalid" in str(exc_info.value)
+
+ def test_verify_webhook_wrong_secret_raises_error(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that signature created with different secret raises error."""
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, "different-secret")
+
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ )
+
+ assert "The signature provided is invalid" in str(exc_info.value)
+
+ def test_verify_webhook_modified_payload_raises_error(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that modified payload after signing raises error."""
+ original_payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(original_payload, test_secret)
+
+ # Modify the payload
+ mock_trigger_data["appName"] = "modified-app"
+ modified_payload = json.dumps(mock_trigger_data)
+
+ with pytest.raises(exceptions.WebhookSignatureVerificationError):
+ triggers.verify_webhook(
+ payload=modified_payload,
+ signature=signature,
+ secret=test_secret,
+ )
+
+ # Payload parsing error tests
+
+ def test_verify_webhook_invalid_json_raises_error(self, triggers, test_secret):
+ """Test that invalid JSON payload raises WebhookPayloadError."""
+ invalid_json = "not-valid-json{"
+ signature = self.create_signature(invalid_json, test_secret)
+
+ with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
+ triggers.verify_webhook(
+ payload=invalid_json,
+ signature=signature,
+ secret=test_secret,
+ )
+
+ assert "Failed to parse webhook payload as JSON" in str(exc_info.value)
+
+ def test_verify_webhook_truncated_json_raises_error(self, triggers, test_secret):
+ """Test that truncated JSON raises WebhookPayloadError."""
+ truncated_json = '{"appName": "github", "clientId":'
+ signature = self.create_signature(truncated_json, test_secret)
+
+ with pytest.raises(exceptions.WebhookPayloadError):
+ triggers.verify_webhook(
+ payload=truncated_json,
+ signature=signature,
+ secret=test_secret,
+ )
+
+ # Timestamp validation tests
+
+ def test_verify_webhook_timestamp_within_tolerance(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that timestamp within tolerance passes validation."""
+ now = datetime.now(timezone.utc).isoformat()
+ mock_trigger_data["timestamp"] = now
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ tolerance=300,
+ )
+
+ assert result is not None
+
+ def test_verify_webhook_timestamp_outside_tolerance_raises_error(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that timestamp outside tolerance raises error."""
+ # Create a timestamp 10 minutes in the past
+ old_time = datetime.now(timezone.utc) - timedelta(minutes=10)
+ mock_trigger_data["timestamp"] = old_time.isoformat()
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ tolerance=300, # 5 minutes
+ )
+
+ assert "outside the allowed tolerance" in str(exc_info.value)
+
+ def test_verify_webhook_skips_timestamp_validation_when_tolerance_zero(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that timestamp validation is skipped when tolerance is 0."""
+ # Create a timestamp 1 hour in the past
+ old_time = datetime.now(timezone.utc) - timedelta(hours=1)
+ mock_trigger_data["timestamp"] = old_time.isoformat()
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ # Should not raise when tolerance is 0
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ tolerance=0,
+ )
+
+ assert result is not None
+
+ def test_verify_webhook_skips_timestamp_validation_when_no_timestamp(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that timestamp validation is skipped when no timestamp in payload."""
+ # mock_trigger_data doesn't have timestamp by default
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ tolerance=300,
+ )
+
+ assert result is not None
+
+ def test_verify_webhook_invalid_timestamp_format_raises_error(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that invalid timestamp format raises WebhookPayloadError."""
+ mock_trigger_data["timestamp"] = "not-a-valid-timestamp"
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
+ triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ tolerance=300,
+ )
+
+ assert "Invalid timestamp in webhook payload" in str(exc_info.value)
+
+ def test_verify_webhook_timestamp_with_z_suffix(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that timestamp with Z suffix is handled correctly."""
+ mock_trigger_data["timestamp"] = "2024-01-01T12:00:00Z"
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, test_secret)
+
+ # This will fail due to timestamp being old, but should parse correctly
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ tolerance=300,
+ )
+
+ # Should fail due to timestamp being outside tolerance, not parsing error
+ assert "outside the allowed tolerance" in str(exc_info.value)
+
+ # Security tests
+
+ def test_verify_webhook_uses_timing_safe_comparison(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that signature comparison is timing-safe."""
+ payload = json.dumps(mock_trigger_data)
+ valid_signature = self.create_signature(payload, test_secret)
+
+ # Valid signature should work
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=valid_signature,
+ secret=test_secret,
+ )
+ assert result is not None
+
+ # Invalid signature with same length should fail
+ invalid_signature = "a" * len(valid_signature)
+ with pytest.raises(exceptions.WebhookSignatureVerificationError):
+ triggers.verify_webhook(
+ payload=payload,
+ signature=invalid_signature,
+ secret=test_secret,
+ )
+
+ def test_verify_webhook_handles_unicode_payload(
+ self, triggers, test_secret, mock_trigger_data
+ ):
+ """Test that unicode in payload is handled correctly."""
+ mock_trigger_data["payload"] = {"message": "你好世界 🌍 مرحبا"}
+ payload = json.dumps(mock_trigger_data, ensure_ascii=False)
+ signature = self.create_signature(payload, test_secret)
+
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=test_secret,
+ )
+
+ assert result["payload"]["message"] == "你好世界 🌍 مرحبا"
+
+ def test_verify_webhook_handles_special_characters_in_secret(
+ self, triggers, mock_trigger_data
+ ):
+ """Test that special characters in secret are handled correctly."""
+ special_secret = "secret!@#$%^&*()_+-=[]{}|;:,.<>?"
+ payload = json.dumps(mock_trigger_data)
+ signature = self.create_signature(payload, special_secret)
+
+ result = triggers.verify_webhook(
+ payload=payload,
+ signature=signature,
+ secret=special_secret,
+ )
+
+ assert result is not None
+
+ # Error class tests
+
+ def test_webhook_signature_verification_error_is_trigger_error(self):
+ """Test that WebhookSignatureVerificationError inherits from TriggerError."""
+ error = exceptions.WebhookSignatureVerificationError("test")
+ assert isinstance(error, exceptions.TriggerError)
+
+ def test_webhook_payload_error_is_trigger_error(self):
+ """Test that WebhookPayloadError inherits from TriggerError."""
+ error = exceptions.WebhookPayloadError("test")
+ assert isinstance(error, exceptions.TriggerError)
diff --git a/ts/packages/core/src/errors/TriggerErrors.ts b/ts/packages/core/src/errors/TriggerErrors.ts
index 3d6f3dda6..10ee5a4c7 100644
--- a/ts/packages/core/src/errors/TriggerErrors.ts
+++ b/ts/packages/core/src/errors/TriggerErrors.ts
@@ -1,5 +1,4 @@
-import { ComposioError } from '@composio/client';
-import { ComposioErrorOptions } from './ComposioError';
+import { ComposioError, ComposioErrorOptions } from './ComposioError';
export const TriggerErrorCodes = {
TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS: 'TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS',
@@ -8,59 +7,114 @@ export const TriggerErrorCodes = {
TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL:
'TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL',
TRIGGER_TYPE_NOT_FOUND: 'TRIGGER_TYPE_NOT_FOUND',
+ WEBHOOK_SIGNATURE_VERIFICATION_FAILED: 'WEBHOOK_SIGNATURE_VERIFICATION_FAILED',
+ WEBHOOK_PAYLOAD_INVALID: 'WEBHOOK_PAYLOAD_INVALID',
} as const;
export class ComposioFailedToGetSDKRealtimeCredentialsError extends ComposioError {
- public name = 'ComposioFailedToGetSDKRealtimeCredentialsError';
- public code = TriggerErrorCodes.TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS;
- public statusCode = 500;
- public possibleFixes = ['Please contact support.'];
-
- constructor(message: string, options?: ComposioErrorOptions) {
- super(message, options);
+ constructor(
+ message: string = 'Failed to get SDK realtime credentials',
+ options: Omit<ComposioErrorOptions, 'code'> = {}
+ ) {
+ super(message, {
+ ...options,
+ code: TriggerErrorCodes.TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS,
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
+ });
+ this.name = 'ComposioFailedToGetSDKRealtimeCredentialsError';
}
}
export class ComposioFailedToCreatePusherClientError extends ComposioError {
- public name = 'ComposioFailedToCreatePusherClientError';
- public code = TriggerErrorCodes.TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT;
- public statusCode = 500;
- public possibleFixes = ['Please contact support.'];
-
- constructor(message: string, options?: ComposioErrorOptions) {
- super(message, options);
+ constructor(
+ message: string = 'Failed to create Pusher client',
+ options: Omit<ComposioErrorOptions, 'code'> = {}
+ ) {
+ super(message, {
+ ...options,
+ code: TriggerErrorCodes.TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT,
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
+ });
+ this.name = 'ComposioFailedToCreatePusherClientError';
}
}
export class ComposioFailedToSubscribeToPusherChannelError extends ComposioError {
- public name = 'ComposioFailedToSubscribeToPusherChannelError';
- public code = TriggerErrorCodes.TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL;
- public statusCode = 500;
- public possibleFixes = ['Please contact support.'];
-
- constructor(message: string, options?: ComposioErrorOptions) {
- super(message, options);
+ constructor(
+ message: string = 'Failed to subscribe to Pusher channel',
+ options: Omit<ComposioErrorOptions, 'code'> = {}
+ ) {
+ super(message, {
+ ...options,
+ code: TriggerErrorCodes.TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL,
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
+ });
+ this.name = 'ComposioFailedToSubscribeToPusherChannelError';
}
}
export class ComposioFailedToUnsubscribeFromPusherChannelError extends ComposioError {
- public name = 'ComposioFailedToUnsubscribeFromPusherChannelError';
- public code = TriggerErrorCodes.TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL;
- public statusCode = 500;
- public possibleFixes = ['Please contact support.'];
-
- constructor(message: string, options?: ComposioErrorOptions) {
- super(message, options);
+ constructor(
+ message: string = 'Failed to unsubscribe from Pusher channel',
+ options: Omit<ComposioErrorOptions, 'code'> = {}
+ ) {
+ super(message, {
+ ...options,
+ code: TriggerErrorCodes.TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL,
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
+ });
+ this.name = 'ComposioFailedToUnsubscribeFromPusherChannelError';
}
}
export class ComposioTriggerTypeNotFoundError extends ComposioError {
- public name = 'ComposioTriggerTypeNotFoundError';
- public code = TriggerErrorCodes.TRIGGER_TYPE_NOT_FOUND;
- public statusCode = 404;
- public possibleFixes = ['Please contact support.'];
+ constructor(
+ message: string = 'Trigger type not found',
+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
+ ) {
+ super(message, {
+ ...options,
+ code: TriggerErrorCodes.TRIGGER_TYPE_NOT_FOUND,
+ statusCode: 404,
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
+ });
+ this.name = 'ComposioTriggerTypeNotFoundError';
+ }
+}
+
+export class ComposioWebhookSignatureVerificationError extends ComposioError {
+ constructor(
+ message: string = 'Webhook signature verification failed',
+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
+ ) {
+ super(message, {
+ ...options,
+ code: TriggerErrorCodes.WEBHOOK_SIGNATURE_VERIFICATION_FAILED,
+ statusCode: 401,
+ possibleFixes: options.possibleFixes || [
+ 'Verify that the webhook secret is correct.',
+ 'Ensure the raw request body is passed without modifications.',
+ 'Check that the signature header value is being passed correctly.',
+ ],
+ });
+ this.name = 'ComposioWebhookSignatureVerificationError';
+ }
+}
- constructor(message: string = 'Trigger type not found', options?: ComposioErrorOptions) {
- super(message, options);
+export class ComposioWebhookPayloadError extends ComposioError {
+ constructor(
+ message: string = 'Invalid webhook payload',
+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
+ ) {
+ super(message, {
+ ...options,
+ code: TriggerErrorCodes.WEBHOOK_PAYLOAD_INVALID,
+ statusCode: 400,
+ possibleFixes: options.possibleFixes || [
+ 'Ensure the webhook payload is valid JSON.',
+ 'Verify the payload structure matches the expected format.',
+ ],
+ });
+ this.name = 'ComposioWebhookPayloadError';
}
}
diff --git a/ts/packages/core/src/errors/index.ts b/ts/packages/core/src/errors/index.ts
index 36709a30e..d89e27c78 100644
--- a/ts/packages/core/src/errors/index.ts
+++ b/ts/packages/core/src/errors/index.ts
@@ -30,3 +30,6 @@ export * from './ValidationErrors';
// SDK Errors
export * from './SDKErrors';
+
+// Trigger Errors
+export * from './TriggerErrors';
diff --git a/ts/packages/core/src/models/Triggers.ts b/ts/packages/core/src/models/Triggers.ts
index 5ceba5742..1e1c999d9 100644
--- a/ts/packages/core/src/models/Triggers.ts
+++ b/ts/packages/core/src/models/Triggers.ts
@@ -1,3 +1,4 @@
+import * as crypto from 'node:crypto';
import ComposioClient, { APIError } from '@composio/client';
import { TriggersTypeRetrieveEnumResponse } from '@composio/client/resources/index';
import {
@@ -18,12 +19,19 @@ import {
TriggersTypeListResponse,
TriggersTypeListParamsSchema,
TriggersTypeRetrieveResponse,
+ VerifyWebhookParams,
+ VerifyWebhookParamsSchema,
+ VerifyWebhookResult,
} from '../types/triggers.types';
import logger from '../utils/logger';
import { telemetry } from '../telemetry/Telemetry';
import { ComposioConnectedAccountNotFoundError, ValidationError } from '../errors';
import { PusherService } from '../services/pusher/Pusher';
-import { ComposioTriggerTypeNotFoundError } from '../errors/TriggerErrors';
+import {
+ ComposioTriggerTypeNotFoundError,
+ ComposioWebhookPayloadError,
+ ComposioWebhookSignatureVerificationError,
+} from '../errors/TriggerErrors';
import { transform } from '../utils/transform';
import {
transformIncomingTriggerPayload,
@@ -452,4 +460,153 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
async unsubscribe() {
await this.pusherService.unsubscribe();
}
+
+ /**
+ * Verify an incoming webhook payload and signature.
+ *
+ * This method validates that the webhook request is authentic by:
+ * 1. Verifying the HMAC-SHA256 signature matches the payload
+ * 2. Optionally checking that the webhook timestamp is within the tolerance window
+ *
+ * @param {VerifyWebhookParams} params - The verification parameters
+ * @param {string} params.payload - The raw webhook payload as a string (request body)
+ * @param {string} params.signature - The signature from the webhook header (e.g., 'x-composio-signature')
+ * @param {string} params.secret - The webhook secret used to sign the payload
+ * @param {number} [params.tolerance=300] - Maximum allowed age of the webhook in seconds (default: 5 minutes). Set to 0 to disable timestamp validation.
+ * @returns {VerifyWebhookResult} The verified and parsed webhook payload
+ *
+ * @throws {ValidationError} If the parameters are invalid
+ * @throws {ComposioWebhookSignatureVerificationError} If the signature verification fails
+ * @throws {ComposioWebhookPayloadError} If the payload cannot be parsed or is invalid
+ *
+ * @example
+ * ```ts
+ * // In an Express.js webhook handler
+ * app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
+ * try {
+ * const payload = composio.triggers.verifyWebhook({
+ * payload: req.body.toString(),
+ * signature: req.headers['x-composio-signature'] as string,
+ * secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
+ * });
+ *
+ * // Process the verified payload
+ * console.log('Received trigger:', payload.triggerSlug);
+ * res.status(200).send('OK');
+ * } catch (error) {
+ * console.error('Webhook verification failed:', error);
+ * res.status(401).send('Unauthorized');
+ * }
+ * });
+ * ```
+ */
+ verifyWebhook(params: VerifyWebhookParams): VerifyWebhookResult {
+ // Validate input parameters
+ const parsedParams = VerifyWebhookParamsSchema.safeParse(params);
+ if (!parsedParams.success) {
+ throw new ValidationError('Invalid parameters passed to verifyWebhook', {
+ cause: parsedParams.error,
+ });
+ }
+
+ const { payload, signature, secret, tolerance } = parsedParams.data;
+
+ // Verify signature
+ this.verifyWebhookSignature(payload, signature, secret);
+
+ // Parse and validate payload
+ let parsedPayload: TriggerData;
+ try {
+ parsedPayload = JSON.parse(payload) as TriggerData;
+ } catch (error) {
+ throw new ComposioWebhookPayloadError('Failed to parse webhook payload as JSON', {
+ cause: error,
+ });
+ }
+
+ // Transform to IncomingTriggerPayload format
+ const transformedPayload = transformIncomingTriggerPayload(parsedPayload);
+
+ // Validate timestamp if tolerance is set and payload contains timestamp
+ if (tolerance > 0) {
+ this.validateWebhookTimestamp(parsedPayload, tolerance);
+ }
+
+ return transformedPayload;
+ }
+
+ /**
+ * Verifies the HMAC-SHA256 signature of a webhook payload
+ * @private
+ */
+ private verifyWebhookSignature(payload: string, signature: string, secret: string): void {
+ if (payload.length === 0) {
+ throw new ComposioWebhookSignatureVerificationError('No webhook payload was provided.');
+ }
+
+ if (signature.length === 0) {
+ throw new ComposioWebhookSignatureVerificationError(
+ 'No signature header value was provided. Please pass the value of the webhook signature header.'
+ );
+ }
+
+ if (secret.length === 0) {
+ throw new ComposioWebhookSignatureVerificationError(
+ 'No webhook secret was provided. You can find your webhook secret in your Composio dashboard.'
+ );
+ }
+
+ const expectedSignature = crypto
+ .createHmac('sha256', secret)
+ .update(payload, 'utf8')
+ .digest('hex');
+
+ // Use timing-safe comparison to prevent timing attacks
+ const signatureBuffer = Buffer.from(signature);
+ const expectedBuffer = Buffer.from(expectedSignature);
+
+ if (
+ signatureBuffer.length !== expectedBuffer.length ||
+ !crypto.timingSafeEqual(signatureBuffer, expectedBuffer)
+ ) {
+ throw new ComposioWebhookSignatureVerificationError('The signature provided is invalid.');
+ }
+ }
+
+ /**
+ * Validates that the webhook timestamp is within the allowed tolerance
+ * @private
+ */
+ private validateWebhookTimestamp(payload: TriggerData, tolerance: number): void {
+ // Check if payload has a timestamp field (may be in metadata or at root level)
+ const timestamp =
+ (payload as unknown as { timestamp?: string }).timestamp ||
+ (payload as unknown as { webhookTimestamp?: string }).webhookTimestamp ||
+ (payload.metadata as unknown as { timestamp?: string })?.timestamp;
+
+ if (!timestamp) {
+ // If no timestamp is present, skip validation
+ // This allows backwards compatibility with webhooks that don't include timestamps
+ logger.debug('No timestamp found in webhook payload, skipping timestamp validation');
+ return;
+ }
+
+ const webhookTime = Date.parse(timestamp);
+ if (Number.isNaN(webhookTime)) {
+ throw new ComposioWebhookPayloadError(
+ `Invalid timestamp in webhook payload: ${timestamp}. Expected ISO 8601 format.`
+ );
+ }
+
+ const currentTime = Date.now();
+ const timeDifference = Math.abs(currentTime - webhookTime);
+
+ if (timeDifference > tolerance * 1000) {
+ throw new ComposioWebhookSignatureVerificationError(
+ `The webhook timestamp is outside the allowed tolerance. ` +
+ `The webhook was sent ${Math.round(timeDifference / 1000)} seconds ago, ` +
+ `but the maximum allowed age is ${tolerance} seconds.`
+ );
+ }
+ }
}
diff --git a/ts/packages/core/src/types/triggers.types.ts b/ts/packages/core/src/types/triggers.types.ts
index 8ae76d7a2..d990155d5 100644
--- a/ts/packages/core/src/types/triggers.types.ts
+++ b/ts/packages/core/src/types/triggers.types.ts
@@ -194,3 +194,29 @@ export type TriggerEventData<TPayload = unknown> = TPayload & {
trigger_nano_id: string;
user_id: string;
};
+
+/**
+ * Parameters for verifying a webhook signature
+ */
+export const VerifyWebhookParamsSchema = z.object({
+ /** The raw webhook payload as a string (request body) */
+ payload: z.string(),
+ /** The signature from the webhook header (e.g., 'x-composio-signature') */
+ signature: z.string(),
+ /** The webhook secret used to sign the payload */
+ secret: z.string(),
+ /**
+ * Maximum allowed age of the webhook in seconds.
+ * If the webhook timestamp is older than this, verification will fail.
+ * Set to 0 to disable timestamp validation.
+ * @default 300 (5 minutes)
+ */
+ tolerance: z.number().optional().default(300),
+});
+
+export type VerifyWebhookParams = z.input<typeof VerifyWebhookParamsSchema>;
+
+/**
+ * Result of a successful webhook verification
+ */
+export type VerifyWebhookResult = IncomingTriggerPayload;
diff --git a/ts/packages/core/test/models/verifyWebhook.test.ts b/ts/packages/core/test/models/verifyWebhook.test.ts
new file mode 100644
index 000000000..e88e0af5d
--- /dev/null
+++ b/ts/packages/core/test/models/verifyWebhook.test.ts
@@ -0,0 +1,592 @@
+import * as crypto from 'node:crypto';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Triggers } from '../../src/models/Triggers';
+import ComposioClient from '@composio/client';
+import { TriggerData } from '../../src/types/triggers.types';
+import { ValidationError } from '../../src/errors';
+import {
+ ComposioWebhookSignatureVerificationError,
+ ComposioWebhookPayloadError,
+} from '../../src/errors/TriggerErrors';
+
+// 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(),
+ },
+});
+
+// Helper to create a valid signature
+const createSignature = (payload: string, secret: string): string => {
+ return crypto.createHmac('sha256', secret).update(payload, 'utf8').digest('hex');
+};
+
+// Mock trigger data that matches TriggerData structure
+const createMockTriggerData = (overrides: Partial<TriggerData> = {}): TriggerData => ({
+ appName: 'github',
+ clientId: 123,
+ payload: { action: 'push', repository: 'test-repo' },
+ originalPayload: { action: 'push', repository: 'test-repo' },
+ metadata: {
+ id: 'trigger-123',
+ nanoId: 'trigger-123-nano',
+ triggerName: 'github_webhook',
+ triggerData: '{"action":"push"}',
+ triggerConfig: { webhook_url: 'https://example.com/webhook' },
+ connection: {
+ id: 'conn-123',
+ connectedAccountNanoId: 'conn-123',
+ integrationId: 'github',
+ authConfigNanoId: 'auth-123',
+ clientUniqueUserId: 'user-456',
+ status: 'ACTIVE',
+ },
+ },
+ ...overrides,
+});
+
+describe('Triggers.verifyWebhook', () => {
+ let triggers: Triggers<any>;
+ let mockClient: ReturnType<typeof createMockClient>;
+ const testSecret = 'test-webhook-secret-12345';
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockClient = createMockClient();
+ triggers = new Triggers(mockClient as unknown as ComposioClient);
+ });
+
+ describe('successful verification', () => {
+ it('should verify a valid webhook payload and signature', () => {
+ const triggerData = createMockTriggerData();
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ });
+
+ expect(result).toBeDefined();
+ expect(result.id).toBe('trigger-123-nano');
+ expect(result.uuid).toBe('trigger-123');
+ expect(result.triggerSlug).toBe('github_webhook');
+ expect(result.toolkitSlug).toBe('github');
+ expect(result.userId).toBe('user-456');
+ });
+
+ it('should verify webhook with tolerance set to 0 (skip timestamp validation)', () => {
+ const triggerData = createMockTriggerData();
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ tolerance: 0,
+ });
+
+ expect(result).toBeDefined();
+ expect(result.triggerSlug).toBe('github_webhook');
+ });
+
+ it('should verify webhook with custom tolerance', () => {
+ const triggerData = createMockTriggerData();
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ tolerance: 600, // 10 minutes
+ });
+
+ expect(result).toBeDefined();
+ });
+
+ it('should correctly transform the payload to IncomingTriggerPayload format', () => {
+ const triggerData = createMockTriggerData();
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ });
+
+ // Verify transformation
+ expect(result.metadata.connectedAccount).toEqual({
+ id: 'conn-123',
+ uuid: 'conn-123',
+ authConfigId: 'auth-123',
+ authConfigUUID: 'github',
+ userId: 'user-456',
+ status: 'ACTIVE',
+ });
+ });
+ });
+
+ describe('signature verification errors', () => {
+ it('should throw error when payload is empty', () => {
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: '',
+ signature: 'some-signature',
+ secret: testSecret,
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: '',
+ signature: 'some-signature',
+ secret: testSecret,
+ })
+ ).toThrow('No webhook payload was provided.');
+ });
+
+ it('should throw error when signature is empty', () => {
+ const payload = JSON.stringify(createMockTriggerData());
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: '',
+ secret: testSecret,
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: '',
+ secret: testSecret,
+ })
+ ).toThrow('No signature header value was provided.');
+ });
+
+ it('should throw error when secret is empty', () => {
+ const payload = JSON.stringify(createMockTriggerData());
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: 'some-signature',
+ secret: '',
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: 'some-signature',
+ secret: '',
+ })
+ ).toThrow('No webhook secret was provided.');
+ });
+
+ it('should throw error when signature is invalid', () => {
+ const payload = JSON.stringify(createMockTriggerData());
+ const invalidSignature = 'invalid-signature-that-does-not-match';
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: invalidSignature,
+ secret: testSecret,
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: invalidSignature,
+ secret: testSecret,
+ })
+ ).toThrow('The signature provided is invalid.');
+ });
+
+ it('should throw error when signature was created with different secret', () => {
+ const payload = JSON.stringify(createMockTriggerData());
+ const signatureWithDifferentSecret = createSignature(payload, 'different-secret');
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: signatureWithDifferentSecret,
+ secret: testSecret,
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+ });
+
+ it('should throw error when payload was modified after signing', () => {
+ const originalPayload = JSON.stringify(createMockTriggerData());
+ const signature = createSignature(originalPayload, testSecret);
+
+ // Modify the payload after signing
+ const modifiedPayload = JSON.stringify({
+ ...createMockTriggerData(),
+ appName: 'modified-app',
+ });
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: modifiedPayload,
+ signature,
+ secret: testSecret,
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+ });
+ });
+
+ describe('payload parsing errors', () => {
+ it('should throw error when payload is not valid JSON', () => {
+ const invalidJson = 'not-valid-json{';
+ const signature = createSignature(invalidJson, testSecret);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: invalidJson,
+ signature,
+ secret: testSecret,
+ })
+ ).toThrow(ComposioWebhookPayloadError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: invalidJson,
+ signature,
+ secret: testSecret,
+ })
+ ).toThrow('Failed to parse webhook payload as JSON');
+ });
+
+ it('should throw error for truncated JSON', () => {
+ const truncatedJson = '{"appName": "github", "clientId":';
+ const signature = createSignature(truncatedJson, testSecret);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: truncatedJson,
+ signature,
+ secret: testSecret,
+ })
+ ).toThrow(ComposioWebhookPayloadError);
+ });
+ });
+
+ describe('timestamp validation', () => {
+ it('should pass when timestamp is within tolerance', () => {
+ const now = new Date().toISOString();
+ const triggerData = {
+ ...createMockTriggerData(),
+ timestamp: now,
+ };
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ // Should not throw
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ tolerance: 300,
+ });
+
+ expect(result).toBeDefined();
+ });
+
+ it('should throw error when timestamp is outside tolerance', () => {
+ // Create a timestamp 10 minutes in the past
+ const oldTimestamp = new Date(Date.now() - 10 * 60 * 1000).toISOString();
+ const triggerData = {
+ ...createMockTriggerData(),
+ timestamp: oldTimestamp,
+ };
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ tolerance: 300, // 5 minutes
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ tolerance: 300,
+ })
+ ).toThrow('The webhook timestamp is outside the allowed tolerance');
+ });
+
+ it('should skip timestamp validation when tolerance is 0', () => {
+ // Create a timestamp 1 hour in the past
+ const oldTimestamp = new Date(Date.now() - 60 * 60 * 1000).toISOString();
+ const triggerData = {
+ ...createMockTriggerData(),
+ timestamp: oldTimestamp,
+ };
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ // Should not throw when tolerance is 0
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ tolerance: 0,
+ });
+
+ expect(result).toBeDefined();
+ });
+
+ it('should skip timestamp validation when no timestamp in payload', () => {
+ const triggerData = createMockTriggerData();
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ // Should not throw when no timestamp is present
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ tolerance: 300,
+ });
+
+ expect(result).toBeDefined();
+ });
+
+ it('should throw error for invalid timestamp format', () => {
+ const triggerData = {
+ ...createMockTriggerData(),
+ timestamp: 'not-a-valid-timestamp',
+ };
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ tolerance: 300,
+ })
+ ).toThrow(ComposioWebhookPayloadError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ tolerance: 300,
+ })
+ ).toThrow('Invalid timestamp in webhook payload');
+ });
+ });
+
+ describe('input validation', () => {
+ it('should throw ValidationError for missing payload parameter', () => {
+ expect(() =>
+ triggers.verifyWebhook({
+ signature: 'some-signature',
+ secret: testSecret,
+ } as any)
+ ).toThrow(ValidationError);
+ });
+
+ it('should throw ValidationError for missing signature parameter', () => {
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: '{}',
+ secret: testSecret,
+ } as any)
+ ).toThrow(ValidationError);
+ });
+
+ it('should throw ValidationError for missing secret parameter', () => {
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: '{}',
+ signature: 'some-signature',
+ } as any)
+ ).toThrow(ValidationError);
+ });
+
+ it('should throw ValidationError for invalid tolerance type', () => {
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: '{}',
+ signature: 'some-signature',
+ secret: testSecret,
+ tolerance: 'invalid' as any,
+ })
+ ).toThrow(ValidationError);
+ });
+
+ it('should use default tolerance of 300 seconds when not provided', () => {
+ // Create a timestamp 4 minutes in the past (within default 5 min tolerance)
+ const recentTimestamp = new Date(Date.now() - 4 * 60 * 1000).toISOString();
+ const triggerData = {
+ ...createMockTriggerData(),
+ timestamp: recentTimestamp,
+ };
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ // Should not throw with default tolerance
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ });
+
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('security considerations', () => {
+ it('should use timing-safe comparison for signatures', () => {
+ // This test verifies the implementation uses timing-safe comparison
+ // by checking that both valid and invalid signatures take similar time
+ // (though this is more of a code review verification)
+ const payload = JSON.stringify(createMockTriggerData());
+ const validSignature = createSignature(payload, testSecret);
+
+ // Valid signature should work
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: validSignature,
+ secret: testSecret,
+ })
+ ).not.toThrow();
+
+ // Invalid signature with same length should fail
+ const invalidSignature = 'a'.repeat(validSignature.length);
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: invalidSignature,
+ secret: testSecret,
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+ });
+
+ it('should reject signatures with different lengths', () => {
+ const payload = JSON.stringify(createMockTriggerData());
+ const shortSignature = 'abc123';
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload,
+ signature: shortSignature,
+ secret: testSecret,
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+ });
+
+ it('should handle unicode in payload correctly', () => {
+ const triggerData = {
+ ...createMockTriggerData(),
+ payload: { message: '你好世界 🌍 مرحبا' },
+ };
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, testSecret);
+
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: testSecret,
+ });
+
+ expect(result).toBeDefined();
+ expect(result.payload).toEqual({ message: '你好世界 🌍 مرحبا' });
+ });
+
+ it('should handle special characters in secret', () => {
+ const specialSecret = 'secret!@#$%^&*()_+-=[]{}|;:,.<>?';
+ const triggerData = createMockTriggerData();
+ const payload = JSON.stringify(triggerData);
+ const signature = createSignature(payload, specialSecret);
+
+ const result = triggers.verifyWebhook({
+ payload,
+ signature,
+ secret: specialSecret,
+ });
+
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('error properties', () => {
+ it('should include proper error code for signature verification error', () => {
+ const payload = JSON.stringify(createMockTriggerData());
+
+ try {
+ triggers.verifyWebhook({
+ payload,
+ signature: 'invalid',
+ secret: testSecret,
+ });
+ expect.fail('Should have thrown');
+ } catch (error) {
+ expect(error).toBeInstanceOf(ComposioWebhookSignatureVerificationError);
+ expect((error as ComposioWebhookSignatureVerificationError).name).toBe(
+ 'ComposioWebhookSignatureVerificationError'
+ );
+ }
+ });
+
+ it('should include proper error code for payload error', () => {
+ const invalidPayload = 'not-json';
+ const signature = createSignature(invalidPayload, testSecret);
+
+ try {
+ triggers.verifyWebhook({
+ payload: invalidPayload,
+ signature,
+ secret: testSecret,
+ });
+ expect.fail('Should have thrown');
+ } catch (error) {
+ expect(error).toBeInstanceOf(ComposioWebhookPayloadError);
+ expect((error as ComposioWebhookPayloadError).name).toBe('ComposioWebhookPayloadError');
+ }
+ });
+ });
+});