@devries-cameron20 / composio Mirror · read-only / commits / 5bff5bdf9
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 18:15 UTC

trigger signarure verification

Sushmithamallesh committed Nov 12, 2025 at 15:13 UTC 5bff5bdf94ae8b2126913e4df70f9f19922f213b
4 files changed +137 -50
fern/fern.config.json
+2 -2
@@ -1,4 +1,4 @@
1 {
2 "organization": "composio",
3 - "version": "0.107.3"
4 -}
\ No newline at end of file
3 + "version": "0.116.0"
4 +}
fern/pages/src/triggers/using-triggers.mdx
+50 -6
@@ -2,7 +2,7 @@
2 title: Using Triggers
3 subtitle: Send payloads to your AI agents or systems based on events in apps.
4 image: "https://og.composio.dev/api/og?title=Using%20Triggers" # image for socials
5 -keywords: 'triggers, webhooks, websockets, events, active triggers'
5 +keywords: 'triggers, webhooks, websockets, events, active triggers, trigger types, verify triggers'
6 hide-nav-links: true
7 ---
8
@@ -92,23 +92,67 @@ Use a publicly accessible URL where Composio can send event payloads. This endpo
92 **Local development:** Use [ngrok](https://ngrok.com) or [webhook.site](https://webhook.site) to
93 expose your local server to the internet for testing.
94 </Tip>
95 -**Implement your webhook handler:**
95
97 -Below are some examples of how to listen in on trigger events
98 -for a FastAPI/Next.js application.
96 +Webhook payloads contain:
97 +- `type`: The trigger type identifier
98 +- `data`: The actual event data
99 +- `timestamp`: When the event occurred
100 +- `log_id`: Unique identifier for this event
101 +
102 +Below are examples of webhook handlers for FastAPI and Next.js applications:
103
104 <CodeGroup>
105 <SnippetCode
106 src="fern/snippets/triggers/python/trigger-webhook.py"
103 - title="app/route.py"
107 + title="Python (FastAPI)"
108 + startLine={36}
109 + endLine={49}
110 />
111
112 <SnippetCode
113 src="fern/snippets/triggers/typescript/trigger-webhook.ts"
108 - title="app/api/webhook/route.ts"
114 + title="TypeScript (Next.js)"
115 + startLine={39}
116 + endLine={70}
117 />
118 </CodeGroup>
119
120 +### Verifying webhook signatures
121 +
122 +Composio signs all webhook requests so you can verify they're authentic. Each webhook includes these headers:
123 +
124 +- `webhook-signature`: HMAC signature in format `v1,<base64_signature>`
125 +- `webhook-id`: Unique message identifier
126 +- `webhook-timestamp`: Unix timestamp when the webhook was sent
127 +
128 +To enable verification:
129 +
130 +1. Obtain your webhook secret from the [Composio dashboard](https://platform.composio.dev?next_page=/settings/webhook) under Project Settings → Webhook.
131 +2. Set it as the `COMPOSIO_WEBHOOK_SECRET` environment variable
132 +3. Use the verification function in your webhook handler:
133 +
134 +<CodeGroup>
135 +<SnippetCode
136 + src="fern/snippets/triggers/python/trigger-webhook.py"
137 + title="Python"
138 + startLine={12}
139 + endLine={34}
140 +/>
141 +
142 +<SnippetCode
143 + src="fern/snippets/triggers/typescript/trigger-webhook.ts"
144 + title="TypeScript"
145 + startLine={12}
146 + endLine={37}
147 +/>
148 +</CodeGroup>
149 +
150 +The signature is calculated as:
151 +```
152 +signing_string = "{webhook-id}.{webhook-timestamp}.{raw_body}"
153 +signature = HMAC-SHA256(signing_string, secret)
154 +```
155 +
156 ### Prototyping with trigger subscriptions
157
158 During development, you can subscribe to triggers directly through the SDK without setting up webhooks.
fern/snippets/triggers/python/trigger-webhook.py
+40 -12
@@ -1,22 +1,50 @@
1 -from fastapi import FastAPI, Request
1 +from fastapi import FastAPI, Request, HTTPException
2 from typing import Dict, Any
3 import uvicorn
4 import json
5 +import hmac
6 +import hashlib
7 +import base64
8 +import os
9
10 app = FastAPI(title="Webhook Demo")
11
12 +def verify_webhook_signature(request: Request, body: bytes) -> bool:
13 + """Verify Composio webhook signature"""
14 + webhook_signature = request.headers.get("webhook-signature")
15 + webhook_id = request.headers.get("webhook-id")
16 + webhook_timestamp = request.headers.get("webhook-timestamp")
17 + webhook_secret = os.getenv("COMPOSIO_WEBHOOK_SECRET")
18 +
19 + if not all([webhook_signature, webhook_id, webhook_timestamp, webhook_secret]):
20 + raise HTTPException(status_code=400, detail="Missing required webhook headers or secret")
21 +
22 + if not webhook_signature.startswith("v1,"):
23 + raise HTTPException(status_code=401, detail="Invalid signature format")
24 +
25 + received = webhook_signature[3:]
26 + signing_string = f"{webhook_id}.{webhook_timestamp}.{body.decode()}"
27 + expected = base64.b64encode(
28 + hmac.new(webhook_secret.encode(), signing_string.encode(), hashlib.sha256).digest()
29 + ).decode()
30 +
31 + if not hmac.compare_digest(received, expected):
32 + raise HTTPException(status_code=401, detail="Invalid webhook signature")
33 +
34 + return True
35 +
36 @app.post("/webhook")
37 async def webhook_handler(request: Request):
10 - # Get the raw payload
38 payload = await request.json()
12 -
13 - # Log the received webhook data
14 - print("Received webhook payload:")
15 - print(json.dumps(payload, indent=2))
16 -
17 - # Return a success response
18 - return {"status": "success", "message": "Webhook received"}
19 -
20 -if __name__ == "__main__":
21 - uvicorn.run(app, host="0.0.0.0", port=8000)
39 +
40 + trigger_type = payload.get("type")
41 + event_data = payload.get("data", {})
42 +
43 + if trigger_type == "github_star_added_event":
44 + repo_name = event_data.get("repository_name")
45 + starred_by = event_data.get("starred_by")
46 + print(f"Repository {repo_name} starred by {starred_by}")
47 + # Add your business logic here
48 +
49 + return {"status": "success", "message": "Webhook processed"}
50
fern/snippets/triggers/typescript/trigger-webhook.ts
+45 -30
@@ -1,57 +1,72 @@
1 import type { NextApiRequest, NextApiResponse } from 'next';
2 import { TriggerEvent } from '@composio/core';
3 +import crypto from 'crypto';
4
4 -// Define type-safe payload for GitHub Star Added event
5 -export type GitHubStarAddedEventPayload = {
6 - action: "created";
7 - repository_id: number;
5 +type GitHubStarEventData = {
6 repository_name: string;
7 repository_url: string;
10 - starred_at: string;
8 starred_by: string;
9 + starred_at: string;
10 };
11
14 -// Type-safe handler function
15 -function handleGitHubStarAddedEvent(event: TriggerEvent<GitHubStarAddedEventPayload>) {
16 - console.log(`⭐ ${event.data.repository_name} starred by ${event.data.starred_by}`);
12 +function verifyWebhookSignature(
13 + req: NextApiRequest,
14 + body: string
15 +): boolean {
16 + const signature = req.headers['webhook-signature'] as string | undefined;
17 + const msgId = req.headers['webhook-id'] as string | undefined;
18 + const timestamp = req.headers['webhook-timestamp'] as string | undefined;
19 + const secret = process.env.COMPOSIO_WEBHOOK_SECRET;
20 +
21 + if (!signature || !msgId || !timestamp || !secret) {
22 + throw new Error('Missing required webhook headers or secret');
23 + }
24 +
25 + if (!signature.startsWith('v1,')) {
26 + throw new Error('Invalid signature format');
27 + }
28 +
29 + const received = signature.slice(3);
30 + const signingString = `${msgId}.${timestamp}.${body}`;
31 + const expected = crypto
32 + .createHmac('sha256', secret)
33 + .update(signingString)
34 + .digest('base64');
35 +
36 + return crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
37 }
38
19 -export default async function handler(req: NextApiRequest, res: NextApiResponse) {
39 +export default async function webhookHandler(req: NextApiRequest, res: NextApiResponse) {
40 if (req.method !== 'POST') {
41 return res.status(405).json({
42 status: 'error',
23 - message: 'Method not allowed. Only POST requests are accepted.'
43 + message: 'Method not allowed'
44 });
45 }
46
47 try {
48 const payload = req.body;
29 -
30 - // Type-safe webhook payload processing
31 - if (payload.triggerSlug === 'GITHUB_STAR_ADDED_EVENT') {
32 - const starEvent: TriggerEvent<GitHubStarAddedEventPayload> = {
33 - type: payload.triggerSlug,
34 - timestamp: new Date().toISOString(),
35 - data: {
36 - ...payload.payload as GitHubStarAddedEventPayload,
37 - connection_nano_id: payload.metadata?.connectedAccount?.id || '',
38 - trigger_nano_id: payload.id || '',
39 - user_id: payload.userId || '',
40 - }
49 +
50 + if (payload.type === 'github_star_added_event') {
51 + const event: TriggerEvent<GitHubStarEventData> = {
52 + type: payload.type,
53 + timestamp: payload.timestamp,
54 + data: payload.data
55 };
56
43 - handleGitHubStarAddedEvent(starEvent);
57 + console.log(`Repository ${event.data.repository_name} starred by ${event.data.starred_by}`);
58 + // Add your business logic here
59 }
45 -
46 - res.status(200).json({
47 - status: 'success',
48 - message: 'Webhook received and processed successfully'
60 +
61 + res.status(200).json({
62 + status: 'success',
63 + message: 'Webhook processed'
64 });
65 } catch (error) {
66 console.error('Error processing webhook:', error);
52 - res.status(500).json({
53 - status: 'error',
54 - message: 'Internal server error while processing webhook'
67 + res.status(500).json({
68 + status: 'error',
69 + message: 'Internal server error'
70 });
71 }
72 }