Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
feat(core): add `composio.triggers.verifyWebhook()` (#2251)
Co-authored-by: jkomyno <12381818+jkomyno@users.noreply.github.com>
Alberto Schiabel committed
Dec 13, 2025 at 08:31 UTC
2ff5ff4f2d1ee072695f71e679d84f9b4ca467c9
8 files changed
+1514
-37
python/composio/core/models/triggers.py
+190
@@ -1,12 +1,15 @@
1
from __future__ import annotations
2
3
import functools
4
+import hashlib
5
+import hmac
6
import json
7
import time
8
import traceback
9
import typing as t
10
import uuid
11
from concurrent.futures import ThreadPoolExecutor
12
+from datetime import datetime, timezone
13
from unittest import mock
14
15
from composio_client.types import TriggersTypeRetrieveResponse
@@ -802,3 +805,190 @@ class Triggers(Resource):
805
:return: The trigger subscription handler.
806
"""
807
return _SubcriptionBuilder(client=self._client).connect(timeout=timeout)
808
+
809
+ def verify_webhook(
810
+ self,
811
+ payload: str,
812
+ signature: str,
813
+ secret: str,
814
+ tolerance: int = 300,
815
+ ) -> TriggerEvent:
816
+ """
817
+ Verify an incoming webhook payload and signature.
818
+
819
+ 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
822
+
823
+ :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
826
+ :param tolerance: Maximum allowed age of the webhook in seconds (default: 300 = 5 minutes).
827
+ Set to 0 to disable timestamp validation.
828
+ :return: The verified and parsed webhook payload as a TriggerEvent
829
+ :raises WebhookSignatureVerificationError: If the signature verification fails
830
+ :raises WebhookPayloadError: If the payload cannot be parsed or is invalid
831
+
832
+ Example:
833
+ # In a Flask webhook handler
834
+ @app.route('/webhook', methods=['POST'])
835
+ def webhook():
836
+ try:
837
+ event = composio.triggers.verify_webhook(
838
+ payload=request.get_data(as_text=True),
839
+ signature=request.headers.get('x-composio-signature', ''),
840
+ secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
841
+ )
842
+
843
+ # Process the verified payload
844
+ print(f"Received trigger: {event['trigger_slug']}")
845
+ return 'OK', 200
846
+ except WebhookSignatureVerificationError:
847
+ return 'Unauthorized', 401
848
+ """
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
+
863
+ # Validate timestamp if tolerance is set
864
+ if tolerance > 0:
865
+ self._validate_webhook_timestamp(data, tolerance)
866
+
867
+ return event
868
+
869
+ def _verify_webhook_signature(
870
+ self, payload: str, signature: str, secret: str
871
+ ) -> None:
872
+ """
873
+ Verify the HMAC-SHA256 signature of a webhook payload.
874
+
875
+ :param payload: The raw webhook payload
876
+ :param signature: The signature to verify
877
+ :param secret: The webhook secret
878
+ :raises WebhookSignatureVerificationError: If verification fails
879
+ """
880
+ if not payload:
881
+ raise exceptions.WebhookSignatureVerificationError(
882
+ "No webhook payload was provided."
883
+ )
884
+
885
+ if not signature:
886
+ raise exceptions.WebhookSignatureVerificationError(
887
+ "No signature header value was provided. "
888
+ "Please pass the value of the webhook signature header."
889
+ )
890
+
891
+ if not secret:
892
+ raise exceptions.WebhookSignatureVerificationError(
893
+ "No webhook secret was provided. "
894
+ "You can find your webhook secret in your Composio dashboard."
895
+ )
896
+
897
+ expected_signature = hmac.new(
898
+ key=secret.encode("utf-8"),
899
+ msg=payload.encode("utf-8"),
900
+ digestmod=hashlib.sha256,
901
+ ).hexdigest()
902
+
903
+ # Use timing-safe comparison to prevent timing attacks
904
+ if not hmac.compare_digest(signature, expected_signature):
905
+ raise exceptions.WebhookSignatureVerificationError(
906
+ "The signature provided is invalid."
907
+ )
908
+
909
+ def _validate_webhook_timestamp(self, data: _TriggerData, tolerance: int) -> None:
910
+ """
911
+ Validate that the webhook timestamp is within the allowed tolerance.
912
+
913
+ :param data: The parsed trigger data
914
+ :param tolerance: Maximum allowed age in seconds
915
+ :raises WebhookSignatureVerificationError: If timestamp is outside tolerance
916
+ :raises WebhookPayloadError: If timestamp format is invalid
917
+ """
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
+
934
+ 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:
941
+ raise exceptions.WebhookPayloadError(
942
+ f"Invalid timestamp in webhook payload: {timestamp_str}. "
943
+ "Expected ISO 8601 format."
944
+ ) from e
945
+
946
+ current_time = datetime.now(timezone.utc)
947
+ time_difference = abs((current_time - webhook_time).total_seconds())
948
+
949
+ if time_difference > tolerance:
950
+ raise exceptions.WebhookSignatureVerificationError(
951
+ f"The webhook timestamp is outside the allowed tolerance. "
952
+ f"The webhook was sent {int(time_difference)} seconds ago, "
953
+ f"but the maximum allowed age is {tolerance} seconds."
954
+ )
955
+
956
+ def _transform_trigger_data(self, data: _TriggerData) -> TriggerEvent:
957
+ """
958
+ Transform raw trigger data to TriggerEvent format.
959
+
960
+ :param data: The raw trigger data
961
+ :return: The transformed TriggerEvent
962
+ """
963
+ return t.cast(
964
+ TriggerEvent,
965
+ {
966
+ "id": data["metadata"]["nanoId"],
967
+ "uuid": data["metadata"]["id"],
968
+ "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
969
+ "toolkit_slug": data["appName"],
970
+ "trigger_slug": data["metadata"]["triggerName"],
971
+ "metadata": {
972
+ "id": data["metadata"]["nanoId"],
973
+ "uuid": data["metadata"]["id"],
974
+ "toolkit_slug": data["appName"],
975
+ "trigger_slug": data["metadata"]["triggerName"],
976
+ "trigger_data": data["metadata"].get("triggerData"),
977
+ "trigger_config": data["metadata"]["triggerConfig"],
978
+ "connected_account": {
979
+ "id": data["metadata"]["connection"]["connectedAccountNanoId"],
980
+ "uuid": data["metadata"]["connection"]["id"],
981
+ "auth_config_id": data["metadata"]["connection"][
982
+ "authConfigNanoId"
983
+ ],
984
+ "auth_config_uuid": data["metadata"]["connection"][
985
+ "integrationId"
986
+ ],
987
+ "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
988
+ "status": data["metadata"]["connection"]["status"],
989
+ },
990
+ },
991
+ "payload": data.get("payload"),
992
+ "original_payload": data.get("originalPayload"),
993
+ },
994
+ )
python/composio/exceptions.py
+12
@@ -176,6 +176,18 @@ class TriggerError(ToolkitError):
176
pass
177
178
179
+class WebhookSignatureVerificationError(TriggerError):
180
+ """Raised when webhook signature verification fails."""
181
+
182
+ pass
183
+
184
+
185
+class WebhookPayloadError(TriggerError):
186
+ """Raised when webhook payload is invalid."""
187
+
188
+ pass
189
+
190
+
191
class ActionError(ToolkitError):
192
pass
193
python/tests/test_triggers.py
+443
@@ -1,6 +1,10 @@
1
"""Tests for Triggers class."""
2
3
+import hashlib
4
+import hmac
5
+import json
6
import pytest
7
+from datetime import datetime, timedelta, timezone
8
from unittest.mock import Mock, patch
9
from composio_client import omit
10
from composio.core.models.triggers import Triggers
@@ -423,3 +427,442 @@ class TestTriggers:
427
428
mock_builder.connect.assert_called_once_with(timeout=15.0)
429
assert result == mock_subscription
430
+
431
+
432
+class TestVerifyWebhook:
433
+ """Test cases for verify_webhook method."""
434
+
435
+ @pytest.fixture
436
+ def mock_client(self):
437
+ """Create a mock HTTP client."""
438
+ client = Mock()
439
+ client.triggers_types = Mock()
440
+ client.trigger_instances = Mock()
441
+ client.trigger_instances.manage = Mock()
442
+ client.connected_accounts = Mock()
443
+ return client
444
+
445
+ @pytest.fixture
446
+ def triggers(self, mock_client):
447
+ """Create a Triggers instance."""
448
+ return Triggers(client=mock_client)
449
+
450
+ @pytest.fixture
451
+ def test_secret(self):
452
+ """Test webhook secret."""
453
+ return "test-webhook-secret-12345"
454
+
455
+ @pytest.fixture
456
+ def mock_trigger_data(self):
457
+ """Create mock trigger data matching _TriggerData structure."""
458
+ return {
459
+ "appName": "github",
460
+ "clientId": 123,
461
+ "payload": {"action": "push", "repository": "test-repo"},
462
+ "originalPayload": {"action": "push", "repository": "test-repo"},
463
+ "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
+ },
477
+ },
478
+ }
479
+
480
+ def create_signature(self, payload: str, secret: str) -> str:
481
+ """Helper to create a valid HMAC-SHA256 signature."""
482
+ return hmac.new(
483
+ key=secret.encode("utf-8"),
484
+ msg=payload.encode("utf-8"),
485
+ digestmod=hashlib.sha256,
486
+ ).hexdigest()
487
+
488
+ # Successful verification tests
489
+
490
+ def test_verify_webhook_valid_payload_and_signature(
491
+ self, triggers, test_secret, mock_trigger_data
492
+ ):
493
+ """Test successful webhook verification."""
494
+ payload = json.dumps(mock_trigger_data)
495
+ signature = self.create_signature(payload, test_secret)
496
+
497
+ result = triggers.verify_webhook(
498
+ payload=payload,
499
+ signature=signature,
500
+ secret=test_secret,
501
+ )
502
+
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"
508
+
509
+ def test_verify_webhook_with_tolerance_zero(
510
+ self, triggers, test_secret, mock_trigger_data
511
+ ):
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)
515
+
516
+ result = triggers.verify_webhook(
517
+ payload=payload,
518
+ signature=signature,
519
+ secret=test_secret,
520
+ tolerance=0,
521
+ )
522
+
523
+ assert result["trigger_slug"] == "GITHUB_COMMIT_EVENT"
524
+
525
+ def test_verify_webhook_with_custom_tolerance(
526
+ self, triggers, test_secret, mock_trigger_data
527
+ ):
528
+ """Test webhook verification with custom tolerance."""
529
+ payload = json.dumps(mock_trigger_data)
530
+ signature = self.create_signature(payload, test_secret)
531
+
532
+ result = triggers.verify_webhook(
533
+ payload=payload,
534
+ signature=signature,
535
+ secret=test_secret,
536
+ tolerance=600, # 10 minutes
537
+ )
538
+
539
+ assert result is not None
540
+
541
+ def test_verify_webhook_transforms_payload_correctly(
542
+ self, triggers, test_secret, mock_trigger_data
543
+ ):
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)
547
+
548
+ result = triggers.verify_webhook(
549
+ payload=payload,
550
+ signature=signature,
551
+ secret=test_secret,
552
+ )
553
+
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"
561
+ )
562
+ assert result["metadata"]["connected_account"]["user_id"] == "user-456"
563
+ assert result["metadata"]["connected_account"]["status"] == "ACTIVE"
564
+
565
+ # Signature verification error tests
566
+
567
+ def test_verify_webhook_empty_payload_raises_error(self, triggers, test_secret):
568
+ """Test that empty payload raises WebhookSignatureVerificationError."""
569
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
570
+ triggers.verify_webhook(
571
+ payload="",
572
+ signature="some-signature",
573
+ secret=test_secret,
574
+ )
575
+
576
+ assert "No webhook payload was provided" in str(exc_info.value)
577
+
578
+ def test_verify_webhook_empty_signature_raises_error(
579
+ self, triggers, test_secret, mock_trigger_data
580
+ ):
581
+ """Test that empty signature raises WebhookSignatureVerificationError."""
582
+ payload = json.dumps(mock_trigger_data)
583
+
584
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
585
+ triggers.verify_webhook(
586
+ payload=payload,
587
+ signature="",
588
+ secret=test_secret,
589
+ )
590
+
591
+ assert "No signature header value was provided" in str(exc_info.value)
592
+
593
+ def test_verify_webhook_empty_secret_raises_error(
594
+ self, triggers, mock_trigger_data
595
+ ):
596
+ """Test that empty secret raises WebhookSignatureVerificationError."""
597
+ payload = json.dumps(mock_trigger_data)
598
+
599
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
600
+ triggers.verify_webhook(
601
+ payload=payload,
602
+ signature="some-signature",
603
+ secret="",
604
+ )
605
+
606
+ assert "No webhook secret was provided" in str(exc_info.value)
607
+
608
+ def test_verify_webhook_invalid_signature_raises_error(
609
+ self, triggers, test_secret, mock_trigger_data
610
+ ):
611
+ """Test that invalid signature raises WebhookSignatureVerificationError."""
612
+ payload = json.dumps(mock_trigger_data)
613
+
614
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
615
+ triggers.verify_webhook(
616
+ payload=payload,
617
+ signature="invalid-signature",
618
+ secret=test_secret,
619
+ )
620
+
621
+ assert "The signature provided is invalid" in str(exc_info.value)
622
+
623
+ def test_verify_webhook_wrong_secret_raises_error(
624
+ self, triggers, test_secret, mock_trigger_data
625
+ ):
626
+ """Test that signature created with different secret raises error."""
627
+ payload = json.dumps(mock_trigger_data)
628
+ signature = self.create_signature(payload, "different-secret")
629
+
630
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
631
+ triggers.verify_webhook(
632
+ payload=payload,
633
+ signature=signature,
634
+ secret=test_secret,
635
+ )
636
+
637
+ assert "The signature provided is invalid" in str(exc_info.value)
638
+
639
+ def test_verify_webhook_modified_payload_raises_error(
640
+ self, triggers, test_secret, mock_trigger_data
641
+ ):
642
+ """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)
645
+
646
+ # Modify the payload
647
+ mock_trigger_data["appName"] = "modified-app"
648
+ modified_payload = json.dumps(mock_trigger_data)
649
+
650
+ with pytest.raises(exceptions.WebhookSignatureVerificationError):
651
+ triggers.verify_webhook(
652
+ payload=modified_payload,
653
+ signature=signature,
654
+ secret=test_secret,
655
+ )
656
+
657
+ # Payload parsing error tests
658
+
659
+ def test_verify_webhook_invalid_json_raises_error(self, triggers, test_secret):
660
+ """Test that invalid JSON payload raises WebhookPayloadError."""
661
+ invalid_json = "not-valid-json{"
662
+ signature = self.create_signature(invalid_json, test_secret)
663
+
664
+ with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
665
+ triggers.verify_webhook(
666
+ payload=invalid_json,
667
+ signature=signature,
668
+ secret=test_secret,
669
+ )
670
+
671
+ assert "Failed to parse webhook payload as JSON" in str(exc_info.value)
672
+
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)
677
+
678
+ with pytest.raises(exceptions.WebhookPayloadError):
679
+ triggers.verify_webhook(
680
+ payload=truncated_json,
681
+ signature=signature,
682
+ secret=test_secret,
683
+ )
684
+
685
+ # Timestamp validation tests
686
+
687
+ def test_verify_webhook_timestamp_within_tolerance(
688
+ self, triggers, test_secret, mock_trigger_data
689
+ ):
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,
701
+ )
702
+
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:
716
+ triggers.verify_webhook(
717
+ payload=payload,
718
+ signature=signature,
719
+ secret=test_secret,
720
+ tolerance=300, # 5 minutes
721
+ )
722
+
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
+ )
742
+
743
+ assert result is not None
744
+
745
+ def test_verify_webhook_skips_timestamp_validation_when_no_timestamp(
746
+ self, triggers, test_secret, mock_trigger_data
747
+ ):
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)
752
+
753
+ result = triggers.verify_webhook(
754
+ payload=payload,
755
+ signature=signature,
756
+ secret=test_secret,
757
+ tolerance=300,
758
+ )
759
+
760
+ assert result is not None
761
+
762
+ def test_verify_webhook_invalid_timestamp_format_raises_error(
763
+ self, triggers, test_secret, mock_trigger_data
764
+ ):
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)
769
+
770
+ with pytest.raises(exceptions.WebhookPayloadError) as exc_info:
771
+ triggers.verify_webhook(
772
+ payload=payload,
773
+ signature=signature,
774
+ secret=test_secret,
775
+ tolerance=300,
776
+ )
777
+
778
+ assert "Invalid timestamp in webhook payload" in str(exc_info.value)
779
+
780
+ def test_verify_webhook_timestamp_with_z_suffix(
781
+ self, triggers, test_secret, mock_trigger_data
782
+ ):
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)
787
+
788
+ # This will fail due to timestamp being old, but should parse correctly
789
+ with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info:
790
+ triggers.verify_webhook(
791
+ payload=payload,
792
+ signature=signature,
793
+ secret=test_secret,
794
+ tolerance=300,
795
+ )
796
+
797
+ # Should fail due to timestamp being outside tolerance, not parsing error
798
+ assert "outside the allowed tolerance" in str(exc_info.value)
799
+
800
+ # Security tests
801
+
802
+ def test_verify_webhook_uses_timing_safe_comparison(
803
+ self, triggers, test_secret, mock_trigger_data
804
+ ):
805
+ """Test that signature comparison is timing-safe."""
806
+ payload = json.dumps(mock_trigger_data)
807
+ valid_signature = self.create_signature(payload, test_secret)
808
+
809
+ # Valid signature should work
810
+ result = triggers.verify_webhook(
811
+ payload=payload,
812
+ signature=valid_signature,
813
+ secret=test_secret,
814
+ )
815
+ assert result is not None
816
+
817
+ # Invalid signature with same length should fail
818
+ invalid_signature = "a" * len(valid_signature)
819
+ with pytest.raises(exceptions.WebhookSignatureVerificationError):
820
+ triggers.verify_webhook(
821
+ payload=payload,
822
+ signature=invalid_signature,
823
+ secret=test_secret,
824
+ )
825
+
826
+ def test_verify_webhook_handles_unicode_payload(
827
+ self, triggers, test_secret, mock_trigger_data
828
+ ):
829
+ """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)
833
+
834
+ result = triggers.verify_webhook(
835
+ payload=payload,
836
+ signature=signature,
837
+ secret=test_secret,
838
+ )
839
+
840
+ assert result["payload"]["message"] == "你好世界 🌍 مرحبا"
841
+
842
+ def test_verify_webhook_handles_special_characters_in_secret(
843
+ self, triggers, mock_trigger_data
844
+ ):
845
+ """Test that special characters in secret are handled correctly."""
846
+ special_secret = "secret!@#$%^&*()_+-=[]{}|;:,.<>?"
847
+ payload = json.dumps(mock_trigger_data)
848
+ signature = self.create_signature(payload, special_secret)
849
+
850
+ result = triggers.verify_webhook(
851
+ payload=payload,
852
+ signature=signature,
853
+ secret=special_secret,
854
+ )
855
+
856
+ assert result is not None
857
+
858
+ # Error class tests
859
+
860
+ def test_webhook_signature_verification_error_is_trigger_error(self):
861
+ """Test that WebhookSignatureVerificationError inherits from TriggerError."""
862
+ error = exceptions.WebhookSignatureVerificationError("test")
863
+ assert isinstance(error, exceptions.TriggerError)
864
+
865
+ def test_webhook_payload_error_is_trigger_error(self):
866
+ """Test that WebhookPayloadError inherits from TriggerError."""
867
+ error = exceptions.WebhookPayloadError("test")
868
+ assert isinstance(error, exceptions.TriggerError)
ts/packages/core/src/errors/TriggerErrors.ts
+90
-36
@@ -1,5 +1,4 @@
1
-import { ComposioError } from '@composio/client';
2
-import { ComposioErrorOptions } from './ComposioError';
1
+import { ComposioError, ComposioErrorOptions } from './ComposioError';
2
3
export const TriggerErrorCodes = {
4
TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS: 'TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS',
@@ -8,59 +7,114 @@ export const TriggerErrorCodes = {
7
TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL:
8
'TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL',
9
TRIGGER_TYPE_NOT_FOUND: 'TRIGGER_TYPE_NOT_FOUND',
10
+ WEBHOOK_SIGNATURE_VERIFICATION_FAILED: 'WEBHOOK_SIGNATURE_VERIFICATION_FAILED',
11
+ WEBHOOK_PAYLOAD_INVALID: 'WEBHOOK_PAYLOAD_INVALID',
12
} as const;
13
14
export class ComposioFailedToGetSDKRealtimeCredentialsError extends ComposioError {
14
- public name = 'ComposioFailedToGetSDKRealtimeCredentialsError';
15
- public code = TriggerErrorCodes.TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS;
16
- public statusCode = 500;
17
- public possibleFixes = ['Please contact support.'];
18
-
19
- constructor(message: string, options?: ComposioErrorOptions) {
20
- super(message, options);
15
+ constructor(
16
+ message: string = 'Failed to get SDK realtime credentials',
17
+ options: Omit<ComposioErrorOptions, 'code'> = {}
18
+ ) {
19
+ super(message, {
20
+ ...options,
21
+ code: TriggerErrorCodes.TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS,
22
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
23
+ });
24
+ this.name = 'ComposioFailedToGetSDKRealtimeCredentialsError';
25
}
26
}
27
28
export class ComposioFailedToCreatePusherClientError extends ComposioError {
25
- public name = 'ComposioFailedToCreatePusherClientError';
26
- public code = TriggerErrorCodes.TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT;
27
- public statusCode = 500;
28
- public possibleFixes = ['Please contact support.'];
29
-
30
- constructor(message: string, options?: ComposioErrorOptions) {
31
- super(message, options);
29
+ constructor(
30
+ message: string = 'Failed to create Pusher client',
31
+ options: Omit<ComposioErrorOptions, 'code'> = {}
32
+ ) {
33
+ super(message, {
34
+ ...options,
35
+ code: TriggerErrorCodes.TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT,
36
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
37
+ });
38
+ this.name = 'ComposioFailedToCreatePusherClientError';
39
}
40
}
41
42
export class ComposioFailedToSubscribeToPusherChannelError extends ComposioError {
36
- public name = 'ComposioFailedToSubscribeToPusherChannelError';
37
- public code = TriggerErrorCodes.TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL;
38
- public statusCode = 500;
39
- public possibleFixes = ['Please contact support.'];
40
-
41
- constructor(message: string, options?: ComposioErrorOptions) {
42
- super(message, options);
43
+ constructor(
44
+ message: string = 'Failed to subscribe to Pusher channel',
45
+ options: Omit<ComposioErrorOptions, 'code'> = {}
46
+ ) {
47
+ super(message, {
48
+ ...options,
49
+ code: TriggerErrorCodes.TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL,
50
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
51
+ });
52
+ this.name = 'ComposioFailedToSubscribeToPusherChannelError';
53
}
54
}
55
56
export class ComposioFailedToUnsubscribeFromPusherChannelError extends ComposioError {
47
- public name = 'ComposioFailedToUnsubscribeFromPusherChannelError';
48
- public code = TriggerErrorCodes.TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL;
49
- public statusCode = 500;
50
- public possibleFixes = ['Please contact support.'];
51
-
52
- constructor(message: string, options?: ComposioErrorOptions) {
53
- super(message, options);
57
+ constructor(
58
+ message: string = 'Failed to unsubscribe from Pusher channel',
59
+ options: Omit<ComposioErrorOptions, 'code'> = {}
60
+ ) {
61
+ super(message, {
62
+ ...options,
63
+ code: TriggerErrorCodes.TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL,
64
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
65
+ });
66
+ this.name = 'ComposioFailedToUnsubscribeFromPusherChannelError';
67
}
68
}
69
70
export class ComposioTriggerTypeNotFoundError extends ComposioError {
58
- public name = 'ComposioTriggerTypeNotFoundError';
59
- public code = TriggerErrorCodes.TRIGGER_TYPE_NOT_FOUND;
60
- public statusCode = 404;
61
- public possibleFixes = ['Please contact support.'];
71
+ constructor(
72
+ message: string = 'Trigger type not found',
73
+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
74
+ ) {
75
+ super(message, {
76
+ ...options,
77
+ code: TriggerErrorCodes.TRIGGER_TYPE_NOT_FOUND,
78
+ statusCode: 404,
79
+ possibleFixes: options.possibleFixes || ['Please contact support.'],
80
+ });
81
+ this.name = 'ComposioTriggerTypeNotFoundError';
82
+ }
83
+}
84
+
85
+export class ComposioWebhookSignatureVerificationError extends ComposioError {
86
+ constructor(
87
+ message: string = 'Webhook signature verification failed',
88
+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
89
+ ) {
90
+ super(message, {
91
+ ...options,
92
+ code: TriggerErrorCodes.WEBHOOK_SIGNATURE_VERIFICATION_FAILED,
93
+ statusCode: 401,
94
+ possibleFixes: options.possibleFixes || [
95
+ 'Verify that the webhook secret is correct.',
96
+ 'Ensure the raw request body is passed without modifications.',
97
+ 'Check that the signature header value is being passed correctly.',
98
+ ],
99
+ });
100
+ this.name = 'ComposioWebhookSignatureVerificationError';
101
+ }
102
+}
103
63
- constructor(message: string = 'Trigger type not found', options?: ComposioErrorOptions) {
64
- super(message, options);
104
+export class ComposioWebhookPayloadError extends ComposioError {
105
+ constructor(
106
+ message: string = 'Invalid webhook payload',
107
+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
108
+ ) {
109
+ super(message, {
110
+ ...options,
111
+ code: TriggerErrorCodes.WEBHOOK_PAYLOAD_INVALID,
112
+ statusCode: 400,
113
+ possibleFixes: options.possibleFixes || [
114
+ 'Ensure the webhook payload is valid JSON.',
115
+ 'Verify the payload structure matches the expected format.',
116
+ ],
117
+ });
118
+ this.name = 'ComposioWebhookPayloadError';
119
}
120
}
ts/packages/core/src/errors/index.ts
+3
@@ -30,3 +30,6 @@ export * from './ValidationErrors';
30
31
// SDK Errors
32
export * from './SDKErrors';
33
+
34
+// Trigger Errors
35
+export * from './TriggerErrors';
ts/packages/core/src/models/Triggers.ts
+158
-1
@@ -1,3 +1,4 @@
1
+import * as crypto from 'node:crypto';
2
import ComposioClient, { APIError } from '@composio/client';
3
import { TriggersTypeRetrieveEnumResponse } from '@composio/client/resources/index';
4
import {
@@ -18,12 +19,19 @@ import {
19
TriggersTypeListResponse,
20
TriggersTypeListParamsSchema,
21
TriggersTypeRetrieveResponse,
22
+ VerifyWebhookParams,
23
+ VerifyWebhookParamsSchema,
24
+ VerifyWebhookResult,
25
} from '../types/triggers.types';
26
import logger from '../utils/logger';
27
import { telemetry } from '../telemetry/Telemetry';
28
import { ComposioConnectedAccountNotFoundError, ValidationError } from '../errors';
29
import { PusherService } from '../services/pusher/Pusher';
26
-import { ComposioTriggerTypeNotFoundError } from '../errors/TriggerErrors';
30
+import {
31
+ ComposioTriggerTypeNotFoundError,
32
+ ComposioWebhookPayloadError,
33
+ ComposioWebhookSignatureVerificationError,
34
+} from '../errors/TriggerErrors';
35
import { transform } from '../utils/transform';
36
import {
37
transformIncomingTriggerPayload,
@@ -452,4 +460,153 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
460
async unsubscribe() {
461
await this.pusherService.unsubscribe();
462
}
463
+
464
+ /**
465
+ * Verify an incoming webhook payload and signature.
466
+ *
467
+ * This method validates that the webhook request is authentic by:
468
+ * 1. Verifying the HMAC-SHA256 signature matches the payload
469
+ * 2. Optionally checking that the webhook timestamp is within the tolerance window
470
+ *
471
+ * @param {VerifyWebhookParams} params - The verification parameters
472
+ * @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')
474
+ * @param {string} params.secret - The webhook secret used to sign the payload
475
+ * @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
477
+ *
478
+ * @throws {ValidationError} If the parameters are invalid
479
+ * @throws {ComposioWebhookSignatureVerificationError} If the signature verification fails
480
+ * @throws {ComposioWebhookPayloadError} If the payload cannot be parsed or is invalid
481
+ *
482
+ * @example
483
+ * ```ts
484
+ * // In an Express.js webhook handler
485
+ * app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
486
+ * try {
487
+ * const payload = composio.triggers.verifyWebhook({
488
+ * payload: req.body.toString(),
489
+ * signature: req.headers['x-composio-signature'] as string,
490
+ * secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
491
+ * });
492
+ *
493
+ * // Process the verified payload
494
+ * console.log('Received trigger:', payload.triggerSlug);
495
+ * res.status(200).send('OK');
496
+ * } catch (error) {
497
+ * console.error('Webhook verification failed:', error);
498
+ * res.status(401).send('Unauthorized');
499
+ * }
500
+ * });
501
+ * ```
502
+ */
503
+ verifyWebhook(params: VerifyWebhookParams): VerifyWebhookResult {
504
+ // Validate input parameters
505
+ const parsedParams = VerifyWebhookParamsSchema.safeParse(params);
506
+ if (!parsedParams.success) {
507
+ throw new ValidationError('Invalid parameters passed to verifyWebhook', {
508
+ cause: parsedParams.error,
509
+ });
510
+ }
511
+
512
+ const { payload, signature, secret, tolerance } = parsedParams.data;
513
+
514
+ // Verify signature
515
+ this.verifyWebhookSignature(payload, signature, secret);
516
+
517
+ // Parse and validate payload
518
+ let parsedPayload: TriggerData;
519
+ try {
520
+ parsedPayload = JSON.parse(payload) as TriggerData;
521
+ } catch (error) {
522
+ throw new ComposioWebhookPayloadError('Failed to parse webhook payload as JSON', {
523
+ cause: error,
524
+ });
525
+ }
526
+
527
+ // Transform to IncomingTriggerPayload format
528
+ const transformedPayload = transformIncomingTriggerPayload(parsedPayload);
529
+
530
+ // Validate timestamp if tolerance is set and payload contains timestamp
531
+ if (tolerance > 0) {
532
+ this.validateWebhookTimestamp(parsedPayload, tolerance);
533
+ }
534
+
535
+ return transformedPayload;
536
+ }
537
+
538
+ /**
539
+ * Verifies the HMAC-SHA256 signature of a webhook payload
540
+ * @private
541
+ */
542
+ private verifyWebhookSignature(payload: string, signature: string, secret: string): void {
543
+ if (payload.length === 0) {
544
+ throw new ComposioWebhookSignatureVerificationError('No webhook payload was provided.');
545
+ }
546
+
547
+ if (signature.length === 0) {
548
+ throw new ComposioWebhookSignatureVerificationError(
549
+ 'No signature header value was provided. Please pass the value of the webhook signature header.'
550
+ );
551
+ }
552
+
553
+ if (secret.length === 0) {
554
+ throw new ComposioWebhookSignatureVerificationError(
555
+ 'No webhook secret was provided. You can find your webhook secret in your Composio dashboard.'
556
+ );
557
+ }
558
+
559
+ const expectedSignature = crypto
560
+ .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);
567
+
568
+ if (
569
+ signatureBuffer.length !== expectedBuffer.length ||
570
+ !crypto.timingSafeEqual(signatureBuffer, expectedBuffer)
571
+ ) {
572
+ throw new ComposioWebhookSignatureVerificationError('The signature provided is invalid.');
573
+ }
574
+ }
575
+
576
+ /**
577
+ * Validates that the webhook timestamp is within the allowed tolerance
578
+ * @private
579
+ */
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
+ }
593
+
594
+ const webhookTime = Date.parse(timestamp);
595
+ if (Number.isNaN(webhookTime)) {
596
+ throw new ComposioWebhookPayloadError(
597
+ `Invalid timestamp in webhook payload: ${timestamp}. Expected ISO 8601 format.`
598
+ );
599
+ }
600
+
601
+ const currentTime = Date.now();
602
+ const timeDifference = Math.abs(currentTime - webhookTime);
603
+
604
+ if (timeDifference > tolerance * 1000) {
605
+ throw new ComposioWebhookSignatureVerificationError(
606
+ `The webhook timestamp is outside the allowed tolerance. ` +
607
+ `The webhook was sent ${Math.round(timeDifference / 1000)} seconds ago, ` +
608
+ `but the maximum allowed age is ${tolerance} seconds.`
609
+ );
610
+ }
611
+ }
612
}
ts/packages/core/src/types/triggers.types.ts
+26
@@ -194,3 +194,29 @@ export type TriggerEventData<TPayload = unknown> = TPayload & {
194
trigger_nano_id: string;
195
user_id: string;
196
};
197
+
198
+/**
199
+ * Parameters for verifying a webhook signature
200
+ */
201
+export const VerifyWebhookParamsSchema = z.object({
202
+ /** The raw webhook payload as a string (request body) */
203
+ 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 */
207
+ secret: z.string(),
208
+ /**
209
+ * Maximum allowed age of the webhook in seconds.
210
+ * If the webhook timestamp is older than this, verification will fail.
211
+ * Set to 0 to disable timestamp validation.
212
+ * @default 300 (5 minutes)
213
+ */
214
+ tolerance: z.number().optional().default(300),
215
+});
216
+
217
+export type VerifyWebhookParams = z.input<typeof VerifyWebhookParamsSchema>;
218
+
219
+/**
220
+ * Result of a successful webhook verification
221
+ */
222
+export type VerifyWebhookResult = IncomingTriggerPayload;
ts/packages/core/test/models/verifyWebhook.test.ts
new
+592
@@ -0,0 +1,592 @@
1
+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';
6
+import { ValidationError } from '../../src/errors';
7
+import {
8
+ ComposioWebhookSignatureVerificationError,
9
+ ComposioWebhookPayloadError,
10
+} from '../../src/errors/TriggerErrors';
11
+
12
+// Mock dependencies
13
+vi.mock('../../src/utils/logger');
14
+vi.mock('../../src/telemetry/Telemetry', () => ({
15
+ telemetry: {
16
+ instrument: vi.fn(),
17
+ },
18
+}));
19
+vi.mock('../../src/services/pusher/Pusher');
20
+
21
+// Create mock client
22
+const createMockClient = () => ({
23
+ baseURL: 'https://api.composio.dev',
24
+ apiKey: 'test-api-key',
25
+ triggerInstances: {
26
+ listActive: vi.fn(),
27
+ upsert: vi.fn(),
28
+ manage: {
29
+ delete: vi.fn(),
30
+ update: vi.fn(),
31
+ },
32
+ },
33
+ triggersTypes: {
34
+ list: vi.fn(),
35
+ retrieve: vi.fn(),
36
+ retrieveEnum: vi.fn(),
37
+ },
38
+ connectedAccounts: {
39
+ list: vi.fn(),
40
+ },
41
+});
42
+
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');
46
+};
47
+
48
+// Mock trigger data that matches TriggerData structure
49
+const createMockTriggerData = (overrides: Partial<TriggerData> = {}): TriggerData => ({
50
+ appName: 'github',
51
+ clientId: 123,
52
+ payload: { action: 'push', repository: 'test-repo' },
53
+ originalPayload: { action: 'push', repository: 'test-repo' },
54
+ 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
+ },
68
+ },
69
+ ...overrides,
70
+});
71
+
72
+describe('Triggers.verifyWebhook', () => {
73
+ let triggers: Triggers<any>;
74
+ let mockClient: ReturnType<typeof createMockClient>;
75
+ const testSecret = 'test-webhook-secret-12345';
76
+
77
+ beforeEach(() => {
78
+ vi.clearAllMocks();
79
+ mockClient = createMockClient();
80
+ triggers = new Triggers(mockClient as unknown as ComposioClient);
81
+ });
82
+
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);
88
+
89
+ const result = triggers.verifyWebhook({
90
+ payload,
91
+ signature,
92
+ secret: testSecret,
93
+ });
94
+
95
+ 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');
101
+ });
102
+
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);
107
+
108
+ const result = triggers.verifyWebhook({
109
+ payload,
110
+ signature,
111
+ secret: testSecret,
112
+ tolerance: 0,
113
+ });
114
+
115
+ expect(result).toBeDefined();
116
+ expect(result.triggerSlug).toBe('github_webhook');
117
+ });
118
+
119
+ it('should verify webhook with custom tolerance', () => {
120
+ const triggerData = createMockTriggerData();
121
+ const payload = JSON.stringify(triggerData);
122
+ const signature = createSignature(payload, testSecret);
123
+
124
+ const result = triggers.verifyWebhook({
125
+ payload,
126
+ signature,
127
+ secret: testSecret,
128
+ tolerance: 600, // 10 minutes
129
+ });
130
+
131
+ expect(result).toBeDefined();
132
+ });
133
+
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);
138
+
139
+ const result = triggers.verifyWebhook({
140
+ payload,
141
+ signature,
142
+ secret: testSecret,
143
+ });
144
+
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',
153
+ });
154
+ });
155
+ });
156
+
157
+ describe('signature verification errors', () => {
158
+ it('should throw error when payload is empty', () => {
159
+ expect(() =>
160
+ triggers.verifyWebhook({
161
+ payload: '',
162
+ signature: 'some-signature',
163
+ secret: testSecret,
164
+ })
165
+ ).toThrow(ComposioWebhookSignatureVerificationError);
166
+
167
+ expect(() =>
168
+ triggers.verifyWebhook({
169
+ payload: '',
170
+ signature: 'some-signature',
171
+ secret: testSecret,
172
+ })
173
+ ).toThrow('No webhook payload was provided.');
174
+ });
175
+
176
+ it('should throw error when signature is empty', () => {
177
+ const payload = JSON.stringify(createMockTriggerData());
178
+
179
+ expect(() =>
180
+ triggers.verifyWebhook({
181
+ payload,
182
+ signature: '',
183
+ secret: testSecret,
184
+ })
185
+ ).toThrow(ComposioWebhookSignatureVerificationError);
186
+
187
+ expect(() =>
188
+ triggers.verifyWebhook({
189
+ payload,
190
+ signature: '',
191
+ secret: testSecret,
192
+ })
193
+ ).toThrow('No signature header value was provided.');
194
+ });
195
+
196
+ it('should throw error when secret is empty', () => {
197
+ const payload = JSON.stringify(createMockTriggerData());
198
+
199
+ expect(() =>
200
+ triggers.verifyWebhook({
201
+ payload,
202
+ signature: 'some-signature',
203
+ secret: '',
204
+ })
205
+ ).toThrow(ComposioWebhookSignatureVerificationError);
206
+
207
+ expect(() =>
208
+ triggers.verifyWebhook({
209
+ payload,
210
+ signature: 'some-signature',
211
+ secret: '',
212
+ })
213
+ ).toThrow('No webhook secret was provided.');
214
+ });
215
+
216
+ it('should throw error when signature is invalid', () => {
217
+ const payload = JSON.stringify(createMockTriggerData());
218
+ const invalidSignature = 'invalid-signature-that-does-not-match';
219
+
220
+ expect(() =>
221
+ triggers.verifyWebhook({
222
+ payload,
223
+ signature: invalidSignature,
224
+ secret: testSecret,
225
+ })
226
+ ).toThrow(ComposioWebhookSignatureVerificationError);
227
+
228
+ expect(() =>
229
+ triggers.verifyWebhook({
230
+ payload,
231
+ signature: invalidSignature,
232
+ secret: testSecret,
233
+ })
234
+ ).toThrow('The signature provided is invalid.');
235
+ });
236
+
237
+ it('should throw error when signature was created with different secret', () => {
238
+ const payload = JSON.stringify(createMockTriggerData());
239
+ const signatureWithDifferentSecret = createSignature(payload, 'different-secret');
240
+
241
+ expect(() =>
242
+ triggers.verifyWebhook({
243
+ payload,
244
+ signature: signatureWithDifferentSecret,
245
+ secret: testSecret,
246
+ })
247
+ ).toThrow(ComposioWebhookSignatureVerificationError);
248
+ });
249
+
250
+ it('should throw error when payload was modified after signing', () => {
251
+ const originalPayload = JSON.stringify(createMockTriggerData());
252
+ const signature = createSignature(originalPayload, testSecret);
253
+
254
+ // Modify the payload after signing
255
+ const modifiedPayload = JSON.stringify({
256
+ ...createMockTriggerData(),
257
+ appName: 'modified-app',
258
+ });
259
+
260
+ expect(() =>
261
+ triggers.verifyWebhook({
262
+ payload: modifiedPayload,
263
+ signature,
264
+ secret: testSecret,
265
+ })
266
+ ).toThrow(ComposioWebhookSignatureVerificationError);
267
+ });
268
+ });
269
+
270
+ describe('payload parsing errors', () => {
271
+ it('should throw error when payload is not valid JSON', () => {
272
+ const invalidJson = 'not-valid-json{';
273
+ const signature = createSignature(invalidJson, testSecret);
274
+
275
+ expect(() =>
276
+ triggers.verifyWebhook({
277
+ payload: invalidJson,
278
+ signature,
279
+ secret: testSecret,
280
+ })
281
+ ).toThrow(ComposioWebhookPayloadError);
282
+
283
+ expect(() =>
284
+ triggers.verifyWebhook({
285
+ payload: invalidJson,
286
+ signature,
287
+ secret: testSecret,
288
+ })
289
+ ).toThrow('Failed to parse webhook payload as JSON');
290
+ });
291
+
292
+ it('should throw error for truncated JSON', () => {
293
+ const truncatedJson = '{"appName": "github", "clientId":';
294
+ const signature = createSignature(truncatedJson, testSecret);
295
+
296
+ expect(() =>
297
+ triggers.verifyWebhook({
298
+ payload: truncatedJson,
299
+ signature,
300
+ secret: testSecret,
301
+ })
302
+ ).toThrow(ComposioWebhookPayloadError);
303
+ });
304
+ });
305
+
306
+ 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
317
+ const result = triggers.verifyWebhook({
318
+ payload,
319
+ signature,
320
+ secret: testSecret,
321
+ tolerance: 300,
322
+ });
323
+
324
+ expect(result).toBeDefined();
325
+ });
326
+
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);
336
+
337
+ expect(() =>
338
+ triggers.verifyWebhook({
339
+ payload,
340
+ signature,
341
+ secret: testSecret,
342
+ tolerance: 300, // 5 minutes
343
+ })
344
+ ).toThrow(ComposioWebhookSignatureVerificationError);
345
+
346
+ expect(() =>
347
+ triggers.verifyWebhook({
348
+ payload,
349
+ signature,
350
+ secret: testSecret,
351
+ tolerance: 300,
352
+ })
353
+ ).toThrow('The webhook timestamp is outside the allowed tolerance');
354
+ });
355
+
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
+
393
+ 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);
400
+
401
+ expect(() =>
402
+ triggers.verifyWebhook({
403
+ payload,
404
+ signature,
405
+ secret: testSecret,
406
+ tolerance: 300,
407
+ })
408
+ ).toThrow(ComposioWebhookPayloadError);
409
+
410
+ expect(() =>
411
+ triggers.verifyWebhook({
412
+ payload,
413
+ signature,
414
+ secret: testSecret,
415
+ tolerance: 300,
416
+ })
417
+ ).toThrow('Invalid timestamp in webhook payload');
418
+ });
419
+ });
420
+
421
+ describe('input validation', () => {
422
+ it('should throw ValidationError for missing payload parameter', () => {
423
+ expect(() =>
424
+ triggers.verifyWebhook({
425
+ signature: 'some-signature',
426
+ secret: testSecret,
427
+ } as any)
428
+ ).toThrow(ValidationError);
429
+ });
430
+
431
+ it('should throw ValidationError for missing signature parameter', () => {
432
+ expect(() =>
433
+ triggers.verifyWebhook({
434
+ payload: '{}',
435
+ secret: testSecret,
436
+ } as any)
437
+ ).toThrow(ValidationError);
438
+ });
439
+
440
+ it('should throw ValidationError for missing secret parameter', () => {
441
+ expect(() =>
442
+ triggers.verifyWebhook({
443
+ payload: '{}',
444
+ signature: 'some-signature',
445
+ } as any)
446
+ ).toThrow(ValidationError);
447
+ });
448
+
449
+ it('should throw ValidationError for invalid tolerance type', () => {
450
+ expect(() =>
451
+ triggers.verifyWebhook({
452
+ payload: '{}',
453
+ signature: 'some-signature',
454
+ secret: testSecret,
455
+ tolerance: 'invalid' as any,
456
+ })
457
+ ).toThrow(ValidationError);
458
+ });
459
+
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
+ });
476
+
477
+ expect(result).toBeDefined();
478
+ });
479
+ });
480
+
481
+ describe('security considerations', () => {
482
+ 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);
488
+
489
+ // Valid signature should work
490
+ expect(() =>
491
+ triggers.verifyWebhook({
492
+ payload,
493
+ signature: validSignature,
494
+ secret: testSecret,
495
+ })
496
+ ).not.toThrow();
497
+
498
+ // Invalid signature with same length should fail
499
+ const invalidSignature = 'a'.repeat(validSignature.length);
500
+ expect(() =>
501
+ triggers.verifyWebhook({
502
+ payload,
503
+ signature: invalidSignature,
504
+ 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,
518
+ })
519
+ ).toThrow(ComposioWebhookSignatureVerificationError);
520
+ });
521
+
522
+ 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);
529
+
530
+ const result = triggers.verifyWebhook({
531
+ payload,
532
+ signature,
533
+ secret: testSecret,
534
+ });
535
+
536
+ expect(result).toBeDefined();
537
+ expect(result.payload).toEqual({ message: '你好世界 🌍 مرحبا' });
538
+ });
539
+
540
+ it('should handle special characters in secret', () => {
541
+ const specialSecret = 'secret!@#$%^&*()_+-=[]{}|;:,.<>?';
542
+ const triggerData = createMockTriggerData();
543
+ const payload = JSON.stringify(triggerData);
544
+ const signature = createSignature(payload, specialSecret);
545
+
546
+ const result = triggers.verifyWebhook({
547
+ payload,
548
+ signature,
549
+ secret: specialSecret,
550
+ });
551
+
552
+ expect(result).toBeDefined();
553
+ });
554
+ });
555
+
556
+ describe('error properties', () => {
557
+ it('should include proper error code for signature verification error', () => {
558
+ const payload = JSON.stringify(createMockTriggerData());
559
+
560
+ try {
561
+ triggers.verifyWebhook({
562
+ payload,
563
+ signature: 'invalid',
564
+ secret: testSecret,
565
+ });
566
+ expect.fail('Should have thrown');
567
+ } catch (error) {
568
+ expect(error).toBeInstanceOf(ComposioWebhookSignatureVerificationError);
569
+ expect((error as ComposioWebhookSignatureVerificationError).name).toBe(
570
+ 'ComposioWebhookSignatureVerificationError'
571
+ );
572
+ }
573
+ });
574
+
575
+ it('should include proper error code for payload error', () => {
576
+ const invalidPayload = 'not-json';
577
+ const signature = createSignature(invalidPayload, testSecret);
578
+
579
+ try {
580
+ triggers.verifyWebhook({
581
+ payload: invalidPayload,
582
+ signature,
583
+ secret: testSecret,
584
+ });
585
+ expect.fail('Should have thrown');
586
+ } catch (error) {
587
+ expect(error).toBeInstanceOf(ComposioWebhookPayloadError);
588
+ expect((error as ComposioWebhookPayloadError).name).toBe('ComposioWebhookPayloadError');
589
+ }
590
+ });
591
+ });
592
+});