@devries-cameron20 / composio-1 / commits / b28c2d7bb
Fork 0

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

fix(core): support v1, v2, v3 in `composio.triggers.verifyWebhooks` (#2361)

Co-authored-by: jkomyno <12381818+jkomyno@users.noreply.github.com>

Alberto Schiabel committed Jan 13, 2026 at 08:36 UTC b28c2d7bb1dd7cd936ef74851234ad003188d4be
12 files changed +2060 -521
python/composio/core/models/triggers.py
+359 -67
@@ -1,5 +1,6 @@
1 from __future__ import annotations
2
3 +import base64
4 import functools
5 import hashlib
6 import hmac
@@ -9,7 +10,7 @@ import traceback
10 import typing as t
11 import uuid
12 from concurrent.futures import ThreadPoolExecutor
12 -from datetime import datetime, timezone
13 +from enum import Enum
14 from unittest import mock
15
16 from composio_client.types import TriggersTypeRetrieveResponse
@@ -82,6 +83,57 @@ class _TriggerData(te.TypedDict):
83 originalPayload: t.Dict
84
85
86 +class WebhookVersion(str, Enum):
87 + """Webhook payload version."""
88 +
89 + V1 = "V1"
90 + V2 = "V2"
91 + V3 = "V3"
92 +
93 +
94 +class WebhookPayloadV1(te.TypedDict):
95 + """V1 webhook payload structure."""
96 +
97 + trigger_name: str
98 + connection_id: str
99 + trigger_id: str
100 + payload: t.Dict[str, t.Any]
101 + log_id: str
102 +
103 +
104 +class WebhookPayloadV2(te.TypedDict):
105 + """V2 webhook payload structure."""
106 +
107 + type: str
108 + timestamp: str
109 + log_id: str
110 + data: t.Dict[str, t.Any]
111 +
112 +
113 +class WebhookPayloadV3Metadata(te.TypedDict):
114 + """V3 webhook payload metadata."""
115 +
116 + log_id: str
117 + trigger_slug: str
118 + trigger_id: str
119 + connected_account_id: str
120 + auth_config_id: str
121 + user_id: str
122 +
123 +
124 +class WebhookPayloadV3(te.TypedDict):
125 + """V3 webhook payload structure."""
126 +
127 + id: str
128 + timestamp: str
129 + type: t.Literal["composio.trigger.message"]
130 + metadata: WebhookPayloadV3Metadata
131 + data: t.Dict[str, t.Any]
132 +
133 +
134 +WebhookPayload = t.Union[WebhookPayloadV1, WebhookPayloadV2, WebhookPayloadV3]
135 +
136 +
137 class TriggerConnectedAccountSchema(t.TypedDict):
138 id: str
139 uuid: str
@@ -115,6 +167,14 @@ class TriggerEvent(t.TypedDict):
167 ] # The original payload of the trigger
168
169
170 +class VerifyWebhookResult(t.TypedDict):
171 + """Result of webhook verification."""
172 +
173 + version: WebhookVersion # The webhook version (V1, V2, or V3)
174 + payload: TriggerEvent # The parsed and normalized webhook payload
175 + raw_payload: WebhookPayload # The original parsed payload
176 +
177 +
178 _ = {
179 "appName": "github",
180 "payload": {
@@ -808,24 +868,30 @@ class Triggers(Resource):
868
869 def verify_webhook(
870 self,
871 + *,
872 + id: str,
873 payload: str,
812 - signature: str,
874 secret: str,
875 + signature: str,
876 + timestamp: str,
877 tolerance: int = 300,
815 - ) -> TriggerEvent:
878 + ) -> VerifyWebhookResult:
879 """
880 Verify an incoming webhook payload and signature.
881
882 This method validates that the webhook request is authentic by:
820 - 1. Verifying the HMAC-SHA256 signature matches the payload
821 - 2. Optionally checking that the webhook timestamp is within the tolerance window
883 + 1. Validating the webhook timestamp is within the tolerance window
884 + 2. Verifying the HMAC-SHA256 signature using the correct algorithm
885 + 3. Parsing the payload and detecting the webhook version (V1, V2, or V3)
886
887 + :param id: The webhook message ID from the 'webhook-id' header (format: 'msg_xxx')
888 :param payload: The raw webhook payload as a string (request body)
824 - :param signature: The signature from the webhook header (e.g., 'x-composio-signature')
825 - :param secret: The webhook secret used to sign the payload
889 + :param secret: The webhook secret used to sign the payload (from Composio dashboard)
890 + :param signature: The signature from the 'webhook-signature' header (format: 'v1,base64EncodedSignature')
891 + :param timestamp: The webhook timestamp from the 'webhook-timestamp' header (Unix seconds)
892 :param tolerance: Maximum allowed age of the webhook in seconds (default: 300 = 5 minutes).
893 Set to 0 to disable timestamp validation.
828 - :return: The verified and parsed webhook payload as a TriggerEvent
894 + :return: VerifyWebhookResult containing version, normalized payload, and raw payload
895 :raises WebhookSignatureVerificationError: If the signature verification fails
896 :raises WebhookPayloadError: If the payload cannot be parsed or is invalid
897
@@ -834,46 +900,62 @@ class Triggers(Resource):
900 @app.route('/webhook', methods=['POST'])
901 def webhook():
902 try:
837 - event = composio.triggers.verify_webhook(
903 + result = composio.triggers.verify_webhook(
904 + id=request.headers.get('webhook-id', ''),
905 payload=request.get_data(as_text=True),
839 - signature=request.headers.get('x-composio-signature', ''),
906 + signature=request.headers.get('webhook-signature', ''),
907 + timestamp=request.headers.get('webhook-timestamp', ''),
908 secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
909 )
910
911 # Process the verified payload
844 - print(f"Received trigger: {event['trigger_slug']}")
912 + print(f"Version: {result['version']}")
913 + print(f"Received trigger: {result['payload']['trigger_slug']}")
914 return 'OK', 200
915 except WebhookSignatureVerificationError:
916 return 'Unauthorized', 401
917 """
849 - # Verify signature
850 - self._verify_webhook_signature(payload, signature, secret)
851 -
852 - # Parse and validate payload
853 - try:
854 - data = t.cast(_TriggerData, json.loads(payload))
855 - except json.JSONDecodeError as e:
856 - raise exceptions.WebhookPayloadError(
857 - f"Failed to parse webhook payload as JSON: {e}"
858 - ) from e
859 -
860 - # Transform to TriggerEvent format
861 - event = self._transform_trigger_data(data)
862 -
918 # Validate timestamp if tolerance is set
919 if tolerance > 0:
865 - self._validate_webhook_timestamp(data, tolerance)
920 + self._validate_webhook_timestamp_header(timestamp, tolerance)
921 +
922 + # Verify signature using the correct algorithm
923 + self._verify_webhook_signature(
924 + webhook_id=id,
925 + webhook_timestamp=timestamp,
926 + payload=payload,
927 + signature=signature,
928 + secret=secret,
929 + )
930 +
931 + # Parse and detect version
932 + version, raw_payload, normalized_payload = self._parse_webhook_payload(payload)
933
867 - return event
934 + return {
935 + "version": version,
936 + "payload": normalized_payload,
937 + "raw_payload": raw_payload,
938 + }
939
940 def _verify_webhook_signature(
870 - self, payload: str, signature: str, secret: str
941 + self,
942 + *,
943 + webhook_id: str,
944 + webhook_timestamp: str,
945 + payload: str,
946 + signature: str,
947 + secret: str,
948 ) -> None:
949 """
950 Verify the HMAC-SHA256 signature of a webhook payload.
951
952 + The signature is computed as: HMAC-SHA256(webhookId.webhookTimestamp.payload, secret)
953 + and then base64 encoded with a 'v1,' prefix.
954 +
955 + :param webhook_id: The webhook message ID from header
956 + :param webhook_timestamp: The webhook timestamp from header
957 :param payload: The raw webhook payload
876 - :param signature: The signature to verify
958 + :param signature: The signature to verify (format: 'v1,base64EncodedSignature')
959 :param secret: The webhook secret
960 :raises WebhookSignatureVerificationError: If verification fails
961 """
@@ -894,65 +976,275 @@ class Triggers(Resource):
976 "You can find your webhook secret in your Composio dashboard."
977 )
978
897 - expected_signature = hmac.new(
898 - key=secret.encode("utf-8"),
899 - msg=payload.encode("utf-8"),
900 - digestmod=hashlib.sha256,
901 - ).hexdigest()
979 + if not webhook_id:
980 + raise exceptions.WebhookSignatureVerificationError(
981 + "No webhook ID was provided. "
982 + "Please pass the value of the 'webhook-id' header."
983 + )
984 +
985 + if not webhook_timestamp:
986 + raise exceptions.WebhookSignatureVerificationError(
987 + "No webhook timestamp was provided. "
988 + "Please pass the value of the 'webhook-timestamp' header."
989 + )
990 +
991 + # Parse signature header - format is "v1,base64Sig" or "v1,sig1 v1,sig2"
992 + # Split by space to handle multiple signatures
993 + signature_parts = signature.split(" ")
994 + v1_signatures: t.List[str] = []
995
903 - # Use timing-safe comparison to prevent timing attacks
904 - if not hmac.compare_digest(signature, expected_signature):
996 + for part in signature_parts:
997 + if part.startswith("v1,"):
998 + v1_signatures.append(part[3:]) # Remove "v1," prefix
999 +
1000 + if not v1_signatures:
1001 raise exceptions.WebhookSignatureVerificationError(
906 - "The signature provided is invalid."
1002 + "No valid v1 signature found in the signature header. "
1003 + "Expected format: 'v1,base64EncodedSignature'"
1004 )
1005
909 - def _validate_webhook_timestamp(self, data: _TriggerData, tolerance: int) -> None:
1006 + # Construct the string to sign: webhookId.webhookTimestamp.payload
1007 + to_sign = f"{webhook_id}.{webhook_timestamp}.{payload}"
1008 +
1009 + # Compute expected signature
1010 + expected_signature_bytes = hmac.new(
1011 + key=secret.encode("utf-8"),
1012 + msg=to_sign.encode("utf-8"),
1013 + digestmod=hashlib.sha256,
1014 + ).digest()
1015 + expected_signature_b64 = base64.b64encode(expected_signature_bytes).decode(
1016 + "utf-8"
1017 + )
1018 +
1019 + # Check if any of the provided signatures match (timing-safe)
1020 + for provided_sig in v1_signatures:
1021 + try:
1022 + if hmac.compare_digest(provided_sig, expected_signature_b64):
1023 + return # Signature is valid
1024 + except Exception:
1025 + continue # Invalid signature format, try next
1026 +
1027 + raise exceptions.WebhookSignatureVerificationError(
1028 + "The signature provided is invalid."
1029 + )
1030 +
1031 + def _validate_webhook_timestamp_header(
1032 + self, timestamp: str, tolerance: int
1033 + ) -> None:
1034 """
911 - Validate that the webhook timestamp is within the allowed tolerance.
1035 + Validate that the webhook timestamp header is within the allowed tolerance.
1036
913 - :param data: The parsed trigger data
1037 + :param timestamp: The webhook timestamp from header (Unix seconds)
1038 :param tolerance: Maximum allowed age in seconds
1039 :raises WebhookSignatureVerificationError: If timestamp is outside tolerance
1040 :raises WebhookPayloadError: If timestamp format is invalid
1041 """
918 - # Check for timestamp in various locations
919 - timestamp_str: t.Optional[str] = None
920 -
921 - # Check root level
922 - if "timestamp" in data: # type: ignore
923 - timestamp_str = data.get("timestamp") # type: ignore
924 - elif "webhookTimestamp" in data: # type: ignore
925 - timestamp_str = data.get("webhookTimestamp") # type: ignore
926 - # Check metadata level
927 - elif "metadata" in data and "timestamp" in data["metadata"]: # type: ignore
928 - timestamp_str = data["metadata"].get("timestamp") # type: ignore
929 -
930 - if timestamp_str is None:
931 - # If no timestamp is present, skip validation for backwards compatibility
932 - return
933 -
1042 try:
935 - # Parse ISO 8601 timestamp
936 - webhook_time = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00"))
937 - # Ensure timezone-aware comparison
938 - if webhook_time.tzinfo is None:
939 - webhook_time = webhook_time.replace(tzinfo=timezone.utc)
940 - except (ValueError, AttributeError) as e:
1043 + timestamp_seconds = int(timestamp)
1044 + except (ValueError, TypeError) as e:
1045 raise exceptions.WebhookPayloadError(
942 - f"Invalid timestamp in webhook payload: {timestamp_str}. "
943 - "Expected ISO 8601 format."
1046 + f"Invalid webhook timestamp: {timestamp}. "
1047 + "Expected Unix timestamp in seconds."
1048 ) from e
1049
946 - current_time = datetime.now(timezone.utc)
947 - time_difference = abs((current_time - webhook_time).total_seconds())
1050 + current_time = int(time.time())
1051 + time_difference = abs(current_time - timestamp_seconds)
1052
1053 if time_difference > tolerance:
1054 raise exceptions.WebhookSignatureVerificationError(
1055 f"The webhook timestamp is outside the allowed tolerance. "
952 - f"The webhook was sent {int(time_difference)} seconds ago, "
1056 + f"The webhook was sent {time_difference} seconds ago, "
1057 f"but the maximum allowed age is {tolerance} seconds."
1058 )
1059
1060 + def _parse_webhook_payload(
1061 + self, payload: str
1062 + ) -> t.Tuple[WebhookVersion, WebhookPayload, TriggerEvent]:
1063 + """
1064 + Parse webhook payload and detect version.
1065 +
1066 + :param payload: The raw webhook payload string
1067 + :return: Tuple of (version, raw_payload, normalized_payload)
1068 + :raises WebhookPayloadError: If payload cannot be parsed
1069 + """
1070 + try:
1071 + data = json.loads(payload)
1072 + except json.JSONDecodeError as e:
1073 + raise exceptions.WebhookPayloadError(
1074 + f"Failed to parse webhook payload as JSON: {e}"
1075 + ) from e
1076 +
1077 + # Try V3 first (has 'type' === 'composio.trigger.message' and 'metadata')
1078 + # Validate metadata is a dict with all required fields (matching TypeScript's zod schema)
1079 + v3_metadata = data.get("metadata") if isinstance(data, dict) else None
1080 + v3_metadata_valid = (
1081 + isinstance(v3_metadata, dict)
1082 + and "log_id" in v3_metadata
1083 + and "trigger_slug" in v3_metadata
1084 + and "trigger_id" in v3_metadata
1085 + and "connected_account_id" in v3_metadata
1086 + and "auth_config_id" in v3_metadata
1087 + and "user_id" in v3_metadata
1088 + )
1089 + if (
1090 + isinstance(data, dict)
1091 + and data.get("type") == "composio.trigger.message"
1092 + and v3_metadata_valid
1093 + and "id" in data
1094 + and "data" in data
1095 + ):
1096 + return (
1097 + WebhookVersion.V3,
1098 + t.cast(WebhookPayloadV3, data),
1099 + self._normalize_v3_payload(t.cast(WebhookPayloadV3, data)),
1100 + )
1101 +
1102 + # Try V2 (has 'type', 'timestamp', 'data' with nested fields)
1103 + if (
1104 + isinstance(data, dict)
1105 + and "type" in data
1106 + and "timestamp" in data
1107 + and "data" in data
1108 + and isinstance(data.get("data"), dict)
1109 + and "connection_id" in data.get("data", {})
1110 + ):
1111 + return (
1112 + WebhookVersion.V2,
1113 + t.cast(WebhookPayloadV2, data),
1114 + self._normalize_v2_payload(t.cast(WebhookPayloadV2, data)),
1115 + )
1116 +
1117 + # Try V1 (has 'trigger_name', 'connection_id', 'trigger_id', 'payload')
1118 + if (
1119 + isinstance(data, dict)
1120 + and "trigger_name" in data
1121 + and "connection_id" in data
1122 + and "trigger_id" in data
1123 + and "payload" in data
1124 + ):
1125 + return (
1126 + WebhookVersion.V1,
1127 + t.cast(WebhookPayloadV1, data),
1128 + self._normalize_v1_payload(t.cast(WebhookPayloadV1, data)),
1129 + )
1130 +
1131 + raise exceptions.WebhookPayloadError(
1132 + "Webhook payload does not match any known version (V1, V2, or V3). "
1133 + "Please ensure the payload structure is correct."
1134 + )
1135 +
1136 + def _normalize_v1_payload(self, data: WebhookPayloadV1) -> TriggerEvent:
1137 + """Normalize V1 payload to TriggerEvent format."""
1138 + return t.cast(
1139 + TriggerEvent,
1140 + {
1141 + "id": data["trigger_id"],
1142 + "uuid": data["trigger_id"],
1143 + "user_id": "", # V1 doesn't have user_id
1144 + "toolkit_slug": "", # V1 doesn't have toolkit_slug
1145 + "trigger_slug": data["trigger_name"],
1146 + "metadata": {
1147 + "id": data["trigger_id"],
1148 + "uuid": data["trigger_id"],
1149 + "toolkit_slug": "",
1150 + "trigger_slug": data["trigger_name"],
1151 + "trigger_data": None,
1152 + "trigger_config": {},
1153 + "connected_account": {
1154 + "id": data["connection_id"],
1155 + "uuid": data["connection_id"],
1156 + "auth_config_id": "",
1157 + "auth_config_uuid": "",
1158 + "user_id": "",
1159 + "status": "ACTIVE",
1160 + },
1161 + },
1162 + "payload": data["payload"],
1163 + "original_payload": None,
1164 + },
1165 + )
1166 +
1167 + def _normalize_v2_payload(self, data: WebhookPayloadV2) -> TriggerEvent:
1168 + """Normalize V2 payload to TriggerEvent format."""
1169 + payload_data = data["data"]
1170 + return t.cast(
1171 + TriggerEvent,
1172 + {
1173 + "id": payload_data.get(
1174 + "trigger_nano_id", payload_data.get("trigger_id", "")
1175 + ),
1176 + "uuid": payload_data.get("trigger_id", ""),
1177 + "user_id": payload_data.get("user_id", ""),
1178 + "toolkit_slug": data["type"].upper() if data.get("type") else "",
1179 + "trigger_slug": data["type"].upper() if data.get("type") else "",
1180 + "metadata": {
1181 + "id": payload_data.get("trigger_nano_id", ""),
1182 + "uuid": payload_data.get("trigger_id", ""),
1183 + "toolkit_slug": data["type"].upper() if data.get("type") else "",
1184 + "trigger_slug": data["type"].upper() if data.get("type") else "",
1185 + "trigger_data": None,
1186 + "trigger_config": {},
1187 + "connected_account": {
1188 + "id": payload_data.get("connection_nano_id", ""),
1189 + "uuid": payload_data.get("connection_id", ""),
1190 + "auth_config_id": "",
1191 + "auth_config_uuid": "",
1192 + "user_id": payload_data.get("user_id", ""),
1193 + "status": "ACTIVE",
1194 + },
1195 + },
1196 + "payload": {
1197 + k: v
1198 + for k, v in payload_data.items()
1199 + if k
1200 + not in (
1201 + "connection_id",
1202 + "connection_nano_id",
1203 + "trigger_nano_id",
1204 + "trigger_id",
1205 + "user_id",
1206 + )
1207 + },
1208 + "original_payload": None,
1209 + },
1210 + )
1211 +
1212 + def _normalize_v3_payload(self, data: WebhookPayloadV3) -> TriggerEvent:
1213 + """Normalize V3 payload to TriggerEvent format."""
1214 + metadata = data["metadata"]
1215 + return t.cast(
1216 + TriggerEvent,
1217 + {
1218 + "id": metadata["trigger_id"],
1219 + "uuid": metadata["trigger_id"],
1220 + "user_id": metadata["user_id"],
1221 + "toolkit_slug": metadata["trigger_slug"].split("_")[0].upper()
1222 + if "_" in metadata["trigger_slug"]
1223 + else "UNKNOWN",
1224 + "trigger_slug": metadata["trigger_slug"],
1225 + "metadata": {
1226 + "id": metadata["trigger_id"],
1227 + "uuid": metadata["trigger_id"],
1228 + "toolkit_slug": metadata["trigger_slug"].split("_")[0].upper()
1229 + if "_" in metadata["trigger_slug"]
1230 + else "UNKNOWN",
1231 + "trigger_slug": metadata["trigger_slug"],
1232 + "trigger_data": None,
1233 + "trigger_config": {},
1234 + "connected_account": {
1235 + "id": metadata["connected_account_id"],
1236 + "uuid": metadata["connected_account_id"],
1237 + "auth_config_id": metadata["auth_config_id"],
1238 + "auth_config_uuid": metadata["auth_config_id"],
1239 + "user_id": metadata["user_id"],
1240 + "status": "ACTIVE",
1241 + },
1242 + },
1243 + "payload": data["data"],
1244 + "original_payload": None,
1245 + },
1246 + )
1247 +
1248 def _transform_trigger_data(self, data: _TriggerData) -> TriggerEvent:
1249 """
1250 Transform raw trigger data to TriggerEvent format.
python/examples/triggers.py
+24
@@ -53,6 +53,30 @@ print(enabled_instance)
53 deleted_instance = composio.triggers.delete(trigger_id="123")
54 print(deleted_instance)
55
56 +
57 +# Verify a webhook (example in Flask)
58 +# @app.route('/webhook', methods=['POST'])
59 +# def webhook():
60 +# try:
61 +# result = composio.triggers.verify_webhook(
62 +# id=request.headers.get('webhook-id', ''),
63 +# payload=request.get_data(as_text=True),
64 +# signature=request.headers.get('webhook-signature', ''),
65 +# timestamp=request.headers.get('webhook-timestamp', ''),
66 +# secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
67 +# )
68 +#
69 +# # Result contains:
70 +# # - version: WebhookVersion (V1, V2, or V3)
71 +# # - payload: Normalized TriggerEvent
72 +# # - raw_payload: Original parsed payload
73 +# print(f"Webhook version: {result['version']}")
74 +# print(f"Trigger: {result['payload']['trigger_slug']}")
75 +# return 'OK', 200
76 +# except WebhookSignatureVerificationError:
77 +# return 'Unauthorized', 401
78 +
79 +
80 # Subscribe to a trigger
81 subscription = composio.triggers.subscribe()
82
python/tests/test_triggers.py
+389 -176
@@ -1,13 +1,15 @@
1 """Tests for Triggers class."""
2
3 +import base64
4 import hashlib
5 import hmac
6 import json
7 +import time
8 import pytest
7 -from datetime import datetime, timedelta, timezone
9 +from datetime import datetime, timezone
10 from unittest.mock import Mock, patch
11 from composio_client import omit
10 -from composio.core.models.triggers import Triggers
12 +from composio.core.models.triggers import Triggers, WebhookVersion
13 from composio import exceptions
14
15
@@ -453,408 +455,619 @@ class TestVerifyWebhook:
455 return "test-webhook-secret-12345"
456
457 @pytest.fixture
456 - def mock_trigger_data(self):
457 - """Create mock trigger data matching _TriggerData structure."""
458 + def test_webhook_id(self):
459 + """Test webhook ID."""
460 + return "msg_test123"
461 +
462 + @pytest.fixture
463 + def test_timestamp(self):
464 + """Test webhook timestamp (current time in Unix seconds)."""
465 + return str(int(time.time()))
466 +
467 + @pytest.fixture
468 + def mock_v1_payload(self):
469 + """Create mock V1 webhook payload."""
470 return {
459 - "appName": "github",
460 - "clientId": 123,
471 + "trigger_name": "GITHUB_PUSH_EVENT",
472 + "connection_id": "conn-123",
473 + "trigger_id": "trigger-123",
474 "payload": {"action": "push", "repository": "test-repo"},
462 - "originalPayload": {"action": "push", "repository": "test-repo"},
475 + "log_id": "log-123",
476 + }
477 +
478 + @pytest.fixture
479 + def mock_v2_payload(self):
480 + """Create mock V2 webhook payload."""
481 + return {
482 + "type": "github_push_event",
483 + "timestamp": datetime.now(timezone.utc).isoformat(),
484 + "log_id": "log-123",
485 + "data": {
486 + "connection_id": "conn-123",
487 + "connection_nano_id": "conn-nano-123",
488 + "trigger_nano_id": "trigger-nano-123",
489 + "trigger_id": "trigger-123",
490 + "user_id": "user-456",
491 + "action": "push",
492 + "repository": "test-repo",
493 + },
494 + }
495 +
496 + @pytest.fixture
497 + def mock_v3_payload(self):
498 + """Create mock V3 webhook payload."""
499 + return {
500 + "id": "evt-123",
501 + "timestamp": datetime.now(timezone.utc).isoformat(),
502 + "type": "composio.trigger.message",
503 "metadata": {
464 - "id": "trigger-123",
465 - "nanoId": "trigger-123-nano",
466 - "triggerName": "GITHUB_COMMIT_EVENT",
467 - "triggerData": '{"action":"push"}',
468 - "triggerConfig": {"webhook_url": "https://example.com/webhook"},
469 - "connection": {
470 - "id": "conn-123",
471 - "connectedAccountNanoId": "conn-123-nano",
472 - "integrationId": "github-integration",
473 - "authConfigNanoId": "auth-123",
474 - "clientUniqueUserId": "user-456",
475 - "status": "ACTIVE",
476 - },
504 + "log_id": "log-123",
505 + "trigger_slug": "GITHUB_PUSH_EVENT",
506 + "trigger_id": "trigger-nano-123",
507 + "connected_account_id": "conn-nano-123",
508 + "auth_config_id": "auth-nano-123",
509 + "user_id": "user-456",
510 },
511 + "data": {"action": "push", "repository": "test-repo"},
512 }
513
480 - def create_signature(self, payload: str, secret: str) -> str:
481 - """Helper to create a valid HMAC-SHA256 signature."""
482 - return hmac.new(
514 + def create_signature(
515 + self, webhook_id: str, timestamp: str, payload: str, secret: str
516 + ) -> str:
517 + """Helper to create a valid v1,base64 signature."""
518 + to_sign = f"{webhook_id}.{timestamp}.{payload}"
519 + signature_bytes = hmac.new(
520 key=secret.encode("utf-8"),
484 - msg=payload.encode("utf-8"),
521 + msg=to_sign.encode("utf-8"),
522 digestmod=hashlib.sha256,
486 - ).hexdigest()
523 + ).digest()
524 + return f"v1,{base64.b64encode(signature_bytes).decode('utf-8')}"
525
488 - # Successful verification tests
526 + # Successful verification tests with V3 payload
527
490 - def test_verify_webhook_valid_payload_and_signature(
491 - self, triggers, test_secret, mock_trigger_data
528 + def test_verify_webhook_v3_payload(
529 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
530 ):
493 - """Test successful webhook verification."""
494 - payload = json.dumps(mock_trigger_data)
495 - signature = self.create_signature(payload, test_secret)
531 + """Test successful V3 webhook verification."""
532 + payload = json.dumps(mock_v3_payload)
533 + signature = self.create_signature(
534 + test_webhook_id, test_timestamp, payload, test_secret
535 + )
536
537 result = triggers.verify_webhook(
538 + id=test_webhook_id,
539 payload=payload,
540 signature=signature,
541 + timestamp=test_timestamp,
542 secret=test_secret,
543 )
544
503 - assert result["id"] == "trigger-123-nano"
504 - assert result["uuid"] == "trigger-123"
505 - assert result["trigger_slug"] == "GITHUB_COMMIT_EVENT"
506 - assert result["toolkit_slug"] == "github"
507 - assert result["user_id"] == "user-456"
545 + assert result["version"] == WebhookVersion.V3
546 + assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT"
547 + assert result["payload"]["user_id"] == "user-456"
548 + assert result["raw_payload"] == mock_v3_payload
549
509 - def test_verify_webhook_with_tolerance_zero(
510 - self, triggers, test_secret, mock_trigger_data
550 + def test_verify_webhook_v3_normalizes_payload(
551 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
552 ):
512 - """Test webhook verification with tolerance set to 0 (skip timestamp validation)."""
513 - payload = json.dumps(mock_trigger_data)
514 - signature = self.create_signature(payload, test_secret)
553 + """Test V3 payload normalization."""
554 + payload = json.dumps(mock_v3_payload)
555 + signature = self.create_signature(
556 + test_webhook_id, test_timestamp, payload, test_secret
557 + )
558
559 result = triggers.verify_webhook(
560 + id=test_webhook_id,
561 payload=payload,
562 signature=signature,
563 + timestamp=test_timestamp,
564 secret=test_secret,
520 - tolerance=0,
565 )
566
523 - assert result["trigger_slug"] == "GITHUB_COMMIT_EVENT"
567 + assert (
568 + result["payload"]["metadata"]["connected_account"]["id"] == "conn-nano-123"
569 + )
570 + assert (
571 + result["payload"]["metadata"]["connected_account"]["auth_config_id"]
572 + == "auth-nano-123"
573 + )
574 + assert (
575 + result["payload"]["metadata"]["connected_account"]["user_id"] == "user-456"
576 + )
577 +
578 + # Successful verification with V2 payload
579
525 - def test_verify_webhook_with_custom_tolerance(
526 - self, triggers, test_secret, mock_trigger_data
580 + def test_verify_webhook_v2_payload(
581 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v2_payload
582 ):
528 - """Test webhook verification with custom tolerance."""
529 - payload = json.dumps(mock_trigger_data)
530 - signature = self.create_signature(payload, test_secret)
583 + """Test successful V2 webhook verification."""
584 + payload = json.dumps(mock_v2_payload)
585 + signature = self.create_signature(
586 + test_webhook_id, test_timestamp, payload, test_secret
587 + )
588
589 result = triggers.verify_webhook(
590 + id=test_webhook_id,
591 payload=payload,
592 signature=signature,
593 + timestamp=test_timestamp,
594 secret=test_secret,
536 - tolerance=600, # 10 minutes
595 )
596
539 - assert result is not None
597 + assert result["version"] == WebhookVersion.V2
598 + assert result["payload"]["user_id"] == "user-456"
599
541 - def test_verify_webhook_transforms_payload_correctly(
542 - self, triggers, test_secret, mock_trigger_data
600 + # Successful verification with V1 payload
601 +
602 + def test_verify_webhook_v1_payload(
603 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v1_payload
604 ):
544 - """Test that payload is correctly transformed to TriggerEvent format."""
545 - payload = json.dumps(mock_trigger_data)
546 - signature = self.create_signature(payload, test_secret)
605 + """Test successful V1 webhook verification."""
606 + payload = json.dumps(mock_v1_payload)
607 + signature = self.create_signature(
608 + test_webhook_id, test_timestamp, payload, test_secret
609 + )
610
611 result = triggers.verify_webhook(
612 + id=test_webhook_id,
613 payload=payload,
614 signature=signature,
615 + timestamp=test_timestamp,
616 secret=test_secret,
617 )
618
554 - # Verify transformation
555 - assert result["metadata"]["connected_account"]["id"] == "conn-123-nano"
556 - assert result["metadata"]["connected_account"]["uuid"] == "conn-123"
557 - assert result["metadata"]["connected_account"]["auth_config_id"] == "auth-123"
558 - assert (
559 - result["metadata"]["connected_account"]["auth_config_uuid"]
560 - == "github-integration"
619 + assert result["version"] == WebhookVersion.V1
620 + assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT"
621 + assert result["payload"]["id"] == "trigger-123"
622 +
623 + # Tolerance tests
624 +
625 + def test_verify_webhook_with_tolerance_zero(
626 + self, triggers, test_secret, test_webhook_id, mock_v3_payload
627 + ):
628 + """Test webhook verification with tolerance set to 0 (skip timestamp validation)."""
629 + # Use an old timestamp (1 hour ago)
630 + old_timestamp = str(int(time.time()) - 3600)
631 + payload = json.dumps(mock_v3_payload)
632 + signature = self.create_signature(
633 + test_webhook_id, old_timestamp, payload, test_secret
634 + )
635 +
636 + result = triggers.verify_webhook(
637 + id=test_webhook_id,
638 + payload=payload,
639 + signature=signature,
640 + timestamp=old_timestamp,
641 + secret=test_secret,
642 + tolerance=0,
643 + )
644 +
645 + assert result["version"] == WebhookVersion.V3
646 +
647 + def test_verify_webhook_with_custom_tolerance(
648 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
649 + ):
650 + """Test webhook verification with custom tolerance."""
651 + payload = json.dumps(mock_v3_payload)
652 + signature = self.create_signature(
653 + test_webhook_id, test_timestamp, payload, test_secret
654 + )
655 +
656 + result = triggers.verify_webhook(
657 + id=test_webhook_id,
658 + payload=payload,
659 + signature=signature,
660 + timestamp=test_timestamp,
661 + secret=test_secret,
662 + tolerance=600, # 10 minutes
663 )
562 - assert result["metadata"]["connected_account"]["user_id"] == "user-456"
563 - assert result["metadata"]["connected_account"]["status"] == "ACTIVE"
664 +
665 + assert result is not None
666
667 # Signature verification error tests
668
567 - def test_verify_webhook_empty_payload_raises_error(self, triggers, test_secret):
669 + def test_verify_webhook_empty_payload_raises_error(
670 + self, triggers, test_secret, test_webhook_id, test_timestamp
671 + ):
672 """Test that empty payload raises WebhookSignatureVerificationError."""
673 with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
674 triggers.verify_webhook(
675 + id=test_webhook_id,
676 payload="",
572 - signature="some-signature",
677 + signature="v1,somesignature",
678 + timestamp=test_timestamp,
679 secret=test_secret,
680 )
681
682 assert "No webhook payload was provided" in str(exc_info.value)
683
684 def test_verify_webhook_empty_signature_raises_error(
579 - self, triggers, test_secret, mock_trigger_data
685 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
686 ):
687 """Test that empty signature raises WebhookSignatureVerificationError."""
582 - payload = json.dumps(mock_trigger_data)
688 + payload = json.dumps(mock_v3_payload)
689
690 with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
691 triggers.verify_webhook(
692 + id=test_webhook_id,
693 payload=payload,
694 signature="",
695 + timestamp=test_timestamp,
696 secret=test_secret,
697 )
698
699 assert "No signature header value was provided" in str(exc_info.value)
700
701 def test_verify_webhook_empty_secret_raises_error(
594 - self, triggers, mock_trigger_data
702 + self, triggers, test_webhook_id, test_timestamp, mock_v3_payload
703 ):
704 """Test that empty secret raises WebhookSignatureVerificationError."""
597 - payload = json.dumps(mock_trigger_data)
705 + payload = json.dumps(mock_v3_payload)
706
707 with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
708 triggers.verify_webhook(
709 + id=test_webhook_id,
710 payload=payload,
602 - signature="some-signature",
711 + signature="v1,somesignature",
712 + timestamp=test_timestamp,
713 secret="",
714 )
715
716 assert "No webhook secret was provided" in str(exc_info.value)
717
718 + def test_verify_webhook_empty_webhook_id_raises_error(
719 + self, triggers, test_secret, test_timestamp, mock_v3_payload
720 + ):
721 + """Test that empty webhook ID raises WebhookSignatureVerificationError."""
722 + payload = json.dumps(mock_v3_payload)
723 +
724 + with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
725 + triggers.verify_webhook(
726 + id="",
727 + payload=payload,
728 + signature="v1,somesignature",
729 + timestamp=test_timestamp,
730 + secret=test_secret,
731 + )
732 +
733 + assert "No webhook ID was provided" in str(exc_info.value)
734 +
735 + def test_verify_webhook_empty_timestamp_raises_error(
736 + self, triggers, test_secret, test_webhook_id, mock_v3_payload
737 + ):
738 + """Test that empty timestamp raises WebhookPayloadError."""
739 + payload = json.dumps(mock_v3_payload)
740 +
741 + with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
742 + triggers.verify_webhook(
743 + id=test_webhook_id,
744 + payload=payload,
745 + signature="v1,somesignature",
746 + timestamp="",
747 + secret=test_secret,
748 + )
749 +
750 + assert "Invalid webhook timestamp" in str(exc_info.value)
751 +
752 + def test_verify_webhook_invalid_signature_format_raises_error(
753 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
754 + ):
755 + """Test that signature without v1 prefix raises error."""
756 + payload = json.dumps(mock_v3_payload)
757 +
758 + with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
759 + triggers.verify_webhook(
760 + id=test_webhook_id,
761 + payload=payload,
762 + signature="invalid-signature-no-prefix",
763 + timestamp=test_timestamp,
764 + secret=test_secret,
765 + )
766 +
767 + assert "No valid v1 signature found" in str(exc_info.value)
768 +
769 def test_verify_webhook_invalid_signature_raises_error(
609 - self, triggers, test_secret, mock_trigger_data
770 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
771 ):
772 """Test that invalid signature raises WebhookSignatureVerificationError."""
612 - payload = json.dumps(mock_trigger_data)
773 + payload = json.dumps(mock_v3_payload)
774
775 with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
776 triggers.verify_webhook(
777 + id=test_webhook_id,
778 payload=payload,
617 - signature="invalid-signature",
779 + signature="v1,invalidbase64signature==",
780 + timestamp=test_timestamp,
781 secret=test_secret,
782 )
783
784 assert "The signature provided is invalid" in str(exc_info.value)
785
786 def test_verify_webhook_wrong_secret_raises_error(
624 - self, triggers, test_secret, mock_trigger_data
787 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
788 ):
789 """Test that signature created with different secret raises error."""
627 - payload = json.dumps(mock_trigger_data)
628 - signature = self.create_signature(payload, "different-secret")
790 + payload = json.dumps(mock_v3_payload)
791 + signature = self.create_signature(
792 + test_webhook_id, test_timestamp, payload, "different-secret"
793 + )
794
795 with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
796 triggers.verify_webhook(
797 + id=test_webhook_id,
798 payload=payload,
799 signature=signature,
800 + timestamp=test_timestamp,
801 secret=test_secret,
802 )
803
804 assert "The signature provided is invalid" in str(exc_info.value)
805
806 def test_verify_webhook_modified_payload_raises_error(
640 - self, triggers, test_secret, mock_trigger_data
807 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
808 ):
809 """Test that modified payload after signing raises error."""
643 - original_payload = json.dumps(mock_trigger_data)
644 - signature = self.create_signature(original_payload, test_secret)
810 + original_payload = json.dumps(mock_v3_payload)
811 + signature = self.create_signature(
812 + test_webhook_id, test_timestamp, original_payload, test_secret
813 + )
814
815 # Modify the payload
647 - mock_trigger_data["appName"] = "modified-app"
648 - modified_payload = json.dumps(mock_trigger_data)
816 + mock_v3_payload["data"] = {"modified": True}
817 + modified_payload = json.dumps(mock_v3_payload)
818
819 with pytest.raises(exceptions.WebhookSignatureVerificationError):
820 triggers.verify_webhook(
821 + id=test_webhook_id,
822 payload=modified_payload,
823 signature=signature,
824 + timestamp=test_timestamp,
825 secret=test_secret,
826 )
827
828 # Payload parsing error tests
829
659 - def test_verify_webhook_invalid_json_raises_error(self, triggers, test_secret):
830 + def test_verify_webhook_invalid_json_raises_error(
831 + self, triggers, test_secret, test_webhook_id, test_timestamp
832 + ):
833 """Test that invalid JSON payload raises WebhookPayloadError."""
834 invalid_json = "not-valid-json{"
662 - signature = self.create_signature(invalid_json, test_secret)
835 + signature = self.create_signature(
836 + test_webhook_id, test_timestamp, invalid_json, test_secret
837 + )
838
839 with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
840 triggers.verify_webhook(
841 + id=test_webhook_id,
842 payload=invalid_json,
843 signature=signature,
844 + timestamp=test_timestamp,
845 secret=test_secret,
846 )
847
848 assert "Failed to parse webhook payload as JSON" in str(exc_info.value)
849
673 - def test_verify_webhook_truncated_json_raises_error(self, triggers, test_secret):
674 - """Test that truncated JSON raises WebhookPayloadError."""
675 - truncated_json = '{"appName": "github", "clientId":'
676 - signature = self.create_signature(truncated_json, test_secret)
850 + def test_verify_webhook_unrecognized_payload_raises_error(
851 + self, triggers, test_secret, test_webhook_id, test_timestamp
852 + ):
853 + """Test that unrecognized payload format raises WebhookPayloadError."""
854 + unknown_payload = json.dumps({"unknown": "format"})
855 + signature = self.create_signature(
856 + test_webhook_id, test_timestamp, unknown_payload, test_secret
857 + )
858
678 - with pytest.raises(exceptions.WebhookPayloadError):
859 + with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
860 triggers.verify_webhook(
680 - payload=truncated_json,
861 + id=test_webhook_id,
862 + payload=unknown_payload,
863 signature=signature,
864 + timestamp=test_timestamp,
865 secret=test_secret,
866 )
867
685 - # Timestamp validation tests
868 + assert "does not match any known version" in str(exc_info.value)
869
687 - def test_verify_webhook_timestamp_within_tolerance(
688 - self, triggers, test_secret, mock_trigger_data
870 + def test_verify_webhook_v3_missing_data_field_raises_error(
871 + self, triggers, test_secret, test_webhook_id, test_timestamp
872 ):
690 - """Test that timestamp within tolerance passes validation."""
691 - now = datetime.now(timezone.utc).isoformat()
692 - mock_trigger_data["timestamp"] = now
693 - payload = json.dumps(mock_trigger_data)
694 - signature = self.create_signature(payload, test_secret)
695 -
696 - result = triggers.verify_webhook(
697 - payload=payload,
698 - signature=signature,
699 - secret=test_secret,
700 - tolerance=300,
873 + """Test that V3-like payload missing 'data' field raises WebhookPayloadError.
874 +
875 + This tests the fix for a potential KeyError crash when a malformed payload
876 + has valid V3 markers (type, id, metadata) but is missing the required 'data' field.
877 + """
878 + # Payload with V3 markers but missing 'data' field
879 + v3_like_payload_missing_data = {
880 + "id": "evt-123",
881 + "timestamp": datetime.now(timezone.utc).isoformat(),
882 + "type": "composio.trigger.message",
883 + "metadata": {
884 + "log_id": "log-123",
885 + "trigger_slug": "GITHUB_PUSH_EVENT",
886 + "trigger_id": "trigger-nano-123",
887 + "connected_account_id": "conn-nano-123",
888 + "auth_config_id": "auth-nano-123",
889 + "user_id": "user-456",
890 + },
891 + # Note: 'data' field is intentionally missing
892 + }
893 + payload = json.dumps(v3_like_payload_missing_data)
894 + signature = self.create_signature(
895 + test_webhook_id, test_timestamp, payload, test_secret
896 )
897
703 - assert result is not None
704 -
705 - def test_verify_webhook_timestamp_outside_tolerance_raises_error(
706 - self, triggers, test_secret, mock_trigger_data
707 - ):
708 - """Test that timestamp outside tolerance raises error."""
709 - # Create a timestamp 10 minutes in the past
710 - old_time = datetime.now(timezone.utc) - timedelta(minutes=10)
711 - mock_trigger_data["timestamp"] = old_time.isoformat()
712 - payload = json.dumps(mock_trigger_data)
713 - signature = self.create_signature(payload, test_secret)
714 -
715 - with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
898 + with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
899 triggers.verify_webhook(
900 + id=test_webhook_id,
901 payload=payload,
902 signature=signature,
903 + timestamp=test_timestamp,
904 secret=test_secret,
720 - tolerance=300, # 5 minutes
905 )
906
723 - assert "outside the allowed tolerance" in str(exc_info.value)
724 -
725 - def test_verify_webhook_skips_timestamp_validation_when_tolerance_zero(
726 - self, triggers, test_secret, mock_trigger_data
727 - ):
728 - """Test that timestamp validation is skipped when tolerance is 0."""
729 - # Create a timestamp 1 hour in the past
730 - old_time = datetime.now(timezone.utc) - timedelta(hours=1)
731 - mock_trigger_data["timestamp"] = old_time.isoformat()
732 - payload = json.dumps(mock_trigger_data)
733 - signature = self.create_signature(payload, test_secret)
734 -
735 - # Should not raise when tolerance is 0
736 - result = triggers.verify_webhook(
737 - payload=payload,
738 - signature=signature,
739 - secret=test_secret,
740 - tolerance=0,
741 - )
907 + # Should be rejected as unrecognized format, not crash with KeyError
908 + assert "does not match any known version" in str(exc_info.value)
909
743 - assert result is not None
910 + # Timestamp validation tests
911
745 - def test_verify_webhook_skips_timestamp_validation_when_no_timestamp(
746 - self, triggers, test_secret, mock_trigger_data
912 + def test_verify_webhook_timestamp_within_tolerance(
913 + self, triggers, test_secret, test_webhook_id, mock_v3_payload
914 ):
748 - """Test that timestamp validation is skipped when no timestamp in payload."""
749 - # mock_trigger_data doesn't have timestamp by default
750 - payload = json.dumps(mock_trigger_data)
751 - signature = self.create_signature(payload, test_secret)
915 + """Test that timestamp within tolerance passes validation."""
916 + recent_timestamp = str(int(time.time()))
917 + payload = json.dumps(mock_v3_payload)
918 + signature = self.create_signature(
919 + test_webhook_id, recent_timestamp, payload, test_secret
920 + )
921
922 result = triggers.verify_webhook(
923 + id=test_webhook_id,
924 payload=payload,
925 signature=signature,
926 + timestamp=recent_timestamp,
927 secret=test_secret,
928 tolerance=300,
929 )
930
931 assert result is not None
932
762 - def test_verify_webhook_invalid_timestamp_format_raises_error(
763 - self, triggers, test_secret, mock_trigger_data
933 + def test_verify_webhook_timestamp_outside_tolerance_raises_error(
934 + self, triggers, test_secret, test_webhook_id, mock_v3_payload
935 ):
765 - """Test that invalid timestamp format raises WebhookPayloadError."""
766 - mock_trigger_data["timestamp"] = "not-a-valid-timestamp"
767 - payload = json.dumps(mock_trigger_data)
768 - signature = self.create_signature(payload, test_secret)
936 + """Test that timestamp outside tolerance raises error."""
937 + # 10 minutes ago
938 + old_timestamp = str(int(time.time()) - 600)
939 + payload = json.dumps(mock_v3_payload)
940 + signature = self.create_signature(
941 + test_webhook_id, old_timestamp, payload, test_secret
942 + )
943
770 - with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
944 + with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
945 triggers.verify_webhook(
946 + id=test_webhook_id,
947 payload=payload,
948 signature=signature,
949 + timestamp=old_timestamp,
950 secret=test_secret,
775 - tolerance=300,
951 + tolerance=300, # 5 minutes
952 )
953
778 - assert "Invalid timestamp in webhook payload" in str(exc_info.value)
954 + assert "outside the allowed tolerance" in str(exc_info.value)
955
780 - def test_verify_webhook_timestamp_with_z_suffix(
781 - self, triggers, test_secret, mock_trigger_data
956 + def test_verify_webhook_invalid_timestamp_format_raises_error(
957 + self, triggers, test_secret, test_webhook_id, mock_v3_payload
958 ):
783 - """Test that timestamp with Z suffix is handled correctly."""
784 - mock_trigger_data["timestamp"] = "2024-01-01T12:00:00Z"
785 - payload = json.dumps(mock_trigger_data)
786 - signature = self.create_signature(payload, test_secret)
959 + """Test that invalid timestamp format raises WebhookPayloadError."""
960 + invalid_timestamp = "not-a-timestamp"
961 + payload = json.dumps(mock_v3_payload)
962 + signature = self.create_signature(
963 + test_webhook_id, invalid_timestamp, payload, test_secret
964 + )
965
788 - # This will fail due to timestamp being old, but should parse correctly
789 - with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
966 + with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
967 triggers.verify_webhook(
968 + id=test_webhook_id,
969 payload=payload,
970 signature=signature,
971 + timestamp=invalid_timestamp,
972 secret=test_secret,
973 tolerance=300,
974 )
975
797 - # Should fail due to timestamp being outside tolerance, not parsing error
798 - assert "outside the allowed tolerance" in str(exc_info.value)
976 + assert "Invalid webhook timestamp" in str(exc_info.value)
977
978 # Security tests
979
980 def test_verify_webhook_uses_timing_safe_comparison(
803 - self, triggers, test_secret, mock_trigger_data
981 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
982 ):
983 """Test that signature comparison is timing-safe."""
806 - payload = json.dumps(mock_trigger_data)
807 - valid_signature = self.create_signature(payload, test_secret)
984 + payload = json.dumps(mock_v3_payload)
985 + valid_signature = self.create_signature(
986 + test_webhook_id, test_timestamp, payload, test_secret
987 + )
988
989 # Valid signature should work
990 result = triggers.verify_webhook(
991 + id=test_webhook_id,
992 payload=payload,
993 signature=valid_signature,
994 + timestamp=test_timestamp,
995 secret=test_secret,
996 )
997 assert result is not None
998
817 - # Invalid signature with same length should fail
818 - invalid_signature = "a" * len(valid_signature)
999 + # Invalid signature with same format should fail
1000 + invalid_signature = "v1," + "a" * 44 # base64 SHA256 is 44 chars
1001 with pytest.raises(exceptions.WebhookSignatureVerificationError):
1002 triggers.verify_webhook(
1003 + id=test_webhook_id,
1004 payload=payload,
1005 signature=invalid_signature,
1006 + timestamp=test_timestamp,
1007 secret=test_secret,
1008 )
1009
1010 def test_verify_webhook_handles_unicode_payload(
827 - self, triggers, test_secret, mock_trigger_data
1011 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
1012 ):
1013 """Test that unicode in payload is handled correctly."""
830 - mock_trigger_data["payload"] = {"message": "你好世界 🌍 مرحبا"}
831 - payload = json.dumps(mock_trigger_data, ensure_ascii=False)
832 - signature = self.create_signature(payload, test_secret)
1014 + mock_v3_payload["data"] = {"message": "你好世界 🌍 مرحبا"}
1015 + payload = json.dumps(mock_v3_payload, ensure_ascii=False)
1016 + signature = self.create_signature(
1017 + test_webhook_id, test_timestamp, payload, test_secret
1018 + )
1019
1020 result = triggers.verify_webhook(
1021 + id=test_webhook_id,
1022 payload=payload,
1023 signature=signature,
1024 + timestamp=test_timestamp,
1025 secret=test_secret,
1026 )
1027
840 - assert result["payload"]["message"] == "你好世界 🌍 مرحبا"
1028 + assert result["payload"]["payload"]["message"] == "你好世界 🌍 مرحبا"
1029
1030 def test_verify_webhook_handles_special_characters_in_secret(
843 - self, triggers, mock_trigger_data
1031 + self, triggers, test_webhook_id, test_timestamp, mock_v3_payload
1032 ):
1033 """Test that special characters in secret are handled correctly."""
1034 special_secret = "secret!@#$%^&*()_+-=[]{}|;:,.<>?"
847 - payload = json.dumps(mock_trigger_data)
848 - signature = self.create_signature(payload, special_secret)
1035 + payload = json.dumps(mock_v3_payload)
1036 + signature = self.create_signature(
1037 + test_webhook_id, test_timestamp, payload, special_secret
1038 + )
1039
1040 result = triggers.verify_webhook(
1041 + id=test_webhook_id,
1042 payload=payload,
1043 signature=signature,
1044 + timestamp=test_timestamp,
1045 secret=special_secret,
1046 )
1047
1048 assert result is not None
1049
1050 + def test_verify_webhook_supports_multiple_signatures(
1051 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
1052 + ):
1053 + """Test that multiple signatures in header are supported."""
1054 + payload = json.dumps(mock_v3_payload)
1055 + valid_signature = self.create_signature(
1056 + test_webhook_id, test_timestamp, payload, test_secret
1057 + )
1058 + # Multiple signatures space-separated
1059 + multiple_signatures = f"v1,invalidsig== {valid_signature}"
1060 +
1061 + result = triggers.verify_webhook(
1062 + id=test_webhook_id,
1063 + payload=payload,
1064 + signature=multiple_signatures,
1065 + timestamp=test_timestamp,
1066 + secret=test_secret,
1067 + )
1068 +
1069 + assert result is not None
1070 +
1071 # Error class tests
1072
1073 def test_webhook_signature_verification_error_is_trigger_error(self):
ts/docs/README.md
+1
@@ -127,6 +127,7 @@ Check out our [examples directory](../examples) for complete code samples:
127 - [Custom Providers](./advanced/custom-providers.md)
128 - [Modifiers](./advanced/modifiers.md)
129 - [Session Management](./advanced/session-management.md)
130 +- [Webhook Verification](./advanced/webhook-verification.md)
131
132 ## Internal Documentation
133
ts/docs/advanced/webhook-verification.md new
+349
@@ -0,0 +1,349 @@
1 +# Webhook Verification
2 +
3 +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.
4 +
5 +## Overview
6 +
7 +The `composio.triggers.verifyWebhook()` method validates incoming webhook requests by:
8 +
9 +1. **Verifying the HMAC-SHA256 signature** to ensure the payload is authentic
10 +2. **Checking the timestamp** to prevent replay attacks (optional, enabled by default)
11 +3. **Parsing and normalizing the payload** across different webhook versions
12 +
13 +## Webhook Versions
14 +
15 +Composio supports three webhook payload versions:
16 +
17 +| Version | Status | Description |
18 +|---------|--------|-------------|
19 +| **V3** | Current (Default) | Latest format used by Composio apps. Includes rich metadata with `type: 'composio.trigger.message'` |
20 +| **V2** | Legacy | Older format with nested `data` object containing connection and trigger info |
21 +| **V1** | Legacy | Original format with flat structure using `trigger_name`, `connection_id`, `trigger_id` |
22 +
23 +The SDK automatically detects the version and normalizes all payloads to a consistent `IncomingTriggerPayload` format.
24 +
25 +## Webhook Headers
26 +
27 +Composio webhooks include these headers for verification:
28 +
29 +| Header | Description | Example |
30 +|--------|-------------|---------|
31 +| `webhook-id` | Unique message identifier | `msg_abc123` |
32 +| `webhook-timestamp` | Unix timestamp in seconds | `1704067200` |
33 +| `webhook-signature` | HMAC-SHA256 signature | `v1,K7gNU3sdo+OL0wNhqoVWhr3g6s...` |
34 +| `x-composio-webhook-version` | Webhook version (V1, V2, V3) | `V3` |
35 +
36 +## API Reference
37 +
38 +### `composio.triggers.verifyWebhook(params)`
39 +
40 +Verifies an incoming webhook payload and signature.
41 +
42 +#### Parameters
43 +
44 +```typescript
45 +interface VerifyWebhookParams {
46 + /** The raw webhook payload as a string (request body) */
47 + payload: string;
48 +
49 + /** The signature from the 'webhook-signature' header */
50 + signature: string;
51 +
52 + /** The webhook secret from your Composio dashboard */
53 + secret: string;
54 +
55 + /** The webhook ID from the 'webhook-id' header */
56 + id: string;
57 +
58 + /** The timestamp from the 'webhook-timestamp' header (Unix seconds) */
59 + timestamp: string;
60 +
61 + /**
62 + * Maximum allowed age of the webhook in seconds.
63 + * Set to 0 to disable timestamp validation.
64 + * @default 300 (5 minutes)
65 + */
66 + tolerance?: number;
67 +}
68 +```
69 +
70 +#### Return Value
71 +
72 +```typescript
73 +interface VerifyWebhookResult {
74 + /** The detected webhook version (V1, V2, or V3) */
75 + version: 'V1' | 'V2' | 'V3';
76 +
77 + /** The normalized webhook payload */
78 + payload: IncomingTriggerPayload;
79 +
80 + /** The raw parsed payload before normalization */
81 + rawPayload: WebhookPayloadV1 | WebhookPayloadV2 | WebhookPayloadV3;
82 +}
83 +```
84 +
85 +#### Errors
86 +
87 +| Error Class | Description |
88 +|-------------|-------------|
89 +| `ValidationError` | Invalid parameters passed to the method |
90 +| `ComposioWebhookSignatureVerificationError` | Signature mismatch, missing headers, or timestamp outside tolerance |
91 +| `ComposioWebhookPayloadError` | Invalid JSON or unrecognized payload format |
92 +
93 +## Usage Examples
94 +
95 +### Express.js
96 +
97 +```typescript
98 +import express from 'express';
99 +import { Composio, ComposioWebhookSignatureVerificationError } from '@composio/core';
100 +
101 +const app = express();
102 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
103 +
104 +// Important: Use express.raw() to get the raw body as a string
105 +app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
106 + try {
107 + const result = composio.triggers.verifyWebhook({
108 + payload: req.body.toString(),
109 + signature: req.headers['webhook-signature'] as string,
110 + id: req.headers['webhook-id'] as string,
111 + timestamp: req.headers['webhook-timestamp'] as string,
112 + secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
113 + });
114 +
115 + // Process the verified payload
116 + console.log('Webhook version:', result.version);
117 + console.log('Trigger:', result.payload.triggerSlug);
118 + console.log('User ID:', result.payload.userId);
119 + console.log('Data:', result.payload.payload);
120 +
121 + res.status(200).send('OK');
122 + } catch (error) {
123 + if (error instanceof ComposioWebhookSignatureVerificationError) {
124 + console.error('Webhook verification failed:', error.message);
125 + res.status(401).send('Unauthorized');
126 + } else {
127 + console.error('Webhook processing error:', error);
128 + res.status(400).send('Bad Request');
129 + }
130 + }
131 +});
132 +
133 +app.listen(3000);
134 +```
135 +
136 +### Next.js API Route (App Router)
137 +
138 +```typescript
139 +import { NextRequest, NextResponse } from 'next/server';
140 +import { Composio, ComposioWebhookSignatureVerificationError } from '@composio/core';
141 +
142 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
143 +
144 +export async function POST(request: NextRequest) {
145 + try {
146 + const payload = await request.text();
147 +
148 + const result = composio.triggers.verifyWebhook({
149 + payload,
150 + signature: request.headers.get('webhook-signature')!,
151 + id: request.headers.get('webhook-id')!,
152 + timestamp: request.headers.get('webhook-timestamp')!,
153 + secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
154 + });
155 +
156 + // Process the verified payload
157 + console.log('Received trigger:', result.payload.triggerSlug);
158 +
159 + return NextResponse.json({ received: true });
160 + } catch (error) {
161 + if (error instanceof ComposioWebhookSignatureVerificationError) {
162 + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
163 + }
164 + return NextResponse.json({ error: 'Bad Request' }, { status: 400 });
165 + }
166 +}
167 +```
168 +
169 +### Fastify
170 +
171 +```typescript
172 +import Fastify from 'fastify';
173 +import { Composio, ComposioWebhookSignatureVerificationError } from '@composio/core';
174 +
175 +const fastify = Fastify();
176 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
177 +
178 +// Get raw body
179 +fastify.addContentTypeParser(
180 + 'application/json',
181 + { parseAs: 'string' },
182 + (req, body, done) => done(null, body)
183 +);
184 +
185 +fastify.post('/webhook', async (request, reply) => {
186 + try {
187 + const result = composio.triggers.verifyWebhook({
188 + payload: request.body as string,
189 + signature: request.headers['webhook-signature'] as string,
190 + id: request.headers['webhook-id'] as string,
191 + timestamp: request.headers['webhook-timestamp'] as string,
192 + secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
193 + });
194 +
195 + console.log('Trigger:', result.payload.triggerSlug);
196 + return { received: true };
197 + } catch (error) {
198 + if (error instanceof ComposioWebhookSignatureVerificationError) {
199 + reply.code(401);
200 + return { error: 'Unauthorized' };
201 + }
202 + reply.code(400);
203 + return { error: 'Bad Request' };
204 + }
205 +});
206 +
207 +fastify.listen({ port: 3000 });
208 +```
209 +
210 +## Signature Algorithm
211 +
212 +The signature is computed as:
213 +
214 +```
215 +HMAC-SHA256(${webhookId}.${webhookTimestamp}.${payload}, secret)
216 +```
217 +
218 +The result is base64-encoded and prefixed with `v1,`:
219 +
220 +```
221 +v1,K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=
222 +```
223 +
224 +## Timestamp Validation
225 +
226 +By default, webhooks older than 5 minutes are rejected to prevent replay attacks. You can customize this behavior:
227 +
228 +```typescript
229 +// Strict: 1 minute tolerance
230 +const result = composio.triggers.verifyWebhook({
231 + ...params,
232 + tolerance: 60,
233 +});
234 +
235 +// Lenient: 10 minute tolerance
236 +const result = composio.triggers.verifyWebhook({
237 + ...params,
238 + tolerance: 600,
239 +});
240 +
241 +// Disable timestamp validation (not recommended for production)
242 +const result = composio.triggers.verifyWebhook({
243 + ...params,
244 + tolerance: 0,
245 +});
246 +```
247 +
248 +## Payload Structures
249 +
250 +### V3 Payload (Current Default)
251 +
252 +```json
253 +{
254 + "id": "msg_abc123",
255 + "timestamp": "2024-01-01T00:00:00.000Z",
256 + "type": "composio.trigger.message",
257 + "metadata": {
258 + "log_id": "log-123",
259 + "trigger_slug": "GITHUB_PUSH_EVENT",
260 + "trigger_id": "trigger-nano-123",
261 + "connected_account_id": "conn-nano-123",
262 + "auth_config_id": "auth-nano-123",
263 + "user_id": "user-456"
264 + },
265 + "data": {
266 + "action": "push",
267 + "repository": "my-repo"
268 + }
269 +}
270 +```
271 +
272 +### V2 Payload (Legacy)
273 +
274 +```json
275 +{
276 + "type": "github_push_event",
277 + "timestamp": "2024-01-01T00:00:00.000Z",
278 + "log_id": "log-123",
279 + "data": {
280 + "connection_id": "conn-123",
281 + "connection_nano_id": "conn-nano-123",
282 + "trigger_nano_id": "trigger-nano-123",
283 + "trigger_id": "trigger-123",
284 + "user_id": "user-456",
285 + "action": "push",
286 + "repository": "my-repo"
287 + }
288 +}
289 +```
290 +
291 +### V1 Payload (Legacy)
292 +
293 +```json
294 +{
295 + "trigger_name": "GITHUB_PUSH_EVENT",
296 + "connection_id": "conn-123",
297 + "trigger_id": "trigger-123",
298 + "payload": {
299 + "action": "push",
300 + "repository": "my-repo"
301 + },
302 + "log_id": "log-123"
303 +}
304 +```
305 +
306 +## Normalized Payload
307 +
308 +Regardless of webhook version, the `payload` field in the result is normalized to:
309 +
310 +```typescript
311 +interface IncomingTriggerPayload {
312 + id: string;
313 + uuid: string;
314 + triggerSlug: string;
315 + toolkitSlug: string;
316 + userId: string;
317 + payload: Record<string, unknown>;
318 + originalPayload: Record<string, unknown>;
319 + metadata: {
320 + id: string;
321 + uuid: string;
322 + toolkitSlug: string;
323 + triggerSlug: string;
324 + triggerConfig: Record<string, unknown>;
325 + connectedAccount: {
326 + id: string;
327 + uuid: string;
328 + authConfigId: string;
329 + authConfigUUID: string;
330 + userId: string;
331 + status: string;
332 + };
333 + };
334 +}
335 +```
336 +
337 +## Security Best Practices
338 +
339 +1. **Always verify webhooks** before processing them in production
340 +2. **Store your webhook secret securely** using environment variables
341 +3. **Use HTTPS** for your webhook endpoint
342 +4. **Keep timestamp tolerance reasonable** (default 5 minutes is recommended)
343 +5. **Parse the raw body** - don't use pre-parsed JSON as middleware may modify it
344 +6. **Handle errors gracefully** - return 401 for signature failures, 400 for parsing errors
345 +7. **Log verification failures** for security monitoring
346 +
347 +## Finding Your Webhook Secret
348 +
349 +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.
ts/examples/triggers/.env.example
+3
@@ -1,6 +1,9 @@
1 # Composio API Key - Get it from https://app.composio.dev
2 COMPOSIO_API_KEY=your_composio_api_key_here
3
4 +# Webhook secret for verifying incoming webhooks - Get it from your Composio dashboard
5 +COMPOSIO_WEBHOOK_SECRET=your_webhook_secret_here
6 +
7 # Add other environment variables as needed for your example
8 # OPENAI_API_KEY=your_openai_api_key_here
9 # ANTHROPIC_API_KEY=your_anthropic_api_key_here
ts/examples/triggers/README.md
+32 -5
@@ -16,26 +16,53 @@ This example demonstrates how to use Composio SDK for triggers.
16
17 Then edit `.env` and add your API keys:
18 - `COMPOSIO_API_KEY`: Get it from [Composio Dashboard](https://app.composio.dev)
19 + - `COMPOSIO_WEBHOOK_SECRET`: Get it from your webhook configuration in Composio Dashboard
20
20 -## Running the Example
21 +## Running the Examples
22 +
23 +### Trigger Subscription (WebSocket)
24
25 ```bash
23 -# Run the example
26 +# Run the subscription example
27 pnpm start
28
29 # Run in development mode (with file watching)
30 pnpm dev
31 ```
32
33 +### Webhook Server (HTTP)
34 +
35 +```bash
36 +# Start the webhook verification server
37 +pnpm webhook:server
38 +
39 +# Then expose it with telebit (https://telebit.cloud/)
40 +telebit http 3000
41 +```
42 +
43 ## What This Example Does
44
45 +### `src/index.ts` - Trigger Subscription
46 - Initializes Composio SDK
33 -- Fetches available tools
34 -- Demonstrates basic usage patterns
47 +- Subscribes to triggers via WebSocket
48 +- Receives real-time trigger events
49 +
50 +### `src/webhook-server.ts` - Webhook Verification
51 +- Starts a Bun HTTP server on port 3000
52 +- Verifies incoming webhook signatures using the new `verifyWebhook` API
53 +- Supports V1, V2, and V3 webhook payload formats
54 +- Returns normalized trigger events
55 +
56 +## Webhook Headers
57 +
58 +When receiving webhooks, the following headers are used:
59 +- `webhook-id`: Unique message ID (format: `msg_xxx`)
60 +- `webhook-timestamp`: Unix timestamp in seconds
61 +- `webhook-signature`: Signature in format `v1,base64EncodedSignature`
62
63 ## Customization
64
38 -Edit `src/index.ts` to:
65 +Edit `src/index.ts` or `src/webhook-server.ts` to:
66 - Add specific apps you want to integrate with
67 - Implement your business logic
68 - Add error handling and logging
ts/examples/triggers/package.json
+1
@@ -8,6 +8,7 @@
8 "clean": "git clean -xdf node_modules",
9 "start": "bun src/index.ts",
10 "dev": "bun --watch src/index.ts",
11 + "webhook:server": "bun src/webhook-server.ts",
12 "test": "echo \"Error: no test specified\" && exit 1"
13 },
14 "keywords": ["composio", "example", "triggers"],
ts/examples/triggers/src/webhook-server.ts new
+125
@@ -0,0 +1,125 @@
1 +/**
2 + * Webhook Verification Server Example
3 + *
4 + * This example demonstrates how to verify incoming Composio webhooks
5 + * using Bun.serve with the new verifyWebhook API.
6 + *
7 + * Prerequisites:
8 + * 1. Set up your COMPOSIO_API_KEY and COMPOSIO_WEBHOOK_SECRET in the .env file
9 + * 2. Install dependencies: pnpm install
10 + * 3. Run the server: pnpm webhook
11 + * 4. Expose your local server using telebit: `telebit http 3000`
12 + * 5. Configure the webhook URL in your Composio dashboard: `https://<your-telebit-url>/webhook`
13 + */
14 +
15 +import {
16 + Composio,
17 + ComposioWebhookSignatureVerificationError,
18 + ComposioWebhookPayloadError,
19 +} from '@composio/core';
20 +import 'dotenv/config';
21 +
22 +const PORT = process.env.PORT || 3000;
23 +const WEBHOOK_SECRET = process.env.COMPOSIO_WEBHOOK_SECRET;
24 +
25 +if (!WEBHOOK_SECRET) {
26 + console.error('❌ COMPOSIO_WEBHOOK_SECRET is required in .env file');
27 + process.exit(1);
28 +}
29 +
30 +const composio = new Composio({
31 + apiKey: process.env.COMPOSIO_API_KEY,
32 +});
33 +
34 +console.log(`🚀 Starting webhook server on port ${PORT}...`);
35 +
36 +const server = Bun.serve({
37 + port: PORT,
38 + async fetch(request) {
39 + const url = new URL(request.url);
40 +
41 + // Health check endpoint
42 + if (url.pathname === '/health') {
43 + return new Response('OK', { status: 200 });
44 + }
45 +
46 + // Webhook endpoint
47 + if (url.pathname === '/webhook' && request.method === 'POST') {
48 + try {
49 + // Get required headers
50 + const webhookId = request.headers.get('webhook-id') || '';
51 + const webhookTimestamp = request.headers.get('webhook-timestamp') || '';
52 + const webhookSignature = request.headers.get('webhook-signature') || '';
53 +
54 + // Get raw payload
55 + const payload = await request.text();
56 +
57 + console.log('\n📨 Received webhook request');
58 + console.log(' Headers:');
59 + console.log(` webhook-id: ${webhookId}`);
60 + console.log(` webhook-timestamp: ${webhookTimestamp}`);
61 + console.log(` webhook-signature: ${webhookSignature.substring(0, 30)}...`);
62 +
63 + // Verify the webhook
64 + const result = composio.triggers.verifyWebhook({
65 + id: webhookId,
66 + timestamp: webhookTimestamp,
67 + signature: webhookSignature,
68 + payload,
69 + secret: WEBHOOK_SECRET,
70 + });
71 +
72 + // Log the verified payload
73 + console.log('\n✅ Webhook verified successfully!');
74 + console.log(` Version: ${result.version}`);
75 + console.log(` Trigger: ${result.payload.triggerSlug}`);
76 + console.log(` User ID: ${result.payload.userId}`);
77 + console.log(` Payload:`, JSON.stringify(result.payload.payload, null, 2));
78 +
79 + // Process the trigger event here
80 + // For example, you could emit an event, call another service, etc.
81 +
82 + return new Response(JSON.stringify({ success: true }), {
83 + status: 200,
84 + headers: { 'Content-Type': 'application/json' },
85 + });
86 + } catch (error) {
87 + console.error('\n❌ Webhook verification failed:', error);
88 +
89 + // Return 401 for signature verification errors
90 + if (error instanceof ComposioWebhookSignatureVerificationError) {
91 + return new Response(JSON.stringify({ error: 'Unauthorized' }), {
92 + status: 401,
93 + headers: { 'Content-Type': 'application/json' },
94 + });
95 + }
96 +
97 + // Return 400 for payload parsing errors
98 + if (error instanceof ComposioWebhookPayloadError) {
99 + return new Response(JSON.stringify({ error: 'Bad Request' }), {
100 + status: 400,
101 + headers: { 'Content-Type': 'application/json' },
102 + });
103 + }
104 +
105 + // Return 500 for unexpected errors
106 + return new Response(JSON.stringify({ error: 'Internal Server Error' }), {
107 + status: 500,
108 + headers: { 'Content-Type': 'application/json' },
109 + });
110 + }
111 + }
112 +
113 + // 404 for other routes
114 + return new Response('Not Found', { status: 404 });
115 + },
116 +});
117 +
118 +console.log(`✅ Webhook server running at http://localhost:${server.port}`);
119 +console.log(`\n📋 Endpoints:`);
120 +console.log(` POST /webhook - Receive and verify webhooks`);
121 +console.log(` GET /health - Health check`);
122 +console.log(`\n💡 Tips:`);
123 +console.log(` 1. Expose this server with telebit: telebit http ${server.port}`);
124 +console.log(` 2. Configure your telebit URL as webhook URL in Composio dashboard`);
125 +console.log(` 3. The webhook secret should match what's configured in Composio`);
ts/packages/core/src/models/Triggers.ts
+279 -49
@@ -22,6 +22,12 @@ import {
22 VerifyWebhookParams,
23 VerifyWebhookParamsSchema,
24 VerifyWebhookResult,
25 + WebhookPayload,
26 + WebhookPayloadV1Schema,
27 + WebhookPayloadV2Schema,
28 + WebhookPayloadV3Schema,
29 + WebhookVersion,
30 + WebhookVersions,
31 } from '../types/triggers.types';
32 import logger from '../utils/logger';
33 import { telemetry } from '../telemetry/Telemetry';
@@ -465,15 +471,20 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
471 * Verify an incoming webhook payload and signature.
472 *
473 * This method validates that the webhook request is authentic by:
468 - * 1. Verifying the HMAC-SHA256 signature matches the payload
474 + * 1. Verifying the HMAC-SHA256 signature matches the payload using the correct signing format
475 * 2. Optionally checking that the webhook timestamp is within the tolerance window
476 *
477 + * The signature is computed as: `HMAC-SHA256(${webhookId}.${webhookTimestamp}.${payload}, secret)`
478 + * and is expected in the format: `v1,base64EncodedSignature`
479 + *
480 * @param {VerifyWebhookParams} params - The verification parameters
481 * @param {string} params.payload - The raw webhook payload as a string (request body)
473 - * @param {string} params.signature - The signature from the webhook header (e.g., 'x-composio-signature')
482 + * @param {string} params.signature - The signature from the 'webhook-signature' header
483 * @param {string} params.secret - The webhook secret used to sign the payload
484 + * @param {string} params.webhookId - The webhook ID from the 'webhook-id' header
485 + * @param {string} params.webhookTimestamp - The timestamp from the 'webhook-timestamp' header (Unix seconds)
486 * @param {number} [params.tolerance=300] - Maximum allowed age of the webhook in seconds (default: 5 minutes). Set to 0 to disable timestamp validation.
476 - * @returns {VerifyWebhookResult} The verified and parsed webhook payload
487 + * @returns {VerifyWebhookResult} The verified and parsed webhook payload with version information
488 *
489 * @throws {ValidationError} If the parameters are invalid
490 * @throws {ComposioWebhookSignatureVerificationError} If the signature verification fails
@@ -484,14 +495,17 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
495 * // In an Express.js webhook handler
496 * app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
497 * try {
487 - * const payload = composio.triggers.verifyWebhook({
498 + * const result = composio.triggers.verifyWebhook({
499 * payload: req.body.toString(),
489 - * signature: req.headers['x-composio-signature'] as string,
500 + * signature: req.headers['webhook-signature'] as string,
501 + * webhookId: req.headers['webhook-id'] as string,
502 + * webhookTimestamp: req.headers['webhook-timestamp'] as string,
503 * secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
504 * });
505 *
506 * // Process the verified payload
494 - * console.log('Received trigger:', payload.triggerSlug);
507 + * console.log('Webhook version:', result.version);
508 + * console.log('Received trigger:', result.payload.triggerSlug);
509 * res.status(200).send('OK');
510 * } catch (error) {
511 * console.error('Webhook verification failed:', error);
@@ -509,44 +523,229 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
523 });
524 }
525
512 - const { payload, signature, secret, tolerance } = parsedParams.data;
526 + const {
527 + payload,
528 + signature,
529 + secret,
530 + id: webhookId,
531 + timestamp: webhookTimestamp,
532 + tolerance,
533 + } = parsedParams.data;
534 +
535 + // Validate timestamp if tolerance is set
536 + if (tolerance > 0) {
537 + this.validateWebhookTimestamp(webhookTimestamp, tolerance);
538 + }
539 +
540 + // Verify signature using the correct format: msgId.timestamp.payload
541 + this.verifyWebhookSignature(webhookId, webhookTimestamp, payload, signature, secret);
542
514 - // Verify signature
515 - this.verifyWebhookSignature(payload, signature, secret);
543 + // Parse the payload and detect version
544 + const { version, rawPayload, normalizedPayload } = this.parseWebhookPayload(payload);
545 +
546 + return {
547 + version,
548 + payload: normalizedPayload,
549 + rawPayload,
550 + };
551 + }
552
517 - // Parse and validate payload
518 - let parsedPayload: TriggerData;
553 + /**
554 + * Parses the webhook payload and detects its version (V1, V2, or V3)
555 + * @private
556 + */
557 + private parseWebhookPayload(payload: string): {
558 + version: WebhookVersion;
559 + rawPayload: WebhookPayload;
560 + normalizedPayload: IncomingTriggerPayload;
561 + } {
562 + let jsonPayload: unknown;
563 try {
520 - parsedPayload = JSON.parse(payload) as TriggerData;
564 + jsonPayload = JSON.parse(payload);
565 } catch (error) {
566 throw new ComposioWebhookPayloadError('Failed to parse webhook payload as JSON', {
567 cause: error,
568 });
569 }
570
527 - // Transform to IncomingTriggerPayload format
528 - const transformedPayload = transformIncomingTriggerPayload(parsedPayload);
571 + // Try V3 first (has 'composio.trigger.message' type)
572 + const v3Result = WebhookPayloadV3Schema.safeParse(jsonPayload);
573 + if (v3Result.success) {
574 + return {
575 + version: WebhookVersions.V3,
576 + rawPayload: v3Result.data,
577 + normalizedPayload: this.normalizeV3Payload(v3Result.data),
578 + };
579 + }
580 +
581 + // Try V2 (has 'type', 'timestamp', 'log_id', and 'data' with specific fields)
582 + const v2Result = WebhookPayloadV2Schema.safeParse(jsonPayload);
583 + if (v2Result.success) {
584 + return {
585 + version: WebhookVersions.V2,
586 + rawPayload: v2Result.data,
587 + normalizedPayload: this.normalizeV2Payload(v2Result.data),
588 + };
589 + }
590
530 - // Validate timestamp if tolerance is set and payload contains timestamp
531 - if (tolerance > 0) {
532 - this.validateWebhookTimestamp(parsedPayload, tolerance);
591 + // Try V1 (has 'trigger_name', 'connection_id', 'trigger_id', 'payload', 'log_id')
592 + const v1Result = WebhookPayloadV1Schema.safeParse(jsonPayload);
593 + if (v1Result.success) {
594 + return {
595 + version: WebhookVersions.V1,
596 + rawPayload: v1Result.data,
597 + normalizedPayload: this.normalizeV1Payload(v1Result.data),
598 + };
599 }
600
535 - return transformedPayload;
601 + // None of the schemas matched
602 + throw new ComposioWebhookPayloadError(
603 + 'Webhook payload does not match any known version (V1, V2, or V3). ' +
604 + 'Please ensure you are using a supported webhook payload format.',
605 + {
606 + cause: {
607 + v1Error: v1Result.error?.message,
608 + v2Error: v2Result.error?.message,
609 + v3Error: v3Result.error?.message,
610 + },
611 + }
612 + );
613 + }
614 +
615 + /**
616 + * Normalizes a V1 webhook payload to IncomingTriggerPayload format
617 + * @private
618 + */
619 + private normalizeV1Payload(
620 + payload: import('../types/triggers.types').WebhookPayloadV1
621 + ): IncomingTriggerPayload {
622 + // V1 has limited information, so we use what's available
623 + // and mark unknown fields appropriately
624 + const triggerName = payload.trigger_name;
625 + const toolkitSlug = triggerName.split('_')[0]?.toUpperCase() || 'UNKNOWN';
626 +
627 + return {
628 + id: payload.trigger_id,
629 + uuid: payload.trigger_id, // V1 doesn't have UUID, use trigger_id
630 + triggerSlug: triggerName,
631 + toolkitSlug,
632 + userId: '', // V1 doesn't provide userId
633 + payload: payload.payload,
634 + originalPayload: payload.payload,
635 + metadata: {
636 + id: payload.trigger_id,
637 + uuid: payload.trigger_id,
638 + toolkitSlug,
639 + triggerSlug: triggerName,
640 + triggerConfig: {},
641 + connectedAccount: {
642 + id: payload.connection_id,
643 + uuid: payload.connection_id,
644 + authConfigId: '',
645 + authConfigUUID: '',
646 + userId: '',
647 + status: 'ACTIVE',
648 + },
649 + },
650 + };
651 }
652
653 /**
539 - * Verifies the HMAC-SHA256 signature of a webhook payload
654 + * Normalizes a V2 webhook payload to IncomingTriggerPayload format
655 * @private
656 */
542 - private verifyWebhookSignature(payload: string, signature: string, secret: string): void {
657 + private normalizeV2Payload(
658 + payload: import('../types/triggers.types').WebhookPayloadV2
659 + ): IncomingTriggerPayload {
660 + const triggerSlug = payload.type.toUpperCase();
661 + const toolkitSlug = triggerSlug.split('_')[0] || 'UNKNOWN';
662 +
663 + // Extract data fields
664 + const { connection_id, connection_nano_id, trigger_nano_id, trigger_id, user_id, ...restData } =
665 + payload.data;
666 +
667 + return {
668 + id: trigger_nano_id,
669 + uuid: trigger_id,
670 + triggerSlug,
671 + toolkitSlug,
672 + userId: user_id,
673 + payload: restData,
674 + originalPayload: restData,
675 + metadata: {
676 + id: trigger_nano_id,
677 + uuid: trigger_id,
678 + toolkitSlug,
679 + triggerSlug,
680 + triggerConfig: {},
681 + connectedAccount: {
682 + id: connection_nano_id,
683 + uuid: connection_id,
684 + authConfigId: '',
685 + authConfigUUID: '',
686 + userId: user_id,
687 + status: 'ACTIVE',
688 + },
689 + },
690 + };
691 + }
692 +
693 + /**
694 + * Normalizes a V3 webhook payload to IncomingTriggerPayload format
695 + * @private
696 + */
697 + private normalizeV3Payload(
698 + payload: import('../types/triggers.types').WebhookPayloadV3
699 + ): IncomingTriggerPayload {
700 + const triggerSlug = payload.metadata.trigger_slug;
701 + const toolkitSlug = triggerSlug.split('_')[0]?.toUpperCase() || 'UNKNOWN';
702 +
703 + return {
704 + id: payload.metadata.trigger_id,
705 + uuid: payload.metadata.trigger_id,
706 + triggerSlug,
707 + toolkitSlug,
708 + userId: payload.metadata.user_id,
709 + payload: payload.data,
710 + originalPayload: payload.data,
711 + metadata: {
712 + id: payload.metadata.trigger_id,
713 + uuid: payload.metadata.trigger_id,
714 + toolkitSlug,
715 + triggerSlug,
716 + triggerConfig: {},
717 + connectedAccount: {
718 + id: payload.metadata.connected_account_id,
719 + uuid: payload.metadata.connected_account_id,
720 + authConfigId: payload.metadata.auth_config_id,
721 + authConfigUUID: payload.metadata.auth_config_id,
722 + userId: payload.metadata.user_id,
723 + status: 'ACTIVE',
724 + },
725 + },
726 + };
727 + }
728 +
729 + /**
730 + * Verifies the HMAC-SHA256 signature of a webhook payload.
731 + * The signature format used by Composio is: `v1,base64EncodedSignature`
732 + * The signing input is: `${msgId}.${timestamp}.${payload}`
733 + * @private
734 + */
735 + private verifyWebhookSignature(
736 + webhookId: string,
737 + webhookTimestamp: string,
738 + payload: string,
739 + signature: string,
740 + secret: string
741 + ): void {
742 if (payload.length === 0) {
743 throw new ComposioWebhookSignatureVerificationError('No webhook payload was provided.');
744 }
745
746 if (signature.length === 0) {
747 throw new ComposioWebhookSignatureVerificationError(
549 - 'No signature header value was provided. Please pass the value of the webhook signature header.'
748 + "No signature header value was provided. Please pass the value of the 'webhook-signature' header."
749 );
750 }
751
@@ -556,20 +755,62 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
755 );
756 }
757
758 + if (webhookId.length === 0) {
759 + throw new ComposioWebhookSignatureVerificationError(
760 + "No webhook ID was provided. Please pass the value of the 'webhook-id' header."
761 + );
762 + }
763 +
764 + if (webhookTimestamp.length === 0) {
765 + throw new ComposioWebhookSignatureVerificationError(
766 + "No webhook timestamp was provided. Please pass the value of the 'webhook-timestamp' header."
767 + );
768 + }
769 +
770 + // Parse signature - may have multiple signatures prefixed with version (e.g., "v1,base64sig")
771 + const signatures = signature.split(' ');
772 + const v1Signatures: string[] = [];
773 +
774 + for (const sig of signatures) {
775 + const [version, value] = sig.split(',');
776 + if (version === 'v1' && value) {
777 + v1Signatures.push(value);
778 + }
779 + }
780 +
781 + if (v1Signatures.length === 0) {
782 + throw new ComposioWebhookSignatureVerificationError(
783 + 'No valid v1 signature found in the webhook-signature header. ' +
784 + "Expected format: 'v1,base64EncodedSignature'"
785 + );
786 + }
787 +
788 + // Compute expected signature: HMAC-SHA256(msgId.timestamp.payload, secret) -> base64
789 + const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
790 const expectedSignature = crypto
791 .createHmac('sha256', secret)
561 - .update(payload, 'utf8')
562 - .digest('hex');
563 -
564 - // Use timing-safe comparison to prevent timing attacks
565 - const signatureBuffer = Buffer.from(signature);
566 - const expectedBuffer = Buffer.from(expectedSignature);
792 + .update(toSign, 'utf8')
793 + .digest('base64');
794 +
795 + // Check if any of the provided signatures match
796 + let isValid = false;
797 + for (const providedSignature of v1Signatures) {
798 + const signatureBuffer = Buffer.from(providedSignature);
799 + const expectedBuffer = Buffer.from(expectedSignature);
800 +
801 + if (
802 + signatureBuffer.length === expectedBuffer.length &&
803 + crypto.timingSafeEqual(signatureBuffer, expectedBuffer)
804 + ) {
805 + isValid = true;
806 + break;
807 + }
808 + }
809
568 - if (
569 - signatureBuffer.length !== expectedBuffer.length ||
570 - !crypto.timingSafeEqual(signatureBuffer, expectedBuffer)
571 - ) {
572 - throw new ComposioWebhookSignatureVerificationError('The signature provided is invalid.');
810 + if (!isValid) {
811 + throw new ComposioWebhookSignatureVerificationError(
812 + 'The signature provided is invalid. Please ensure you are using the correct webhook secret.'
813 + );
814 }
815 }
816
@@ -577,29 +818,18 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
818 * Validates that the webhook timestamp is within the allowed tolerance
819 * @private
820 */
580 - private validateWebhookTimestamp(payload: TriggerData, tolerance: number): void {
581 - // Check if payload has a timestamp field (may be in metadata or at root level)
582 - const timestamp =
583 - (payload as unknown as { timestamp?: string }).timestamp ||
584 - (payload as unknown as { webhookTimestamp?: string }).webhookTimestamp ||
585 - (payload.metadata as unknown as { timestamp?: string })?.timestamp;
586 -
587 - if (!timestamp) {
588 - // If no timestamp is present, skip validation
589 - // This allows backwards compatibility with webhooks that don't include timestamps
590 - logger.debug('No timestamp found in webhook payload, skipping timestamp validation');
591 - return;
592 - }
821 + private validateWebhookTimestamp(webhookTimestamp: string, tolerance: number): void {
822 + const timestampSeconds = parseInt(webhookTimestamp, 10);
823
594 - const webhookTime = Date.parse(timestamp);
595 - if (Number.isNaN(webhookTime)) {
824 + if (Number.isNaN(timestampSeconds)) {
825 throw new ComposioWebhookPayloadError(
597 - `Invalid timestamp in webhook payload: ${timestamp}. Expected ISO 8601 format.`
826 + `Invalid webhook timestamp: ${webhookTimestamp}. Expected Unix timestamp in seconds.`
827 );
828 }
829
830 + const webhookTimeMs = timestampSeconds * 1000;
831 const currentTime = Date.now();
602 - const timeDifference = Math.abs(currentTime - webhookTime);
832 + const timeDifference = Math.abs(currentTime - webhookTimeMs);
833
834 if (timeDifference > tolerance * 1000) {
835 throw new ComposioWebhookSignatureVerificationError(
ts/packages/core/src/types/triggers.types.ts
+91 -5
@@ -195,16 +195,94 @@ export type TriggerEventData<TPayload = unknown> = TPayload & {
195 user_id: string;
196 };
197
198 +/**
199 + * Webhook payload schemas for V1, V2, V3 versions
200 + * These schemas represent the raw payload structure sent by Composio's webhook system
201 + */
202 +
203 +/** V1 webhook payload - legacy format */
204 +export const WebhookPayloadV1Schema = z.object({
205 + trigger_name: z.string(),
206 + connection_id: z.string(),
207 + trigger_id: z.string(),
208 + payload: z.record(z.unknown()),
209 + log_id: z.string(),
210 +});
211 +export type WebhookPayloadV1 = z.infer<typeof WebhookPayloadV1Schema>;
212 +
213 +/** V2 webhook payload - includes timestamp and nested data */
214 +export const WebhookPayloadV2Schema = z.object({
215 + type: z.string(),
216 + timestamp: z.string(),
217 + log_id: z.string(),
218 + data: z
219 + .object({
220 + connection_id: z.string(),
221 + connection_nano_id: z.string(),
222 + trigger_nano_id: z.string(),
223 + trigger_id: z.string(),
224 + user_id: z.string(),
225 + })
226 + .passthrough(),
227 +});
228 +export type WebhookPayloadV2 = z.infer<typeof WebhookPayloadV2Schema>;
229 +
230 +/** V3 webhook payload - current format with metadata */
231 +export const WebhookPayloadV3Schema = z.object({
232 + id: z.string(),
233 + timestamp: z.string(),
234 + type: z.literal('composio.trigger.message'),
235 + metadata: z.object({
236 + log_id: z.string(),
237 + trigger_slug: z.string(),
238 + trigger_id: z.string(),
239 + connected_account_id: z.string(),
240 + auth_config_id: z.string(),
241 + user_id: z.string(),
242 + }),
243 + data: z.record(z.unknown()),
244 +});
245 +export type WebhookPayloadV3 = z.infer<typeof WebhookPayloadV3Schema>;
246 +
247 +/** Union of all webhook payload versions */
248 +export const WebhookPayloadSchema = z.union([
249 + WebhookPayloadV3Schema,
250 + WebhookPayloadV2Schema,
251 + WebhookPayloadV1Schema,
252 +]);
253 +export type WebhookPayload = z.infer<typeof WebhookPayloadSchema>;
254 +
255 +/** Webhook version enum */
256 +export const WebhookVersions = {
257 + V1: 'V1',
258 + V2: 'V2',
259 + V3: 'V3',
260 +} as const;
261 +export type WebhookVersion = (typeof WebhookVersions)[keyof typeof WebhookVersions];
262 +
263 /**
264 * Parameters for verifying a webhook signature
265 */
266 export const VerifyWebhookParamsSchema = z.object({
267 + /**
268 + * The webhook message ID from the 'webhook-id' header.
269 + * Format: 'msg_xxx'
270 + */
271 + id: z.string(),
272 /** The raw webhook payload as a string (request body) */
273 payload: z.string(),
204 - /** The signature from the webhook header (e.g., 'x-composio-signature') */
205 - signature: z.string(),
206 - /** The webhook secret used to sign the payload */
274 + /** The webhook secret used to sign the payload (from Composio dashboard) */
275 secret: z.string(),
276 + /**
277 + * The signature from the 'webhook-signature' header.
278 + * Format: 'v1,base64EncodedSignature'
279 + */
280 + signature: z.string(),
281 + /**
282 + * The webhook timestamp from the 'webhook-timestamp' header.
283 + * This is the Unix timestamp in seconds when the webhook was sent.
284 + */
285 + timestamp: z.string(),
286 /**
287 * Maximum allowed age of the webhook in seconds.
288 * If the webhook timestamp is older than this, verification will fail.
@@ -217,6 +295,14 @@ export const VerifyWebhookParamsSchema = z.object({
295 export type VerifyWebhookParams = z.input<typeof VerifyWebhookParamsSchema>;
296
297 /**
220 - * Result of a successful webhook verification
298 + * Result of a successful webhook verification.
299 + * Contains the parsed payload along with version information.
300 */
222 -export type VerifyWebhookResult = IncomingTriggerPayload;
301 +export type VerifyWebhookResult = {
302 + /** The webhook version (V1, V2, or V3), from 'x-composio-webhook-version' */
303 + version: WebhookVersion;
304 + /** The parsed and normalized webhook payload */
305 + payload: IncomingTriggerPayload;
306 + /** The raw parsed payload before normalization */
307 + rawPayload: WebhookPayload;
308 +};
ts/packages/core/test/models/verifyWebhook.test.ts
+407 -219
@@ -2,7 +2,12 @@ import * as crypto from 'node:crypto';
2 import { describe, it, expect, vi, beforeEach } from 'vitest';
3 import { Triggers } from '../../src/models/Triggers';
4 import ComposioClient from '@composio/client';
5 -import { TriggerData } from '../../src/types/triggers.types';
5 +import {
6 + WebhookPayloadV1,
7 + WebhookPayloadV2,
8 + WebhookPayloadV3,
9 + WebhookVersions,
10 +} from '../../src/types/triggers.types';
11 import { ValidationError } from '../../src/errors';
12 import {
13 ComposioWebhookSignatureVerificationError,
@@ -40,32 +45,62 @@ const createMockClient = () => ({
45 },
46 });
47
43 -// Helper to create a valid signature
44 -const createSignature = (payload: string, secret: string): string => {
45 - return crypto.createHmac('sha256', secret).update(payload, 'utf8').digest('hex');
48 +/**
49 + * Helper to create a valid webhook signature in the format used by Composio.
50 + * Format: v1,base64(HMAC-SHA256(msgId.timestamp.payload, secret))
51 + */
52 +const createSignature = (
53 + webhookId: string,
54 + webhookTimestamp: string,
55 + payload: string,
56 + secret: string
57 +): string => {
58 + const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
59 + const signature = crypto.createHmac('sha256', secret).update(toSign, 'utf8').digest('base64');
60 + return `v1,${signature}`;
61 };
62
48 -// Mock trigger data that matches TriggerData structure
49 -const createMockTriggerData = (overrides: Partial<TriggerData> = {}): TriggerData => ({
50 - appName: 'github',
51 - clientId: 123,
63 +// Mock V1 webhook payload
64 +const createMockV1Payload = (overrides: Partial<WebhookPayloadV1> = {}): WebhookPayloadV1 => ({
65 + trigger_name: 'GITHUB_PUSH_EVENT',
66 + connection_id: 'conn-123',
67 + trigger_id: 'trigger-123',
68 payload: { action: 'push', repository: 'test-repo' },
53 - originalPayload: { action: 'push', repository: 'test-repo' },
69 + log_id: 'log-123',
70 + ...overrides,
71 +});
72 +
73 +// Mock V2 webhook payload
74 +const createMockV2Payload = (overrides: Partial<WebhookPayloadV2> = {}): WebhookPayloadV2 => ({
75 + type: 'github_push_event',
76 + timestamp: new Date().toISOString(),
77 + log_id: 'log-123',
78 + data: {
79 + connection_id: 'conn-123',
80 + connection_nano_id: 'conn-nano-123',
81 + trigger_nano_id: 'trigger-nano-123',
82 + trigger_id: 'trigger-123',
83 + user_id: 'user-456',
84 + action: 'push',
85 + repository: 'test-repo',
86 + },
87 + ...overrides,
88 +});
89 +
90 +// Mock V3 webhook payload
91 +const createMockV3Payload = (overrides: Partial<WebhookPayloadV3> = {}): WebhookPayloadV3 => ({
92 + id: 'msg_abc123',
93 + timestamp: new Date().toISOString(),
94 + type: 'composio.trigger.message',
95 metadata: {
55 - id: 'trigger-123',
56 - nanoId: 'trigger-123-nano',
57 - triggerName: 'github_webhook',
58 - triggerData: '{"action":"push"}',
59 - triggerConfig: { webhook_url: 'https://example.com/webhook' },
60 - connection: {
61 - id: 'conn-123',
62 - connectedAccountNanoId: 'conn-123',
63 - integrationId: 'github',
64 - authConfigNanoId: 'auth-123',
65 - clientUniqueUserId: 'user-456',
66 - status: 'ACTIVE',
67 - },
96 + log_id: 'log-123',
97 + trigger_slug: 'GITHUB_PUSH_EVENT',
98 + trigger_id: 'trigger-nano-123',
99 + connected_account_id: 'conn-nano-123',
100 + auth_config_id: 'auth-nano-123',
101 + user_id: 'user-456',
102 },
103 + data: { action: 'push', repository: 'test-repo' },
104 ...overrides,
105 });
106
@@ -73,6 +108,8 @@ describe('Triggers.verifyWebhook', () => {
108 let triggers: Triggers<any>;
109 let mockClient: ReturnType<typeof createMockClient>;
110 const testSecret = 'test-webhook-secret-12345';
111 + const testWebhookId = 'msg_test123';
112 + const testTimestamp = Math.floor(Date.now() / 1000).toString();
113
114 beforeEach(() => {
115 vi.clearAllMocks();
@@ -80,77 +117,129 @@ describe('Triggers.verifyWebhook', () => {
117 triggers = new Triggers(mockClient as unknown as ComposioClient);
118 });
119
83 - describe('successful verification', () => {
84 - it('should verify a valid webhook payload and signature', () => {
85 - const triggerData = createMockTriggerData();
86 - const payload = JSON.stringify(triggerData);
87 - const signature = createSignature(payload, testSecret);
120 + describe('successful verification with V3 payload', () => {
121 + it('should verify a valid V3 webhook payload and signature', () => {
122 + const v3Payload = createMockV3Payload();
123 + const payloadStr = JSON.stringify(v3Payload);
124 + const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
125
126 const result = triggers.verifyWebhook({
90 - payload,
127 + payload: payloadStr,
128 signature,
129 secret: testSecret,
130 + id: testWebhookId,
131 + timestamp: testTimestamp,
132 });
133
134 expect(result).toBeDefined();
96 - expect(result.id).toBe('trigger-123-nano');
97 - expect(result.uuid).toBe('trigger-123');
98 - expect(result.triggerSlug).toBe('github_webhook');
99 - expect(result.toolkitSlug).toBe('github');
100 - expect(result.userId).toBe('user-456');
135 + expect(result.version).toBe(WebhookVersions.V3);
136 + expect(result.payload.triggerSlug).toBe('GITHUB_PUSH_EVENT');
137 + expect(result.payload.userId).toBe('user-456');
138 + expect(result.rawPayload).toEqual(v3Payload);
139 });
140
103 - it('should verify webhook with tolerance set to 0 (skip timestamp validation)', () => {
104 - const triggerData = createMockTriggerData();
105 - const payload = JSON.stringify(triggerData);
106 - const signature = createSignature(payload, testSecret);
141 + it('should correctly normalize V3 payload to IncomingTriggerPayload format', () => {
142 + const v3Payload = createMockV3Payload();
143 + const payloadStr = JSON.stringify(v3Payload);
144 + const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
145
146 const result = triggers.verifyWebhook({
109 - payload,
147 + payload: payloadStr,
148 signature,
149 secret: testSecret,
112 - tolerance: 0,
150 + id: testWebhookId,
151 + timestamp: testTimestamp,
152 + });
153 +
154 + expect(result.payload.metadata.connectedAccount).toEqual({
155 + id: 'conn-nano-123',
156 + uuid: 'conn-nano-123',
157 + authConfigId: 'auth-nano-123',
158 + authConfigUUID: 'auth-nano-123',
159 + userId: 'user-456',
160 + status: 'ACTIVE',
161 + });
162 + });
163 + });
164 +
165 + describe('successful verification with V2 payload', () => {
166 + it('should verify a valid V2 webhook payload and signature', () => {
167 + const v2Payload = createMockV2Payload();
168 + const payloadStr = JSON.stringify(v2Payload);
169 + const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
170 +
171 + const result = triggers.verifyWebhook({
172 + payload: payloadStr,
173 + signature,
174 + secret: testSecret,
175 + id: testWebhookId,
176 + timestamp: testTimestamp,
177 });
178
179 expect(result).toBeDefined();
116 - expect(result.triggerSlug).toBe('github_webhook');
180 + expect(result.version).toBe(WebhookVersions.V2);
181 + expect(result.payload.triggerSlug).toBe('GITHUB_PUSH_EVENT');
182 + expect(result.payload.userId).toBe('user-456');
183 });
184 + });
185
119 - it('should verify webhook with custom tolerance', () => {
120 - const triggerData = createMockTriggerData();
121 - const payload = JSON.stringify(triggerData);
122 - const signature = createSignature(payload, testSecret);
186 + describe('successful verification with V1 payload', () => {
187 + it('should verify a valid V1 webhook payload and signature', () => {
188 + const v1Payload = createMockV1Payload();
189 + const payloadStr = JSON.stringify(v1Payload);
190 + const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
191
192 const result = triggers.verifyWebhook({
125 - payload,
193 + payload: payloadStr,
194 signature,
195 secret: testSecret,
128 - tolerance: 600, // 10 minutes
196 + id: testWebhookId,
197 + timestamp: testTimestamp,
198 });
199
200 expect(result).toBeDefined();
201 + expect(result.version).toBe(WebhookVersions.V1);
202 + expect(result.payload.triggerSlug).toBe('GITHUB_PUSH_EVENT');
203 + expect(result.payload.id).toBe('trigger-123');
204 });
205 + });
206
134 - it('should correctly transform the payload to IncomingTriggerPayload format', () => {
135 - const triggerData = createMockTriggerData();
136 - const payload = JSON.stringify(triggerData);
137 - const signature = createSignature(payload, testSecret);
207 + describe('tolerance settings', () => {
208 + it('should verify webhook with tolerance set to 0 (skip timestamp validation)', () => {
209 + const v3Payload = createMockV3Payload();
210 + const payloadStr = JSON.stringify(v3Payload);
211 + // Use an old timestamp
212 + const oldTimestamp = Math.floor((Date.now() - 60 * 60 * 1000) / 1000).toString();
213 + const signature = createSignature(testWebhookId, oldTimestamp, payloadStr, testSecret);
214
215 const result = triggers.verifyWebhook({
140 - payload,
216 + payload: payloadStr,
217 signature,
218 secret: testSecret,
219 + id: testWebhookId,
220 + timestamp: oldTimestamp,
221 + tolerance: 0,
222 });
223
145 - // Verify transformation
146 - expect(result.metadata.connectedAccount).toEqual({
147 - id: 'conn-123',
148 - uuid: 'conn-123',
149 - authConfigId: 'auth-123',
150 - authConfigUUID: 'github',
151 - userId: 'user-456',
152 - status: 'ACTIVE',
224 + expect(result).toBeDefined();
225 + expect(result.version).toBe(WebhookVersions.V3);
226 + });
227 +
228 + it('should verify webhook with custom tolerance', () => {
229 + const v3Payload = createMockV3Payload();
230 + const payloadStr = JSON.stringify(v3Payload);
231 + const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
232 +
233 + const result = triggers.verifyWebhook({
234 + payload: payloadStr,
235 + signature,
236 + secret: testSecret,
237 + id: testWebhookId,
238 + timestamp: testTimestamp,
239 + tolerance: 600, // 10 minutes
240 });
241 +
242 + expect(result).toBeDefined();
243 });
244 });
245
@@ -159,102 +248,197 @@ describe('Triggers.verifyWebhook', () => {
248 expect(() =>
249 triggers.verifyWebhook({
250 payload: '',
162 - signature: 'some-signature',
251 + signature: 'v1,somesignature',
252 secret: testSecret,
253 + id: testWebhookId,
254 + timestamp: testTimestamp,
255 })
256 ).toThrow(ComposioWebhookSignatureVerificationError);
257
258 expect(() =>
259 triggers.verifyWebhook({
260 payload: '',
170 - signature: 'some-signature',
261 + signature: 'v1,somesignature',
262 secret: testSecret,
263 + id: testWebhookId,
264 + timestamp: testTimestamp,
265 })
266 ).toThrow('No webhook payload was provided.');
267 });
268
269 it('should throw error when signature is empty', () => {
177 - const payload = JSON.stringify(createMockTriggerData());
270 + const payloadStr = JSON.stringify(createMockV3Payload());
271
272 expect(() =>
273 triggers.verifyWebhook({
181 - payload,
274 + payload: payloadStr,
275 signature: '',
276 secret: testSecret,
277 + id: testWebhookId,
278 + timestamp: testTimestamp,
279 })
280 ).toThrow(ComposioWebhookSignatureVerificationError);
281
282 expect(() =>
283 triggers.verifyWebhook({
189 - payload,
284 + payload: payloadStr,
285 signature: '',
286 secret: testSecret,
287 + id: testWebhookId,
288 + timestamp: testTimestamp,
289 })
290 ).toThrow('No signature header value was provided.');
291 });
292
293 it('should throw error when secret is empty', () => {
197 - const payload = JSON.stringify(createMockTriggerData());
294 + const payloadStr = JSON.stringify(createMockV3Payload());
295
296 expect(() =>
297 triggers.verifyWebhook({
201 - payload,
202 - signature: 'some-signature',
298 + payload: payloadStr,
299 + signature: 'v1,somesignature',
300 secret: '',
301 + id: testWebhookId,
302 + timestamp: testTimestamp,
303 })
304 ).toThrow(ComposioWebhookSignatureVerificationError);
305
306 expect(() =>
307 triggers.verifyWebhook({
209 - payload,
210 - signature: 'some-signature',
308 + payload: payloadStr,
309 + signature: 'v1,somesignature',
310 secret: '',
311 + id: testWebhookId,
312 + timestamp: testTimestamp,
313 })
314 ).toThrow('No webhook secret was provided.');
315 });
316
317 + it('should throw error when webhookId is empty', () => {
318 + const payloadStr = JSON.stringify(createMockV3Payload());
319 +
320 + expect(() =>
321 + triggers.verifyWebhook({
322 + payload: payloadStr,
323 + signature: 'v1,somesignature',
324 + secret: testSecret,
325 + id: '',
326 + timestamp: testTimestamp,
327 + })
328 + ).toThrow(ComposioWebhookSignatureVerificationError);
329 +
330 + expect(() =>
331 + triggers.verifyWebhook({
332 + payload: payloadStr,
333 + signature: 'v1,somesignature',
334 + secret: testSecret,
335 + id: '',
336 + timestamp: testTimestamp,
337 + })
338 + ).toThrow('No webhook ID was provided.');
339 + });
340 +
341 + it('should throw error when webhookTimestamp is empty', () => {
342 + const payloadStr = JSON.stringify(createMockV3Payload());
343 +
344 + // Empty timestamp is treated as invalid timestamp format (parseInt('') = NaN)
345 + expect(() =>
346 + triggers.verifyWebhook({
347 + payload: payloadStr,
348 + signature: 'v1,somesignature',
349 + secret: testSecret,
350 + id: testWebhookId,
351 + timestamp: '',
352 + })
353 + ).toThrow(ComposioWebhookPayloadError);
354 +
355 + expect(() =>
356 + triggers.verifyWebhook({
357 + payload: payloadStr,
358 + signature: 'v1,somesignature',
359 + secret: testSecret,
360 + id: testWebhookId,
361 + timestamp: '',
362 + })
363 + ).toThrow('Invalid webhook timestamp');
364 + });
365 +
366 + it('should throw error when signature format is invalid (no v1 prefix)', () => {
367 + const payloadStr = JSON.stringify(createMockV3Payload());
368 +
369 + expect(() =>
370 + triggers.verifyWebhook({
371 + payload: payloadStr,
372 + signature: 'invalid-signature-no-prefix',
373 + secret: testSecret,
374 + id: testWebhookId,
375 + timestamp: testTimestamp,
376 + })
377 + ).toThrow(ComposioWebhookSignatureVerificationError);
378 +
379 + expect(() =>
380 + triggers.verifyWebhook({
381 + payload: payloadStr,
382 + signature: 'invalid-signature-no-prefix',
383 + secret: testSecret,
384 + id: testWebhookId,
385 + timestamp: testTimestamp,
386 + })
387 + ).toThrow('No valid v1 signature found');
388 + });
389 +
390 it('should throw error when signature is invalid', () => {
217 - const payload = JSON.stringify(createMockTriggerData());
218 - const invalidSignature = 'invalid-signature-that-does-not-match';
391 + const payloadStr = JSON.stringify(createMockV3Payload());
392
393 expect(() =>
394 triggers.verifyWebhook({
222 - payload,
223 - signature: invalidSignature,
395 + payload: payloadStr,
396 + signature: 'v1,invalidbase64signature==',
397 secret: testSecret,
398 + id: testWebhookId,
399 + timestamp: testTimestamp,
400 })
401 ).toThrow(ComposioWebhookSignatureVerificationError);
402
403 expect(() =>
404 triggers.verifyWebhook({
230 - payload,
231 - signature: invalidSignature,
405 + payload: payloadStr,
406 + signature: 'v1,invalidbase64signature==',
407 secret: testSecret,
408 + id: testWebhookId,
409 + timestamp: testTimestamp,
410 })
411 ).toThrow('The signature provided is invalid.');
412 });
413
414 it('should throw error when signature was created with different secret', () => {
238 - const payload = JSON.stringify(createMockTriggerData());
239 - const signatureWithDifferentSecret = createSignature(payload, 'different-secret');
415 + const payloadStr = JSON.stringify(createMockV3Payload());
416 + const signatureWithDifferentSecret = createSignature(
417 + testWebhookId,
418 + testTimestamp,
419 + payloadStr,
420 + 'different-secret'
421 + );
422
423 expect(() =>
424 triggers.verifyWebhook({
243 - payload,
425 + payload: payloadStr,
426 signature: signatureWithDifferentSecret,
427 secret: testSecret,
428 + id: testWebhookId,
429 + timestamp: testTimestamp,
430 })
431 ).toThrow(ComposioWebhookSignatureVerificationError);
432 });
433
434 it('should throw error when payload was modified after signing', () => {
251 - const originalPayload = JSON.stringify(createMockTriggerData());
252 - const signature = createSignature(originalPayload, testSecret);
435 + const originalPayload = createMockV3Payload();
436 + const payloadStr = JSON.stringify(originalPayload);
437 + const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
438
254 - // Modify the payload after signing
439 const modifiedPayload = JSON.stringify({
256 - ...createMockTriggerData(),
257 - appName: 'modified-app',
440 + ...originalPayload,
441 + data: { modified: true },
442 });
443
444 expect(() =>
@@ -262,6 +446,8 @@ describe('Triggers.verifyWebhook', () => {
446 payload: modifiedPayload,
447 signature,
448 secret: testSecret,
449 + id: testWebhookId,
450 + timestamp: testTimestamp,
451 })
452 ).toThrow(ComposioWebhookSignatureVerificationError);
453 });
@@ -270,13 +456,15 @@ describe('Triggers.verifyWebhook', () => {
456 describe('payload parsing errors', () => {
457 it('should throw error when payload is not valid JSON', () => {
458 const invalidJson = 'not-valid-json{';
273 - const signature = createSignature(invalidJson, testSecret);
459 + const signature = createSignature(testWebhookId, testTimestamp, invalidJson, testSecret);
460
461 expect(() =>
462 triggers.verifyWebhook({
463 payload: invalidJson,
464 signature,
465 secret: testSecret,
466 + id: testWebhookId,
467 + timestamp: testTimestamp,
468 })
469 ).toThrow(ComposioWebhookPayloadError);
470
@@ -285,136 +473,114 @@ describe('Triggers.verifyWebhook', () => {
473 payload: invalidJson,
474 signature,
475 secret: testSecret,
476 + id: testWebhookId,
477 + timestamp: testTimestamp,
478 })
479 ).toThrow('Failed to parse webhook payload as JSON');
480 });
481
292 - it('should throw error for truncated JSON', () => {
293 - const truncatedJson = '{"appName": "github", "clientId":';
294 - const signature = createSignature(truncatedJson, testSecret);
482 + it('should throw error for unrecognized payload format', () => {
483 + const unknownPayload = JSON.stringify({ unknown: 'format' });
484 + const signature = createSignature(testWebhookId, testTimestamp, unknownPayload, testSecret);
485
486 expect(() =>
487 triggers.verifyWebhook({
298 - payload: truncatedJson,
488 + payload: unknownPayload,
489 signature,
490 secret: testSecret,
491 + id: testWebhookId,
492 + timestamp: testTimestamp,
493 })
494 ).toThrow(ComposioWebhookPayloadError);
495 +
496 + expect(() =>
497 + triggers.verifyWebhook({
498 + payload: unknownPayload,
499 + signature,
500 + secret: testSecret,
501 + id: testWebhookId,
502 + timestamp: testTimestamp,
503 + })
504 + ).toThrow('does not match any known version');
505 });
506 });
507
508 describe('timestamp validation', () => {
307 - it('should pass when timestamp is within tolerance', () => {
308 - const now = new Date().toISOString();
309 - const triggerData = {
310 - ...createMockTriggerData(),
311 - timestamp: now,
312 - };
313 - const payload = JSON.stringify(triggerData);
314 - const signature = createSignature(payload, testSecret);
315 -
316 - // Should not throw
509 + it('should pass when webhook timestamp is within tolerance', () => {
510 + const v3Payload = createMockV3Payload();
511 + const payloadStr = JSON.stringify(v3Payload);
512 + const recentTimestamp = Math.floor(Date.now() / 1000).toString();
513 + const signature = createSignature(testWebhookId, recentTimestamp, payloadStr, testSecret);
514 +
515 const result = triggers.verifyWebhook({
318 - payload,
516 + payload: payloadStr,
517 signature,
518 secret: testSecret,
519 + id: testWebhookId,
520 + timestamp: recentTimestamp,
521 tolerance: 300,
522 });
523
524 expect(result).toBeDefined();
525 });
526
327 - it('should throw error when timestamp is outside tolerance', () => {
328 - // Create a timestamp 10 minutes in the past
329 - const oldTimestamp = new Date(Date.now() - 10 * 60 * 1000).toISOString();
330 - const triggerData = {
331 - ...createMockTriggerData(),
332 - timestamp: oldTimestamp,
333 - };
334 - const payload = JSON.stringify(triggerData);
335 - const signature = createSignature(payload, testSecret);
527 + it('should throw error when webhook timestamp is outside tolerance', () => {
528 + const v3Payload = createMockV3Payload();
529 + const payloadStr = JSON.stringify(v3Payload);
530 + // 10 minutes ago
531 + const oldTimestamp = Math.floor((Date.now() - 10 * 60 * 1000) / 1000).toString();
532 + const signature = createSignature(testWebhookId, oldTimestamp, payloadStr, testSecret);
533
534 expect(() =>
535 triggers.verifyWebhook({
339 - payload,
536 + payload: payloadStr,
537 signature,
538 secret: testSecret,
539 + id: testWebhookId,
540 + timestamp: oldTimestamp,
541 tolerance: 300, // 5 minutes
542 })
543 ).toThrow(ComposioWebhookSignatureVerificationError);
544
545 expect(() =>
546 triggers.verifyWebhook({
348 - payload,
547 + payload: payloadStr,
548 signature,
549 secret: testSecret,
550 + id: testWebhookId,
551 + timestamp: oldTimestamp,
552 tolerance: 300,
553 })
554 ).toThrow('The webhook timestamp is outside the allowed tolerance');
555 });
556
356 - it('should skip timestamp validation when tolerance is 0', () => {
357 - // Create a timestamp 1 hour in the past
358 - const oldTimestamp = new Date(Date.now() - 60 * 60 * 1000).toISOString();
359 - const triggerData = {
360 - ...createMockTriggerData(),
361 - timestamp: oldTimestamp,
362 - };
363 - const payload = JSON.stringify(triggerData);
364 - const signature = createSignature(payload, testSecret);
365 -
366 - // Should not throw when tolerance is 0
367 - const result = triggers.verifyWebhook({
368 - payload,
369 - signature,
370 - secret: testSecret,
371 - tolerance: 0,
372 - });
373 -
374 - expect(result).toBeDefined();
375 - });
376 -
377 - it('should skip timestamp validation when no timestamp in payload', () => {
378 - const triggerData = createMockTriggerData();
379 - const payload = JSON.stringify(triggerData);
380 - const signature = createSignature(payload, testSecret);
381 -
382 - // Should not throw when no timestamp is present
383 - const result = triggers.verifyWebhook({
384 - payload,
385 - signature,
386 - secret: testSecret,
387 - tolerance: 300,
388 - });
389 -
390 - expect(result).toBeDefined();
391 - });
392 -
557 it('should throw error for invalid timestamp format', () => {
394 - const triggerData = {
395 - ...createMockTriggerData(),
396 - timestamp: 'not-a-valid-timestamp',
397 - };
398 - const payload = JSON.stringify(triggerData);
399 - const signature = createSignature(payload, testSecret);
558 + const v3Payload = createMockV3Payload();
559 + const payloadStr = JSON.stringify(v3Payload);
560 + const invalidTimestamp = 'not-a-timestamp';
561 + const signature = createSignature(testWebhookId, invalidTimestamp, payloadStr, testSecret);
562
563 expect(() =>
564 triggers.verifyWebhook({
403 - payload,
565 + payload: payloadStr,
566 signature,
567 secret: testSecret,
568 + id: testWebhookId,
569 + timestamp: invalidTimestamp,
570 tolerance: 300,
571 })
572 ).toThrow(ComposioWebhookPayloadError);
573
574 expect(() =>
575 triggers.verifyWebhook({
412 - payload,
576 + payload: payloadStr,
577 signature,
578 secret: testSecret,
579 + id: testWebhookId,
580 + timestamp: invalidTimestamp,
581 tolerance: 300,
582 })
417 - ).toThrow('Invalid timestamp in webhook payload');
583 + ).toThrow('Invalid webhook timestamp');
584 });
585 });
586
@@ -422,8 +588,10 @@ describe('Triggers.verifyWebhook', () => {
588 it('should throw ValidationError for missing payload parameter', () => {
589 expect(() =>
590 triggers.verifyWebhook({
425 - signature: 'some-signature',
591 + signature: 'v1,sig',
592 secret: testSecret,
593 + webhookId: testWebhookId,
594 + webhookTimestamp: testTimestamp,
595 } as any)
596 ).toThrow(ValidationError);
597 });
@@ -433,6 +601,8 @@ describe('Triggers.verifyWebhook', () => {
601 triggers.verifyWebhook({
602 payload: '{}',
603 secret: testSecret,
604 + webhookId: testWebhookId,
605 + webhookTimestamp: testTimestamp,
606 } as any)
607 ).toThrow(ValidationError);
608 });
@@ -441,112 +611,126 @@ describe('Triggers.verifyWebhook', () => {
611 expect(() =>
612 triggers.verifyWebhook({
613 payload: '{}',
444 - signature: 'some-signature',
614 + signature: 'v1,sig',
615 + webhookId: testWebhookId,
616 + webhookTimestamp: testTimestamp,
617 } as any)
618 ).toThrow(ValidationError);
619 });
620
449 - it('should throw ValidationError for invalid tolerance type', () => {
621 + it('should throw ValidationError for missing webhookId parameter', () => {
622 expect(() =>
623 triggers.verifyWebhook({
624 payload: '{}',
453 - signature: 'some-signature',
625 + signature: 'v1,sig',
626 secret: testSecret,
455 - tolerance: 'invalid' as any,
456 - })
627 + webhookTimestamp: testTimestamp,
628 + } as any)
629 ).toThrow(ValidationError);
630 });
631
460 - it('should use default tolerance of 300 seconds when not provided', () => {
461 - // Create a timestamp 4 minutes in the past (within default 5 min tolerance)
462 - const recentTimestamp = new Date(Date.now() - 4 * 60 * 1000).toISOString();
463 - const triggerData = {
464 - ...createMockTriggerData(),
465 - timestamp: recentTimestamp,
466 - };
467 - const payload = JSON.stringify(triggerData);
468 - const signature = createSignature(payload, testSecret);
469 -
470 - // Should not throw with default tolerance
471 - const result = triggers.verifyWebhook({
472 - payload,
473 - signature,
474 - secret: testSecret,
475 - });
632 + it('should throw ValidationError for missing webhookTimestamp parameter', () => {
633 + expect(() =>
634 + triggers.verifyWebhook({
635 + payload: '{}',
636 + signature: 'v1,sig',
637 + secret: testSecret,
638 + webhookId: testWebhookId,
639 + } as any)
640 + ).toThrow(ValidationError);
641 + });
642
477 - expect(result).toBeDefined();
643 + it('should throw ValidationError for invalid tolerance type', () => {
644 + expect(() =>
645 + triggers.verifyWebhook({
646 + payload: '{}',
647 + signature: 'v1,sig',
648 + secret: testSecret,
649 + id: testWebhookId,
650 + timestamp: testTimestamp,
651 + tolerance: 'invalid' as any,
652 + })
653 + ).toThrow(ValidationError);
654 });
655 });
656
657 describe('security considerations', () => {
658 it('should use timing-safe comparison for signatures', () => {
483 - // This test verifies the implementation uses timing-safe comparison
484 - // by checking that both valid and invalid signatures take similar time
485 - // (though this is more of a code review verification)
486 - const payload = JSON.stringify(createMockTriggerData());
487 - const validSignature = createSignature(payload, testSecret);
659 + const v3Payload = createMockV3Payload();
660 + const payloadStr = JSON.stringify(v3Payload);
661 + const validSignature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
662
663 // Valid signature should work
664 expect(() =>
665 triggers.verifyWebhook({
492 - payload,
666 + payload: payloadStr,
667 signature: validSignature,
668 secret: testSecret,
669 + id: testWebhookId,
670 + timestamp: testTimestamp,
671 })
672 ).not.toThrow();
673
498 - // Invalid signature with same length should fail
499 - const invalidSignature = 'a'.repeat(validSignature.length);
674 + // Invalid signature with same format should fail
675 + const invalidSignature = 'v1,' + 'a'.repeat(44); // base64 SHA256 is 44 chars
676 expect(() =>
677 triggers.verifyWebhook({
502 - payload,
678 + payload: payloadStr,
679 signature: invalidSignature,
680 secret: testSecret,
505 - })
506 - ).toThrow(ComposioWebhookSignatureVerificationError);
507 - });
508 -
509 - it('should reject signatures with different lengths', () => {
510 - const payload = JSON.stringify(createMockTriggerData());
511 - const shortSignature = 'abc123';
512 -
513 - expect(() =>
514 - triggers.verifyWebhook({
515 - payload,
516 - signature: shortSignature,
517 - secret: testSecret,
681 + id: testWebhookId,
682 + timestamp: testTimestamp,
683 })
684 ).toThrow(ComposioWebhookSignatureVerificationError);
685 });
686
687 it('should handle unicode in payload correctly', () => {
523 - const triggerData = {
524 - ...createMockTriggerData(),
525 - payload: { message: '你好世界 🌍 مرحبا' },
526 - };
527 - const payload = JSON.stringify(triggerData);
528 - const signature = createSignature(payload, testSecret);
688 + const v3Payload = createMockV3Payload({ data: { message: '你好世界 🌍 مرحبا' } });
689 + const payloadStr = JSON.stringify(v3Payload);
690 + const signature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
691
692 const result = triggers.verifyWebhook({
531 - payload,
693 + payload: payloadStr,
694 signature,
695 secret: testSecret,
696 + id: testWebhookId,
697 + timestamp: testTimestamp,
698 });
699
700 expect(result).toBeDefined();
537 - expect(result.payload).toEqual({ message: '你好世界 🌍 مرحبا' });
701 + expect(result.payload.payload).toEqual({ message: '你好世界 🌍 مرحبا' });
702 });
703
704 it('should handle special characters in secret', () => {
705 const specialSecret = 'secret!@#$%^&*()_+-=[]{}|;:,.<>?';
542 - const triggerData = createMockTriggerData();
543 - const payload = JSON.stringify(triggerData);
544 - const signature = createSignature(payload, specialSecret);
706 + const v3Payload = createMockV3Payload();
707 + const payloadStr = JSON.stringify(v3Payload);
708 + const signature = createSignature(testWebhookId, testTimestamp, payloadStr, specialSecret);
709
710 const result = triggers.verifyWebhook({
547 - payload,
711 + payload: payloadStr,
712 signature,
713 secret: specialSecret,
714 + id: testWebhookId,
715 + timestamp: testTimestamp,
716 + });
717 +
718 + expect(result).toBeDefined();
719 + });
720 +
721 + it('should support multiple signatures in header', () => {
722 + const v3Payload = createMockV3Payload();
723 + const payloadStr = JSON.stringify(v3Payload);
724 + const validSignature = createSignature(testWebhookId, testTimestamp, payloadStr, testSecret);
725 + // Multiple signatures space-separated
726 + const multipleSignatures = `v1,invalidsig== ${validSignature}`;
727 +
728 + const result = triggers.verifyWebhook({
729 + payload: payloadStr,
730 + signature: multipleSignatures,
731 + secret: testSecret,
732 + id: testWebhookId,
733 + timestamp: testTimestamp,
734 });
735
736 expect(result).toBeDefined();
@@ -554,14 +738,16 @@ describe('Triggers.verifyWebhook', () => {
738 });
739
740 describe('error properties', () => {
557 - it('should include proper error code for signature verification error', () => {
558 - const payload = JSON.stringify(createMockTriggerData());
741 + it('should include proper error class for signature verification error', () => {
742 + const payloadStr = JSON.stringify(createMockV3Payload());
743
744 try {
745 triggers.verifyWebhook({
562 - payload,
563 - signature: 'invalid',
746 + payload: payloadStr,
747 + signature: 'v1,invalid',
748 secret: testSecret,
749 + id: testWebhookId,
750 + timestamp: testTimestamp,
751 });
752 expect.fail('Should have thrown');
753 } catch (error) {
@@ -572,15 +758,17 @@ describe('Triggers.verifyWebhook', () => {
758 }
759 });
760
575 - it('should include proper error code for payload error', () => {
761 + it('should include proper error class for payload error', () => {
762 const invalidPayload = 'not-json';
577 - const signature = createSignature(invalidPayload, testSecret);
763 + const signature = createSignature(testWebhookId, testTimestamp, invalidPayload, testSecret);
764
765 try {
766 triggers.verifyWebhook({
767 payload: invalidPayload,
768 signature,
769 secret: testSecret,
770 + id: testWebhookId,
771 + timestamp: testTimestamp,
772 });
773 expect.fail('Should have thrown');
774 } catch (error) {