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(core): support v1, v2, v3 in `composio.triggers.verifyWebhooks` (#2361)

Alberto Schiabelb28c2d7bb1dd
diff --git a/python/composio/core/models/triggers.py b/python/composio/core/models/triggers.py
index be4be9ff1..3f2857f05 100644
--- a/python/composio/core/models/triggers.py
+++ b/python/composio/core/models/triggers.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import base64
import functools
import hashlib
import hmac
@@ -9,7 +10,7 @@ import traceback
import typing as t
import uuid
from concurrent.futures import ThreadPoolExecutor
-from datetime import datetime, timezone
+from enum import Enum
from unittest import mock
from composio_client.types import TriggersTypeRetrieveResponse
@@ -82,6 +83,57 @@ class _TriggerData(te.TypedDict):
originalPayload: t.Dict
+class WebhookVersion(str, Enum):
+ """Webhook payload version."""
+
+ V1 = "V1"
+ V2 = "V2"
+ V3 = "V3"
+
+
+class WebhookPayloadV1(te.TypedDict):
+ """V1 webhook payload structure."""
+
+ trigger_name: str
+ connection_id: str
+ trigger_id: str
+ payload: t.Dict[str, t.Any]
+ log_id: str
+
+
+class WebhookPayloadV2(te.TypedDict):
+ """V2 webhook payload structure."""
+
+ type: str
+ timestamp: str
+ log_id: str
+ data: t.Dict[str, t.Any]
+
+
+class WebhookPayloadV3Metadata(te.TypedDict):
+ """V3 webhook payload metadata."""
+
+ log_id: str
+ trigger_slug: str
+ trigger_id: str
+ connected_account_id: str
+ auth_config_id: str
+ user_id: str
+
+
+class WebhookPayloadV3(te.TypedDict):
+ """V3 webhook payload structure."""
+
+ id: str
+ timestamp: str
+ type: t.Literal["composio.trigger.message"]
+ metadata: WebhookPayloadV3Metadata
+ data: t.Dict[str, t.Any]
+
+
+WebhookPayload = t.Union[WebhookPayloadV1, WebhookPayloadV2, WebhookPayloadV3]
+
+
class TriggerConnectedAccountSchema(t.TypedDict):
id: str
uuid: str
@@ -115,6 +167,14 @@ class TriggerEvent(t.TypedDict):
] # The original payload of the trigger
+class VerifyWebhookResult(t.TypedDict):
+ """Result of webhook verification."""
+
+ version: WebhookVersion # The webhook version (V1, V2, or V3)
+ payload: TriggerEvent # The parsed and normalized webhook payload
+ raw_payload: WebhookPayload # The original parsed payload
+
+
_ = {
"appName": "github",
"payload": {
@@ -808,24 +868,30 @@ class Triggers(Resource):
def verify_webhook(
self,
+ *,
+ id: str,
payload: str,
- signature: str,
secret: str,
+ signature: str,
+ timestamp: str,
tolerance: int = 300,
- ) -> TriggerEvent:
+ ) -> VerifyWebhookResult:
"""
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
+ 1. Validating the webhook timestamp is within the tolerance window
+ 2. Verifying the HMAC-SHA256 signature using the correct algorithm
+ 3. Parsing the payload and detecting the webhook version (V1, V2, or V3)
+ :param id: The webhook message ID from the 'webhook-id' header (format: 'msg_xxx')
: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 secret: The webhook secret used to sign the payload (from Composio dashboard)
+ :param signature: The signature from the 'webhook-signature' header (format: 'v1,base64EncodedSignature')
+ :param timestamp: The webhook timestamp from the 'webhook-timestamp' header (Unix seconds)
: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
+ :return: VerifyWebhookResult containing version, normalized payload, and raw payload
:raises WebhookSignatureVerificationError: If the signature verification fails
:raises WebhookPayloadError: If the payload cannot be parsed or is invalid
@@ -834,46 +900,62 @@ class Triggers(Resource):
@app.route('/webhook', methods=['POST'])
def webhook():
try:
- event = composio.triggers.verify_webhook(
+ result = composio.triggers.verify_webhook(
+ id=request.headers.get('webhook-id', ''),
payload=request.get_data(as_text=True),
- signature=request.headers.get('x-composio-signature', ''),
+ signature=request.headers.get('webhook-signature', ''),
+ timestamp=request.headers.get('webhook-timestamp', ''),
secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
)
# Process the verified payload
- print(f"Received trigger: {event['trigger_slug']}")
+ print(f"Version: {result['version']}")
+ print(f"Received trigger: {result['payload']['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)
+ self._validate_webhook_timestamp_header(timestamp, tolerance)
+
+ # Verify signature using the correct algorithm
+ self._verify_webhook_signature(
+ webhook_id=id,
+ webhook_timestamp=timestamp,
+ payload=payload,
+ signature=signature,
+ secret=secret,
+ )
+
+ # Parse and detect version
+ version, raw_payload, normalized_payload = self._parse_webhook_payload(payload)
- return event
+ return {
+ "version": version,
+ "payload": normalized_payload,
+ "raw_payload": raw_payload,
+ }
def _verify_webhook_signature(
- self, payload: str, signature: str, secret: str
+ self,
+ *,
+ webhook_id: str,
+ webhook_timestamp: str,
+ payload: str,
+ signature: str,
+ secret: str,
) -> None:
"""
Verify the HMAC-SHA256 signature of a webhook payload.
+ The signature is computed as: HMAC-SHA256(webhookId.webhookTimestamp.payload, secret)
+ and then base64 encoded with a 'v1,' prefix.
+
+ :param webhook_id: The webhook message ID from header
+ :param webhook_timestamp: The webhook timestamp from header
:param payload: The raw webhook payload
- :param signature: The signature to verify
+ :param signature: The signature to verify (format: 'v1,base64EncodedSignature')
:param secret: The webhook secret
:raises WebhookSignatureVerificationError: If verification fails
"""
@@ -894,65 +976,275 @@ class Triggers(Resource):
"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()
+ if not webhook_id:
+ raise exceptions.WebhookSignatureVerificationError(
+ "No webhook ID was provided. "
+ "Please pass the value of the 'webhook-id' header."
+ )
+
+ if not webhook_timestamp:
+ raise exceptions.WebhookSignatureVerificationError(
+ "No webhook timestamp was provided. "
+ "Please pass the value of the 'webhook-timestamp' header."
+ )
+
+ # Parse signature header - format is "v1,base64Sig" or "v1,sig1 v1,sig2"
+ # Split by space to handle multiple signatures
+ signature_parts = signature.split(" ")
+ v1_signatures: t.List[str] = []
- # Use timing-safe comparison to prevent timing attacks
- if not hmac.compare_digest(signature, expected_signature):
+ for part in signature_parts:
+ if part.startswith("v1,"):
+ v1_signatures.append(part[3:]) # Remove "v1," prefix
+
+ if not v1_signatures:
raise exceptions.WebhookSignatureVerificationError(
- "The signature provided is invalid."
+ "No valid v1 signature found in the signature header. "
+ "Expected format: 'v1,base64EncodedSignature'"
)
- def _validate_webhook_timestamp(self, data: _TriggerData, tolerance: int) -> None:
+ # Construct the string to sign: webhookId.webhookTimestamp.payload
+ to_sign = f"{webhook_id}.{webhook_timestamp}.{payload}"
+
+ # Compute expected signature
+ expected_signature_bytes = hmac.new(
+ key=secret.encode("utf-8"),
+ msg=to_sign.encode("utf-8"),
+ digestmod=hashlib.sha256,
+ ).digest()
+ expected_signature_b64 = base64.b64encode(expected_signature_bytes).decode(
+ "utf-8"
+ )
+
+ # Check if any of the provided signatures match (timing-safe)
+ for provided_sig in v1_signatures:
+ try:
+ if hmac.compare_digest(provided_sig, expected_signature_b64):
+ return # Signature is valid
+ except Exception:
+ continue # Invalid signature format, try next
+
+ raise exceptions.WebhookSignatureVerificationError(
+ "The signature provided is invalid."
+ )
+
+ def _validate_webhook_timestamp_header(
+ self, timestamp: str, tolerance: int
+ ) -> None:
"""
- Validate that the webhook timestamp is within the allowed tolerance.
+ Validate that the webhook timestamp header is within the allowed tolerance.
- :param data: The parsed trigger data
+ :param timestamp: The webhook timestamp from header (Unix seconds)
: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:
+ timestamp_seconds = int(timestamp)
+ except (ValueError, TypeError) as e:
raise exceptions.WebhookPayloadError(
- f"Invalid timestamp in webhook payload: {timestamp_str}. "
- "Expected ISO 8601 format."
+ f"Invalid webhook timestamp: {timestamp}. "
+ "Expected Unix timestamp in seconds."
) from e
- current_time = datetime.now(timezone.utc)
- time_difference = abs((current_time - webhook_time).total_seconds())
+ current_time = int(time.time())
+ time_difference = abs(current_time - timestamp_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"The webhook was sent {time_difference} seconds ago, "
f"but the maximum allowed age is {tolerance} seconds."
)
+ def _parse_webhook_payload(
+ self, payload: str
+ ) -> t.Tuple[WebhookVersion, WebhookPayload, TriggerEvent]:
+ """
+ Parse webhook payload and detect version.
+
+ :param payload: The raw webhook payload string
+ :return: Tuple of (version, raw_payload, normalized_payload)
+ :raises WebhookPayloadError: If payload cannot be parsed
+ """
+ try:
+ data = json.loads(payload)
+ except json.JSONDecodeError as e:
+ raise exceptions.WebhookPayloadError(
+ f"Failed to parse webhook payload as JSON: {e}"
+ ) from e
+
+ # Try V3 first (has 'type' === 'composio.trigger.message' and 'metadata')
+ # Validate metadata is a dict with all required fields (matching TypeScript's zod schema)
+ v3_metadata = data.get("metadata") if isinstance(data, dict) else None
+ v3_metadata_valid = (
+ isinstance(v3_metadata, dict)
+ and "log_id" in v3_metadata
+ and "trigger_slug" in v3_metadata
+ and "trigger_id" in v3_metadata
+ and "connected_account_id" in v3_metadata
+ and "auth_config_id" in v3_metadata
+ and "user_id" in v3_metadata
+ )
+ if (
+ isinstance(data, dict)
+ and data.get("type") == "composio.trigger.message"
+ and v3_metadata_valid
+ and "id" in data
+ and "data" in data
+ ):
+ return (
+ WebhookVersion.V3,
+ t.cast(WebhookPayloadV3, data),
+ self._normalize_v3_payload(t.cast(WebhookPayloadV3, data)),
+ )
+
+ # Try V2 (has 'type', 'timestamp', 'data' with nested fields)
+ if (
+ isinstance(data, dict)
+ and "type" in data
+ and "timestamp" in data
+ and "data" in data
+ and isinstance(data.get("data"), dict)
+ and "connection_id" in data.get("data", {})
+ ):
+ return (
+ WebhookVersion.V2,
+ t.cast(WebhookPayloadV2, data),
+ self._normalize_v2_payload(t.cast(WebhookPayloadV2, data)),
+ )
+
+ # Try V1 (has 'trigger_name', 'connection_id', 'trigger_id', 'payload')
+ if (
+ isinstance(data, dict)
+ and "trigger_name" in data
+ and "connection_id" in data
+ and "trigger_id" in data
+ and "payload" in data
+ ):
+ return (
+ WebhookVersion.V1,
+ t.cast(WebhookPayloadV1, data),
+ self._normalize_v1_payload(t.cast(WebhookPayloadV1, data)),
+ )
+
+ raise exceptions.WebhookPayloadError(
+ "Webhook payload does not match any known version (V1, V2, or V3). "
+ "Please ensure the payload structure is correct."
+ )
+
+ def _normalize_v1_payload(self, data: WebhookPayloadV1) -> TriggerEvent:
+ """Normalize V1 payload to TriggerEvent format."""
+ return t.cast(
+ TriggerEvent,
+ {
+ "id": data["trigger_id"],
+ "uuid": data["trigger_id"],
+ "user_id": "", # V1 doesn't have user_id
+ "toolkit_slug": "", # V1 doesn't have toolkit_slug
+ "trigger_slug": data["trigger_name"],
+ "metadata": {
+ "id": data["trigger_id"],
+ "uuid": data["trigger_id"],
+ "toolkit_slug": "",
+ "trigger_slug": data["trigger_name"],
+ "trigger_data": None,
+ "trigger_config": {},
+ "connected_account": {
+ "id": data["connection_id"],
+ "uuid": data["connection_id"],
+ "auth_config_id": "",
+ "auth_config_uuid": "",
+ "user_id": "",
+ "status": "ACTIVE",
+ },
+ },
+ "payload": data["payload"],
+ "original_payload": None,
+ },
+ )
+
+ def _normalize_v2_payload(self, data: WebhookPayloadV2) -> TriggerEvent:
+ """Normalize V2 payload to TriggerEvent format."""
+ payload_data = data["data"]
+ return t.cast(
+ TriggerEvent,
+ {
+ "id": payload_data.get(
+ "trigger_nano_id", payload_data.get("trigger_id", "")
+ ),
+ "uuid": payload_data.get("trigger_id", ""),
+ "user_id": payload_data.get("user_id", ""),
+ "toolkit_slug": data["type"].upper() if data.get("type") else "",
+ "trigger_slug": data["type"].upper() if data.get("type") else "",
+ "metadata": {
+ "id": payload_data.get("trigger_nano_id", ""),
+ "uuid": payload_data.get("trigger_id", ""),
+ "toolkit_slug": data["type"].upper() if data.get("type") else "",
+ "trigger_slug": data["type"].upper() if data.get("type") else "",
+ "trigger_data": None,
+ "trigger_config": {},
+ "connected_account": {
+ "id": payload_data.get("connection_nano_id", ""),
+ "uuid": payload_data.get("connection_id", ""),
+ "auth_config_id": "",
+ "auth_config_uuid": "",
+ "user_id": payload_data.get("user_id", ""),
+ "status": "ACTIVE",
+ },
+ },
+ "payload": {
+ k: v
+ for k, v in payload_data.items()
+ if k
+ not in (
+ "connection_id",
+ "connection_nano_id",
+ "trigger_nano_id",
+ "trigger_id",
+ "user_id",
+ )
+ },
+ "original_payload": None,
+ },
+ )
+
+ def _normalize_v3_payload(self, data: WebhookPayloadV3) -> TriggerEvent:
+ """Normalize V3 payload to TriggerEvent format."""
+ metadata = data["metadata"]
+ return t.cast(
+ TriggerEvent,
+ {
+ "id": metadata["trigger_id"],
+ "uuid": metadata["trigger_id"],
+ "user_id": metadata["user_id"],
+ "toolkit_slug": metadata["trigger_slug"].split("_")[0].upper()
+ if "_" in metadata["trigger_slug"]
+ else "UNKNOWN",
+ "trigger_slug": metadata["trigger_slug"],
+ "metadata": {
+ "id": metadata["trigger_id"],
+ "uuid": metadata["trigger_id"],
+ "toolkit_slug": metadata["trigger_slug"].split("_")[0].upper()
+ if "_" in metadata["trigger_slug"]
+ else "UNKNOWN",
+ "trigger_slug": metadata["trigger_slug"],
+ "trigger_data": None,
+ "trigger_config": {},
+ "connected_account": {
+ "id": metadata["connected_account_id"],
+ "uuid": metadata["connected_account_id"],
+ "auth_config_id": metadata["auth_config_id"],
+ "auth_config_uuid": metadata["auth_config_id"],
+ "user_id": metadata["user_id"],
+ "status": "ACTIVE",
+ },
+ },
+ "payload": data["data"],
+ "original_payload": None,
+ },
+ )
+
def _transform_trigger_data(self, data: _TriggerData) -> TriggerEvent:
"""
Transform raw trigger data to TriggerEvent format.
diff --git a/python/examples/triggers.py b/python/examples/triggers.py
index 7813e9a86..144630f35 100644
--- a/python/examples/triggers.py
+++ b/python/examples/triggers.py
@@ -53,6 +53,30 @@ print(enabled_instance)
deleted_instance = composio.triggers.delete(trigger_id="123")
print(deleted_instance)
+
+# Verify a webhook (example in Flask)
+# @app.route('/webhook', methods=['POST'])
+# def webhook():
+# try:
+# result = composio.triggers.verify_webhook(
+# id=request.headers.get('webhook-id', ''),
+# payload=request.get_data(as_text=True),
+# signature=request.headers.get('webhook-signature', ''),
+# timestamp=request.headers.get('webhook-timestamp', ''),
+# secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
+# )
+#
+# # Result contains:
+# # - version: WebhookVersion (V1, V2, or V3)
+# # - payload: Normalized TriggerEvent
+# # - raw_payload: Original parsed payload
+# print(f"Webhook version: {result['version']}")
+# print(f"Trigger: {result['payload']['trigger_slug']}")
+# return 'OK', 200
+# except WebhookSignatureVerificationError:
+# return 'Unauthorized', 401
+
+
# Subscribe to a trigger
subscription = composio.triggers.subscribe()
diff --git a/python/tests/test_triggers.py b/python/tests/test_triggers.py
index c622d726d..c4beea757 100644
--- a/python/tests/test_triggers.py
+++ b/python/tests/test_triggers.py
@@ -1,13 +1,15 @@
"""Tests for Triggers class."""
+import base64
import hashlib
import hmac
import json
+import time
import pytest
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timezone
from unittest.mock import Mock, patch
from composio_client import omit
-from composio.core.models.triggers import Triggers
+from composio.core.models.triggers import Triggers, WebhookVersion
from composio import exceptions
@@ -453,408 +455,619 @@ class TestVerifyWebhook:
return "test-webhook-secret-12345"
@pytest.fixture
- def mock_trigger_data(self):
- """Create mock trigger data matching _TriggerData structure."""
+ def test_webhook_id(self):
+ """Test webhook ID."""
+ return "msg_test123"
+
+ @pytest.fixture
+ def test_timestamp(self):
+ """Test webhook timestamp (current time in Unix seconds)."""
+ return str(int(time.time()))
+
+ @pytest.fixture
+ def mock_v1_payload(self):
+ """Create mock V1 webhook payload."""
return {
- "appName": "github",
- "clientId": 123,
+ "trigger_name": "GITHUB_PUSH_EVENT",
+ "connection_id": "conn-123",
+ "trigger_id": "trigger-123",
"payload": {"action": "push", "repository": "test-repo"},
- "originalPayload": {"action": "push", "repository": "test-repo"},
+ "log_id": "log-123",
+ }
+
+ @pytest.fixture
+ def mock_v2_payload(self):
+ """Create mock V2 webhook payload."""
+ return {
+ "type": "github_push_event",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "log_id": "log-123",
+ "data": {
+ "connection_id": "conn-123",
+ "connection_nano_id": "conn-nano-123",
+ "trigger_nano_id": "trigger-nano-123",
+ "trigger_id": "trigger-123",
+ "user_id": "user-456",
+ "action": "push",
+ "repository": "test-repo",
+ },
+ }
+
+ @pytest.fixture
+ def mock_v3_payload(self):
+ """Create mock V3 webhook payload."""
+ return {
+ "id": "evt-123",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "type": "composio.trigger.message",
"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",
- },
+ "log_id": "log-123",
+ "trigger_slug": "GITHUB_PUSH_EVENT",
+ "trigger_id": "trigger-nano-123",
+ "connected_account_id": "conn-nano-123",
+ "auth_config_id": "auth-nano-123",
+ "user_id": "user-456",
},
+ "data": {"action": "push", "repository": "test-repo"},
}
- def create_signature(self, payload: str, secret: str) -> str:
- """Helper to create a valid HMAC-SHA256 signature."""
- return hmac.new(
+ def create_signature(
+ self, webhook_id: str, timestamp: str, payload: str, secret: str
+ ) -> str:
+ """Helper to create a valid v1,base64 signature."""
+ to_sign = f"{webhook_id}.{timestamp}.{payload}"
+ signature_bytes = hmac.new(
key=secret.encode("utf-8"),
- msg=payload.encode("utf-8"),
+ msg=to_sign.encode("utf-8"),
digestmod=hashlib.sha256,
- ).hexdigest()
+ ).digest()
+ return f"v1,{base64.b64encode(signature_bytes).decode('utf-8')}"
- # Successful verification tests
+ # Successful verification tests with V3 payload
- def test_verify_webhook_valid_payload_and_signature(
- self, triggers, test_secret, mock_trigger_data
+ def test_verify_webhook_v3_payload(
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
):
- """Test successful webhook verification."""
- payload = json.dumps(mock_trigger_data)
- signature = self.create_signature(payload, test_secret)
+ """Test successful V3 webhook verification."""
+ payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, test_secret
+ )
result = triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=test_timestamp,
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"
+ assert result["version"] == WebhookVersion.V3
+ assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT"
+ assert result["payload"]["user_id"] == "user-456"
+ assert result["raw_payload"] == mock_v3_payload
- def test_verify_webhook_with_tolerance_zero(
- self, triggers, test_secret, mock_trigger_data
+ def test_verify_webhook_v3_normalizes_payload(
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
):
- """Test webhook verification with tolerance set to 0 (skip timestamp validation)."""
- payload = json.dumps(mock_trigger_data)
- signature = self.create_signature(payload, test_secret)
+ """Test V3 payload normalization."""
+ payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, test_secret
+ )
result = triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=test_timestamp,
secret=test_secret,
- tolerance=0,
)
- assert result["trigger_slug"] == "GITHUB_COMMIT_EVENT"
+ assert (
+ result["payload"]["metadata"]["connected_account"]["id"] == "conn-nano-123"
+ )
+ assert (
+ result["payload"]["metadata"]["connected_account"]["auth_config_id"]
+ == "auth-nano-123"
+ )
+ assert (
+ result["payload"]["metadata"]["connected_account"]["user_id"] == "user-456"
+ )
+
+ # Successful verification with V2 payload
- def test_verify_webhook_with_custom_tolerance(
- self, triggers, test_secret, mock_trigger_data
+ def test_verify_webhook_v2_payload(
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v2_payload
):
- """Test webhook verification with custom tolerance."""
- payload = json.dumps(mock_trigger_data)
- signature = self.create_signature(payload, test_secret)
+ """Test successful V2 webhook verification."""
+ payload = json.dumps(mock_v2_payload)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, test_secret
+ )
result = triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=test_timestamp,
secret=test_secret,
- tolerance=600, # 10 minutes
)
- assert result is not None
+ assert result["version"] == WebhookVersion.V2
+ assert result["payload"]["user_id"] == "user-456"
- def test_verify_webhook_transforms_payload_correctly(
- self, triggers, test_secret, mock_trigger_data
+ # Successful verification with V1 payload
+
+ def test_verify_webhook_v1_payload(
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v1_payload
):
- """Test that payload is correctly transformed to TriggerEvent format."""
- payload = json.dumps(mock_trigger_data)
- signature = self.create_signature(payload, test_secret)
+ """Test successful V1 webhook verification."""
+ payload = json.dumps(mock_v1_payload)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, test_secret
+ )
result = triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=test_timestamp,
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["version"] == WebhookVersion.V1
+ assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT"
+ assert result["payload"]["id"] == "trigger-123"
+
+ # Tolerance tests
+
+ def test_verify_webhook_with_tolerance_zero(
+ self, triggers, test_secret, test_webhook_id, mock_v3_payload
+ ):
+ """Test webhook verification with tolerance set to 0 (skip timestamp validation)."""
+ # Use an old timestamp (1 hour ago)
+ old_timestamp = str(int(time.time()) - 3600)
+ payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, old_timestamp, payload, test_secret
+ )
+
+ result = triggers.verify_webhook(
+ id=test_webhook_id,
+ payload=payload,
+ signature=signature,
+ timestamp=old_timestamp,
+ secret=test_secret,
+ tolerance=0,
+ )
+
+ assert result["version"] == WebhookVersion.V3
+
+ def test_verify_webhook_with_custom_tolerance(
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
+ ):
+ """Test webhook verification with custom tolerance."""
+ payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, test_secret
+ )
+
+ result = triggers.verify_webhook(
+ id=test_webhook_id,
+ payload=payload,
+ signature=signature,
+ timestamp=test_timestamp,
+ secret=test_secret,
+ tolerance=600, # 10 minutes
)
- assert result["metadata"]["connected_account"]["user_id"] == "user-456"
- assert result["metadata"]["connected_account"]["status"] == "ACTIVE"
+
+ assert result is not None
# Signature verification error tests
- def test_verify_webhook_empty_payload_raises_error(self, triggers, test_secret):
+ def test_verify_webhook_empty_payload_raises_error(
+ self, triggers, test_secret, test_webhook_id, test_timestamp
+ ):
"""Test that empty payload raises WebhookSignatureVerificationError."""
with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
triggers.verify_webhook(
+ id=test_webhook_id,
payload="",
- signature="some-signature",
+ signature="v1,somesignature",
+ timestamp=test_timestamp,
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
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
):
"""Test that empty signature raises WebhookSignatureVerificationError."""
- payload = json.dumps(mock_trigger_data)
+ payload = json.dumps(mock_v3_payload)
with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature="",
+ timestamp=test_timestamp,
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
+ self, triggers, test_webhook_id, test_timestamp, mock_v3_payload
):
"""Test that empty secret raises WebhookSignatureVerificationError."""
- payload = json.dumps(mock_trigger_data)
+ payload = json.dumps(mock_v3_payload)
with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
- signature="some-signature",
+ signature="v1,somesignature",
+ timestamp=test_timestamp,
secret="",
)
assert "No webhook secret was provided" in str(exc_info.value)
+ def test_verify_webhook_empty_webhook_id_raises_error(
+ self, triggers, test_secret, test_timestamp, mock_v3_payload
+ ):
+ """Test that empty webhook ID raises WebhookSignatureVerificationError."""
+ payload = json.dumps(mock_v3_payload)
+
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ triggers.verify_webhook(
+ id="",
+ payload=payload,
+ signature="v1,somesignature",
+ timestamp=test_timestamp,
+ secret=test_secret,
+ )
+
+ assert "No webhook ID was provided" in str(exc_info.value)
+
+ def test_verify_webhook_empty_timestamp_raises_error(
+ self, triggers, test_secret, test_webhook_id, mock_v3_payload
+ ):
+ """Test that empty timestamp raises WebhookPayloadError."""
+ payload = json.dumps(mock_v3_payload)
+
+ with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
+ triggers.verify_webhook(
+ id=test_webhook_id,
+ payload=payload,
+ signature="v1,somesignature",
+ timestamp="",
+ secret=test_secret,
+ )
+
+ assert "Invalid webhook timestamp" in str(exc_info.value)
+
+ def test_verify_webhook_invalid_signature_format_raises_error(
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
+ ):
+ """Test that signature without v1 prefix raises error."""
+ payload = json.dumps(mock_v3_payload)
+
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ triggers.verify_webhook(
+ id=test_webhook_id,
+ payload=payload,
+ signature="invalid-signature-no-prefix",
+ timestamp=test_timestamp,
+ secret=test_secret,
+ )
+
+ assert "No valid v1 signature found" in str(exc_info.value)
+
def test_verify_webhook_invalid_signature_raises_error(
- self, triggers, test_secret, mock_trigger_data
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
):
"""Test that invalid signature raises WebhookSignatureVerificationError."""
- payload = json.dumps(mock_trigger_data)
+ payload = json.dumps(mock_v3_payload)
with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
- signature="invalid-signature",
+ signature="v1,invalidbase64signature==",
+ timestamp=test_timestamp,
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
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
):
"""Test that signature created with different secret raises error."""
- payload = json.dumps(mock_trigger_data)
- signature = self.create_signature(payload, "different-secret")
+ payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, "different-secret"
+ )
with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=test_timestamp,
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
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
):
"""Test that modified payload after signing raises error."""
- original_payload = json.dumps(mock_trigger_data)
- signature = self.create_signature(original_payload, test_secret)
+ original_payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, original_payload, test_secret
+ )
# Modify the payload
- mock_trigger_data["appName"] = "modified-app"
- modified_payload = json.dumps(mock_trigger_data)
+ mock_v3_payload["data"] = {"modified": True}
+ modified_payload = json.dumps(mock_v3_payload)
with pytest.raises(exceptions.WebhookSignatureVerificationError):
triggers.verify_webhook(
+ id=test_webhook_id,
payload=modified_payload,
signature=signature,
+ timestamp=test_timestamp,
secret=test_secret,
)
# Payload parsing error tests
- def test_verify_webhook_invalid_json_raises_error(self, triggers, test_secret):
+ def test_verify_webhook_invalid_json_raises_error(
+ self, triggers, test_secret, test_webhook_id, test_timestamp
+ ):
"""Test that invalid JSON payload raises WebhookPayloadError."""
invalid_json = "not-valid-json{"
- signature = self.create_signature(invalid_json, test_secret)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, invalid_json, test_secret
+ )
with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
triggers.verify_webhook(
+ id=test_webhook_id,
payload=invalid_json,
signature=signature,
+ timestamp=test_timestamp,
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)
+ def test_verify_webhook_unrecognized_payload_raises_error(
+ self, triggers, test_secret, test_webhook_id, test_timestamp
+ ):
+ """Test that unrecognized payload format raises WebhookPayloadError."""
+ unknown_payload = json.dumps({"unknown": "format"})
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, unknown_payload, test_secret
+ )
- with pytest.raises(exceptions.WebhookPayloadError):
+ with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
triggers.verify_webhook(
- payload=truncated_json,
+ id=test_webhook_id,
+ payload=unknown_payload,
signature=signature,
+ timestamp=test_timestamp,
secret=test_secret,
)
- # Timestamp validation tests
+ assert "does not match any known version" in str(exc_info.value)
- def test_verify_webhook_timestamp_within_tolerance(
- self, triggers, test_secret, mock_trigger_data
+ def test_verify_webhook_v3_missing_data_field_raises_error(
+ self, triggers, test_secret, test_webhook_id, test_timestamp
):
- """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,
+ """Test that V3-like payload missing 'data' field raises WebhookPayloadError.
+
+ This tests the fix for a potential KeyError crash when a malformed payload
+ has valid V3 markers (type, id, metadata) but is missing the required 'data' field.
+ """
+ # Payload with V3 markers but missing 'data' field
+ v3_like_payload_missing_data = {
+ "id": "evt-123",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "type": "composio.trigger.message",
+ "metadata": {
+ "log_id": "log-123",
+ "trigger_slug": "GITHUB_PUSH_EVENT",
+ "trigger_id": "trigger-nano-123",
+ "connected_account_id": "conn-nano-123",
+ "auth_config_id": "auth-nano-123",
+ "user_id": "user-456",
+ },
+ # Note: 'data' field is intentionally missing
+ }
+ payload = json.dumps(v3_like_payload_missing_data)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, test_secret
)
- 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:
+ with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=test_timestamp,
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,
- )
+ # Should be rejected as unrecognized format, not crash with KeyError
+ assert "does not match any known version" in str(exc_info.value)
- assert result is not None
+ # Timestamp validation tests
- def test_verify_webhook_skips_timestamp_validation_when_no_timestamp(
- self, triggers, test_secret, mock_trigger_data
+ def test_verify_webhook_timestamp_within_tolerance(
+ self, triggers, test_secret, test_webhook_id, mock_v3_payload
):
- """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)
+ """Test that timestamp within tolerance passes validation."""
+ recent_timestamp = str(int(time.time()))
+ payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, recent_timestamp, payload, test_secret
+ )
result = triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=recent_timestamp,
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
+ def test_verify_webhook_timestamp_outside_tolerance_raises_error(
+ self, triggers, test_secret, test_webhook_id, mock_v3_payload
):
- """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)
+ """Test that timestamp outside tolerance raises error."""
+ # 10 minutes ago
+ old_timestamp = str(int(time.time()) - 600)
+ payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, old_timestamp, payload, test_secret
+ )
- with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=old_timestamp,
secret=test_secret,
- tolerance=300,
+ tolerance=300, # 5 minutes
)
- assert "Invalid timestamp in webhook payload" in str(exc_info.value)
+ assert "outside the allowed tolerance" in str(exc_info.value)
- def test_verify_webhook_timestamp_with_z_suffix(
- self, triggers, test_secret, mock_trigger_data
+ def test_verify_webhook_invalid_timestamp_format_raises_error(
+ self, triggers, test_secret, test_webhook_id, mock_v3_payload
):
- """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)
+ """Test that invalid timestamp format raises WebhookPayloadError."""
+ invalid_timestamp = "not-a-timestamp"
+ payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, invalid_timestamp, payload, test_secret
+ )
- # This will fail due to timestamp being old, but should parse correctly
- with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
+ with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=invalid_timestamp,
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)
+ assert "Invalid webhook timestamp" in str(exc_info.value)
# Security tests
def test_verify_webhook_uses_timing_safe_comparison(
- self, triggers, test_secret, mock_trigger_data
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
):
"""Test that signature comparison is timing-safe."""
- payload = json.dumps(mock_trigger_data)
- valid_signature = self.create_signature(payload, test_secret)
+ payload = json.dumps(mock_v3_payload)
+ valid_signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, test_secret
+ )
# Valid signature should work
result = triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=valid_signature,
+ timestamp=test_timestamp,
secret=test_secret,
)
assert result is not None
- # Invalid signature with same length should fail
- invalid_signature = "a" * len(valid_signature)
+ # Invalid signature with same format should fail
+ invalid_signature = "v1," + "a" * 44 # base64 SHA256 is 44 chars
with pytest.raises(exceptions.WebhookSignatureVerificationError):
triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=invalid_signature,
+ timestamp=test_timestamp,
secret=test_secret,
)
def test_verify_webhook_handles_unicode_payload(
- self, triggers, test_secret, mock_trigger_data
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
):
"""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)
+ mock_v3_payload["data"] = {"message": "你好世界 🌍 مرحبا"}
+ payload = json.dumps(mock_v3_payload, ensure_ascii=False)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, test_secret
+ )
result = triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=test_timestamp,
secret=test_secret,
)
- assert result["payload"]["message"] == "你好世界 🌍 مرحبا"
+ assert result["payload"]["payload"]["message"] == "你好世界 🌍 مرحبا"
def test_verify_webhook_handles_special_characters_in_secret(
- self, triggers, mock_trigger_data
+ self, triggers, test_webhook_id, test_timestamp, mock_v3_payload
):
"""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)
+ payload = json.dumps(mock_v3_payload)
+ signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, special_secret
+ )
result = triggers.verify_webhook(
+ id=test_webhook_id,
payload=payload,
signature=signature,
+ timestamp=test_timestamp,
secret=special_secret,
)
assert result is not None
+ def test_verify_webhook_supports_multiple_signatures(
+ self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
+ ):
+ """Test that multiple signatures in header are supported."""
+ payload = json.dumps(mock_v3_payload)
+ valid_signature = self.create_signature(
+ test_webhook_id, test_timestamp, payload, test_secret
+ )
+ # Multiple signatures space-separated
+ multiple_signatures = f"v1,invalidsig== {valid_signature}"
+
+ result = triggers.verify_webhook(
+ id=test_webhook_id,
+ payload=payload,
+ signature=multiple_signatures,
+ timestamp=test_timestamp,
+ secret=test_secret,
+ )
+
+ assert result is not None
+
# Error class tests
def test_webhook_signature_verification_error_is_trigger_error(self):
diff --git a/ts/docs/README.md b/ts/docs/README.md
index 189a7953b..f06893d67 100644
--- a/ts/docs/README.md
+++ b/ts/docs/README.md
@@ -127,6 +127,7 @@ Check out our [examples directory](../examples) for complete code samples:
- [Custom Providers](./advanced/custom-providers.md)
- [Modifiers](./advanced/modifiers.md)
- [Session Management](./advanced/session-management.md)
+- [Webhook Verification](./advanced/webhook-verification.md)
## Internal Documentation
diff --git a/ts/docs/advanced/webhook-verification.md b/ts/docs/advanced/webhook-verification.md
new file mode 100644
index 000000000..392f6479c
--- /dev/null
+++ b/ts/docs/advanced/webhook-verification.md
@@ -0,0 +1,349 @@
+# Webhook Verification
+
+Composio sends webhook payloads to notify your application when triggers fire. To ensure these webhooks are authentic and haven't been tampered with, you should verify the webhook signature before processing.
+
+## Overview
+
+The `composio.triggers.verifyWebhook()` method validates incoming webhook requests by:
+
+1. **Verifying the HMAC-SHA256 signature** to ensure the payload is authentic
+2. **Checking the timestamp** to prevent replay attacks (optional, enabled by default)
+3. **Parsing and normalizing the payload** across different webhook versions
+
+## Webhook Versions
+
+Composio supports three webhook payload versions:
+
+| Version | Status | Description |
+|---------|--------|-------------|
+| **V3** | Current (Default) | Latest format used by Composio apps. Includes rich metadata with `type: 'composio.trigger.message'` |
+| **V2** | Legacy | Older format with nested `data` object containing connection and trigger info |
+| **V1** | Legacy | Original format with flat structure using `trigger_name`, `connection_id`, `trigger_id` |
+
+The SDK automatically detects the version and normalizes all payloads to a consistent `IncomingTriggerPayload` format.
+
+## Webhook Headers
+
+Composio webhooks include these headers for verification:
+
+| Header | Description | Example |
+|--------|-------------|---------|
+| `webhook-id` | Unique message identifier | `msg_abc123` |
+| `webhook-timestamp` | Unix timestamp in seconds | `1704067200` |
+| `webhook-signature` | HMAC-SHA256 signature | `v1,K7gNU3sdo+OL0wNhqoVWhr3g6s...` |
+| `x-composio-webhook-version` | Webhook version (V1, V2, V3) | `V3` |
+
+## API Reference
+
+### `composio.triggers.verifyWebhook(params)`
+
+Verifies an incoming webhook payload and signature.
+
+#### Parameters
+
+```typescript
+interface VerifyWebhookParams {
+ /** The raw webhook payload as a string (request body) */
+ payload: string;
+
+ /** The signature from the 'webhook-signature' header */
+ signature: string;
+
+ /** The webhook secret from your Composio dashboard */
+ secret: string;
+
+ /** The webhook ID from the 'webhook-id' header */
+ id: string;
+
+ /** The timestamp from the 'webhook-timestamp' header (Unix seconds) */
+ timestamp: string;
+
+ /**
+ * Maximum allowed age of the webhook in seconds.
+ * Set to 0 to disable timestamp validation.
+ * @default 300 (5 minutes)
+ */
+ tolerance?: number;
+}
+```
+
+#### Return Value
+
+```typescript
+interface VerifyWebhookResult {
+ /** The detected webhook version (V1, V2, or V3) */
+ version: 'V1' | 'V2' | 'V3';
+
+ /** The normalized webhook payload */
+ payload: IncomingTriggerPayload;
+
+ /** The raw parsed payload before normalization */
+ rawPayload: WebhookPayloadV1 | WebhookPayloadV2 | WebhookPayloadV3;
+}
+```
+
+#### Errors
+
+| Error Class | Description |
+|-------------|-------------|
+| `ValidationError` | Invalid parameters passed to the method |
+| `ComposioWebhookSignatureVerificationError` | Signature mismatch, missing headers, or timestamp outside tolerance |
+| `ComposioWebhookPayloadError` | Invalid JSON or unrecognized payload format |
+
+## Usage Examples
+
+### Express.js
+
+```typescript
+import express from 'express';
+import { Composio, ComposioWebhookSignatureVerificationError } from '@composio/core';
+
+const app = express();
+const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
+
+// Important: Use express.raw() to get the raw body as a string
+app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
+ try {
+ const result = composio.triggers.verifyWebhook({
+ payload: req.body.toString(),
+ signature: req.headers['webhook-signature'] as string,
+ id: req.headers['webhook-id'] as string,
+ timestamp: req.headers['webhook-timestamp'] as string,
+ secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
+ });
+
+ // Process the verified payload
+ console.log('Webhook version:', result.version);
+ console.log('Trigger:', result.payload.triggerSlug);
+ console.log('User ID:', result.payload.userId);
+ console.log('Data:', result.payload.payload);
+
+ res.status(200).send('OK');
+ } catch (error) {
+ if (error instanceof ComposioWebhookSignatureVerificationError) {
+ console.error('Webhook verification failed:', error.message);
+ res.status(401).send('Unauthorized');
+ } else {
+ console.error('Webhook processing error:', error);
+ res.status(400).send('Bad Request');
+ }
+ }
+});
+
+app.listen(3000);
+```
+
+### Next.js API Route (App Router)
+
+```typescript
+import { NextRequest, NextResponse } from 'next/server';
+import { Composio, ComposioWebhookSignatureVerificationError } from '@composio/core';
+
+const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
+
+export async function POST(request: NextRequest) {
+ try {
+ const payload = await request.text();
+
+ const result = composio.triggers.verifyWebhook({
+ payload,
+ signature: request.headers.get('webhook-signature')!,
+ id: request.headers.get('webhook-id')!,
+ timestamp: request.headers.get('webhook-timestamp')!,
+ secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
+ });
+
+ // Process the verified payload
+ console.log('Received trigger:', result.payload.triggerSlug);
+
+ return NextResponse.json({ received: true });
+ } catch (error) {
+ if (error instanceof ComposioWebhookSignatureVerificationError) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+ return NextResponse.json({ error: 'Bad Request' }, { status: 400 });
+ }
+}
+```
+
+### Fastify
+
+```typescript
+import Fastify from 'fastify';
+import { Composio, ComposioWebhookSignatureVerificationError } from '@composio/core';
+
+const fastify = Fastify();
+const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
+
+// Get raw body
+fastify.addContentTypeParser(
+ 'application/json',
+ { parseAs: 'string' },
+ (req, body, done) => done(null, body)
+);
+
+fastify.post('/webhook', async (request, reply) => {
+ try {
+ const result = composio.triggers.verifyWebhook({
+ payload: request.body as string,
+ signature: request.headers['webhook-signature'] as string,
+ id: request.headers['webhook-id'] as string,
+ timestamp: request.headers['webhook-timestamp'] as string,
+ secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
+ });
+
+ console.log('Trigger:', result.payload.triggerSlug);
+ return { received: true };
+ } catch (error) {
+ if (error instanceof ComposioWebhookSignatureVerificationError) {
+ reply.code(401);
+ return { error: 'Unauthorized' };
+ }
+ reply.code(400);
+ return { error: 'Bad Request' };
+ }
+});
+
+fastify.listen({ port: 3000 });
+```
+
+## Signature Algorithm
+
+The signature is computed as:
+
+```
+HMAC-SHA256(${webhookId}.${webhookTimestamp}.${payload}, secret)
+```
+
+The result is base64-encoded and prefixed with `v1,`:
+
+```
+v1,K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=
+```
+
+## Timestamp Validation
+
+By default, webhooks older than 5 minutes are rejected to prevent replay attacks. You can customize this behavior:
+
+```typescript
+// Strict: 1 minute tolerance
+const result = composio.triggers.verifyWebhook({
+ ...params,
+ tolerance: 60,
+});
+
+// Lenient: 10 minute tolerance
+const result = composio.triggers.verifyWebhook({
+ ...params,
+ tolerance: 600,
+});
+
+// Disable timestamp validation (not recommended for production)
+const result = composio.triggers.verifyWebhook({
+ ...params,
+ tolerance: 0,
+});
+```
+
+## Payload Structures
+
+### V3 Payload (Current Default)
+
+```json
+{
+ "id": "msg_abc123",
+ "timestamp": "2024-01-01T00:00:00.000Z",
+ "type": "composio.trigger.message",
+ "metadata": {
+ "log_id": "log-123",
+ "trigger_slug": "GITHUB_PUSH_EVENT",
+ "trigger_id": "trigger-nano-123",
+ "connected_account_id": "conn-nano-123",
+ "auth_config_id": "auth-nano-123",
+ "user_id": "user-456"
+ },
+ "data": {
+ "action": "push",
+ "repository": "my-repo"
+ }
+}
+```
+
+### V2 Payload (Legacy)
+
+```json
+{
+ "type": "github_push_event",
+ "timestamp": "2024-01-01T00:00:00.000Z",
+ "log_id": "log-123",
+ "data": {
+ "connection_id": "conn-123",
+ "connection_nano_id": "conn-nano-123",
+ "trigger_nano_id": "trigger-nano-123",
+ "trigger_id": "trigger-123",
+ "user_id": "user-456",
+ "action": "push",
+ "repository": "my-repo"
+ }
+}
+```
+
+### V1 Payload (Legacy)
+
+```json
+{
+ "trigger_name": "GITHUB_PUSH_EVENT",
+ "connection_id": "conn-123",
+ "trigger_id": "trigger-123",
+ "payload": {
+ "action": "push",
+ "repository": "my-repo"
+ },
+ "log_id": "log-123"
+}
+```
+
+## Normalized Payload
+
+Regardless of webhook version, the `payload` field in the result is normalized to:
+
+```typescript
+interface IncomingTriggerPayload {
+ id: string;
+ uuid: string;
+ triggerSlug: string;
+ toolkitSlug: string;
+ userId: string;
+ payload: Record<string, unknown>;
+ originalPayload: Record<string, unknown>;
+ metadata: {
+ id: string;
+ uuid: string;
+ toolkitSlug: string;
+ triggerSlug: string;
+ triggerConfig: Record<string, unknown>;
+ connectedAccount: {
+ id: string;
+ uuid: string;
+ authConfigId: string;
+ authConfigUUID: string;
+ userId: string;
+ status: string;
+ };
+ };
+}
+```
+
+## Security Best Practices
+
+1. **Always verify webhooks** before processing them in production
+2. **Store your webhook secret securely** using environment variables
+3. **Use HTTPS** for your webhook endpoint
+4. **Keep timestamp tolerance reasonable** (default 5 minutes is recommended)
+5. **Parse the raw body** - don't use pre-parsed JSON as middleware may modify it
+6. **Handle errors gracefully** - return 401 for signature failures, 400 for parsing errors
+7. **Log verification failures** for security monitoring
+
+## Finding Your Webhook Secret
+
+Your webhook secret is available in the [Composio Dashboard](https://app.composio.dev) under your project settings. Keep this secret secure and never expose it in client-side code.
diff --git a/ts/examples/triggers/.env.example b/ts/examples/triggers/.env.example
index 0e728257c..5d451712e 100644
--- a/ts/examples/triggers/.env.example
+++ b/ts/examples/triggers/.env.example
@@ -1,6 +1,9 @@
# Composio API Key - Get it from https://app.composio.dev
COMPOSIO_API_KEY=your_composio_api_key_here
+# Webhook secret for verifying incoming webhooks - Get it from your Composio dashboard
+COMPOSIO_WEBHOOK_SECRET=your_webhook_secret_here
+
# Add other environment variables as needed for your example
# OPENAI_API_KEY=your_openai_api_key_here
# ANTHROPIC_API_KEY=your_anthropic_api_key_here
diff --git a/ts/examples/triggers/README.md b/ts/examples/triggers/README.md
index edfc440cb..e2b38a6f1 100644
--- a/ts/examples/triggers/README.md
+++ b/ts/examples/triggers/README.md
@@ -16,26 +16,53 @@ This example demonstrates how to use Composio SDK for triggers.
Then edit `.env` and add your API keys:
- `COMPOSIO_API_KEY`: Get it from [Composio Dashboard](https://app.composio.dev)
+ - `COMPOSIO_WEBHOOK_SECRET`: Get it from your webhook configuration in Composio Dashboard
-## Running the Example
+## Running the Examples
+
+### Trigger Subscription (WebSocket)
```bash
-# Run the example
+# Run the subscription example
pnpm start
# Run in development mode (with file watching)
pnpm dev
```
+### Webhook Server (HTTP)
+
+```bash
+# Start the webhook verification server
+pnpm webhook:server
+
+# Then expose it with telebit (https://telebit.cloud/)
+telebit http 3000
+```
+
## What This Example Does
+### `src/index.ts` - Trigger Subscription
- Initializes Composio SDK
-- Fetches available tools
-- Demonstrates basic usage patterns
+- Subscribes to triggers via WebSocket
+- Receives real-time trigger events
+
+### `src/webhook-server.ts` - Webhook Verification
+- Starts a Bun HTTP server on port 3000
+- Verifies incoming webhook signatures using the new `verifyWebhook` API
+- Supports V1, V2, and V3 webhook payload formats
+- Returns normalized trigger events
+
+## Webhook Headers
+
+When receiving webhooks, the following headers are used:
+- `webhook-id`: Unique message ID (format: `msg_xxx`)
+- `webhook-timestamp`: Unix timestamp in seconds
+- `webhook-signature`: Signature in format `v1,base64EncodedSignature`
## Customization
-Edit `src/index.ts` to:
+Edit `src/index.ts` or `src/webhook-server.ts` to:
- Add specific apps you want to integrate with
- Implement your business logic
- Add error handling and logging
diff --git a/ts/examples/triggers/package.json b/ts/examples/triggers/package.json
index 100065a63..e4f5b650c 100644
--- a/ts/examples/triggers/package.json
+++ b/ts/examples/triggers/package.json
@@ -8,6 +8,7 @@
"clean": "git clean -xdf node_modules",
"start": "bun src/index.ts",
"dev": "bun --watch src/index.ts",
+ "webhook:server": "bun src/webhook-server.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": ["composio", "example", "triggers"],
diff --git a/ts/examples/triggers/src/webhook-server.ts b/ts/examples/triggers/src/webhook-server.ts
new file mode 100644
index 000000000..5240fa88d
--- /dev/null
+++ b/ts/examples/triggers/src/webhook-server.ts
@@ -0,0 +1,125 @@
+/**
+ * Webhook Verification Server Example
+ *
+ * This example demonstrates how to verify incoming Composio webhooks
+ * using Bun.serve with the new verifyWebhook API.
+ *
+ * Prerequisites:
+ * 1. Set up your COMPOSIO_API_KEY and COMPOSIO_WEBHOOK_SECRET in the .env file
+ * 2. Install dependencies: pnpm install
+ * 3. Run the server: pnpm webhook
+ * 4. Expose your local server using telebit: `telebit http 3000`
+ * 5. Configure the webhook URL in your Composio dashboard: `https://<your-telebit-url>/webhook`
+ */
+
+import {
+ Composio,
+ ComposioWebhookSignatureVerificationError,
+ ComposioWebhookPayloadError,
+} from '@composio/core';
+import 'dotenv/config';
+
+const PORT = process.env.PORT || 3000;
+const WEBHOOK_SECRET = process.env.COMPOSIO_WEBHOOK_SECRET;
+
+if (!WEBHOOK_SECRET) {
+ console.error('❌ COMPOSIO_WEBHOOK_SECRET is required in .env file');
+ process.exit(1);
+}
+
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+});
+
+console.log(`🚀 Starting webhook server on port ${PORT}...`);
+
+const server = Bun.serve({
+ port: PORT,
+ async fetch(request) {
+ const url = new URL(request.url);
+
+ // Health check endpoint
+ if (url.pathname === '/health') {
+ return new Response('OK', { status: 200 });
+ }
+
+ // Webhook endpoint
+ if (url.pathname === '/webhook' && request.method === 'POST') {
+ try {
+ // Get required headers
+ const webhookId = request.headers.get('webhook-id') || '';
+ const webhookTimestamp = request.headers.get('webhook-timestamp') || '';
+ const webhookSignature = request.headers.get('webhook-signature') || '';
+
+ // Get raw payload
+ const payload = await request.text();
+
+ console.log('\n📨 Received webhook request');
+ console.log(' Headers:');
+ console.log(` webhook-id: ${webhookId}`);
+ console.log(` webhook-timestamp: ${webhookTimestamp}`);
+ console.log(` webhook-signature: ${webhookSignature.substring(0, 30)}...`);
+
+ // Verify the webhook
+ const result = composio.triggers.verifyWebhook({
+ id: webhookId,
+ timestamp: webhookTimestamp,
+ signature: webhookSignature,
+ payload,
+ secret: WEBHOOK_SECRET,
+ });
+
+ // Log the verified payload
+ console.log('\n✅ Webhook verified successfully!');
+ console.log(` Version: ${result.version}`);
+ console.log(` Trigger: ${result.payload.triggerSlug}`);
+ console.log(` User ID: ${result.payload.userId}`);
+ console.log(` Payload:`, JSON.stringify(result.payload.payload, null, 2));
+
+ // Process the trigger event here
+ // For example, you could emit an event, call another service, etc.
+
+ return new Response(JSON.stringify({ success: true }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ } catch (error) {
+ console.error('\n❌ Webhook verification failed:', error);
+
+ // Return 401 for signature verification errors
+ if (error instanceof ComposioWebhookSignatureVerificationError) {
+ return new Response(JSON.stringify({ error: 'Unauthorized' }), {
+ status: 401,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ // Return 400 for payload parsing errors
+ if (error instanceof ComposioWebhookPayloadError) {
+ return new Response(JSON.stringify({ error: 'Bad Request' }), {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ // Return 500 for unexpected errors
+ return new Response(JSON.stringify({ error: 'Internal Server Error' }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+ }
+
+ // 404 for other routes
+ return new Response('Not Found', { status: 404 });
+ },
+});
+
+console.log(`✅ Webhook server running at http://localhost:${server.port}`);
+console.log(`\n📋 Endpoints:`);
+console.log(` POST /webhook - Receive and verify webhooks`);
+console.log(` GET /health - Health check`);
+console.log(`\n💡 Tips:`);
+console.log(` 1. Expose this server with telebit: telebit http ${server.port}`);
+console.log(` 2. Configure your telebit URL as webhook URL in Composio dashboard`);
+console.log(` 3. The webhook secret should match what's configured in Composio`);
diff --git a/ts/packages/core/src/models/Triggers.ts b/ts/packages/core/src/models/Triggers.ts
index 1e1c999d9..c66a4f21f 100644
--- a/ts/packages/core/src/models/Triggers.ts
+++ b/ts/packages/core/src/models/Triggers.ts
@@ -22,6 +22,12 @@ import {
VerifyWebhookParams,
VerifyWebhookParamsSchema,
VerifyWebhookResult,
+ WebhookPayload,
+ WebhookPayloadV1Schema,
+ WebhookPayloadV2Schema,
+ WebhookPayloadV3Schema,
+ WebhookVersion,
+ WebhookVersions,
} from '../types/triggers.types';
import logger from '../utils/logger';
import { telemetry } from '../telemetry/Telemetry';
@@ -465,15 +471,20 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
* 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
+ * 1. Verifying the HMAC-SHA256 signature matches the payload using the correct signing format
* 2. Optionally checking that the webhook timestamp is within the tolerance window
*
+ * The signature is computed as: `HMAC-SHA256(${webhookId}.${webhookTimestamp}.${payload}, secret)`
+ * and is expected in the format: `v1,base64EncodedSignature`
+ *
* @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.signature - The signature from the 'webhook-signature' header
* @param {string} params.secret - The webhook secret used to sign the payload
+ * @param {string} params.webhookId - The webhook ID from the 'webhook-id' header
+ * @param {string} params.webhookTimestamp - The timestamp from the 'webhook-timestamp' header (Unix seconds)
* @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
+ * @returns {VerifyWebhookResult} The verified and parsed webhook payload with version information
*
* @throws {ValidationError} If the parameters are invalid
* @throws {ComposioWebhookSignatureVerificationError} If the signature verification fails
@@ -484,14 +495,17 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
* // In an Express.js webhook handler
* app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
* try {
- * const payload = composio.triggers.verifyWebhook({
+ * const result = composio.triggers.verifyWebhook({
* payload: req.body.toString(),
- * signature: req.headers['x-composio-signature'] as string,
+ * signature: req.headers['webhook-signature'] as string,
+ * webhookId: req.headers['webhook-id'] as string,
+ * webhookTimestamp: req.headers['webhook-timestamp'] as string,
* secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
* });
*
* // Process the verified payload
- * console.log('Received trigger:', payload.triggerSlug);
+ * console.log('Webhook version:', result.version);
+ * console.log('Received trigger:', result.payload.triggerSlug);
* res.status(200).send('OK');
* } catch (error) {
* console.error('Webhook verification failed:', error);
@@ -509,44 +523,229 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
});
}
- const { payload, signature, secret, tolerance } = parsedParams.data;
+ const {
+ payload,
+ signature,
+ secret,
+ id: webhookId,
+ timestamp: webhookTimestamp,
+ tolerance,
+ } = parsedParams.data;
+
+ // Validate timestamp if tolerance is set
+ if (tolerance > 0) {
+ this.validateWebhookTimestamp(webhookTimestamp, tolerance);
+ }
+
+ // Verify signature using the correct format: msgId.timestamp.payload
+ this.verifyWebhookSignature(webhookId, webhookTimestamp, payload, signature, secret);
- // Verify signature
- this.verifyWebhookSignature(payload, signature, secret);
+ // Parse the payload and detect version
+ const { version, rawPayload, normalizedPayload } = this.parseWebhookPayload(payload);
+
+ return {
+ version,
+ payload: normalizedPayload,
+ rawPayload,
+ };
+ }
- // Parse and validate payload
- let parsedPayload: TriggerData;
+ /**
+ * Parses the webhook payload and detects its version (V1, V2, or V3)
+ * @private
+ */
+ private parseWebhookPayload(payload: string): {
+ version: WebhookVersion;
+ rawPayload: WebhookPayload;
+ normalizedPayload: IncomingTriggerPayload;
+ } {
+ let jsonPayload: unknown;
try {
- parsedPayload = JSON.parse(payload) as TriggerData;
+ jsonPayload = JSON.parse(payload);
} catch (error) {
throw new ComposioWebhookPayloadError('Failed to parse webhook payload as JSON', {
cause: error,
});
}
- // Transform to IncomingTriggerPayload format
- const transformedPayload = transformIncomingTriggerPayload(parsedPayload);
+ // Try V3 first (has 'composio.trigger.message' type)
+ const v3Result = WebhookPayloadV3Schema.safeParse(jsonPayload);
+ if (v3Result.success) {
+ return {
+ version: WebhookVersions.V3,
+ rawPayload: v3Result.data,
+ normalizedPayload: this.normalizeV3Payload(v3Result.data),
+ };
+ }
+
+ // Try V2 (has 'type', 'timestamp', 'log_id', and 'data' with specific fields)
+ const v2Result = WebhookPayloadV2Schema.safeParse(jsonPayload);
+ if (v2Result.success) {
+ return {
+ version: WebhookVersions.V2,
+ rawPayload: v2Result.data,
+ normalizedPayload: this.normalizeV2Payload(v2Result.data),
+ };
+ }
- // Validate timestamp if tolerance is set and payload contains timestamp
- if (tolerance > 0) {
- this.validateWebhookTimestamp(parsedPayload, tolerance);
+ // Try V1 (has 'trigger_name', 'connection_id', 'trigger_id', 'payload', 'log_id')
+ const v1Result = WebhookPayloadV1Schema.safeParse(jsonPayload);
+ if (v1Result.success) {
+ return {
+ version: WebhookVersions.V1,
+ rawPayload: v1Result.data,
+ normalizedPayload: this.normalizeV1Payload(v1Result.data),
+ };
}
- return transformedPayload;
+ // None of the schemas matched
+ throw new ComposioWebhookPayloadError(
+ 'Webhook payload does not match any known version (V1, V2, or V3). ' +
+ 'Please ensure you are using a supported webhook payload format.',
+ {
+ cause: {
+ v1Error: v1Result.error?.message,
+ v2Error: v2Result.error?.message,
+ v3Error: v3Result.error?.message,
+ },
+ }
+ );
+ }
+
+ /**
+ * Normalizes a V1 webhook payload to IncomingTriggerPayload format
+ * @private
+ */
+ private normalizeV1Payload(
+ payload: import('../types/triggers.types').WebhookPayloadV1
+ ): IncomingTriggerPayload {
+ // V1 has limited information, so we use what's available
+ // and mark unknown fields appropriately
+ const triggerName = payload.trigger_name;
+ const toolkitSlug = triggerName.split('_')[0]?.toUpperCase() || 'UNKNOWN';
+
+ return {
+ id: payload.trigger_id,
+ uuid: payload.trigger_id, // V1 doesn't have UUID, use trigger_id
+ triggerSlug: triggerName,
+ toolkitSlug,
+ userId: '', // V1 doesn't provide userId
+ payload: payload.payload,
+ originalPayload: payload.payload,
+ metadata: {
+ id: payload.trigger_id,
+ uuid: payload.trigger_id,
+ toolkitSlug,
+ triggerSlug: triggerName,
+ triggerConfig: {},
+ connectedAccount: {
+ id: payload.connection_id,
+ uuid: payload.connection_id,
+ authConfigId: '',
+ authConfigUUID: '',
+ userId: '',
+ status: 'ACTIVE',
+ },
+ },
+ };
}
/**
- * Verifies the HMAC-SHA256 signature of a webhook payload
+ * Normalizes a V2 webhook payload to IncomingTriggerPayload format
* @private
*/
- private verifyWebhookSignature(payload: string, signature: string, secret: string): void {
+ private normalizeV2Payload(
+ payload: import('../types/triggers.types').WebhookPayloadV2
+ ): IncomingTriggerPayload {
+ const triggerSlug = payload.type.toUpperCase();
+ const toolkitSlug = triggerSlug.split('_')[0] || 'UNKNOWN';
+
+ // Extract data fields
+ const { connection_id, connection_nano_id, trigger_nano_id, trigger_id, user_id, ...restData } =
+ payload.data;
+
+ return {
+ id: trigger_nano_id,
+ uuid: trigger_id,
+ triggerSlug,
+ toolkitSlug,
+ userId: user_id,
+ payload: restData,
+ originalPayload: restData,
+ metadata: {
+ id: trigger_nano_id,
+ uuid: trigger_id,
+ toolkitSlug,
+ triggerSlug,
+ triggerConfig: {},
+ connectedAccount: {
+ id: connection_nano_id,
+ uuid: connection_id,
+ authConfigId: '',
+ authConfigUUID: '',
+ userId: user_id,
+ status: 'ACTIVE',
+ },
+ },
+ };
+ }
+
+ /**
+ * Normalizes a V3 webhook payload to IncomingTriggerPayload format
+ * @private
+ */
+ private normalizeV3Payload(
+ payload: import('../types/triggers.types').WebhookPayloadV3
+ ): IncomingTriggerPayload {
+ const triggerSlug = payload.metadata.trigger_slug;
+ const toolkitSlug = triggerSlug.split('_')[0]?.toUpperCase() || 'UNKNOWN';
+
+ return {
+ id: payload.metadata.trigger_id,
+ uuid: payload.metadata.trigger_id,
+ triggerSlug,
+ toolkitSlug,
+ userId: payload.metadata.user_id,
+ payload: payload.data,
+ originalPayload: payload.data,
+ metadata: {
+ id: payload.metadata.trigger_id,
+ uuid: payload.metadata.trigger_id,
+ toolkitSlug,
+ triggerSlug,
+ triggerConfig: {},
+ connectedAccount: {
+ id: payload.metadata.connected_account_id,
+ uuid: payload.metadata.connected_account_id,
+ authConfigId: payload.metadata.auth_config_id,
+ authConfigUUID: payload.metadata.auth_config_id,
+ userId: payload.metadata.user_id,
+ status: 'ACTIVE',
+ },
+ },
+ };
+ }
+
+ /**
+ * Verifies the HMAC-SHA256 signature of a webhook payload.
+ * The signature format used by Composio is: `v1,base64EncodedSignature`
+ * The signing input is: `${msgId}.${timestamp}.${payload}`
+ * @private
+ */
+ private verifyWebhookSignature(
+ webhookId: string,
+ webhookTimestamp: string,
+ 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.'
+ "No signature header value was provided. Please pass the value of the 'webhook-signature' header."
);
}
@@ -556,20 +755,62 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
);
}
+ if (webhookId.length === 0) {
+ throw new ComposioWebhookSignatureVerificationError(
+ "No webhook ID was provided. Please pass the value of the 'webhook-id' header."
+ );
+ }
+
+ if (webhookTimestamp.length === 0) {
+ throw new ComposioWebhookSignatureVerificationError(
+ "No webhook timestamp was provided. Please pass the value of the 'webhook-timestamp' header."
+ );
+ }
+
+ // Parse signature - may have multiple signatures prefixed with version (e.g., "v1,base64sig")
+ const signatures = signature.split(' ');
+ const v1Signatures: string[] = [];
+
+ for (const sig of signatures) {
+ const [version, value] = sig.split(',');
+ if (version === 'v1' && value) {
+ v1Signatures.push(value);
+ }
+ }
+
+ if (v1Signatures.length === 0) {
+ throw new ComposioWebhookSignatureVerificationError(
+ 'No valid v1 signature found in the webhook-signature header. ' +
+ "Expected format: 'v1,base64EncodedSignature'"
+ );
+ }
+
+ // Compute expected signature: HMAC-SHA256(msgId.timestamp.payload, secret) -> base64
+ const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
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);
+ .update(toSign, 'utf8')
+ .digest('base64');
+
+ // Check if any of the provided signatures match
+ let isValid = false;
+ for (const providedSignature of v1Signatures) {
+ const signatureBuffer = Buffer.from(providedSignature);
+ const expectedBuffer = Buffer.from(expectedSignature);
+
+ if (
+ signatureBuffer.length === expectedBuffer.length &&
+ crypto.timingSafeEqual(signatureBuffer, expectedBuffer)
+ ) {
+ isValid = true;
+ break;
+ }
+ }
- if (
- signatureBuffer.length !== expectedBuffer.length ||
- !crypto.timingSafeEqual(signatureBuffer, expectedBuffer)
- ) {
- throw new ComposioWebhookSignatureVerificationError('The signature provided is invalid.');
+ if (!isValid) {
+ throw new ComposioWebhookSignatureVerificationError(
+ 'The signature provided is invalid. Please ensure you are using the correct webhook secret.'
+ );
}
}
@@ -577,29 +818,18 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
* 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;
- }
+ private validateWebhookTimestamp(webhookTimestamp: string, tolerance: number): void {
+ const timestampSeconds = parseInt(webhookTimestamp, 10);
- const webhookTime = Date.parse(timestamp);
- if (Number.isNaN(webhookTime)) {
+ if (Number.isNaN(timestampSeconds)) {
throw new ComposioWebhookPayloadError(
- `Invalid timestamp in webhook payload: ${timestamp}. Expected ISO 8601 format.`
+ `Invalid webhook timestamp: ${webhookTimestamp}. Expected Unix timestamp in seconds.`
);
}
+ const webhookTimeMs = timestampSeconds * 1000;
const currentTime = Date.now();
- const timeDifference = Math.abs(currentTime - webhookTime);
+ const timeDifference = Math.abs(currentTime - webhookTimeMs);
if (timeDifference > tolerance * 1000) {
throw new ComposioWebhookSignatureVerificationError(
diff --git a/ts/packages/core/src/types/triggers.types.ts b/ts/packages/core/src/types/triggers.types.ts
index d990155d5..c51daa4e6 100644
--- a/ts/packages/core/src/types/triggers.types.ts
+++ b/ts/packages/core/src/types/triggers.types.ts
@@ -195,16 +195,94 @@ export type TriggerEventData<TPayload = unknown> = TPayload & {
user_id: string;
};
+/**
+ * Webhook payload schemas for V1, V2, V3 versions
+ * These schemas represent the raw payload structure sent by Composio's webhook system
+ */
+
+/** V1 webhook payload - legacy format */
+export const WebhookPayloadV1Schema = z.object({
+ trigger_name: z.string(),
+ connection_id: z.string(),
+ trigger_id: z.string(),
+ payload: z.record(z.unknown()),
+ log_id: z.string(),
+});
+export type WebhookPayloadV1 = z.infer<typeof WebhookPayloadV1Schema>;
+
+/** V2 webhook payload - includes timestamp and nested data */
+export const WebhookPayloadV2Schema = z.object({
+ type: z.string(),
+ timestamp: z.string(),
+ log_id: z.string(),
+ data: z
+ .object({
+ connection_id: z.string(),
+ connection_nano_id: z.string(),
+ trigger_nano_id: z.string(),
+ trigger_id: z.string(),
+ user_id: z.string(),
+ })
+ .passthrough(),
+});
+export type WebhookPayloadV2 = z.infer<typeof WebhookPayloadV2Schema>;
+
+/** V3 webhook payload - current format with metadata */
+export const WebhookPayloadV3Schema = z.object({
+ id: z.string(),
+ timestamp: z.string(),
+ type: z.literal('composio.trigger.message'),
+ metadata: z.object({
+ log_id: z.string(),
+ trigger_slug: z.string(),
+ trigger_id: z.string(),
+ connected_account_id: z.string(),
+ auth_config_id: z.string(),
+ user_id: z.string(),
+ }),
+ data: z.record(z.unknown()),
+});
+export type WebhookPayloadV3 = z.infer<typeof WebhookPayloadV3Schema>;
+
+/** Union of all webhook payload versions */
+export const WebhookPayloadSchema = z.union([
+ WebhookPayloadV3Schema,
+ WebhookPayloadV2Schema,
+ WebhookPayloadV1Schema,
+]);
+export type WebhookPayload = z.infer<typeof WebhookPayloadSchema>;
+
+/** Webhook version enum */
+export const WebhookVersions = {
+ V1: 'V1',
+ V2: 'V2',
+ V3: 'V3',
+} as const;
+export type WebhookVersion = (typeof WebhookVersions)[keyof typeof WebhookVersions];
+
/**
* Parameters for verifying a webhook signature
*/
export const VerifyWebhookParamsSchema = z.object({
+ /**
+ * The webhook message ID from the 'webhook-id' header.
+ * Format: 'msg_xxx'
+ */
+ id: z.string(),
/** 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 */
+ /** The webhook secret used to sign the payload (from Composio dashboard) */
secret: z.string(),
+ /**
+ * The signature from the 'webhook-signature' header.
+ * Format: 'v1,base64EncodedSignature'
+ */
+ signature: z.string(),
+ /**
+ * The webhook timestamp from the 'webhook-timestamp' header.
+ * This is the Unix timestamp in seconds when the webhook was sent.
+ */
+ timestamp: z.string(),
/**
* Maximum allowed age of the webhook in seconds.
* If the webhook timestamp is older than this, verification will fail.
@@ -217,6 +295,14 @@ export const VerifyWebhookParamsSchema = z.object({
export type VerifyWebhookParams = z.input<typeof VerifyWebhookParamsSchema>;
/**
- * Result of a successful webhook verification
+ * Result of a successful webhook verification.
+ * Contains the parsed payload along with version information.
*/
-export type VerifyWebhookResult = IncomingTriggerPayload;
+export type VerifyWebhookResult = {
+ /** The webhook version (V1, V2, or V3), from 'x-composio-webhook-version' */
+ version: WebhookVersion;
+ /** The parsed and normalized webhook payload */
+ payload: IncomingTriggerPayload;
+ /** The raw parsed payload before normalization */
+ rawPayload: WebhookPayload;
+};
diff --git a/ts/packages/core/test/models/verifyWebhook.test.ts b/ts/packages/core/test/models/verifyWebhook.test.ts
index e88e0af5d..5d93331a8 100644
--- a/ts/packages/core/test/models/verifyWebhook.test.ts
+++ b/ts/packages/core/test/models/verifyWebhook.test.ts
@@ -2,7 +2,12 @@ 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 {
+ WebhookPayloadV1,
+ WebhookPayloadV2,
+ WebhookPayloadV3,
+ WebhookVersions,
+} from '../../src/types/triggers.types';
import { ValidationError } from '../../src/errors';
import {
ComposioWebhookSignatureVerificationError,
@@ -40,32 +45,62 @@ const createMockClient = () => ({
},
});
-// Helper to create a valid signature
-const createSignature = (payload: string, secret: string): string => {
- return crypto.createHmac('sha256', secret).update(payload, 'utf8').digest('hex');
+/**
+ * Helper to create a valid webhook signature in the format used by Composio.
+ * Format: v1,base64(HMAC-SHA256(msgId.timestamp.payload, secret))
+ */
+const createSignature = (
+ webhookId: string,
+ webhookTimestamp: string,
+ payload: string,
+ secret: string
+): string => {
+ const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
+ const signature = crypto.createHmac('sha256', secret).update(toSign, 'utf8').digest('base64');
+ return `v1,${signature}`;
};
-// Mock trigger data that matches TriggerData structure
-const createMockTriggerData = (overrides: Partial<TriggerData> = {}): TriggerData => ({
- appName: 'github',
- clientId: 123,
+// Mock V1 webhook payload
+const createMockV1Payload = (overrides: Partial<WebhookPayloadV1> = {}): WebhookPayloadV1 => ({
+ trigger_name: 'GITHUB_PUSH_EVENT',
+ connection_id: 'conn-123',
+ trigger_id: 'trigger-123',
payload: { action: 'push', repository: 'test-repo' },
- originalPayload: { action: 'push', repository: 'test-repo' },
+ log_id: 'log-123',
+ ...overrides,
+});
+
+// Mock V2 webhook payload
+const createMockV2Payload = (overrides: Partial<WebhookPayloadV2> = {}): WebhookPayloadV2 => ({
+ type: 'github_push_event',
+ timestamp: new Date().toISOString(),
+ log_id: 'log-123',
+ data: {
+ connection_id: 'conn-123',
+ connection_nano_id: 'conn-nano-123',
+ trigger_nano_id: 'trigger-nano-123',
+ trigger_id: 'trigger-123',
+ user_id: 'user-456',
+ action: 'push',
+ repository: 'test-repo',
+ },
+ ...overrides,
+});
+
+// Mock V3 webhook payload
+const createMockV3Payload = (overrides: Partial<WebhookPayloadV3> = {}): WebhookPayloadV3 => ({
+ id: 'msg_abc123',
+ timestamp: new Date().toISOString(),
+ type: 'composio.trigger.message',
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',
- },
+ log_id: 'log-123',
+ trigger_slug: 'GITHUB_PUSH_EVENT',
+ trigger_id: 'trigger-nano-123',
+ connected_account_id: 'conn-nano-123',
+ auth_config_id: 'auth-nano-123',
+ user_id: 'user-456',
},
+ data: { action: 'push', repository: 'test-repo' },
...overrides,
});
@@ -73,6 +108,8 @@ describe('Triggers.verifyWebhook', () => {
let triggers: Triggers<any>;
let mockClient: ReturnType<typeof createMockClient>;
const testSecret = 'test-webhook-secret-12345';
+ const testWebhookId = 'msg_test123';
+ const testTimestamp = Math.floor(Date.now() / 1000).toString();
beforeEach(() => {
vi.clearAllMocks();
@@ -80,77 +117,129 @@ describe('Triggers.verifyWebhook', () => {
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);
+ describe('successful verification with V3 payload', () => {
+ it('should verify a valid V3 webhook payload and signature', () => {
+ const v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
const result = triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
});
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');
+ expect(result.version).toBe(WebhookVersions.V3);
+ expect(result.payload.triggerSlug).toBe('GITHUB_PUSH_EVENT');
+ expect(result.payload.userId).toBe('user-456');
+ expect(result.rawPayload).toEqual(v3Payload);
});
- 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);
+ it('should correctly normalize V3 payload to IncomingTriggerPayload format', () => {
+ const v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
const result = triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
- tolerance: 0,
+ id: testWebhookId,
+ timestamp: testTimestamp,
+ });
+
+ expect(result.payload.metadata.connectedAccount).toEqual({
+ id: 'conn-nano-123',
+ uuid: 'conn-nano-123',
+ authConfigId: 'auth-nano-123',
+ authConfigUUID: 'auth-nano-123',
+ userId: 'user-456',
+ status: 'ACTIVE',
+ });
+ });
+ });
+
+ describe('successful verification with V2 payload', () => {
+ it('should verify a valid V2 webhook payload and signature', () => {
+ const v2Payload = createMockV2Payload();
+ const payloadStr = JSON.stringify(v2Payload);
+ const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
+
+ const result = triggers.verifyWebhook({
+ payload: payloadStr,
+ signature,
+ secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
});
expect(result).toBeDefined();
- expect(result.triggerSlug).toBe('github_webhook');
+ expect(result.version).toBe(WebhookVersions.V2);
+ expect(result.payload.triggerSlug).toBe('GITHUB_PUSH_EVENT');
+ expect(result.payload.userId).toBe('user-456');
});
+ });
- it('should verify webhook with custom tolerance', () => {
- const triggerData = createMockTriggerData();
- const payload = JSON.stringify(triggerData);
- const signature = createSignature(payload, testSecret);
+ describe('successful verification with V1 payload', () => {
+ it('should verify a valid V1 webhook payload and signature', () => {
+ const v1Payload = createMockV1Payload();
+ const payloadStr = JSON.stringify(v1Payload);
+ const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
const result = triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
- tolerance: 600, // 10 minutes
+ id: testWebhookId,
+ timestamp: testTimestamp,
});
expect(result).toBeDefined();
+ expect(result.version).toBe(WebhookVersions.V1);
+ expect(result.payload.triggerSlug).toBe('GITHUB_PUSH_EVENT');
+ expect(result.payload.id).toBe('trigger-123');
});
+ });
- it('should correctly transform the payload to IncomingTriggerPayload format', () => {
- const triggerData = createMockTriggerData();
- const payload = JSON.stringify(triggerData);
- const signature = createSignature(payload, testSecret);
+ describe('tolerance settings', () => {
+ it('should verify webhook with tolerance set to 0 (skip timestamp validation)', () => {
+ const v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ // Use an old timestamp
+ const oldTimestamp = Math.floor((Date.now() - 60 * 60 * 1000) / 1000).toString();
+ const signature = createSignature(testWebhookId, oldTimestamp, payloadStr, testSecret);
const result = triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: oldTimestamp,
+ tolerance: 0,
});
- // Verify transformation
- expect(result.metadata.connectedAccount).toEqual({
- id: 'conn-123',
- uuid: 'conn-123',
- authConfigId: 'auth-123',
- authConfigUUID: 'github',
- userId: 'user-456',
- status: 'ACTIVE',
+ expect(result).toBeDefined();
+ expect(result.version).toBe(WebhookVersions.V3);
+ });
+
+ it('should verify webhook with custom tolerance', () => {
+ const v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
+
+ const result = triggers.verifyWebhook({
+ payload: payloadStr,
+ signature,
+ secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
+ tolerance: 600, // 10 minutes
});
+
+ expect(result).toBeDefined();
});
});
@@ -159,102 +248,197 @@ describe('Triggers.verifyWebhook', () => {
expect(() =>
triggers.verifyWebhook({
payload: '',
- signature: 'some-signature',
+ signature: 'v1,somesignature',
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow(ComposioWebhookSignatureVerificationError);
expect(() =>
triggers.verifyWebhook({
payload: '',
- signature: 'some-signature',
+ signature: 'v1,somesignature',
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow('No webhook payload was provided.');
});
it('should throw error when signature is empty', () => {
- const payload = JSON.stringify(createMockTriggerData());
+ const payloadStr = JSON.stringify(createMockV3Payload());
expect(() =>
triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature: '',
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow(ComposioWebhookSignatureVerificationError);
expect(() =>
triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature: '',
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow('No signature header value was provided.');
});
it('should throw error when secret is empty', () => {
- const payload = JSON.stringify(createMockTriggerData());
+ const payloadStr = JSON.stringify(createMockV3Payload());
expect(() =>
triggers.verifyWebhook({
- payload,
- signature: 'some-signature',
+ payload: payloadStr,
+ signature: 'v1,somesignature',
secret: '',
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow(ComposioWebhookSignatureVerificationError);
expect(() =>
triggers.verifyWebhook({
- payload,
- signature: 'some-signature',
+ payload: payloadStr,
+ signature: 'v1,somesignature',
secret: '',
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow('No webhook secret was provided.');
});
+ it('should throw error when webhookId is empty', () => {
+ const payloadStr = JSON.stringify(createMockV3Payload());
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: payloadStr,
+ signature: 'v1,somesignature',
+ secret: testSecret,
+ id: '',
+ timestamp: testTimestamp,
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: payloadStr,
+ signature: 'v1,somesignature',
+ secret: testSecret,
+ id: '',
+ timestamp: testTimestamp,
+ })
+ ).toThrow('No webhook ID was provided.');
+ });
+
+ it('should throw error when webhookTimestamp is empty', () => {
+ const payloadStr = JSON.stringify(createMockV3Payload());
+
+ // Empty timestamp is treated as invalid timestamp format (parseInt('') = NaN)
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: payloadStr,
+ signature: 'v1,somesignature',
+ secret: testSecret,
+ id: testWebhookId,
+ timestamp: '',
+ })
+ ).toThrow(ComposioWebhookPayloadError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: payloadStr,
+ signature: 'v1,somesignature',
+ secret: testSecret,
+ id: testWebhookId,
+ timestamp: '',
+ })
+ ).toThrow('Invalid webhook timestamp');
+ });
+
+ it('should throw error when signature format is invalid (no v1 prefix)', () => {
+ const payloadStr = JSON.stringify(createMockV3Payload());
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: payloadStr,
+ signature: 'invalid-signature-no-prefix',
+ secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
+ })
+ ).toThrow(ComposioWebhookSignatureVerificationError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: payloadStr,
+ signature: 'invalid-signature-no-prefix',
+ secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
+ })
+ ).toThrow('No valid v1 signature found');
+ });
+
it('should throw error when signature is invalid', () => {
- const payload = JSON.stringify(createMockTriggerData());
- const invalidSignature = 'invalid-signature-that-does-not-match';
+ const payloadStr = JSON.stringify(createMockV3Payload());
expect(() =>
triggers.verifyWebhook({
- payload,
- signature: invalidSignature,
+ payload: payloadStr,
+ signature: 'v1,invalidbase64signature==',
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow(ComposioWebhookSignatureVerificationError);
expect(() =>
triggers.verifyWebhook({
- payload,
- signature: invalidSignature,
+ payload: payloadStr,
+ signature: 'v1,invalidbase64signature==',
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).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');
+ const payloadStr = JSON.stringify(createMockV3Payload());
+ const signatureWithDifferentSecret = createSignature(
+ testWebhookId,
+ testTimestamp,
+ payloadStr,
+ 'different-secret'
+ );
expect(() =>
triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature: signatureWithDifferentSecret,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow(ComposioWebhookSignatureVerificationError);
});
it('should throw error when payload was modified after signing', () => {
- const originalPayload = JSON.stringify(createMockTriggerData());
- const signature = createSignature(originalPayload, testSecret);
+ const originalPayload = createMockV3Payload();
+ const payloadStr = JSON.stringify(originalPayload);
+ const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
- // Modify the payload after signing
const modifiedPayload = JSON.stringify({
- ...createMockTriggerData(),
- appName: 'modified-app',
+ ...originalPayload,
+ data: { modified: true },
});
expect(() =>
@@ -262,6 +446,8 @@ describe('Triggers.verifyWebhook', () => {
payload: modifiedPayload,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow(ComposioWebhookSignatureVerificationError);
});
@@ -270,13 +456,15 @@ describe('Triggers.verifyWebhook', () => {
describe('payload parsing errors', () => {
it('should throw error when payload is not valid JSON', () => {
const invalidJson = 'not-valid-json{';
- const signature = createSignature(invalidJson, testSecret);
+ const signature = createSignature(testWebhookId, testTimestamp, invalidJson, testSecret);
expect(() =>
triggers.verifyWebhook({
payload: invalidJson,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow(ComposioWebhookPayloadError);
@@ -285,136 +473,114 @@ describe('Triggers.verifyWebhook', () => {
payload: invalidJson,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).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);
+ it('should throw error for unrecognized payload format', () => {
+ const unknownPayload = JSON.stringify({ unknown: 'format' });
+ const signature = createSignature(testWebhookId, testTimestamp, unknownPayload, testSecret);
expect(() =>
triggers.verifyWebhook({
- payload: truncatedJson,
+ payload: unknownPayload,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).toThrow(ComposioWebhookPayloadError);
+
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: unknownPayload,
+ signature,
+ secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
+ })
+ ).toThrow('does not match any known version');
});
});
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
+ it('should pass when webhook timestamp is within tolerance', () => {
+ const v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ const recentTimestamp = Math.floor(Date.now() / 1000).toString();
+ const signature = createSignature(testWebhookId, recentTimestamp, payloadStr, testSecret);
+
const result = triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: recentTimestamp,
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);
+ it('should throw error when webhook timestamp is outside tolerance', () => {
+ const v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ // 10 minutes ago
+ const oldTimestamp = Math.floor((Date.now() - 10 * 60 * 1000) / 1000).toString();
+ const signature = createSignature(testWebhookId, oldTimestamp, payloadStr, testSecret);
expect(() =>
triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: oldTimestamp,
tolerance: 300, // 5 minutes
})
).toThrow(ComposioWebhookSignatureVerificationError);
expect(() =>
triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: oldTimestamp,
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);
+ const v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ const invalidTimestamp = 'not-a-timestamp';
+ const signature = createSignature(testWebhookId, invalidTimestamp, payloadStr, testSecret);
expect(() =>
triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: invalidTimestamp,
tolerance: 300,
})
).toThrow(ComposioWebhookPayloadError);
expect(() =>
triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: invalidTimestamp,
tolerance: 300,
})
- ).toThrow('Invalid timestamp in webhook payload');
+ ).toThrow('Invalid webhook timestamp');
});
});
@@ -422,8 +588,10 @@ describe('Triggers.verifyWebhook', () => {
it('should throw ValidationError for missing payload parameter', () => {
expect(() =>
triggers.verifyWebhook({
- signature: 'some-signature',
+ signature: 'v1,sig',
secret: testSecret,
+ webhookId: testWebhookId,
+ webhookTimestamp: testTimestamp,
} as any)
).toThrow(ValidationError);
});
@@ -433,6 +601,8 @@ describe('Triggers.verifyWebhook', () => {
triggers.verifyWebhook({
payload: '{}',
secret: testSecret,
+ webhookId: testWebhookId,
+ webhookTimestamp: testTimestamp,
} as any)
).toThrow(ValidationError);
});
@@ -441,112 +611,126 @@ describe('Triggers.verifyWebhook', () => {
expect(() =>
triggers.verifyWebhook({
payload: '{}',
- signature: 'some-signature',
+ signature: 'v1,sig',
+ webhookId: testWebhookId,
+ webhookTimestamp: testTimestamp,
} as any)
).toThrow(ValidationError);
});
- it('should throw ValidationError for invalid tolerance type', () => {
+ it('should throw ValidationError for missing webhookId parameter', () => {
expect(() =>
triggers.verifyWebhook({
payload: '{}',
- signature: 'some-signature',
+ signature: 'v1,sig',
secret: testSecret,
- tolerance: 'invalid' as any,
- })
+ webhookTimestamp: testTimestamp,
+ } 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,
- });
+ it('should throw ValidationError for missing webhookTimestamp parameter', () => {
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: '{}',
+ signature: 'v1,sig',
+ secret: testSecret,
+ webhookId: testWebhookId,
+ } as any)
+ ).toThrow(ValidationError);
+ });
- expect(result).toBeDefined();
+ it('should throw ValidationError for invalid tolerance type', () => {
+ expect(() =>
+ triggers.verifyWebhook({
+ payload: '{}',
+ signature: 'v1,sig',
+ secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
+ tolerance: 'invalid' as any,
+ })
+ ).toThrow(ValidationError);
});
});
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);
+ const v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ const validSignature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
// Valid signature should work
expect(() =>
triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature: validSignature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).not.toThrow();
- // Invalid signature with same length should fail
- const invalidSignature = 'a'.repeat(validSignature.length);
+ // Invalid signature with same format should fail
+ const invalidSignature = 'v1,' + 'a'.repeat(44); // base64 SHA256 is 44 chars
expect(() =>
triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
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,
+ id: testWebhookId,
+ timestamp: testTimestamp,
})
).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 v3Payload = createMockV3Payload({ data: { message: '你好世界 🌍 مرحبا' } });
+ const payloadStr = JSON.stringify(v3Payload);
+ const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
const result = triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
});
expect(result).toBeDefined();
- expect(result.payload).toEqual({ message: '你好世界 🌍 مرحبا' });
+ expect(result.payload.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 v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ const signature = createSignature(testWebhookId, testTimestamp, payloadStr, specialSecret);
const result = triggers.verifyWebhook({
- payload,
+ payload: payloadStr,
signature,
secret: specialSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
+ });
+
+ expect(result).toBeDefined();
+ });
+
+ it('should support multiple signatures in header', () => {
+ const v3Payload = createMockV3Payload();
+ const payloadStr = JSON.stringify(v3Payload);
+ const validSignature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
+ // Multiple signatures space-separated
+ const multipleSignatures = `v1,invalidsig== ${validSignature}`;
+
+ const result = triggers.verifyWebhook({
+ payload: payloadStr,
+ signature: multipleSignatures,
+ secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
});
expect(result).toBeDefined();
@@ -554,14 +738,16 @@ describe('Triggers.verifyWebhook', () => {
});
describe('error properties', () => {
- it('should include proper error code for signature verification error', () => {
- const payload = JSON.stringify(createMockTriggerData());
+ it('should include proper error class for signature verification error', () => {
+ const payloadStr = JSON.stringify(createMockV3Payload());
try {
triggers.verifyWebhook({
- payload,
- signature: 'invalid',
+ payload: payloadStr,
+ signature: 'v1,invalid',
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
});
expect.fail('Should have thrown');
} catch (error) {
@@ -572,15 +758,17 @@ describe('Triggers.verifyWebhook', () => {
}
});
- it('should include proper error code for payload error', () => {
+ it('should include proper error class for payload error', () => {
const invalidPayload = 'not-json';
- const signature = createSignature(invalidPayload, testSecret);
+ const signature = createSignature(testWebhookId, testTimestamp, invalidPayload, testSecret);
try {
triggers.verifyWebhook({
payload: invalidPayload,
signature,
secret: testSecret,
+ id: testWebhookId,
+ timestamp: testTimestamp,
});
expect.fail('Should have thrown');
} catch (error) {