Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
trigger signarure verification
Sushmithamallesh5bff5bdf94ae
diff --git a/fern/fern.config.json b/fern/fern.config.jsonindex 108c9b69f..da5ec9937 100644--- a/fern/fern.config.json+++ b/fern/fern.config.json@@ -1,4 +1,4 @@{"organization": "composio",- "version": "0.107.3"-}\ No newline at end of file+ "version": "0.116.0"+}diff --git a/fern/pages/src/triggers/using-triggers.mdx b/fern/pages/src/triggers/using-triggers.mdxindex 42f124478..af389214a 100644--- a/fern/pages/src/triggers/using-triggers.mdx+++ b/fern/pages/src/triggers/using-triggers.mdx@@ -2,7 +2,7 @@title: Using Triggerssubtitle: Send payloads to your AI agents or systems based on events in apps.image: "https://og.composio.dev/api/og?title=Using%20Triggers" # image for socials-keywords: 'triggers, webhooks, websockets, events, active triggers'+keywords: 'triggers, webhooks, websockets, events, active triggers, trigger types, verify triggers'hide-nav-links: true---@@ -92,23 +92,67 @@ Use a publicly accessible URL where Composio can send event payloads. This endpo**Local development:** Use [ngrok](https://ngrok.com) or [webhook.site](https://webhook.site) toexpose your local server to the internet for testing.</Tip>-**Implement your webhook handler:**-Below are some examples of how to listen in on trigger events-for a FastAPI/Next.js application.+Webhook payloads contain:+- `type`: The trigger type identifier+- `data`: The actual event data+- `timestamp`: When the event occurred+- `log_id`: Unique identifier for this event++Below are examples of webhook handlers for FastAPI and Next.js applications:<CodeGroup><SnippetCodesrc="fern/snippets/triggers/python/trigger-webhook.py"- title="app/route.py"+ title="Python (FastAPI)"+ startLine={36}+ endLine={49}/><SnippetCodesrc="fern/snippets/triggers/typescript/trigger-webhook.ts"- title="app/api/webhook/route.ts"+ title="TypeScript (Next.js)"+ startLine={39}+ endLine={70}/></CodeGroup>+### Verifying webhook signatures++Composio signs all webhook requests so you can verify they're authentic. Each webhook includes these headers:++- `webhook-signature`: HMAC signature in format `v1,<base64_signature>`+- `webhook-id`: Unique message identifier+- `webhook-timestamp`: Unix timestamp when the webhook was sent++To enable verification:++1. Obtain your webhook secret from the [Composio dashboard](https://platform.composio.dev?next_page=/settings/webhook) under Project Settings → Webhook.+2. Set it as the `COMPOSIO_WEBHOOK_SECRET` environment variable+3. Use the verification function in your webhook handler:++<CodeGroup>+<SnippetCode+ src="fern/snippets/triggers/python/trigger-webhook.py"+ title="Python"+ startLine={12}+ endLine={34}+/>++<SnippetCode+ src="fern/snippets/triggers/typescript/trigger-webhook.ts"+ title="TypeScript"+ startLine={12}+ endLine={37}+/>+</CodeGroup>++The signature is calculated as:+```+signing_string = "{webhook-id}.{webhook-timestamp}.{raw_body}"+signature = HMAC-SHA256(signing_string, secret)+```+### Prototyping with trigger subscriptionsDuring development, you can subscribe to triggers directly through the SDK without setting up webhooks.diff --git a/fern/snippets/triggers/python/trigger-webhook.py b/fern/snippets/triggers/python/trigger-webhook.pyindex 6014ee109..b4187baad 100644--- a/fern/snippets/triggers/python/trigger-webhook.py+++ b/fern/snippets/triggers/python/trigger-webhook.py@@ -1,22 +1,50 @@-from fastapi import FastAPI, Request+from fastapi import FastAPI, Request, HTTPExceptionfrom typing import Dict, Anyimport uvicornimport json+import hmac+import hashlib+import base64+import osapp = FastAPI(title="Webhook Demo")+def verify_webhook_signature(request: Request, body: bytes) -> bool:+ """Verify Composio webhook signature"""+ webhook_signature = request.headers.get("webhook-signature")+ webhook_id = request.headers.get("webhook-id")+ webhook_timestamp = request.headers.get("webhook-timestamp")+ webhook_secret = os.getenv("COMPOSIO_WEBHOOK_SECRET")++ if not all([webhook_signature, webhook_id, webhook_timestamp, webhook_secret]):+ raise HTTPException(status_code=400, detail="Missing required webhook headers or secret")++ if not webhook_signature.startswith("v1,"):+ raise HTTPException(status_code=401, detail="Invalid signature format")++ received = webhook_signature[3:]+ signing_string = f"{webhook_id}.{webhook_timestamp}.{body.decode()}"+ expected = base64.b64encode(+ hmac.new(webhook_secret.encode(), signing_string.encode(), hashlib.sha256).digest()+ ).decode()++ if not hmac.compare_digest(received, expected):+ raise HTTPException(status_code=401, detail="Invalid webhook signature")++ return True+@app.post("/webhook")async def webhook_handler(request: Request):- # Get the raw payloadpayload = await request.json()-- # Log the received webhook data- print("Received webhook payload:")- print(json.dumps(payload, indent=2))-- # Return a success response- return {"status": "success", "message": "Webhook received"}--if __name__ == "__main__":- uvicorn.run(app, host="0.0.0.0", port=8000)++ trigger_type = payload.get("type")+ event_data = payload.get("data", {})++ if trigger_type == "github_star_added_event":+ repo_name = event_data.get("repository_name")+ starred_by = event_data.get("starred_by")+ print(f"Repository {repo_name} starred by {starred_by}")+ # Add your business logic here++ return {"status": "success", "message": "Webhook processed"}diff --git a/fern/snippets/triggers/typescript/trigger-webhook.ts b/fern/snippets/triggers/typescript/trigger-webhook.tsindex 2be02d230..8ba7a35da 100644--- a/fern/snippets/triggers/typescript/trigger-webhook.ts+++ b/fern/snippets/triggers/typescript/trigger-webhook.ts@@ -1,57 +1,72 @@import type { NextApiRequest, NextApiResponse } from 'next';import { TriggerEvent } from '@composio/core';+import crypto from 'crypto';-// Define type-safe payload for GitHub Star Added event-export type GitHubStarAddedEventPayload = {- action: "created";- repository_id: number;+type GitHubStarEventData = {repository_name: string;repository_url: string;- starred_at: string;starred_by: string;+ starred_at: string;};-// Type-safe handler function-function handleGitHubStarAddedEvent(event: TriggerEvent<GitHubStarAddedEventPayload>) {- console.log(`⭐ ${event.data.repository_name} starred by ${event.data.starred_by}`);+function verifyWebhookSignature(+ req: NextApiRequest,+ body: string+): boolean {+ const signature = req.headers['webhook-signature'] as string | undefined;+ const msgId = req.headers['webhook-id'] as string | undefined;+ const timestamp = req.headers['webhook-timestamp'] as string | undefined;+ const secret = process.env.COMPOSIO_WEBHOOK_SECRET;++ if (!signature || !msgId || !timestamp || !secret) {+ throw new Error('Missing required webhook headers or secret');+ }++ if (!signature.startsWith('v1,')) {+ throw new Error('Invalid signature format');+ }++ const received = signature.slice(3);+ const signingString = `${msgId}.${timestamp}.${body}`;+ const expected = crypto+ .createHmac('sha256', secret)+ .update(signingString)+ .digest('base64');++ return crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));}-export default async function handler(req: NextApiRequest, res: NextApiResponse) {+export default async function webhookHandler(req: NextApiRequest, res: NextApiResponse) {if (req.method !== 'POST') {return res.status(405).json({status: 'error',- message: 'Method not allowed. Only POST requests are accepted.'+ message: 'Method not allowed'});}try {const payload = req.body;-- // Type-safe webhook payload processing- if (payload.triggerSlug === 'GITHUB_STAR_ADDED_EVENT') {- const starEvent: TriggerEvent<GitHubStarAddedEventPayload> = {- type: payload.triggerSlug,- timestamp: new Date().toISOString(),- data: {- ...payload.payload as GitHubStarAddedEventPayload,- connection_nano_id: payload.metadata?.connectedAccount?.id || '',- trigger_nano_id: payload.id || '',- user_id: payload.userId || '',- }++ if (payload.type === 'github_star_added_event') {+ const event: TriggerEvent<GitHubStarEventData> = {+ type: payload.type,+ timestamp: payload.timestamp,+ data: payload.data};- handleGitHubStarAddedEvent(starEvent);+ console.log(`Repository ${event.data.repository_name} starred by ${event.data.starred_by}`);+ // Add your business logic here}-- res.status(200).json({- status: 'success',- message: 'Webhook received and processed successfully'++ res.status(200).json({+ status: 'success',+ message: 'Webhook processed'});} catch (error) {console.error('Error processing webhook:', error);- res.status(500).json({- status: 'error',- message: 'Internal server error while processing webhook'+ res.status(500).json({+ status: 'error',+ message: 'Internal server error'});}}